Showing posts with label reference. Show all posts
Showing posts with label reference. Show all posts

Tuesday, August 23, 2011

The maximum number of matrix dimensions in MATLAB

[ Background: I was asked what the maximum number of matrix dimensions was in MATLAB today. I responded as follows. ]

You are only limited by the amount of memory available and the maximum number of ELEMENTS (as opposed to dimensions) in a matrix. The actual number of dimensions is just a detail about how the memory is indexed. You can reshape any existing matrix to any number of dimensions (I'll give details below). You can only create a new matrix if it abides by the memory and element limits that vary by computer.

To find out the maximum number of elements for a matrix on your computer, use the MATLAB command "computer" (do "help computer" for details). For example:
[~,maxsize,~]=computer
tells me that I can have 2.8147e+14 elements in matrices on my computer. So I better be sure that:
(number of rows)
   × (number of columns)
   × (number of cubes)
   × (number of 4-th dimensional thinggies)
   × (...)
is less than that number.

To find out about memory limits on your system see, the command "memory" ("help memory" or "doc memory"). Unfortunately, memory may not be available on your system. Alternatively, you can see:

http://www.mathworks.com/support/tech-notes/1100/1110.html

for information about memory limits in MATLAB. For information about the maximum number of elements (and the command "computer" that I discussed above), see (UPDATE: MATLAB has moved this page, and this link doesn't land in the right spot anymore):

http://www.mathworks.com/support/tech-notes/1200/1207.html#15

Regarding dimensions, you can use the command "reshape" to re-index any existing matrix. For example, if I start with the column vector:
A=ones(100,1)
I can turn it into a row vector:
newA = reshape(A, 1, 100)
or a matrix of any number of dimensions so long as the number of elements is still 100.
newA = reshape( A, 2, 2, 25 )
newA = reshape( A, 1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 1 )
newA = reshape( A, 1, 1, 1, 2, 1, 50, 1, 1, 1, 1, 1, 1, 1, 1 )
% etc.
Now, I'm assuming you're using regular MATLAB matrices. Alternatively, you can use sparse matrices so long as you limit yourself to functions that work with sparse matrices:
help sparfun
A sparse matrix stores an index with every element. That lets it "skip over" the 0 elements of the matrix. Consequently, you can store VERY large matrices with an abstract number of elements far larger than anything you can work with in MATLAB... however, most of those abstract elements will be 0.

Monday, June 13, 2011

Someone asked me for some references on LaTeX today...

I got an e-mail today asking for some recommended references on LaTeX. Here is my response, which is a marked-up paste of an e-mail.

[ This post can also be found on my web page. ]
The reference that I keep handy is:

The LaTeX Companion (Tools and Techniques for Computer Typesetting)
The LaTeX Companion, Second Edition by Mittelbach and Goosens

That reference, often called TLC2, is a standard one. You really can't
go wrong with it. It's dense, includes lots of examples, and is pretty
easy to use. One other book that came in handy when I started drawing
graphics in LaTeX is:

LaTeX Graphics Companion, The (2nd Edition)
The LaTeX Graphics Companion by Goosens, Rahtz, and Mittelbach

That introduced me to things like picture environments and PSTricks. I
use PSTricks a lot now, and the book really is only meant to be an
introduction (albeit a nice one) to PSTricks as well as other competing
(and complementary) tools. Now I typically use the PSTricks
documentation on the PSTricks home page at TUG (you can google for
"PStricks"
to find the web page).

A nice small reference to LaTeX is:

LaTeX: A Document Preparation System (2nd Edition)

A very complete but also intimidating reference for TeX is:

Computers & Typesetting, Volume B: TeX: The Program
The TeXbook by Knuth

Three other notable and popular books on TeX (that are far less
intimidating) are:
You can still get that last book in print from some sources that print
out of print books (lulu.com), but I believe it has been released for free as a PDF as well. Yes, see:


for the free download link (released under GNU FDL).

[ If you really don't want to get into the nitty gritty details, I would
recommend sticking to the LaTeX references. ]

Otherwise, I've just done a lot of learning by doing. It helped to
learn about typesetting in general. A good reference for both things is
the documentation that comes with the memoir package:
That documentation link (memman.pdf) is an excellent introduction to all
of the basic typographical elements of a book... and memoir is a nice
LaTeX package in general.

After that, see comp.text.tex (available as a Google group) which is
known simply as "CTT" to insiders...


LaTeX and TeX experts watch that group and will answer your questions
about how to do things. You can also search the group for some previous
answers to similar questions. You can also see announcements of new
versions of packages that do cool things. It's a great resource.

Finally, seeing the LaTeX 2e source (implemented in TeX) can be helpful
to understand exactly what goes on when you do things like a \section.
"source2e.pdf" is included with the LaTeX distribution. You can also
view it on-line here:


That includes all of the TeX implementations for the LaTeX macros and
gives you some idea of what goes on when you build a LaTeX document.

Off the top of my head, that's all I can think of. Just go into things
thinking that LaTeX probably *CAN* do whatever you want it to (including
solving and plotting differential equations, which pure LaTeX (as
opposed to PDFLaTeX) can do). Like a sculptor, you just have to figure
out what to chip away to get it to do it. Keep trying things until
something is qualitatively similar to what you want, and then tune
(perhaps with the help of CTT) after that. Eventually you'll come up
with better and better implementations. If you come up with something
especially novel, post it on-line. In fact, contributing to CTAN
directly is usually recommended.

Another thing that helps me is to remember that TeX is really is just a
giant machine that tokenizes, parses, and expands. It's not a
"programming language" so much as it is a text "filter" in that a single
run of LaTeX doesn't necessarily result in what you want. Keeping this
in the back of my head helps me anticipate the problems I might have
with certain approaches, and it further helps me figure out how to
approach LaTeX in order to succeed.

Tuesday, March 08, 2011

Installing Adobe Digital Editions on Linux with Wine

UPDATE: I have not had time to address the download issues some people have had when trying to install ADE. However, see the comments on this post for some additional tips on where to find an ADE installer download that you can run inside Wine.
Unfortunately, Adobe does not provide a simple download link for the Windows version of Digital Editions, and so if you want to purchase a PDF or ePub e-book with Adobe ADEPT DRM protection, it is very difficult to get up and running on Linux even if you have Wine installed. Here's how I did it.
  1. Install Wine on your system. Most Linux distributions provide Wine as an optional install (e.g., sudo yum install wine from the command line on Fedora).
  2. You will need Gecko extensions available to run the iexplore.exe web browser that comes with Wine. Visit the Wine Wiki's Gecko page for information on how to install Gecko. Your Linux distribution may have a "wine-gecko" package. If it doesn't, then follow the simple instructions on the Wine Wiki.
  3. You will also need Adobe Flash installed on your Wine system, and so you should visit the Wine Wiki's Flash page to get the install_flash_player.exe download link. Download the exe and run it in Wine (e.g., wine install_flash_player.exe from the command line).
  4. Now, start the iexplore.exe browser bundled with Wine. After I ran Wine for the first time, it setup a .wine directory in my home directory (i.e., ~/.wine). I found the iexplore.exe in ~/.wine/drive_c/Program Files/Internet Explorer. Change to that directory and run iexplore.exe (e.g, wine iexplore.exe from the command line).
  5. Now you can visit the Digital Editions installer (which is written in Flash). From the Wine Internet Explorer, enter in the URL:
    http://www.adobe.com/products/digitaleditions/ade_web_library.swf
    That should startup a little installer. Follow the prompts to download and install Digital Editions. You will even be able to launch it from there.
    • The installer will install the single Digital Editions executable to ~/.wine/drive_c/Program Files (x86)/Adobe/Adobe Digital Editions as digitaleditions.exe.
    • You can run it again but executing that file through wine (e.g., wine digitaleditions.exe from the command line in that directory)
    • Alternatively, you can use the "Digital Editions" shortcuts that the installer probably placed on your desktop.
  6. Once Digital Editions is started, you should be able to drag-and-drop ACSM files you've downloaded from e-Book commerce sites (like Google Books), and it should download the Adept-DRM'd version of your media.
    • DRM'd books are stored in the My Digital Editions folder that will be created in your home directory.
    • If you want to put them elsewhere, you need to edit the symbolic links in ~/.wine/drive_c/users/USERNAME where USERNAME is your Linux username. The My Documents folder was symlinked to my home directory by default. I got rid of the symlink and created a real directory there instead, but you could point the symlink somewhere else if you'd rather. Regardless, the My Digital Editions folder will reside inside the My Documents folder (alongside a My Books folder, but I don't know what gets put in there... maybe non-DRM stuff you put into ADE?).
Once you have your DRM'd books, you should be able to transfer them onto devices that have also been authorized with your Adept key (e.g., a Sony Reader that has been authorized with the same account you used inside Digital Editions). I suppose it's possible to get the Digital Editions running inside Wine to notice when your reader is connected, but I haven't tried it (that might involve installing the Sony Reader Library software within Wine, and I received some ugly errors when I tried to do that (but YMMV)).

Friday, July 24, 2009

Installing docutils for Mercurial (rst2man and rst2html)

If you're building Mercurial from its source, you might notice that the latest versions are using reStructuredText to markup their documentation. Hence, you'll need to install docutils. Additionally:
  • You'll have to install the rst2man tool that is presently only available in the docutils "Sandbox," which you have to download separately.
  • You'll have to make sure you have the new rst2man.py tool accessible in your PATH as rst2man.
  • You'll have to make sure you have the included rst2html.py tool accessible in your PATH as rst2html.
So it's no surprise that yet-another-Python-related-adventure is yet-another-Python-related-headache. Here's how to get up and running. Things should get substantially simpler if and when docutils starts including rst2man as part of their standard distribution (however, you'll probably still have to make the simlinks unless Mercurial's installer is able to call the rst scripts with their .py extension). Meanwhile, here are some steps that will hopefully get you (the UNIX or Mac/OS X user) moving in the right direction.
  • First, go to the docutils website and download the docutils snapshot as well as the docutils sandbox snapshot.
  • tar zxf those tarballs to extract the docutils source code. That should give docutils and sandbox directories.
  • Copy sandbox/manpage-writer/tools/rst2man.py to somewhere in your PATH (e.g., /usr/local/bin/rst2man.py or ~/bin/rst2man.py if you have ~/bin in your PATH).
  • Create a symbolic link in your PATH from the rst2man.py you just placed there to rst2man. For example, symlink /usr/local/bin/rst2man.py to /usr/local/bin/rst2man by doing ln -s rst2man.py rst2man in the /usr/local/bin directory.
  • Copy sandbox/manpage-writer/docutils/writers/manpage.py to docutils/docutils/writers/manpage.py.
  • In the docutils directory, run python setup.py install (for a global installation) or python setup.py install --home ~ (for a home installation).
  • Copy docutils/rst2html.py to somewhere in your PATH (e.g., /usr/local/bin/rst2html.py or ~/bin/rst2html.py).
  • Create a symbolic link in your PATH from the rst2html.py you just placed there to rst2html. For example, ln -s rst2html.py rst2html inside your /usr/local/bin or ~/bin directory.
  • Fetch the latest version of Mercurial and build it. Assuming you have all of the other dependencies, it should build OK.
Of course, YMMV, but I hope that at least helps get you on your way.

Friday, September 19, 2008

Pretty analog docs

Lately, I've noticed more hits on my website for documents that I put together for some classes that I've taught. So I decided to collect all the substantial ones and list them in one place. I figured I'd do the same here...

Tuesday, August 19, 2008

Building MATLAB images from Makefiles

Recently I beefed up my LaTeX Makefiles to make image generation more automatic. These implicit rules have worked very well for me (note that the indentation is done with TABS — that's important).
%.pdf : %.eps
epstopdf $*.eps

%.eps : %.m
matlab -nosplash -nodesktop -r "$*;quit"

%.eps : %.png
convert -density $(RESOLUTION) $*.png $*.eps

%.eps : %.jpg
convert -density $(RESOLUTION) $*.jpg $*.eps

%.eps : %.dvi
dvips $* -D $(RESOLUTION) -E -o $*.eps

%.dvi : %.tex
latex -interaction=nonstopmode $*.tex
rm -f $*.log
rm -f $*.aux
That if, if I need a file called FILENAME.eps or FILENAME.pdf, the Makefile will look for FILENAME.m, FILENAME.png, FILENAME.jpg, or FILENAME.tex. Depending on which one it finds, it will run the appropriate command to generate the image I need. Note that I define RESOLUTION=1500 in the top of my Makefile.

I want to point out the MATLAB build line:
matlab -nosplash -nodesktop -r "$*;quit"
That handy line starts up as little of MATLAB as possible and runs a script that contains something like:
% First, generate a figure somehow

% Next, setup the figure's print proportions
set( gcf, 'PaperType', 'usletter', ...
'PaperOrientation', 'portrait', ...
'PaperPosition', [0.0 3.5 11 3.5] );

% Finally, save the figure as a (color) EPS
saveas( gcf, 'FILENAME.eps', 'epsc2' );
After the script finishes, MATLAB exits. It won't get started on any subsequent makes so long as the script file doesn't change or the image isn't deleted.

Getting back to the more general case, up high in my Makefile, I have something like
RESOLUTION=1500
BASETEXIMAGES=$(shell perl -ne \
'/\\includegraphics\s*(?:\[.*?\]|)\s*{\s*(.*?)\s*}/ \
&& do { print "$$1 " \
if (-e "$${1}.tex" || \
-e "$${1}.png" || \
-e "$${1}.jpg" || \
-e "$${1}.m"); };' *.tex)
TEXIMAGES=$(addsuffix .eps,$(BASETEXIMAGES))
and a little later I make $(TEXIMAGES) a dependency for my document (or something equivalent to that).

Those lines have saved me a lot of time, and I'm pretty happy about them.

Monday, July 28, 2008

Adding section or subsection to every reference (but not label)

In the form topic, "Full context variable depth references to list labels?," someone wanted to force LaTeX to
  • use legal-format lists
  • reformat its references to prefix them with the full subsection number (e.g., "2.1-") when inside a subsection and section number (e.g., "2-") otherwise.
I suggested:
\usepackage{enumitem}
\newlist{legal}{enumerate}{10}
\makeatletter
\setlist[legal]{label*=\arabic*.,
ref=\csname
the\enit@prevlabel
\endcsname\arabic*.}
\newcommand\thesectionlabel{%
\ifnum\value{subsection}=0
\thesection
\else
\thesubsection
\fi}
\newcommand{\thelegal}{\thesectionlabel-}
\makeatother

\usepackage{varioref}
\labelformat{equation}%
{\thesectionlabel-\textup{(#1)}}
\labelformat{figure}{\thesectionlabel-#1}
\labelformat{table}{\thesectionlabel-#1}
I've wrapped lines (by inserting VERY important % characters in special places to make the snippet viewable in this thin blog. As you can see in the original thread, my suggestion looked shorter because the lines were unwrapped.

It seems to work well and is one of those solutions that TeXnicians would probably do on their own without a second thought and would never document, but it's something complicated-enough that everyone else would tear their hair out searching for it.

Saturday, June 28, 2008

pedagogical moment: LaTeX, TeX, environments, and csname

On the MiKTeX mailing list, a thread descended into a flame that someone bracketed with \flameon and \flameoff, which is a sort of Fantastic Four version of a LaTeX environment. The thread involved the differences between TeX, Plain TeX, and LaTeX, and so I took the opportunity to point a few things out. I received several positive responses, and so I decided to reproduce my post here.
\pedagogical

There's a TeX vs. LaTeX teachable moment here . . .

> > \flameon
...
> > \flameoff


     As an example, if you're using LaTeX, the proper code for a flame environment is:
\begin{flame}
\end{flame}
However, the \begin and \end macros do nothing more than call:
\flame
\endflame
and so bracketing an environment in these macros is (in principle) equivalent to using the \begin and \end environments.

     Further, a naive implementation of \begin and \end is:
\newcommand\begin[1]{\csname #1\endcsname}
\newcommand\end[1]{\csname end#1\endcsname}
which is equivalent to the "raw" TeX (which may also be used in LaTeX):
\def\begin#1{\csname #1\endcsname}
\def\end#1{\csname end#1\endcsname}
In other words, \newcommand and \def are basically the same beast. However, \newcommand is a macro (created with \def) that checks to make sure you haven't already \newcommand'd before. SIMILARLY, the REAL \begin and \end wrappers have extra sanity checks for safety.

     Finally, that leaves
\csname BLAH\endcsname
which is equivalent to
\BLAH
Notice that it looks like an environment. So I could also do:
\begin{csname}today\end{csname}
which actually gives me the same output as \today.

\endpedagogical

     --Ted
I should also note that the source code for LaTeX is listed in the source2e.pdf documentation that comes with nearly every LaTeX distribution (it does not appear to come with MiKTeX). Execute
texdoc source2e
to see the document on your system.

Thursday, June 12, 2008

LaTeX generated figures: Using preview instead of pst-eps

I've been using the pst-eps package when I want to generate EPS versions of coded graphics (e.g., graphics produced with PSTricks or the standard picture environment). From the pst-eps description:
Pst-eps is a PSTricks (pstricks)-based package for exporting PSTricks images ‘on the fly’ to encapsulated PostScript (EPS) image files, which can then be read into a document in the usual way.
By wrapping lines in a TeXtoEPS environment, you setup LaTeX to produce an image of the enclosed content with a tight bounding box. It works well, but you must use dvips -E to generate your EPS files with the proper bounding box. If you want to then generate a PDF, you have to use something like epstopdf (possibly with the EPSCrop GhostScript option) to do it. Additionally, there's a lot of overhead within the actual TeX source. In other words, it's not quite easy to use.

A BETTER OPTION: Today, I discovered the preview package, which is described with:
The package is a free-standing part of the preview-latex bundle. The package provides the support preview-latex needs, when it chooses the matter it will preview. The output may reasonably be expected to have other uses, as in html translators, etc.
This package appears to be a much nicer solution. You can use standard latex or pdflatex to compile. If you need to use latex but still want EPS or PDF outputs, you can use dvips and ps2pdf without any special options. Otherwise, the introduced preview environment works very similar to the old TeXtoEPS environment, but it requires less work to use and seems to apply to a broader class of content.

Here's an example that should not require anything fancy to build. If you don't have the amsmath package (you should), you can omit it and get rid of the gather* environment:
\documentclass{article} 
\usepackage{amsmath} % for gather*
\usepackage[active, % Turns previewing on
tightpage, % Squeezes pages around previews
textmath, % Subjects textual math to a preview
displaymath, % Subjects math displays to preview
floats % Subjects floats to preview
]{preview}
% There is a ``graphics'' option too that subjects
% includegraphics to preview. If they are already in a
% float, the ``floats'' option is sufficient.
\begin{document}

This text will NOT get printed.

\begin{equation}
a = b
\end{equation}

The math following the colon gets printed: $x = 5$?

\begin{gather*}
c = d
\end{gather*}

More text not printed.

\begin{preview}
Page 2 is here (with tight border).
\end{preview}

You'll never see this text.

\begin{figure}
\fbox{\fbox{\fbox{A figure that is printed}}}
\end{figure}

\end{document}
If the active option of preview is commented out, the file builds as if preview didn't exist. However, with it turned on, only the sections in preview environments get printed, and they each get put on a separate page with tight borders. Options like displaymath, textmath, and floats cause those types of content to get automatically wrapped with a preview environment.

Related posts:

Tuesday, July 10, 2007

TeX Reference Card (and others)

UPDATE 3: I found the source of the popular LaTeX cheat sheet. It includes a PS version, a PDF version, PNG views [Page 1, Page 2], and the LaTeX source. It's nice that the source is available. That makes it easier to shift from A4 to letter paper and back.

UPDATE 2: More reference cards can be found in the follow-up to this message.

UPDATE 1: Check out refcards.com and the old version old.refcards.com. There are lots of useful cards, including some of the ones I linked below. This TeX card and this Vim card look familiar. There are other EMmacs and Vim cards in the editors section. There is also a typesetting section that includes a LaTeX cheat sheet.

The Brown University Center for Fluid Mechanics, Turbulence and Computation (CFM) has a collection of computing tutorials. Buried in there somewhere is a useful Plain TeX reference card in PostScript format. I have generated a PDF version of this reference card.

I stress that this is a Plain TeX reference card, and so there are different ("better"?) ways of doing some of these things using other LaTeX macros (note TeX vs. Plain TeX vs. LaTeX differences: [1, 2, 3, 4, and more]). However, this is still a very useful reference card. It prints out as two landscape-oriented pages (weirdly sized: 11.7" x 8.3"). I plan on printing this out and taping it next to my desk at the office. I also found a useful longer Plain TeX reference sheet that may be helpful to some people. Of course, there are even longer Plain TeX reference documents also available.

Oh, I also found this AUC TeX reference card PDF with available source code. I don't use AUC TeX (I favor VIM-LaTeX), but maybe someone who does could use this. FYI, AUC TeX is a package for EMacs providing extra support for LaTeX (and others).

Speaking of Vim: So that's nice.

Thursday, June 28, 2007

Preamble for Journal of Mathematical Biology

Update 5: The updated svglov2.clo and svglov3.clo are not needed if the preamble is used below (i.e., if the \RequirePackage{fix-cm} line is added before the documentclass line.

Update 4: See the section that redefines \autoref. Changed definition to support starred commands that are unlinked.

Update 3: See the section starting with the comment "%% Level 1 Subsections". It forces subsections to show up like sections in the PDF bookmarks; this is a (strange) JMB convention. In the comment I make some suggestions for improvements.

Update 2: See the small commented section "%%%% Table Support". If the LaTeX code is uncommented there, there is no need for the \noalign{\smallskip} stuff around \hline horizontal table rules. It uses the tabls package to do this.

Update 1: I've mirrored this content on my web page.

I'd like to combine some of the previous posts. I've been trying to fix and modernize some of the Springer LaTeX support files for the Journal of Mathematical Biology (JMB). I've come up with these...

  • svglov2.clo - document class option for svjour2.cls. I used fix-cm to get rid of some of the warnings about not being able to scale the Computer Modern fonts. This is not needed if the preamble below is used (i.e., with the fix-cm line before the documentclass line).

  • svglov3.clo - document class option for svjour3.cls. I used fix-cm to get rid of some of the warnings about not being able to scale the Computer Modern fonts. This is not needed if the preamble below is used (i.e., with the fix-cm line before the documentclass line).

  • spmpsci.bst - BiBTeX bibliography style file for JMB. The original version of this did not reverse the first and last name of the editors as required; I fixed that.

  • spmpscinat.bst - natbib compatible BiBTeX bibliography style file for JMB. Be sure to include natbib with numbers and sort&compress options.
I recommend using a preamble like this one...
%%%% Journal of Mathematical Biology (JMB) setup

% Allow Computer Modern fonts to be scaled (must be before svjour3)
\RequirePackage{fix-cm}

% Use running heads
\documentclass[runningheads]{svjour3}

% The journal's name
\journalname{Journal of Mathematical Biology}

% use Times fonts
\usepackage{mathptmx}

% flush right qed marks (Halmos square),
% e.g., at end of proof
\smartqed

% Use natbib for \citet, \citep, etc.
% (JMB: numbered citations that are sorted
% and compressed)
\usepackage[numbers,sort&compress]{natbib}
%\bibliographystyle{spmpsci}
\bibliographystyle{spmpscinat}

%%%% Some useful packages

% Allow for smarter labeling of enumerations
% and itemizations (consider using enumitem instead)
\usepackage{paralist}

% Provides \labelformat, which changes how \ref
% references look
\usepackage{varioref}

% Mathematical symbols, etc.
\usepackage{amssymb,amsfonts,amsmath}

%%%% Table Support

% UNCOMMENT THE FOLLOWING LINES TO GET RID OF
% \noalign{\smallskip} STUFF AROUND \hline's IN
% TABLES
%
% % The following three lines remove the need for
% % the \noalign{\smallskip} around the \hline's
% % in the _Journal of Mathematical Biology_ LaTeX
% % template
% \usepackage{tabls}
% \addtolength\extrarulesep{\smallskipamount}
% \addtolength\extrarulesep{1pt}

%%%% Graphics and Figure Support

% Use subfig for subfigures
\usepackage[nearskip=-3pt,captionskip=4pt,
listofformat=subsimple,
labelformat=simple]{subfig}

% Make sure subfigures have parentheses around
% them everywhere
\renewcommand\thesubfigure{(\alph{subfigure})}

% Use graphicx for including graphics
\usepackage{graphicx}

% When picture environments are used, use
% pict2e for better resolution and flexibility
\usepackage{pict2e}

%%%% Hyperlink and Autoreference Support

%% Level 1 Subsections
%
% JMB does this weird thing where all
% subsection-level PDF bookmarks are displayed as
% section-level bookmarks. Strangely, they do
% *NOT* turn on the ``bookmarksnumbered'' hyperref
% option. I think their articles would be MUCH more
% readable with all level-1 bookmarks if they were
% prefixed by their section number. I'm sure they'd
% argue that since the sections are linked within
% the document, this is not needed.
%
% (note: another option is to set tocdepth=2 and turn
% on the ``bookmarksopen'' hyperref option)
%
% Anyway, the following redefines \addcontents line
% to setup the bookmarks like JMB articles. Must do
% this after hyperref because it redefines
% \addcontentsline. Therefore, just use an
% AtBeginDocument.
%
\usepackage{ifthen}
\AtBeginDocument{%
\let\orgaddcontentsline\addcontentsline
\renewcommand{\addcontentsline}[3]{
\ifthenelse{\equal{#1}{toc}}
{\ifthenelse{\equal{#2}{subsection}}
{\orgaddcontentsline{#1}{section}{#3}}
{\orgaddcontentsline{#1}{#2}{#3}}}
{\orgaddcontentsline{#1}{#2}{#3}}}}

% Include hyperref for link support
% Include hyperref for link support
%\usepackage[dvipdfmx, % If need dvipdfmx
%\usepackage[dvips, % If need dvips
\usepackage[% % Fine in most cases
pdfpagelabels,hypertexnames=true,
plainpages=false,
naturalnames=false]{hyperref}

% Configure the hyperlink color
\usepackage{color}
\definecolor{darkblue}{rgb}{0,0.1,0.5}
\hypersetup{colorlinks,
linkcolor=darkblue,
anchorcolor=darkblue,
citecolor=darkblue}

% In the future, it would be nice to use the package
%
% cleveref
%
% Right now, it breaks svjour3 and svjour2, so we just
% have to use autoref and labelformat :(.

% Make sure \autoref puts parentheses around
% equations and enumeration items (similar to \eqref)
% NOTE: This allows us to use \ref instead of \eqref
\labelformat{equation}{\textup{(#1)}}
\labelformat{enumi}{\textup{(#1)}}

% Make sure equations are numbered by section
\numberwithin{equation}{section}

%% We need to redefine \autoref. We should use
%% abbreviations inside the sentence and full names
%% at the beginning of sentences. Additionally,
%% need to handle the plural cases.

% \Autoref is for the beginning of the sentence
\let\orgautoref\autoref
\providecommand{\Autoref}
{\def\equationautorefname{Equation}%
\def\figureautorefname{Figure}%
\def\subfigureautorefname{Figure}%
\def\sectionautorefname{Section}%
\def\subsectionautorefname{Section}%
\def\subsubsectionautorefname{Section}%
\def\Itemautorefname{Item}%
\def\tableautorefname{Table}%
\orgautoref}

% \Autorefs is plural for the beginning of the sentence
\providecommand{\Autorefs}
{\def\equationautorefname{Equations}%
\def\figureautorefname{Figures}%
\def\subfigureautorefname{Figures}%
\def\sectionautorefname{Sections}%
\def\subsectionautorefname{Sections}%
\def\subsubsectionautorefname{Sections}%
\def\Itemautorefname{Items}%
\def\tableautorefname{Tables}%
\orgautoref}

% \autoref is used inside a sentence
% (this is a renew of the standard)
\renewcommand{\autoref}
{\def\equationautorefname{Eq.}%
\def\figureautorefname{Fig.}%
\def\subfigureautorefname{Fig.}%
\def\sectionautorefname{Sect.}%
\def\subsectionautorefname{Sect.}%
\def\subsubsectionautorefname{Sect.}%
\def\Itemautorefname{item}%
\def\tableautorefname{Table}%
\orgautoref}

% \autorefs is plural for inside a sentence
\providecommand{\autorefs}
{\def\equationautorefname{Eqs.}%
\def\figureautorefname{Figs.}%
\def\subfigureautorefname{Figs.}%
\def\sectionautorefname{Sects.}%
\def\subsectionautorefname{Sects.}%
\def\subsubsectionautorefname{Sects.}%
\def\Itemautorefname{items}%
\def\tableautorefname{Tables}%
\orgautoref}

This lets you do cool things like... (hyperlinks depicted in blue)

\ref{eq:1} produces linked "(1)"
\ref*{eq:1} produces unlinked "(1)"
\autoref{eq:1} produces linked "Eq. (1)"
\autoref*{eq:1} produces unlinked "Eq. (1)"
\Autoref{eq:1} produces linked "Equation (1)"
\autoref{sec:2} produces linked "Sect. 2.1"
\Autoref{sec:2} produces linked "Section 2.1"
\Autorefs{sec:1} and \ref{sec:2} produces linked "Sections 1 and 2.1"
\autorefs{sec:1} and \ref{sec:2} produces linked "Sects. 1 and 2.1"
\autoref{item:1} produces linked "item (i)"
\autorefs{item:1} and \ref{item:2} produces linked "items (i) and (ii)"
\citep{SK86} produces linked "[61]"
\citep[p.~41]{SK86} produces linked "[61, p. 41]"
\citep{Cha76,SK86} produces linked "[14, 61]"
\citep[e.g.,][]{SK86,Cha76} produces linked "[e.g., 14, 61]"
\citeauthor{SK86} produces linked "Stephens and Krebs"
\citet{SK86} produces linked "Stephens and Krebs [61]"

Tuesday, June 26, 2007

Most PostScript to PDF LaTeX Stuff: pst-pdf

This is a follow-up to Bounding Boxes and EPS to PDF Conversion (in LaTeX).

There is also the LaTeX package pst-pdf, which uses the tool from the package ps4pdf.

This is a clever package with a more general approach to PS-to-PDF conversion than epstopdf. Rather than focusing only on the EPS graphics, it looks at the document as a whole. This means that it takes care of converting PSTricks (CTAN, TUG) graphics as well. It's a simple way of using pdflatex to produce a PDF while using constructs inside the document that are normally only allowed with latex (I assume that psfrag/psfragx will also work well with pst-pdf).

Of course, regardless of what you are producing, you should not be using epsfig anymore; use graphics and graphicx instead. In fact, epsfig isn't even supported anymore. There is a version included with the graphicx package for backwards compatibility.

For more information about including imported EPS files in LaTeX, see epslatex.pdf.

Related post:

Bounding Boxes and EPS to PDF Conversion (in LaTeX)

Another development: More bounding box related issues are discussed in this CTT thread. It turns out that dvips -E basically guesses RANDOMLY at what the bounding box should be, and so its answers can be inconsistent. GhostScript (gs) has a bbox driver that circumscribes your EPS with a rectangle and uses the rectangular dimensions as the bounding box. The epstool command can use this GhostScript calculation to update your EPS. So you can imagine doing things like...
latex file.tex
dvips -E file.tex -o tmp.eps
epstool --bbox --copy --ouput file.eps tmp.eps
epstopdf file.eps
The epspdf script has similar functionality (when you are converting from EPS to PDF) and will be included in TeXLive 2008.

Related post: LaTeX generated figures: Using preview instead of pst-eps

Follow-up: See another interesting option (pst-pdf) in this follow-up.

Update: Another interesting option is purifyeps, which requires pstoedit and Perl. See below.

None of the following is too special. This is all well-known stuff. However, it's not the easiest to find with a Google search, so I'm going to post it here.

Pretty often, I have to generate an EPS file with MATLAB. That EPS figure will go into a LaTeX document. To generate a PDF document from my LaTeX source, I will probably use PDFLaTeX/PDFTeX. However, that means I need to convert that MATLAB EPS figure to PDF. Most EPS-to-PDF distillers I use will mess up the bounding box information and the result of the conversion will be a FULL PAGE PDF rather than the nice tiny EPS figure.

Keep this scenario in mind and consider these notes:
(*) ps2pdf command: To convert EPS to PDF and maintain the proper bounding box, try including the "EPSCrop" GhostScript (GS) option:
ps2pdf -dEPSCrop blah.eps blah.pdf
Without the -dEPSCrop option, I get the full-page PDF from a MATLAB EPS. However, with the -dEPSCrop option, things work fine.

(*) epstopdf command: ALTERNATIVELY, try this line instead:
epstopdf blah.eps
This works for me. If it doesn't, try this (on Windows with MiKTeX 2.6):
epstopdf --gsopt=-dEPSCrop blah.eps
That also works for me.

(*) epstopdf LaTeX package: You may be interested in the epstopdf package which comes with the oberdiek bundle. It should be included in your LaTeX distribution. If not, install the oberdiek bundle. You can find information (and download) about these here:
From that last link, you'll find this epstopdf usage (this will work for the graphics package as well):
\usepackage[pdftex]{graphicx}
\usepackage{epstopdf}
Then you can include graphics two different ways:
% Way 1: Includes blah.eps. Will ALWAYS generate 
% blah.pdf regardless of whether it already exists.
\includegraphics{blah.eps}

% Way 2: Includes blah.eps. If blah.pdf DOES NOT EXIST,
% it will automatically be generated.
\includegraphics{blah}
There are configuration options too. Consider the following:
% The default eps to pdf rule
\DeclareGraphicsRule{.eps}{pdf}{.pdf}{`epstopdf #1}

% Alternative eps to pdf rule
\DeclareGraphicsRule{.eps}{pdf}{.pdf}
{`ps2pdf -dEPSCrop #1}

% A rule for converting gif to png using ImageMagick
% NOTE: The placement of the % signs IS important
\DeclareGraphicsRule{.gif}{png}{.png}{%
`convert #1 `basename #1 .gif`.png%
}

% The same gif-to-png rule for Windows
% (i.e., without basename support)
\makeatletter
\DeclareGraphicsRule{.gif}{png}{.png}{%
`convert #1 \noexpand\Gin@base.png%
}
\makeatother
FINALLY, if you want to add .gif to the list of extensions that the package graphicx (or graphics package) searches if the file extension is not given in \includegraphics, you can either use the command \GraphicsExtensions OR doing something like:
\makeatletter
\g@addto@macro\Gin@extensions{,.gif}
\makeatother
Leaving the file extension off of the \includegraphics macro makes a lot of sense; however, remember that epstopdf will only be run the first time latex or pdflatex gets run. If you want it to convert all of your graphics every run, be sure to leave the extensions on.

(*) purifyeps command: There is also purifyeps, which requires pstoedit and Perl. Taken from purifyeps's CTAN page:
While pdfLaTeX has a number of nice features, its primary shortcoming relative to standard LaTeX+dvips is that it is unable to read ordinary Encapsulated PostScript (EPS) files, the most common graphics format in the LaTeX world. purifyeps converts EPS files into a "purified" form that can be read by *both* LaTeX+dvips and pdfLaTeX. The trick is that the standard LaTeX2e graphics packages can parse MetaPost-produced EPS directly. Hence, purifyeps need only convert an arbitrary EPS file into the same stylized format that MetaPost outputs.
I haven't actually played with this at all. I recommend reading purifyeps.pdf for more information about why you want a "purified" EPS rather than some other format. I assume that the bounding box problem shouldn't be an issue here, but I have no idea.

(*) pstoedit command:
MPS files can be used DIRECTLY by BOTH latex and pdflatex (pdflatex does MPS-to-PDF conversion on-the-fly). You can easily convert EPS files to MPS files yourself as long as you have psttoedit (download and install it from the pstoedit page). Take a look at section 5.4 (MetaPost) of epslatex.pdf for information on that. From the instructions there:
pstoedit -f mpost graphic.eps graphic.mp
mpost graphic.mp
rename graphic.1 graphic.mps
That is, run psttoedit to convert to MP and then use mpost to create the MPS from the MP. Simple, huh? Now, does it fix the bounding box problem? As with the last bullet, I have no idea. Maybe someday I'll try this.

Hopefully some of that will be useful to someone; it will at least be a good reference for me. :)

Saturday, June 23, 2007

A LaTeX Bulletin Board

Every once in a while I get an urge to create a topic blog. Those blogs receive the most traffic and probably do the most practical good in the world, right? I have trouble coming up with a topic though... If I had to chose one, I would probably make a LaTeX blog. Certainly I don't have the background in TeX to be a TeXpert, but I do pretty well among my peers with my LaTeX.

Well, I'm not ready for that yet. However, I just found a LaTeX bulletin board that I think might be more useful than comp.text.tex (a USENET newsgroup) for the young LaTeX user.

http://www.latex-community.org/

I don't know how long that's been around. Give it a look if you need some LaTeX help. Search through the archives for some useful tips and solutions.