\comment This is the source for the Asymptote FAQ list, in
\comment the Bizarre Format With No Name.  It is turned into Lout
\comment input, HTML, plain ASCII and an Info document by a Perl script.
\comment
\comment The format and scripts come from the Linux FAQ, by
\comment Ian Jackson.
\set brieftitle Asymptote FAQ
\set author     <A href="http://asymptote.sourceforge.net">Asymptote</A> 
\set title      Asymptote Frequently Asked Questions
\copyto ASCII
            ASYMPTOTE FREQUENTLY ASKED QUESTIONS
                            `date '+%d %h %Y'`
                           
\endcopy
\copyto INFO
INFO-DIR-SECTION Languages
START-INFO-DIR-ENTRY
* asymptote FAQ: (asy-faq).    Asymptote Frequently Asked Questions.
END-INFO-DIR-ENTRY


File: asy-faq.info, Node: Top, Next: Question 1.1, Up: (dir)

            ASYMPTOTE FREQUENTLY ASKED QUESTIONS
                            `date '+%d %h %Y'`
                          
\endcopy

This is the list of Frequently Asked Questions about Asymptote (asy).

\section  Index

\index

\comment ######################################################################

\section  About Asymptote

\question 26jun:whatisasy What is Asymptote?

Asymptote is a vector graphics language designed for
technical graphics, inspired by MetaPost but with IEEE floating-point numerics,
native three-dimensional graphics, Grayscale/RGB/CMYK colourspaces, and a
C++-like syntax. Unlike MetaPost, it natively supports multiple-segment paths
(and hence regions other than simply connected ones), tiling patterns, Gouraud
 shading, tensor patch shading, and PostScript images. 

\question 22jun:whereisasy How do I obtain Asymptote?

