<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="/pattern.xsl"?>
<pattern id="">
  <name>
    Recursion
  </name>
  <relatedPatterns>
    <relatedPattern ref="">
      <patternLink>
      </patternLink>
    </relatedPattern>
  </relatedPatterns>
  <diagram>
    <web>
	<img src="DiagramRecuSm.jpg" width="400"  />	
	</web>
	<latex>
    <img src="DiagramRecu.png" width="400"  />		
	</latex>
  </diagram>
  <what>
    <paragraph>
      Create a pattern by recursively replicating a motif.
      <latex>\label{sec:pattern:Recursion}</latex>
    </paragraph>		
  </what>
  <when>
    <paragraph>
     <latex>\index{algorithm!recursion|(}</latex>
      <latex>\index{function!recursive|(}</latex>
     Hierarchy as design strategy conflates wholes and parts. The
     parts are transformed versions of the whole. This naturally leads
     to a hierarchcial information structure of layers, where the properties of a
     layer are based on those of the layer immediately superior to
     it. Recursive algorithms are natural traversers of such
     hierarchical structures. Use this pattern when you are working
     with hierarchy in design.
    </paragraph>
  </when>
  <why>
    <paragraph>
      Some complex models such as spirals<latex>\index{spiras}</latex>, branching structures or
      space-filling curves can be elegantly represented with a
      recursive function. In fact, it is often so difficult to
      represent such structures non-recursively that designers give up
      and try something easier. A recursive function typically takes a
      motif and a replication rule and calls itself on the copies of
      the motif that the rule generates. A word of warning
      though---recursive algorithms are often hard to understand in
      the abstract. We humans are not good at extrapolating a pattern
      from a motif and a replication rule
      <latex>\ref{Carlson94}</latex>. Another word of
      warning. Recursive algorithms as update methods can be
      slow. Typically, limiting the depth of the recursion is the only
      way to maintain an adequate interactive update rate.
    </paragraph>
  </why>
  <how>
    <paragraph>
      <patternName>Recursion</patternName> requires a motif (a
      geometric object) and a replication rule. The simplest
      rule is simply a coordinate system<latex>\index{frame}</latex> with some
      combination of translation, rotation, scale and shear. Other
      more complex rules are possible, including ones that change
      or abstract the motif itself.
    </paragraph>
    <paragraph>
      The body of a the recursive function uses the replication rule
      to generate a collection of clones of the motif. It then calls
      itself on each clone, typically (but not necessarily) using the
      same replication rule.  So, in each step, the recursive function
      takes an existing motif, replicates it and calls itself. Every
      recursive function requires a termination condition to specify
      when to stop this process.
    </paragraph>
  </how>
  <samples newpage="false">		
    <sample id="Square">
      <name>Square</name>
      <when>
	<paragraph>
	  Nest a sequence of squares inside an initial square.
	</paragraph>
      </when>
      <how>
	<paragraph>
	  Start with a square (actually, any polygon<latex>\index{polygon}</latex> will do). This is
	  the initial motif --- the input to the recursion.
	</paragraph>
	<paragraph>
	  The recursive function must transform the motif as a copy
	  and call itself on the copy. In this sample, the
	  transformation is specified as a parameter <math
	  latex="t">t</math>. The new motif's vertices are parametric
	  points on the original motifs edges with parameter <math
	  latex="t">t</math>.
	</paragraph>
	<paragraph>
	  In a computer recursions must stop (though this is not true
	  in mathematics!). They either stop by design or by overflow
	  of some data structure, typically the recursion stack, in
	  the programming language. In this sample, <em>depth</em> is the control and therefore is
	  an argument to the recursive function. Each subsequent call
	  to the function reduces the depth argument by one. Inside
	  the function, a test for depth returns the motif unchanged
	  if <em>depth</em> is equal to one, else
	  proceeds with the recursion.
	</paragraph>
	<paragraph>
	  Assigning each of the squares an elevation results in a
	  <math latex="3D">3D</math> "stack" of polygons.  Using this
	  stack as the arguments for a surface gives a twisted
	  vertical pyramid.
	</paragraph>
	<paragraph>
	  This sample defines one copy of the motif at each recursive
	  call. The result is a linear list of motifs --- the
	  structure of the list mirrors the geometric structure of the
	  result. Defining more than one motif within the function
	  results in a <em>tree</em>.
	</paragraph>
      <latex>\setlength{\storedWidth}{\currentWidth}
             \setlength{\currentWidth}{\currentWidth*\real{0.5}}
             \hfill</latex>
	<diagram>
	  <img src="Samples/RecuSquare/RecursionSquareDiagram.pdf" width="400"  />
	</diagram>
      <latex>\hfill
             \setlength{\currentWidth}{\storedWidth}</latex>
      </how>
      <a href="Samples/RecuSquare/RecuSquare.gct" >Click to download RecuSquare.gct</a> 				
      <animation src="Samples/RecuSquare/AnimationSquare.swf"/>	
      <a href="Samples/RecuSquare/RecuSquare3D.gct" >Click to download RecuSquare3D.gct</a>
      <animation src="Samples/RecuSquare/AnimationSquare3D.swf"/>		
    </sample>		
    

    <sample id="Tree">
      <name>Tree</name>
      <when>
	<paragraph>
	  Define a tree --- both graphically and as a data structure.
	</paragraph>
      </when>
      <how>
	<paragraph>
	  In this sample, the motif is a single line<latex>\index{line}</latex>. The focus here
	  is more on the geometric layout and data structure and less
	  on the resulting pattern.
	</paragraph>
	<paragraph>
	  The motif transformation places two copies of the motif,
	  each starting at the end point of the original motif. The
	  copies are rotated by the parameter <math
	  latex="rot">rot</math> and scaled by the parameter <math
	  latex="scale">scale</math>. 
	</paragraph>
	<paragraph>
	  As for any recursive function, you need to make sure that
	  the recursion will stop. As in the prior sample, the
	  stopping condition is set by the depth of the recursion. 
	</paragraph>
	<paragraph>
	  With the hindsight gained by seeing the recursion in
	  operation, we can gain a good idea of what this particular
	  function will produce under a variety of settings of the
	  parameters <math latex="rot">rot</math> and <math
	  latex="scale">scale</math>. With compound motifs and more
	  complex transformations, such intuitions completely
	  dissolve <latex>\ref{Carlson94}</latex>
	</paragraph>
	<paragraph>
	  A tree is a data structure<latex>\index{data structure!tree}</latex> that has branches. Each branch is
	  either null or itself a tree.  The data structure produced
	  is sensitive to the details of the recursive
	  function. Usually, the preferred structure is one that
	  provides a <em>path</em> to each of the motifs that mirrors
	  the geometric structure. For example, a sensible path might
	  be one that starts with the root of the tree and that
	  records which branch of the tree is followed to reach the
	  motif. Thus, for a tree with depth <math latex="4">4</math>
	  (with the base motif at depth <math latex="0">0</math>), one
	  path to a node would be <math latex="tree \lbrack 1
	  \rbrack\lbrack 2 \rbrack\lbrack 2 \rbrack\lbrack 1
	  \rbrack">tree[1][2][2][1]</math>. Interpret this as taking
	  the right branch on a <math latex="1">1</math> and the left
	  branch on a <math latex="2">2</math>. The data structure is
	  thus a list where the <math latex="1^{st}">first</math> item
	  in the list is the right branch of the tree and the <math
	  latex="2^{nd}">secon</math> item in the list is the left
	  branch of the tree. The motif itself is must be stored
	  somewhere and is assigned to the <math
	  latex="0^{th}">zeroth</math> branch of the data
	  structure. So a path to a motif needs an index of <math
	  latex="0">0</math> at its end, for example, <math
	  latex="tree \lbrack 1 \rbrack\lbrack 2 \rbrack\lbrack 2
	  \rbrack\lbrack 1 \rbrack\lbrack 0
	  \rbrack">tree[1][2][2][1][0]</math>.
	</paragraph>
	<diagram>
	  <img src="Samples/RecuTree/RecursionTreeDiagram.pdf" width="400"  />
	</diagram>
      </how>
      <latex>\newpage</latex>
<pre>
treeFn function (CoordinateSystem cs, 
                 Line startLine, 
                 int depth, 
                 double rotation, double scale)
 {                                            
  Line resultLine = {};
  if (depth &lt; 1){
   resultLine[0] = null;
   resultLine[1] = null;
  }
  else{
   CoordinateSystem rightCS = new CoordinateSystem();                                            
   rightCS.ByOriginRotationAboutCoordinateSystem
           (startLine.EndPoint, 
	    cs, 
	    rotation, 
	    AxisOption.Y);
   CoordinateSystem leftCS = new CoordinateSystem();
   leftCS.ByOriginRotationAboutCoordinateSystem
          (startLine.EndPoint, 
	   cs, 
	   -rotation, 
	   AxisOption.Y);
   Line rightLine = new Line();
   rightLine.ByStartPointDirectionLength
             (rightCS, 
	      rightCS.ZDirection, 
	      startLine.Length*scale);
   Line leftLine = new Line();
   leftLine.ByStartPointDirectionLength
            (leftCS, 
	     leftCS.ZDirection, 
	     startLine.Length*scale);
   resultLine[0]=treeFn(rightCS, 
                        rightLine, 
			depth-1, 
			rotation, 
			scale); 
   resultLine[1]=treeFn(leftCS, 
                        leftLine, 
			depth-1, 
			rotation, 
			scale);
  }
  resultLine[2]=startLine;
  return resultLine;
 };
</pre>
      <more>
	<paragraph>
	  Note the calls to the <arg>treeFn</arg> function. The two
	  separate calls ensure that the right and left branches of
	  the tree are themselves trees.  The base case of the
	  recursion occurs when the depth is less than one and results
	  in a tree with null branches being returned. At the end of
	  the function, the motif is stored in  the <math
	  latex="2^{nd}">second</math> member of
	  <arg>resultLine</arg>, completing the data structure, which
	  now stored both the tree structure and all the motifs.
	</paragraph>
	<paragraph>
	  A word to the wise. Writing recursive functions so that they
	  return appropriate data structures is careful, error-prone
	  work. Doing it well is key to making effective use of the
	  results.
	</paragraph>
      </more>
      <a href="Samples/RecuTree/RecuTree.gct" >Click to download RecuTree.gct</a> 				
      <animation src="Samples/RecuTree/AnimationTree.swf"/>			
    </sample>
    
    <sample id="Circles">
      <name>Circles</name>
      <when>
	<paragraph>
	  Nest circles within a circle, alternating the direction of
	  nesting at each level.
	</paragraph>
      </when>
      <how>
	<paragraph>
	  The motif is a circle<latex>\index{circle}</latex>. It replicates twice inside itself,
	  with the two new circles of half the radius and tangent to
	  both themselves and the orginal circle. The line joining
	  their centres is initially horizontal.  At each level of the
	  recursion, the line needs to alternate between horizontal
	  and vertical.  This requires a check on the parity of
	  recursion depth within the function. As with the prior
	  samples, the recursion is depth-limited.
	</paragraph>
	<diagram>
	  <img src="Samples/RecuCircles/RecursionCirclesDiagram.pdf" width="400"  />
	</diagram>
      </how>
      <a href="Samples/RecuCircles/RecuCircles.gct" >Click to download RecuCircles.gct</a> 				
      <animation src="Samples/RecuCircles/AnimationCircles02.swf"/>				
    </sample>
    
    <sample id="GoldenRectangle">
      <name>Golden Rectangle</name>
      <when>
	<paragraph>
	  Subdivide a Golden Rectangle into a square and another
	  Golden Rectangle.
	</paragraph>
      </when>
      <how>
        <paragraph>
	  A Golden Rectangle is a rectangle<latex>\index{rectangle!Golden}</latex> whose side lengths are in
	  the golden ratio <math latex="1:\phi">1:φ</math>, that is, approximately 1:1.618. A distinctive
	  feature of this shape is that when a square section is
	  removed, the remainder is another golden rectangle, that is,
	  having the same proportions as the original.
	</paragraph>
	<paragraph>
	  <web><img src="Samples/RecuGoldenRectangle/RecuGoldenRectangle40.jpg" width="200"  /></web>
	</paragraph>
	<paragraph>
	  <web>
	    ("golden rectangle." Wikipedia. Wikipedia,
	    2007. http://en.wikipedia.org/wiki/Goldenrectangle)
	  </web>
	  <latex>
	    \begin{bodyNote}
	      \begin{drSc}{0.4}
                \drLiSeg{(1,1)}{(12.09,1)}{poly, modelLineara}
		\drLiSeg{(12.09,1)}{(12.09,12.09)}{poly, modelLineara}
		\drLiSeg{(12.09,12.09)}{(1,12.09)}{poly, modelLineara}
		\drLiSeg{(1,12.09)}{(1,1)}{poly, modelLineara}
		\drLiSeg{(18.944,1)}{(18.944,12.09)}{poly, modelLineara}
		\drLiSeg{(18.944,12.09)}{(12.09,12.09)}{poly, modelLineara}
		\drLiSeg{(12.09,12.09)}{(12.09,1)}{poly, modelLineara}
		\drLiSeg{(12.09,1)}{(18.944,1)}{poly, modelLineara}
		\drLiSeg{(6.545,12.09)}{(6.545,1)}{poly, emphLineara}
		\drLiSeg{(6.545,1)}{(12.09,12.09)}{poly,emphLineara,vector}
		\drDim{(1,1)}{(12.09,1)}{-15mm}{\begin{math}1\end{math}}{0.5}{8mm}
		\drDim{(1,1)}{(18.944,1)}{-35mm}{\begin{math}\phi=\frac{1+\sqrt{5}}{2}\end{math}}{0.5}{10mm}
		\drDim{(1,1)}{(1,12.09)}{15mm}{\begin{math}1\end{math}}{0.5}{-10mm}
		\drArcCeStEn{cm}{(6.545,1)}{(12,-0.3)}{(5,13)}{12.399}{}
		\end{drSc}
		\end{bodyNote}
	  </latex>
	</paragraph>
	<paragraph>
	  This sample represents a Golden Rectangle of length <math
	  latex="l">l</math> as a sequence of rectangles. If there is
	  only one member of the sequence, it is a Golden Rectangle
	  with the short side of length <math latex="l">l</math> and
	  long side of length <math
	  latex="(1+\sqrt{5})/2">(1+Sqrt(5))/2</math>. If there is
	  more than one member, each member but the last is a square,
	  starting with side length <math latex="l">l</math> and
	  reducing by <math latex="1/\phi">1/φ</math> at every
	  member. The final member is a Golden Rectangle. Each
	  successive square is located <math latex="l*\phi">l*φ</math> away
	  and rotated <math latex="90^\circ">90 degrees</math> from
	  the last.
	</paragraph>
	<paragraph>
	  In this sample, the recursion condition is area. When the
	  area of the next square would be less than a threshold<math
	  latex="minArea">minArea</math>, the function produces a
	  single Golden Rectangle and returns. Such a constraint is
	  more realistic than recursion depth---in design
	  there may be a minimum feature size for fabrication.
	</paragraph>
	<paragraph>
	  The data structure<latex>\index{data structure!list}</latex> produced is simple: a linked list of
	  rectangles, all but the last being a square.
	</paragraph>
	<paragraph>
	  You can also create Golden Rectangles from inside out by
	  adding squares to a seed rectangle.
	</paragraph>
      </how>
      <a href="Samples/RecuGoldenRectangle/RecuGoldenRectangleSubdivide.gct" >Click to download RecuGoldenRectangleSubdivide.gct</a>
      <animation src="Samples/RecuGoldenRectangle/AnimationGoldenRectangle00.swf"/>		
      <a href="Samples/RecuGoldenRectangle/RecuGoldenRectangleAdditive.gct" >Click to download RecuGoldenRectangleAdditive.gct</a>
      <animation src="Samples/RecuGoldenRectangle/AnimationGoldenRectangle20.swf"/>	
    </sample>
    
    <sample id="SierpinskiCarpet">
      <name>Sierpinski Carpet</name>
      <when>
	<paragraph>
	  Define a Sierpinski Carpet.
	</paragraph>
      </when>
      <paragraph>
	The Sierpinski carpet is a plane fractal, that is a recursive,
	self-similar form.  <web>Wacław
	Sierpiński</web><latex>Wac{\l}aw Sierpi\'{n}ski</latex>
	discovered it in 1916. Its construction begins with a
	square<latex>\index{square}</latex>. Conceptually, the square is cut into nine congruent
	subsquares in a <math latex="3 x 3">3 x 3</math> grid, and the
	central subsquare is removed. The same procedure is then
	applied recursively to the remaining eight subsquares.
      </paragraph>
      <how>
	<paragraph>
	  At each recursive level, the carpet comprises a motif: a
	  square of <math latex="1/3">1/3</math> the size of the
	  carpet at that level and placed as the centre of the
	  carpet. At all but the base levels, the it has <math
	  latex="8">8</math> additional carpets arranged around the
	  motif. Both the recursive function and the data structure
	  should reflect this arrangement. 
	</paragraph>
	<paragraph>
         The number of times a recursive function calls itself at a
         single level is called its <em>branching factor</em>. A level
         <math latex="0">0</math> carpet has a single motif. A level
         <math latex="2">1</math> carpet has nine motifs. The number
         grows very quickly. A level <math latex="6">6</math> carpet
         has <math
         latex="1+8+64+512+4096+32768+262144=299593">1+8+64+512+4,096+32,768+262,144=299,593</math>
         motifs. Clearly you have to be careful in limiting recursion
         depth in the face of high branching factors.
	</paragraph>
	<diagram>
	  <img src="Samples/RecuSierpinskiCarpet/RecursionSierpinskiDiagram.pdf" width="400"  />
	</diagram>
      </how>
      <a href="Samples/RecuSierpinskiCarpet/RecuSierpinskiCarpet.gct" >Click to download RecuSierpinskiCarpet.gct</a> 
      <animation src="Samples/RecuSierpinskiCarpet/AnimationSierpinskiCarpet.swf"/>			
    </sample>
    
    <sample id="3DPlanes">
      <name>3D Planes</name>
      <when>
	<paragraph>
	  Recursively divide space with three perpendicular polygons<latex>\index{polygon}</latex>.
	</paragraph>			
      </when>
      <web>
      <img src="Samples/Recu3DPlanes/Recu3DPlanes21.jpg" width="450"  />
      </web>
      <how>
	<paragraph>
	  The motif comprises a <math latex="3D">3D</math> cruciform
	  of square polygons<latex>\index{polygon}</latex>. The cruciform divides the space it
	  occupies into <math latex="8">8</math> cubes and at each
	  level, the recursive function places a scaled copy of the
	  cruciform into three of these.
	</paragraph>
	<paragraph>
	  This sample displays more architectural reality than the
	  prior samples. In fact, it resembles a recurrent motif in
	  the work of Arthur Erickson, for example, the image below shows the Simon
	  Fraser University academic quadrangle.
	</paragraph>
	<web>
	  <img src="Samples/Recu3DPlanes/SFUQuadrangle.jpg" width="400"  />
	</web>
	<latex>
	\begin{bodyNote}
	 \pbOneCol[r]
	  {\pbIncludeGraphics[\extImagesPath/SFUQuadrangleCropped.png]{width=\currentWidth}
	  \source{Greg Ehlers / Media Design, Simon Fraser University}}
	\end{bodyNote}	  
	</latex>
      </how>
      <a href="Samples/Recu3DPlanes/Recu3DPlanes.gct" >Click to download Recu3DPlanes.gct</a> 				
      <animation src="Samples/Recu3DPlanes/Animation3DPlanes.swf"/>			
    </sample>
    
    <sample id="HilbertCurve">
      <name>Hilbert Curve</name>
      <when>
	<paragraph>
	   Progressively fill space with a single curve<latex>\index{curve}</latex>.
	</paragraph>
      </when>
      <how>
	<paragraph>
	  The Hilbert Curve fills space. At the <math latex =
	  "n^{th}">n<sup>th</sup></math> recursive level it visits
	  every point in an <math latex = "(2^{n+1}) \times (2^{n+1})">(2<sup>n+1</sup>)) X (2<sup>n+1</sup>)</math>
	  integer dimensioned space. For example, at the <math latex = "0^{th}">0<sup>th</sup></math> level it visits all points in
	  a <math latex = "2 \times 2">2 X 2</math> space.
	</paragraph>
	<paragraph>
	  At the <math latex = "0^{th}">0<sup>th</sup></math> level,
	  shown in (a) below, the curve comprises three lines<latex>\index{line}</latex>, joining
	  centres of the four quarters of the <math latex = "2 \times
	  2">2 X 2</math> space.  At the second level, shown in (b), a
	  new <math latex = "2 \times 2">2 X 2</math> space replaces
	  each of the four points.  The points of this space define
	  four new curves. Joining the end-points of each curve
	  segment (c) with the start point of the next produces a
	  continuous curve.  At each subsequent level (d), a further
	  <math latex = "2 \times 2">2 X 2</math> space replaces each
	  point at the previous level. Successive levels of the
	  Hilbert thus form a progressively elaborating sequence (d).
	  <latex>\index{algorithm!recursion|)}</latex>\index{function!recursive|)}
	</paragraph>
	<paragraph>
	  <latex>
	    \begin{bodyNote}
 	      \pbTwoCol
	        {\input{\GCFigsPath/Patterns/RecursionHilbertCurveExplain00.tex}}
	        {\currentWidth/2}
	        {\input{\GCFigsPath/Patterns/RecursionHilbertCurveExplain10.tex}}
	        {\currentWidth/2}
 	      \pbTwoCol[c]{\textsf{(a)}}{\currentWidth/2}{\textsf{(b)}}{\currentWidth/2}
	      \pbTwoCol
	        {\input{\GCFigsPath/Patterns/RecursionHilbertCurveExplain20.tex}}
	        {\currentWidth/2}
	        {\input{\GCFigsPath/Patterns/RecursionHilbertCurveExplain30.tex}}
	        {\currentWidth/2}
 	      \pbTwoCol[c]{\textsf{(c)}}{\currentWidth/2}{\textsf{(d)}}{\currentWidth/2}
	    \end{bodyNote}
      </latex>
	</paragraph>
      </how>
      <a href="Samples/RecuHilbertCurve/RecuHilbertCurve.gct" >Click to download RecuHilbertCurve.gct</a>
      <animation src="Samples/RecuHilbertCurve/AnimationHilbertCurve.swf"/>			
    </sample>
    
  </samples>
 
</pattern>