Binary releases are available for Linux, MacOS X, and Microsoft Windows
platforms, in addition to full source code, from the website
\docref{http://asymptote.sourceforge.net/\}.  Many Linux distributions
(such as RedHat and Debian) now include an Asymptote package (check your
distribution's documentation for further information about this).

\question 28jun:beforeasking Where can I ask questions about Asymptote? 

If you have a question, please try to find an answer in this FAQ, in the 
extensive Asymptote documentation at
\docref{http://asymptote.sourceforge.net/doc/\}, or search the forum:
\docref{http://sourceforge.net/forum/forum.php?forum_id=409349\}.

\question 02sep:whyasy Why was the name Asymptote chosen?

Well, it isn't the perfect graphics package, but we do think it is getting there
asymptotically...

\question 02sep:whycamp In the internal Asymptote source code, what does the name \courier{camp\} refer to?

That was our original tentative name for this project, which stood for 
"C's Answer to MetaPost" (the language that inspired Asymptote).
However, we eventually decided that the name \courier{Asymptote\} better
emphasizes the mathematical and graphical nature of this language.

\comment ######################################################################

\section  Questions about installation and setup

\question 26jun:osx Is it possible to install Asymptote on Mac OS X?

It is easy to compile Asymptote directly from the source code at
\docref{http://sourceforge.net/project/showfiles.php?group_id=120000\}
We recommend first upgrading to the latest GNU readline library, unless you
don't care about interactive readline support (in which case configure will
automatically detect and disable obsolete versions of the readline library).
Marius Schamschula also maintains a binary package for various MacOS X
platforms 
\docref{http://www.hmug.org/pub/MacOS_X/X/Applications/Publishing/asymptote\}.

\question 26jun:osxbadCPU Why do I get the error \courier{Bad CPU type in executable\} on installing Asymptote from the MAC OS binary?

This means either that you have a binary distribution for another MAC
architecture, or (according to Marius Schamschula) that you may have a missing
library. The simplest solution is to compile Asymptote directly from the
official source:
\docref{http://sourceforge.net/project/showfiles.php?group_id=120000\}.

\question 04nov:brokenpdftex What do I do if I get the error: \courier{Error: pdfetex (file pdftex.cfg): cannot open config file...texinfo.tex appears to be broken\}?

Simply put \docref{http://asymptote.sourceforge.net/asymptote.pdf\}
in the directory \courier{doc\} and repeat the command \courier{make all\}.
Or, if you don't want to build a local copy of the documentation, simply
proceed with \courier{make install-asy\}.

\question 04nov:brokentexinfo What do I do if I get the error: \courier{! Undefined control sequence. l.6 @copying\}?

Either upgrade your \courier{texinfo\} package or follow one of the easy work arounds in \qref brokenpdftex.

\question 27jun:latexintegration Is it possible to integrate Asymptote into LaTeX?

Yes, see the example latexusage.tex. Dario Teixeira has also written a detailed
guide on the topic. You can download it from
\docref{http://dario.dse.nl/projects/asylatex/\}.

Philippe Ivaldi has contributed an Asymptote mode for Emacs users
\docref{http://asymptote.sourceforge.net/doc/Editing-modes.html\},
which includes a \courier{lasy-mode\} that allows one to compile and view
the output of one \\begin{asy}...\\end{asy} section at a time.

\question 02sep:pdflatex Is it possible to integrate Asymptote into latex or pdflatex?

Yes, as of version 1.14, Asymptote supports latex and pdflatex (both in
EPS/PDF and inline mode), as illustrated by the example
\courier{latexusage.tex\}:

\verbatim
pdflatex latexusage
asy latexusage
pdflatex latexusage
\endverbatim

\question 02sep:tkinterdepend Do I need the \courier{tkinter\} package to install an Asymptote rpm binary?
 
No, you don't need \courier{tkinter\} unless you want to try out the GUI \courier{xasy\}. Try

\verbatim
rpm -Uvh --nodeps asymptote-x.xx-1.i386.rpm
\endverbatim

where \courier{x.xx\} represents the version number.

\question 26jun:windir What does the path \courier{%USERPROFILE%\\.asy\\config.asy\} mean?

That is the way that Microsoft Windows refers to the user profile directory. 
There's nothing really to understand here, just put your configuration
commands in the file \courier{config.asy\} in a new folder \courier{%USERPROFILE%\\.asy\}.

\question 25dec:escapechar Why do I get the error "string not terminated" when I try to set \courier{settings.dir="C:\\asymptote\\";\}?
 
The backslash is an escape character here, so
\courier{\\"\} is interpreted as a verbatim quotation mark, leaving the string
without a terminating quotation mark. Fortunately, this is the
only escaped character in double-quoted strings. A final backslash isn't
needed here anyway, but should you really want one somewhere, you can say:
\courier{settings.dir="C:\\asymptote"+'\\\\';\}.

\question 27jun:winglobal How do I change environment variables in Microsoft Windows, for example, in order to change the default PostScript viewer?

While it is easier to set the corresponding Asymptote configuration
variable in your \courier{config.asy\} file, here is the procedure for changing
Microsoft Windows environment variables:
 
Click on the [Start] button 

* RIGHT-click on 'My Computer' 

* Choose 'Properties' from the popup menu 

* Click the 'Advanced' tab 

* Click the 'Environment Variables' button. 

\question 02sep:convert Under Microsoft Windows XP, why do I get an error like "Invalid Parameter - 432x432"?

This means that ImageMagick wasn't properly installed and you are using the
MSDOS convert program rather than the ImageMagick one. Or you may have
installed ImageMagick but ran Asymptote from an existing MSDOS window.
In that case, simply open a new window and try again. If that doesn't work,
check that 
 
\verbatim
convert --version 
\endverbatim
 
returns something like
 
\verbatim
Version: ImageMagick 6.2.8 06/27/06 Q16 http://www.imagemagick.org
\endverbatim

\question 26jun:miktex Why does Asymptote freeze upon trying to draw a label with my MikTex installation under Microsoft Windows?

Likely, this means that latex and dvips are not in your default path.
Try adding the appropriate paths in your \courier{config.asy\} file, 
for example:

\verbatim
import settings;
latex="C:\Program Files\MiKTeX 2.7\miktex\bin\latex.exe";
dvips="C:\Program Files\MiKTeX 2.7\miktex\bin\dvips.exe";
\endverbatim

\comment #####################################################################

\section Questions about paths

\question 02sep:tensionsyntax Why do I get a syntax error message when I specify an integer value for the path tension?

What is happening here is that

\verbatim
draw((0,0)..tension 2..(0,50)..(100,100));
\endverbatim
 
is read as 

\verbatim
draw((0,0)..tension 2. .(0,50)..(100,100));
\endverbatim
 
So the first . after the two is treated as a decimal point.
Just put a space after the integer tension value:
 
\verbatim
draw((0,0)..tension 2 ..(0,50)..(100,100));
\endverbatim

\question 27jun:dots Shouldn't dots always be the same size?

From the documentation: 
 
"The dot command defined in the module plain draws a dot having a diameter 
equal to an explicit pen linewidth or the default linewidth magnified by 
dotfactor (6 by default)."
 
Thus, when you use the default pen, the dot will have size 6*linewidth,
but when you give a pen with an explicit width specified, you will 
have a dot of size linewidth. If you want the first case to behave like the
second, you may set dotfactor=1.

\comment #####################################################################

\section Questions about labels

\question 02sep:greek How do I get Greek letters like omega to show up in my labels?

In (La)TeX, Greek letters can be obtained in math mode by prepending a 
backslash to the letter name. So for a omega symbol, use "$\\omega$". Everything
between the dollar signs is considered to be a math formula. Uppercase Greek
letters can be used by capitalizing the first letter of the name:

\verbatim
label("$\omega$",(0,0));
label("$\Omega$",(20,0));
\endverbatim

\question 29jun:matlabels Can Asymptote use matrices as labels?

Yes: 
\verbatim
usepackage("amsmath");
label("$\begin{matrix} 1 & 2 \\\ 1 & 1 \end{matrix}$",(0,0));
\endverbatim

\question 27jun:latexpackage How do I tell Asymptote to load a particular LaTeX package, like \courier{mathptmx\}?

Put 
 
\verbatim
usepackage("mathptmx");
\endverbatim

at the beginning of your file. Note: to enable the Adobe Times Roman font
for text, you will also need to say:
\verbatim
defaultpen(TimesRoman());
\endverbatim


\question 28jun:internatfonts How can I use international fonts in Asymptote labels?

See \docref{http://asymptote.sourceforge.net/doc/unicode.html\}.

\question 10jul:Fourier How can I use Fourier fonts? 

\verbatim
usepackage("fourier");
defaultpen(font("T1","fut\textfamilyextension","m","n"));
\endverbatim

\question 26jun:decsep Is there any way to change the default appearance of the decimal separator, using a comma instead of a dot?

Just set your locale appropriately:
 
\verbatim
locale("it_IT");
usepackage("icomma");
label(format(0.5));
\endverbatim

\question 02sep:rotatelabel How can I get a rotated label with the filled box rotated as well so that it fits the text? 

\verbatim
frame f;
label(f,"This is some text",white,Fill(blue));
add(rotate(65)*f);
\endverbatim


\question 02sep:rotatelabel3D How can I rotate labels in a 3D figure?

You need to first project the triple to a pair like this: 
 
\verbatim
import three;
size(100,100);

draw(rotate(90,project(Z))*"A",O--X);
\endverbatim

\question 02sep:fixedsize How can I draw some squares and circles of a fixed size and put a label in the middle of them?

Fixed-size objects should be drawn on a separate picture and then added to 
currentpicture. Here is one way (see also \docref{http://asymptote.sourceforge.net/gallery/subpictures.asy\} and \docref{http://asymptote.sourceforge.net/gallery/mosquito.asy\}): 

\verbatim
real u=2cm;
 
picture square;
draw(square,scale(u)*shift(-0.5,-0.5)*unitsquare);
 
picture circle;
draw(circle,scale(0.5u)*unitcircle);
 
void add(picture pic=currentpicture, Label L, picture object, pair z) { 
add(pic,object,z);
label(pic,L,z);
} 
 
add("square",square,(0,0));
add("circle",circle,(5cm,0));
\endverbatim

\question 27jun:colorssaturation The binary operator * can be used to scale the color of a pen by a real number. Does this scaling factor have to be less than 1?

The scaling factor can be greater than 1. But keep in mind that the rgb color 
components saturate at 1. 
 
Try  
\verbatim
write(cyan); write(0.8*cyan); write(1.5*cyan);
\endverbatim
and you will quickly see what is going on. 
 
To get a lighter cyan you can say white+cyan, 
which yields rgb(0.5,1,1). If you want something even lighter specify the 
rgb colors directly, 
for example, rgb(0.9,1,1). 
 
Alternatively, work in cmyk colour space, which is nicer in that it handles 
saturation separately from hue: 
 
0.1*Cyan is light and 0.9*Cyan is dark. 
You can also say 0.1*cmyk(red).

\question 05mar:commadecimalseparator Why is the space after the comma decimal separator in my locale so large?

LaTeX is treating the comma as punctuation and not as a decimal separator.
The solution is to load the \courier{icomma\} package near the beginning of your file:
\verbatim
usepackage("icomma");
\endverbatim

\question 11mar:hyperref How can I prevent \courier{texpreamble("\\usepackage[pdftex]{hyperref}")\} from changing the page size?

\verbatim
texpreamble("\usepackage[pdftex,setpagesize=false]{hyperref}");
\endverbatim

\comment #####################################################################

\section Questions about arrows

\question 02sep:doublearrows How do I draw two arrows at arbitrary positions along a path?

Assuming that at least one of the arrowheads is to be filled, you can do this:

\verbatim
size(200); 
path g = (0,0)..(1,3)..(3,0); 
draw(g,Arrow(Relative(0.9))); 
add(arrow(g,invisible,FillDraw(black),Relative(0.5))); 
add(arrow(reverse(g),invisible,FillDraw(white,black),Relative(0.9))); 
\endverbatim

If both of the arrowheads are to be drawn with filltype NoFill,
one will need to create a specialized version of the arrow routine in 
\courier{plain_arrows.asy\}:

\verbatim
void arrow(frame f, arrowhead arrowhead=DefaultHead,
           path g, pen p=currentpen, real size=0,
           real angle=arrowangle, filltype filltype=arrowhead.defaultfilltype,
           position position=EndPoint, bool forwards=true,
           margin margin=NoMargin, bool center=false);
\endverbatim

\question 02sep:reversearrow How do I reverse the direction of an arrowhead?

Simply reverse the direction of the path.

\verbatim
path g=((0,0)--(5cm,0));
draw(reverse(g),Arrow(Relative(0.55)));
\endverbatim

\question 02sep:reversearrow How do I change the size of all arrows?

To override the arrowsize you can give every Arrow drawing attribute a real
size argument. If you want to do this globally, you can override the
pen-dependent arrowsize function like this:
 
\verbatim
arrowsize=new real(pen p=currentpen) {return 2mm;};
\endverbatim
 
\question 26jun:arrowhead Can I create other arrowhead styles?

Yes, you can build custom arrowheads like this (see the predefined
arrowhead styles in \courier{plain_arrows.asy\} for further examples): 
 
\verbatim
arrowhead DotHead;
DotHead.head=new path(path g, position position=EndPoint, pen p=currentpen,
                      real size=0, real angle=arrowangle) {
  if(size == 0) size=DotHead.size(p);
  bool relative=position.relative;
  real position=position.position.x;
  if(relative) position=reltime(g,position);
  path r=subpath(g,position,0);
  pair x=point(r,0);
  real t=arctime(r,size);
  pair y=point(r,t);
  return circle(0.5(x+y),0.5size);
};

size(100);
draw((0,0)..(1,1)..(2,0),Arrow(DotHead));
dot((2,0),red);
\endverbatim

If you submit your alternate arrowheads to the Forum or the Patch 
Tracking System, we'll consider including them in a future release.

\comment #####################################################################

\section  Questions about 2D graphs

\question 02sep:axisticks How can I draw x axis ticks on the right side, with the tick labels on the left side (relative to the axis path)?
 
\verbatim
import graph;

size(250,200,IgnoreAspect);

draw(graph(exp,-1,1),red);

xaxis("$x$",RightTicks(Label(align=left)));
yaxis("$y$",RightTicks);
\endverbatim

\question 02sep:axislabel How can I reposition the x axis label to three-quarters along the axis length?
 
\verbatim
import graph;

size(250,200,IgnoreAspect);

draw(graph(exp,-1,1),red);

xaxis(Label("$x$",0.75),LeftTicks);
yaxis("$y$",RightTicks);
\endverbatim

\question 02sep:axislabeldown How can I move the x axis label down 10bp?
 
\verbatim
import graph;
size(250,200,IgnoreAspect);

draw(graph(exp,-1,1),red);

xaxis(shift(0,-10)*"$x$",LeftTicks);
yaxis("$y$",RightTicks);
\endverbatim

\question 02sep:threeaxispens Can I use different pens for the axis, the axis label, and the tick labels?

Yes:

\verbatim
import graph;
size(300,200,IgnoreAspect);

xlimits(-50,50);
ylimits(0,100);

xaxis(Label("$x$",MidPoint,red),Bottom,blue,LeftTicks(green));
yaxis("$y$",Left,RightTicks);
\endverbatim

\question 02sep:axislabelfont How can I change the font type of the axes label?
 
\verbatim
import graph;
size(300,200,IgnoreAspect);

xlimits(-50,50);
ylimits(0,100);

xaxis("x",Bottom,Courier("m","n"),LeftTicks);
yaxis("$y$",Left,RightTicks);
\endverbatim

\question 02sep:axisticklabelfont How can I change the font type of the tick labels on an axis?
 
Tick labels are by default typeset in (TeX) math mode, so to use other
fonts you need to override the default tick format:
 
\verbatim
import graph;
size(300,200,IgnoreAspect);

xlimits(-50,50);
ylimits(0,100);

xaxis("$x$",Bottom,LeftTicks("%.4g",Courier("m","n")+fontsize(12)));
yaxis("$y$",Left,RightTicks);
\endverbatim

\question 26jun:overlappingticklabels How can I prevent axes tick labels from rendering on top of each other?

Either:

(i) give LeftTicks/RightTicks/Ticks the arguments beginlabel=false
and/or endlabel=false;

(ii) explicitly remove specific ticks and their labels (drawing them manually;
see \docref{http://asymptote.svn.sourceforge.net/viewvc/asymptote/trunk/asymptote/base/graph.asy\} for the definition of NoZero):

\verbatim
import graph;

size(10cm);

real f(real x) {return x^2;}
 
draw(graph(f,-2,2));

xaxis(Ticks(NoZero));
yaxis(Ticks(NoZero));

label("$0$",(0,0),SW);
\endverbatim

(iii) explicitly remove specific tick labels and draw them manually
(see \docref{http://asymptote.svn.sourceforge.net/viewvc/asymptote/trunk/asymptote/base/graph.asy\} for the definition of NoZeroFormat):

\verbatim
import graph;

size(10cm);

real f(real x) {return x^2;}
 
draw(graph(f,-2,2));

xaxis(Ticks(NoZeroFormat));
yaxis(Ticks(NoZeroFormat));

label("$0$",(0,0),SW);
\endverbatim

(iv) use the xasy GUI to move overlapping labels;

(v) change the Label argument of LeftTicks, RightTicks, or Ticks to:

\verbatim
Label(currentpen+overwrite(Move))
\endverbatim

Solution (v) will move labels that might otherwise overwrite a previous
label. Other possible overwrite arguments are Allow (allows overlapping
labels; the default), Suppress (an overlapping label will not be written at
all), SuppressQuiet, and MoveQuiet. The last two achieve the same result as
the non-quiet types, but will not notify you which labels are overlapping. See: 
\docref{http://asymptote.sourceforge.net/doc/Pens.html\}.
 
In the case of a user-specified tick array, you can change which labels get
suppressed/moved by changing the order of array entries.

\question 04nov:fixedsizegraphs How do I make the plot region of a graph, ignoring labels and legends, have a fixed size?
 
Either:

i) Specify an explicit unitsize, which overrides any call to \courier{size\}:
\verbatim
unitsize(x=1cm,y=2cm);
\endverbatim
 
ii) Explicitly tell Asymptote to map the plot region to a specific size:
\verbatim
import graph;
real[] x={0,1,2,3};
real[] y=x^2;
draw(graph(x,y),red);
xaxis("$x$",BottomTop,LeftTicks);
yaxis("$y$",LeftRight,RightTicks);

size(5cm,5cm,point(SW),point(NE));

label("$f_\mathrm{T}$",point(N),2N);
\endverbatim

iii) Specify the points in user coordinates that should correspond to a
given picture size:
 
\verbatim
import graph;

size(250,200,IgnoreAspect);

draw(graph(exp,-1,1),red);

xaxis("$x$",BottomTop,LeftTicks);
yaxis("$y$",LeftRight,RightTicks);

fixedscaling((-1.5,-0.5),(1.5,3.5));
\endverbatim
 
In this example, the user coordinate \courier{(-1.5,-0.5)\} will end up
being the lower left corner of the figure and \courier{(1.5,3.5)\} will be
the upper right corner. You can use this option to ensure multiple figures
have the same scaling and same resulting figure size (just ensure the two
coordinates given to \courier{fixedscaling()\} leaves room for any labels).
 
See also
\docref{http://asymptote.sourceforge.net/doc/Frames-and-pictures.html\}.
 
\question 26jun:graphlimits How can I plot a function f(x) within [0,1]x[0,2] without explicitly calculating the x values for which f(x) hits the boundary?

Call \courier{limits\} with the \courier{Crop\} option before drawing the graph:
\verbatim
import graph;

size(250,200,IgnoreAspect);

draw(graph(exp,-1,1),red);

limits((0,0),(1,2),Crop);

xaxis("$x$",BottomTop,LeftTicks);
yaxis("$y$",LeftRight,RightTicks);
\endverbatim
 
See also \docref{http://asymptote.sourceforge.net/doc/graph.html\}.
 
\question 26jun:custompalettes Is it possible to define customized palettes?

Yes, you may generate your own pen[] array. For example: 

\verbatim
int NColors=32768;
pen[] MyPalette=new pen[NColors];
real step=1/(NColors-1.0);
// Start at black: rgb(0,0,0) 
// End at yellow: rgb(1,1,0) 
for(int i=0; i < NColors; ++i) { 
  real rgval=i*step;
  MyPalette[i]=rgb(rgval,rgval,0.0);
} 
\endverbatim

\question 26jun:factorial Is there an easy way to graph factorial functions nicely?

The example below shows a continuous function and two methods for placing 
markers at integer values of x: 
 
\verbatim
import graph;
 
size(200,200,IgnoreAspect);
 
real factorial(real t) {return gamma(t+1);} 
 
scale(Linear,Log);
 
// Graph the factorial function.
draw(graph(factorial,0,10));
 
// Method 1: Draw nodes, but hide line
pair F(int t) {return (t,factorial(t));} 
// Graph of factorial function from 0 to 10
pair[] z=sequence(F,11);
draw(graph(z),invisible,marker(scale(0.8mm)*unitcircle,blue,Fill));
 
// Method 2: Nongraphing routines require explicit scaling:
pair dotloc(int t) {return Scale(F(t));} 
pair[] dotlocs=sequence(dotloc,11);
dot(dotlocs);
 
xaxis("$x$",BottomTop,LeftTicks);
yaxis("$y$",LeftRight,RightTicks);
\endverbatim

\question 26jun:length How do I indicate that a certain length should be exactly the size I prescribe with no rescaling, within a picture which has its own size?

Here's an easy way to do this.
 
\verbatim
size(12cm,0);
 
void distance(picture pic=currentpicture, pair A, pair B, Label L="", real n=0,
              pen p=currentpen) 
{
  real d=3mm;
  path g=A--B;
  transform T=shift(-n*d*unit(B-A)*I);
  pic.add(new void(frame f, transform t) {
    picture opic;
    path G=T*t*g;
    draw(opic,Label(L,Center,UnFill(1)),G,p,Arrows(NoFill),Bars,PenMargins);
    add(f,opic.fit());
  });
  pic.addBox(min(g),max(g),T*min(p),T*max(p));
} 
 
pair A=(0,0), B=(3,3);
 
dot(A);
dot(B);
 
distance(A,B,"$\ell$",1);
\endverbatim

\question 26jun:log2 How can I make the y axis display base-2 logarithmic values?

See the example \docref{http://asymptote.sourceforge.net/gallery/2D graphs/log2graph.asy\}. 

\question 27jun:align How can I align the x axes of two graphs on the same figure?

An easy way to do this, if the axes to be aligned have the same scaling
and size, is illustrated in the example \docref{http://asymptote.sourceforge.net/gallery/2D graphs/alignedaxis.asy\}.

Here is a more general solution to the problem of aligning two arbitrary axes.
One fits the second picture to a frame based on the horizontal scaling for
the first picture:

\verbatim
import graph;

real width=15cm;
real aspect=0.3;

picture pic1,pic2;

size(pic1,width,aspect*width,IgnoreAspect);
size(pic2,width,aspect*width,IgnoreAspect);

scale(pic1,false);
scale(pic2,false);

real xmin1=6;
real xmax1=9;
real xmin2=8;
real xmax2=16;

real a1=1;
real a2=0.001;

real f1(real x) {return a1*sin(x/2*pi);}
real f2(real x) {return a2*sin(x/4*pi);}

draw(pic1,graph(pic1,f1,xmin1,xmax1));
draw(pic2,graph(pic2,f2,xmin2,xmax2));

xaxis(pic1,Bottom,LeftTicks());
yaxis(pic1,"$f_1(x)$",Left,RightTicks);

xaxis(pic2,"$x$",Bottom,LeftTicks(Step=4));
yaxis(pic2,"$f_2(x)$",Left,RightTicks);

yequals(pic1,0,Dotted);
yequals(pic2,0,Dotted);

pair min1=point(pic1,SW);
pair max1=point(pic1,NE);

pair min2=point(pic2,SW);
pair max2=point(pic2,NE);

real scale=(max1.x-min1.x)/(max2.x-min2.x);
real shift=min1.x/scale-min2.x;

transform t1=pic1.calculateTransform();
transform t2=pic2.calculateTransform();
transform T=xscale(scale*t1.xx)*yscale(t2.yy);

add(pic1.fit());
real height=truepoint(N,user=false).y-truepoint(S,user=false).y;
add(shift(0,-height)*(shift(shift)*pic2).fit(T));
\endverbatim

\question 27jun:changeaxis How can I change the direction of the y-axis, such that negatives values are on the upper y-axis?

Here is a simple example (see also the example \docref{http://asymptote.sourceforge.net/gallery/2D graphs/diatom.asy\} or the discussion
of Linear(-1) in the documentation):
 
\verbatim
import graph;
size(250,200,IgnoreAspect);

scale(Linear,Linear(-1));

draw(graph(log,0.1,10),red);

xaxis("$x$",LeftTicks);
yaxis("$y$",RightTicks);
\endverbatim

\question 27jun:functioncolor How can I fill a path with a function that defines the color of each location?

Use \courier{functionshade\} with a PDF tex engine, as illustrated
by the example {functionshading.asy}.
 
If you want to produce PostScript output, an approximate solution for now
would be to superimpose a fine grid and specify colors to 
\courier{latticeshade\} that depend on position as a single pen[][]
lattice. Alternatively, it may be more efficient to use \courier{tensorshade}.

\question 27jun:nonexplicitfun Is there a way to draw a function that is not explicitly given, such as (y - 2)^2 = x - 1 ?

Yes, use the parametric form 

\verbatim
y=t 
x=(t-2)^2+1 
\endverbatim

See the example \docref{http://asymptote.sourceforge.net/gallery/2D graphs/parametricgraph.asy\}. 

\question 27jun:scalesecondaryaxis  Is it possible to reverse or stretch an axis?

The real scaling argument to Linear is used to stretch (or reverse) the axis. 
To see the effect of axis stretching, be sure not to specify IgnoreAspect in 
the picture size command.
 
A secondary axis has the same length as the primary axis, so stretching cannot 
have any effect. But one can still reverse the axis, with Linear(-1).

\question 02sep:emptymarkers Why can't I use the UnFill option to draw graphs with empty markers?

UnFill won't work here because it only affects the local frame the markers
are initially drawn on, before being added to currentpicture. 
Here is a way of achieving the desired effect (assuming a white background):
 
\verbatim
import graph;
size(10cm,0);
pair[] z={(0,0),(0.5,0.5),(1,1)};
path g=graph(z);
 
draw(shift(0,.5)*g,marker(scale(5)*unitcircle,FillDraw(white)));
 
xaxis(BottomTop,LeftTicks);
yaxis(LeftRight,RightTicks);
\endverbatim

\question 02sep:paletterange How can I force several images to use the same palette range (e.g. the entire 0-255 grayscale range)?

The palette color space corresponds to a range of values specified by the
argument range, which can be \courier{Full\}, \courier{Automatic\} or an
explicit range \courier{Range(pair min, pair max)\}. Here \courier{Full}
specifies a range varying from the minimum to maximum values of the
function over the sampling interval, while \courier{Automatic\} selects
"nice" limits.

\comment #####################################################################

\section Questions about programming

\question 27jun:comporint Is Asymptote an interpreter or a compiler?  

Asymptote compiles Asymptote commands into its own virtual machine code. It 
then runs this pseudocode on a virtual machine to produce PostScript code. 

\question 05sep:framepicture What is the difference between a frame and a picture? 

Frames are canvases for drawing in PostScript coordinates. While working
with frames directly is occasionally necessary for constructing deferred
drawing routines, pictures are usually more convenient to work with.
See \qref unitsizes.

\question 05sep:pathguide What is the difference between a path and a guide? 

A path is a cubic spline with fixed endpoint conditions.

A guide is an unresolved cubic spline (list of cubic-spline nodes and
control points). A guide is like a path except that the computation of the cubic
spline is deferred until drawing time (when it is resolved into a path);
this allows two guides with free endpoint conditions to be joined together
smoothly.

\question 27jun:picarray What is a convenient way to declare and initialize an array of pictures?

You could write yourself a routine such as:
\verbatim
picture[] picture(int n) { 
  picture[] pic;
  for(int i=0; i < n; ++i) { 
    pic[i]=new picture;
    size(pic[i],19cm,0);
  } 
  return pic;
} 
 
picture[] pic=picture(6);
\endverbatim

\question 27jun:genarrays Is there a way to define functions that act on arrays in general (i.e. work for arrays of any type)?

Generic types aren't yet implemented. 
 
But for now you can at least say 
\verbatim
typedef string T;
include F;
 
typedef real T;
include F;
\endverbatim

where \courier{F.asy\} contains some type-dependent code like
\verbatim
T[] operator $(T A, T B) {return new T[] {A,B};}
\endverbatim

\question 27jun:cirdep Is there any way to declare structures ahead of their definition, e.g. where struct A performs some operation on struct B, but B contains an A member?

Asymptote does not support forward declaration of types. You can, however, 
nest structures, so that both types are visible for parts of the bodies of 
both structure definitions. For example: 
 
\verbatim
struct B { 
  typedef void someroutine(B b);
 
  static struct A { 
    someroutine routine;
    void operator init(someroutine routine) { 
      this.routine=routine;
    } 
  } 
 
  string test="Testing";
} 
 
typedef B.A A;
 
A a=B.A(new void(B b){write(b.test);});
 
B b;
a.routine(b);
\endverbatim

\question 04nov:static Where are static variables in for loops allocated?

In the example 

\verbatim
void f() { 
  for(int i=0; i < 3; ++i) { 
    static int n;
    ++n;
    write(n);
  }
} 

f(); // Writes 1, 2, 3
\endverbatim

the static qualifier means that \courier{n\} is allocated not just outside
of the for loop, but also outside the function. This is clear if you call 
\courier{f\} multiple times; there is still only one instance of \courier{n\}.
 
The "level" of a variable (where it is allocated) has nothing to do with
the "scope" of a variable (how long it can be referred to by name).
The curly braces enclosing a block affect only a variable's scope, not
its level.
 
Static modifiers are meaningless at the top level; they generate a warning
and are simply ignored:

\verbatim
for(int i=0; i < 3; ++i) { 
  static int n;
  ++n;
  write(n);
}
// Writes warning about top-level static modifier and then 1, 1, 1
\endverbatim

Since version 1.22, non-static variables allocated in a loop body are allocated
anew every iteration.  This is only noticable in obscure cases where a variable
in a loop is accessed in the closure of a function defined in the loop:
 
\verbatim
int f();
 
for(int i=0; i < 10; ++i) { 
  int j=10*i;
  if(i == 5)
    f=new int() {return j;};
} 
 
write(f()); // Writes 50
\endverbatim
 
Variables in the body of a loop last as long as that iteration of the loop,
unless they are kept alive by a function closure as in the example above.  In a
function body, variables will last at least as long as the function call, though
because of closures and garbage collection, they may last longer than that.  If
defined at the top level of a file or at the interactive prompt, they will last
at least until the end of the file or prompt's run.

\question 26jun:debug Is there a debugger for asy?

Yes, Asymptote includes a line-based debugger:

\docref{http://asymptote.sourceforge.net/doc/Debugger.html\}

\question 27jun:patches Do you accept patches for Asymptote?

Yes, in fact we would prefer that users submit patches for customized features
(to \docref{http://sourceforge.net/tracker/?atid=685685&group_id=120000\})
instead of relying on us to do all of the coding. Development will proceed 
faster that way. 
 
\comment #####################################################################

\section Questions about differences between Asymptote and MetaPost

\question 29jun:interp What is the equivalent of the MetaPost c[a,b] interpolation operator? 

\verbatim
interp(a,b,c);
\endverbatim

\question 02sep:automaticscaling How does picture scaling differ in Asymptote and MetaPost?
 
Asymptote includes an optional facility to do automatic scaling of pictures
to achieve a given overall picture size, whereas Metapost only supports manual
scaling. Asymptote defers drawing of objects drawn to pictures and
distinguishes between true-size objects and objects that should scale with
the picture size. The resulting linear programming problem is solved via
the Simplex method. 

See the \docref{http://asymptote.sourceforge.net/gallery/dimension.asy\} example for an example of how deferred drawing is
used to accomodate both user and true-size (PostScript) coordinates.
 
\question 02sep:manualscaling How can I avoid automatic scaling of a picture?
 
If you really like Metapost-style manual (hard-wired) scaling either: 
 
(i) use the default size(0,0) for the entire picture and do all of the 
scaling by hand, just like in MetaPost;
 
(ii) draw to a separate picture pic and add(pic.fit());
 
(iii) use frames. 
 
\question 23jun:mp3dots What is the equivalent of MetaPost ... command?

The connector \courier{::\} is a macro for tension atleast 1:

\verbatim
size(100);
pair z0=(0,0);
pair z1=(1,0.25);
pair z2=(2,0);
draw(z0{up}::z1{right}::z2{down});
\endverbatim

\question 23jun:mppickup What is the equivalent of the MetaPost pickup command?

Just say, for example:

\verbatim
currentpen=red;
\endverbatim

\question 29aug:whatever What is the equivalent of the MetaPost whatever command?

Asymptote does not implicitly solve linear equations and therefore does not
have the notion of a \courier{whatever\} unknown. Such a facility could
certainly be added (perhaps using the notation \courier{?=\} since
\courier{=\} means assignment).
However, the most common uses of \courier{whatever\} in MetaPost are covered by
functions like \courier{extension\} in \courier{math.asy\}: 
\verbatim
pair extension(pair P, pair Q, pair p, pair q);
\endverbatim
this returns the intersection point of the extensions of the line segments 
\courier{PQ\} and \courier{pq\}. We find using routines like
\courier{extension\} more explicit and less confusing to new users. But we
could be persuaded to add something similar if someone can justify the
need. In the meantime, one can always use the explicit built-in linear
solver \courier{solve\} (see
\docref{http://asymptote.sourceforge.net/doc/solve.html\}), which uses LU
decomposition. 

\question 23jun:lray What is the equivalent for the MetaPost command for \courier{lray - horiz*v - verti*u = whatever*(LightSource - R)\}, a system of three linear equations for three unknowns: \courier{horiz, verti, whatever\}?

Since \courier{horiz*v+verti*u\} spans a plane, you could use
\verbatim
real intersect(vector P, vector Q, vector n, vector Z);
\endverbatim

to find the intersection time for the line 
\courier{lray-whatever*(LightSource - R)\}
and then extract the three desired values from there. (You'll still need to
use the built-in explicit linear solver to solve a 2x2 system to get 
\courier{horiz\} and \courier{verti\}.)

\question 27jun:unitsizes In MetaPost, it is possible to have a drawing remain the same size in different pictures by defining a unit \courier{u\} and explicitly multiply all the coordinates by \courier{u\}. Is there a better way to do this in Asymptote?

Yes, Asymptote has a better way: you definitely don't want to manually scale 
all of your coordinates. To make the user coordinates represent multiples
of exactly \courier{1cm\}:

\verbatim
unitsize(1cm);
draw(unitsquare);
\endverbatim

One can also specify different x and y unit sizes:

\verbatim
unitsize(x=1cm,y=2cm);
draw(unitsquare);
\endverbatim

Another way is to draw your fixed size object to a frame and add it to
currentpicture like this:
 
\verbatim
path p=(0,0)--(1,0);
frame object;
draw(object,scale(100)*p);
 
add(object);
add(object,(0,-10));
\endverbatim

To understand the difference between frames and pictures, try this: 
 
\verbatim
size(300,300);
 
path p=(0,0)--(1,0);
picture object;
draw(object,scale(100)*p);
 
add(object);
add(object,(0,-10)); // Adds truesize object to currentpicture 
\endverbatim

\question 28jun:tiles In MetaPost, one could produce tiling pictures by generating a picture, and then clipping the picture to a rectangle of fixed dimensions around the center of the picture. How is that done in Asymptote?

If you are using currentpicture the way one would in MetaPost (drawing in 
raw PostScript coordinates), you can simply do something like: 
 
\verbatim
fill((0,0)--(100,100)--(200,0)--cycle);
 
pair center(picture pic=currentpicture) {return 0.5*(pic.min()+pic.max());} 
 
real height=100;
real width=100;
pair delta=0.5(width,height);
pair c=center();
clip(box(c-delta,c+delta));
\endverbatim

However, drawing in PostScript coordinates is often inconvenient. Here's the 
Asymptote way of doing the same thing, using deferred drawing: 
 
\verbatim
size(200,100);
fill((0,0)--(1,1)--(2,0)--cycle);
 
void clip(picture pic=currentpicture, real width, real height) 
{
  pic.clip(new void (frame f, transform) { 
    pair center=0.5(min(f)+max(f));
    pair delta=0.5(width,height);
    clip(f,box(center-delta,center+delta));
  });
} 
 
clip(100,100);
\endverbatim

See also the discussion of tilings in the documentation: 
\docref{http://asymptote.sourceforge.net/doc/Pens.html\}.

\comment ######################################################################

\section  Questions about output

\question 27jun:psviewer How can I disable automatic invocation of the PS viewer after an asy file is done processing?

It's actually not on by default, unless you happen to be using Microsoft
Windows (because that is what most Microsoft Windows users
expect). Microsoft Windows users can turn this feature off with the
command-line option -noV or by putting  
 
\verbatim
import settings;
interactiveView=false;
batchView=false;
\endverbatim

in their \courier{config.asy\} file. See
\docref{http://asymptote.sourceforge.net/doc/Options.html\}.

\question 26jun:jpeg How do I output jpeg images?

If you have the ImageMagick convert program installed, simply type

\verbatim
asy -f jpg test.asy 
\endverbatim

\question 27jun:embedbitmaps Can I embed bitmaps (photos) into my drawings and position and scale them? 

Convert them to eps format and use the graphic(string) function just like a
Label:

\verbatim
label(graphic("file"),(0,0));
\endverbatim

See the example \docref{http://asymptote.sourceforge.net/gallery/orthocenter.asy\} and
\docref{http://asymptote.sourceforge.net/doc/label.html\}.

\question 28jun:directpdf Does Asymptote support direct PDF output?

Yes, PDF output can be produced by the -f pdf option or -tex pdflatex option.
This supports transparency, annotations, embedded movies, and U3D/PRC content.

\question 28jun:bigpictures How to I produce large pictures of high quality in raster format (e.g. png, giff etc). 

Try using some of the options to convert, mainly -geometry and -density. For example: 
\verbatim
convert -geometry 1000x3000 example.eps example.png 
\endverbatim
 
You can also change the default resolution of the image with: 
\verbatim
convert -geometry 1000x3000 -density 300 -units PixelsPerInch example.eps example.png 
\endverbatim
This does not change the number of pixels in the image, but just gives a hint 
as to how large each pixel should be displayed.
 
If you include the -density option without the -geometry option, convert will 
keep the image size constant (so a 4cm x 3cm eps figure will generate a 4cm x
3cm png 
image). 

\question 28jun:multipage Is it possible to produce multi-page documents with asymptote? 

Yes, simply call the newpage() function. This is used by the
\courier{slide.asy\} package to produce high-quality slide presentations
(easier to use than Prosper).

\comment Here it ends!
