Kevin Ryde > Math-PlanePath > Math::PlanePath

Math-PlanePath-126.tar.gz

Dependencies

Annotate this POD

Website

# CPAN RT

 Open 0
View/Report Bugs
Module Version: 126

# NAME

Math::PlanePath -- points on a path through the 2-D plane

# SYNOPSIS

``` use Math::PlanePath;
# only a base class, see the subclasses for actual operation```

# DESCRIPTION

This is a base class for some mathematical paths which map an integer position `\$n` to and from coordinates `\$x,\$y` in the 2D plane.

The current classes include the following. The intention is that any `Math::PlanePath::Something` is a PlanePath, and supporting base classes or related things are further down like `Math::PlanePath::Base::Xyzzy`.

```    SquareSpiral           four-sided spiral
PyramidSpiral          square base pyramid
TriangleSpiral         equilateral triangle spiral
TriangleSpiralSkewed   equilateral skewed for compactness
DiamondSpiral          four-sided spiral, looping faster
PentSpiral             five-sided spiral
PentSpiralSkewed       five-sided spiral, compact
HexSpiral              six-sided spiral
HexSpiralSkewed        six-sided spiral skewed for compactness
HeptSpiralSkewed       seven-sided spiral, compact
AnvilSpiral            anvil shape
OctagramSpiral         eight pointed star
KnightSpiral           an infinite knight's tour
CretanLabyrinth        7-circuit extended infinitely

SquareArms             four-arm square spiral
DiamondArms            four-arm diamond spiral
AztecDiamondRings      four-sided rings
HexArms                six-arm hexagonal spiral
GreekKeySpiral         square spiral with Greek key motif
MPeaks                 "M" shape layers

SacksSpiral            quadratic on an Archimedean spiral
VogelFloret            seeds in a sunflower
TheodorusSpiral        unit steps at right angles
ArchimedeanChords      unit chords on an Archimedean spiral
MultipleRings          concentric circles
PixelRings             concentric rings of midpoint pixels
FilledRings            concentric rings of pixels
Hypot                  points by distance
HypotOctant            first octant points by distance
TriangularHypot        points by triangular distance
PythagoreanTree        X^2+Y^2=Z^2 by trees

WunderlichSerpentine   transpose parts of PeanoCurve
HilbertSpiral          2x2 self-similar whole-plane
ZOrderCurve            replicating Z shapes
GrayCode               Gray code splits
BetaOmega              2x2 self-similar half-plane
AR2W2Curve             2x2 self-similar of four parts
KochelCurve            3x3 self-similar of two parts
DekkingCurve           5x5 self-similar, edges
DekkingCentres         5x5 self-similar, centres
CincoCurve             5x5 self-similar

ImaginaryBase          replicate in four directions
ImaginaryHalf          half-plane replicate three directions
CubicBase              replicate in three directions
SquareReplicate        3x3 replicating squares
CornerReplicate        2x2 replicating "U"
LTiling                self-simlar L shapes
DigitGroups            digits grouped by zeros
FibonacciWordFractal   turns by Fibonacci word bits

Flowsnake              self-similar hexagonal tile traversal
FlowsnakeCentres         likewise but centres of hexagons
GosperReplicate        self-similar hexagonal tiling
GosperIslands          concentric island rings

QuintetCurve           self-similar "+" traversal
QuintetCentres           likewise but centres of squares
QuintetReplicate       self-similar "+" tiling

DragonCurve            paper folding
DragonRounded          paper folding rounded corners
DragonMidpoint         paper folding segment midpoints
AlternatePaper         alternating direction folding
AlternatePaperMidpoint alternating direction folding, midpoints
TerdragonCurve         ternary dragon
TerdragonRounded       ternary dragon rounded corners
TerdragonMidpoint      ternary dragon segment midpoints
AlternateTerdragon     alternate ternary dragon
CCurve                 "C" curve
ComplexPlus            base i+realpart
ComplexMinus           base i-realpart, including twindragon
ComplexRevolving       revolving base i+1

SierpinskiCurve        self-similar right-triangles
SierpinskiCurveStair   self-similar right-triangles, stair-step
HIndexing              self-similar right-triangles, squared up

KochCurve              replicating triangular notches
KochPeaks              two replicating notches
KochSnowflakes         concentric notched 3-sided rings
KochSquareflakes       concentric notched 4-sided rings
SierpinskiTriangle     self-similar triangle by rows
SierpinskiArrowheadCentres  likewise but centres of triangles

Rows                   fixed-width rows
Columns                fixed-height columns
Diagonals              diagonals between X and Y axes
DiagonalsAlternating   diagonals Y to X and back again
DiagonalsOctant        diagonals between Y axis and X=Y centre
Staircase              stairs down from the Y to X axes
StaircaseAlternating   stairs Y to X and back again
Corner                 expanding stripes around a corner
PyramidRows            expanding stacked rows pyramid
PyramidSides           along the sides of a 45-degree pyramid
CellularRule           cellular automaton by rule number
CellularRule54         cellular automaton rows pattern
CellularRule57         cellular automaton (rule 99 mirror too)
CellularRule190        cellular automaton (rule 246 mirror too)
UlamWarburton          cellular automaton diamonds
UlamWarburtonQuarter   cellular automaton quarter-plane

DiagonalRationals      rationals X/Y by diagonals
FactorRationals        rationals X/Y by prime factorization
GcdRationals           rationals X/Y by rows with GCD integer
RationalsTree          rationals X/Y by tree
FractionsTree          fractions 0<X/Y<1 by tree
ChanTree               rationals X/Y multi-child tree
CfracDigits            continued fraction 0<X/Y<1 by digits
CoprimeColumns         coprime X,Y
DivisibleColumns       X divisible by Y
WythoffArray           Fibonacci recurrences
WythoffPreliminaryTriangle
PowerArray             powers in rows
File                   points from a disk file```

And in the separate Math-PlanePath-Toothpick distribution

```    ToothpickTree          pattern of toothpicks
ToothpickReplicate     same by replication rather than tree
ToothpickUpist         toothpicks only growing upwards
ToothpickSpiral        toothpicks around the origin

LCornerTree            L-shape corner growth
LCornerReplicate       same by replication rather than tree
OneOfEight
HTree                  H shapes replicated```

The paths are object oriented to allow parameters, though many have none. See `examples/numbers.pl` in the Math-PlanePath sources for a sample printout of numbers from selected paths or all paths.

## Number Types

The `\$n` and `\$x,\$y` parameters can be either integers or floating point. The paths are meant to do something sensible with fractions but expect round-off for big floating point exponents.

Floating point infinities (when available) give NaN or infinite returns of some kind (some unspecified kind as yet). `n_to_xy()` on negative infinity is an empty return the same as other negative `\$n`.

Floating point NaNs (when available) give NaN, infinite, or empty/undef returns, but again of some unspecified kind as yet.

Most of the classes can operate on overloaded number types as inputs and give corresponding outputs.

```    Math::BigInt        maybe perl 5.8 up for ** operator
Math::BigRat
Math::BigFloat
Number::Fraction    1.14 or higher for abs()```

A few classes might truncate a bignum or a fraction to a float as yet. In general the intention is to make the calculations generic enough to act on any sensible number type. Recent enough versions of the bignum modules might be required, perhaps `BigInt` of Perl 5.8 or higher for `**` exponentiation operator.

For reference, an `undef` input as `\$n`, `\$x`, `\$y`, etc, is designed to provoke an uninitialized value warning when warnings are enabled. Perhaps that will change, but the warning at least prevents bad inputs going unnoticed.

# FUNCTIONS

In the following `Foo` is one of the various subclasses, see the list above and under "SEE ALSO".

## Constructor

`\$path = Math::PlanePath::Foo->new (key=>value, ...)`

Create and return a new path object. Optional key/value parameters may control aspects of the object.

## Coordinate Methods

`(\$x,\$y) = \$path->n_to_xy (\$n)`

Return X,Y coordinates of point `\$n` on the path. If there's no point `\$n` then the return is an empty list. For example

```    my (\$x,\$y) = \$path->n_to_xy (-123)
or next;   # no negatives in \$path```

Paths start from `\$path->n_start()` below, though some will give a position for N=0 or N=-0.5 too.

`(\$dx,\$dy) = \$path->n_to_dxdy (\$n)`

Return the change in X and Y going from point `\$n` to point `\$n+1`, or for paths with multiple arms from `\$n` to `\$n+\$arms_count` (thus advancing one point along the arm of `\$n`).

```    +  \$n+1 == \$next_x,\$next_y
^
|
|                    \$dx = \$next_x - \$x
+  \$n == \$x,\$y       \$dy = \$next_y - \$y```

`\$n` can be fractional and in that case the dX,dY is from that fractional `\$n` position to `\$n+1` (or `\$n+\$arms`).

```           frac \$n+1 == \$next_x,\$next_y
v
integer *---+----
|  /
| /
|/                 \$dx = \$next_x - \$x
frac +  \$n == \$x,\$y     \$dy = \$next_y - \$y
|
integer *```

In both cases `n_to_dxdy()` is the difference `\$dx=\$next_x-\$x, \$dy=\$next_y-\$y`. Currently for most paths it's merely two `n_to_xy()` calls to calculate the two points, but some paths can calculate a dX,dY with a little less work.

`\$rsquared = \$path->n_to_radius (\$n)`
`\$rsquared = \$path->n_to_rsquared (\$n)`

Return the radial distance R=sqrt(X^2+Y^2) of point `\$n`, or the radius squared R^2=X^2+Y^2. If there's no point `\$n` then the return is `undef`.

For a few paths these might be calculated with less work than `n_to_xy()`. For example the `SacksSpiral` is simply R^2=N, or the `MultipleRings` path with its default step=6 has an integer radius for integer `\$n` whereas `\$x,\$y` are fractional (and so inexact).

`\$n = \$path->xy_to_n (\$x,\$y)`

Return the N point number at coordinates `\$x,\$y`. If there's nothing at `\$x,\$y` then return `undef`.

```    my \$n = \$path->xy_to_n(20,20);
if (! defined \$n) {
next;   # nothing at this X,Y
}```

`\$x` and `\$y` can be fractional and the path classes will give an integer `\$n` which contains `\$x,\$y` within a unit square, circle, or intended figure centred on the integer `\$n`.

For paths which completely fill the plane there's always an `\$n` to return, but for the spread-out paths an `\$x,\$y` position may fall in between (no `\$n` close enough) and give `undef`.

`@n_list = \$path->xy_to_n_list (\$x,\$y)`

Return a list of N point numbers at coordinates `\$x,\$y`. If there's nothing at `\$x,\$y` then return an empty list.

`    my @n_list = \$path->xy_to_n(20,20);`

Most paths have just a single N for a given X,Y but some such as `DragonCurve` and `TerdragonCurve` have multiple N's and this method returns all of them.

Currently all paths have a finite number of N at a given location. It's unspecified what might happen for an infinite list, if that ever occurred.

`@n_list = \$path->n_to_n_list (\$n)`

Return a list of all N point numbers at the location of `\$n`. This is equivalent to `xy_to_n_list(n_to_xy(\$n))`.

The return list includes `\$n` itself. If there is no `\$n` in the path then return an empty list.

This function is convenient for paths like `DragonCurve` or `TerdragonCurve` with double or triple visited points so an N may have other N at the same location.

`\$bool = \$path->xy_is_visited (\$x,\$y)`

Return true if `\$x,\$y` is visited. This is equivalent to

`    defined(\$path->xy_to_n(\$x,\$y))`

Some paths cover the plane and for them `xy_is_visited()` is always true. For others it might be less work to test a point than to calculate its `\$n`.

`\$n = \$path->xyxy_to_n(\$x1,\$y1, \$x2,\$y2)`
`\$n = \$path->xyxy_to_n_either(\$x1,\$y1, \$x2,\$y2)`
`@n_list = \$path->xyxy_to_n_list(\$x1,\$y1, \$x2,\$y2)`
`@n_list = \$path->xyxy_to_n_list_either(\$x1,\$y1, \$x2,\$y2)`

Return <\$n> which goes from `\$x1,\$y1` to `\$x2,\$y2`. <\$n> is at `\$x1,\$y1` and `\$n+1` is at `\$x2,\$y2`, or for a multi-arm path `\$n+\$arms` so a step along the same arm. If there's no such `\$n` then return `undef`.

The `either()` forms allow <\$n> in either direction, so `\$x1,\$y1` to `\$x2,\$y2` or the other way `\$x2,\$y2` to `\$x1,\$y1`.

The `n_list()` forms return a list of all `\$n` going between `\$x1,\$y1` and `\$x2,\$y2`. For example in `Math::PlanePath::CCurve` some segments are traversed twice, once in each direction.

The possible N values at each X,Y are determined the same way as for `xy_to_n()`.

`(\$n_lo, \$n_hi) = \$path->rect_to_n_range (\$x1,\$y1, \$x2,\$y2)`

Return a range of N values covering or exceeding a rectangle with corners at `\$x1`,`\$y1` and `\$x2`,`\$y2`. The range is inclusive. For example,

```     my (\$n_lo, \$n_hi) = \$path->rect_to_n_range (-5,-5, 5,5);
foreach my \$n (\$n_lo .. \$n_hi) {
my (\$x, \$y) = \$path->n_to_xy(\$n) or next;
print "\$n  \$x,\$y";
}```

The return might be an over-estimate of the N range required to cover the rectangle. Even if the range is exact the nature of the path may mean many points between `\$n_lo` and `\$n_hi` are outside the rectangle. But the range is at least a lower and upper bound on the N values which occur in the rectangle. Classes which can guarantee an exact lo/hi range say so in their docs.

`\$n_hi` is usually no more than an extra partial row, revolution, or self-similar level. `\$n_lo` might be merely the starting `\$path->n_start()`, which is fine if the origin is in the desired rectangle but away from the origin might actually start higher.

`\$x1`,`\$y1` and `\$x2`,`\$y2` can be fractional. If they partly overlap some N figures then those N's are included in the return.

If there's no points in the rectangle then the return can be a "crossed" range like `\$n_lo=1`, `\$n_hi=0` (which makes a `foreach` do no loops). But `rect_to_n_range()` may not always notice there's no points in the rectangle and might instead return some over-estimate.

## Descriptive Methods

`\$n = \$path->n_start()`

Return the first N in the path. The start is usually either 0 or 1 according to what is most natural for the path. Some paths have an `n_start` parameter to control the numbering.

Some classes have secret dubious undocumented support for N values below this start (zero or negative), but `n_start()` is the intended starting point.

`\$f = \$path->n_frac_discontinuity()`

Return the fraction of N at which there may be discontinuities in the path. For example if there's a jump in the coordinates between N=7.4999 and N=7.5 then the returned `\$f` is 0.5. Or `\$f` is 0 if there's a discontinuity between 6.999 and 7.0.

If there's no discontinuities in the path then the return is `undef`. That means for example fractions between N=7 to N=8 give smooth continuous X,Y values (of some kind).

This is mainly of interest for drawing line segments between N points. If there's discontinuities then the idea is to draw from say N=7.0 to N=7.499 and then another line from N=7.5 to N=8.

`\$arms = \$path->arms_count()`

Return the number of arms in a "multi-arm" path.

For example in `SquareArms` this is 4 and each arm increments in turn, so the first arm is N=1,5,9,13,etc starting from `\$path->n_start()` and incrementing by 4 each time.

`\$bool = \$path->x_negative()`
`\$bool = \$path->y_negative()`

Return true if the path extends into negative X coordinates and/or negative Y coordinates respectively.

`\$bool = Math::PlanePath::Foo->class_x_negative()`
`\$bool = Math::PlanePath::Foo->class_y_negative()`
`\$bool = \$path->class_x_negative()`
`\$bool = \$path->class_y_negative()`

Return true if any paths made by this class extend into negative X coordinates and/or negative Y coordinates, respectively.

For some classes the X or Y extent may depend on parameter values.

`\$n = \$path->x_negative_at_n()`
`\$n = \$path->y_negative_at_n()`

Return the integer N where X or Y respectively first goes negative, or return `undef` if it does not go negative (`x_negative()` or `y_negative()` respectively is false).

`\$x = \$path->x_minimum()`
`\$y = \$path->y_minimum()`
`\$x = \$path->x_maximum()`
`\$y = \$path->y_maximum()`

Return the minimum or maximum of the X or Y coordinate reached by integer N values in the path. If there's no minimum or maximum then return `undef`.

`\$dx = \$path->dx_minimum()`
`\$dx = \$path->dx_maximum()`
`\$dy = \$path->dy_minimum()`
`\$dy = \$path->dy_maximum()`

Return the minimum or maximum change dX, dY occurring in the path for integer N to N+1. For a multi-arm path the change is N to N+arms so it's the change along the same arm.

Various paths which go by rows have non-decreasing Y. For them `dy_minimum()` is 0.

`\$adx = \$path->absdx_minimum()`
`\$adx = \$path->absdx_maximum()`
`\$ady = \$path->absdy_minimum()`
`\$ady = \$path->absdy_maximum()`

Return the minimum or maximum change abs(dX) or abs(dY) occurring in the path for integer N to N+1. For a multi-arm path the change is N to N+arms so it's the change along the same arm.

`absdx_maximum()` is simply max(dXmax,-dXmin), the biggest change either positive or negative. `absdy_maximum()` similarly.

`absdx_minimum()` is 0 if dX=0 occurs anywhere in the path, which means any vertical step. If X always changes then `absdx_minimum()` will be something bigger than 0. `absdy_minimum()` likewise 0 if any horizontal dY=0, or bigger if Y always changes.

`\$sum = \$path->sumxy_minimum()`
`\$sum = \$path->sumxy_maximum()`

Return the minimum or maximum values taken by coordinate sum X+Y reached by integer N values in the path. If there's no minimum or maximum then return `undef`.

S=X+Y is an anti-diagonal. A path which is always right and above some anti-diagonal has a minimum. Some paths might be entirely left and below and so have a maximum, though that's unusual.

```                          \        Path always above
\ |     has minimum S=X+Y
\|
---o----
Path always below      |\
has maximum S=X+Y      | \
\  S=X+Y```
`\$sum = \$path->sumabsxy_minimum()`
`\$sum = \$path->sumabsxy_maximum()`

Return the minimum or maximum values taken by coordinate sum abs(X)+abs(Y) reached by integer N values in the path. A minimum always exists but if there's no maximum then return `undef`.

SumAbs=abs(X)+abs(Y) is sometimes called the "taxi-cab" or "Manhattan" distance, being how far to travel through a square-grid city to get to X,Y. `sumabsxy_minimum()` is then how close to the origin the path extends.

SumAbs can also be interpreted geometrically as numbering the anti-diagonals of the quadrant containing X,Y, which is equivalent to asking which diamond shape X,Y falls on. `sumabsxy_minimum()` is then the smallest such diamond reached by the path.

```         |
/|\       SumAbs = which diamond X,Y falls on
/ | \
/  |  \
-----o-----
\  |  /
\ | /
\|/
|```
`\$diffxy = \$path->diffxy_minimum()`
`\$diffxy = \$path->diffxy_maximum()`

Return the minimum or maximum values taken by coordinate difference X-Y reached by integer N values in the path. If there's no minimum or maximum then return `undef`.

D=X-Y is a leading diagonal. A path which is always right and below such a diagonal has a minimum, for example `HypotOctant`. A path which is always left and above some diagonal has a maximum D=X-Y. For example various wedge-like paths such as `PyramidRows` in its default step=2, and "upper octant" paths have a maximum.

```                                 /   D=X-Y
Path always below     | /
has maximum D=X-Y     |/
---o----
/|
/ |      Path always above
/         has minimum D=X-Y```
`\$absdiffxy = \$path->absdiffxy_minimum()`
`\$absdiffxy = \$path->absdiffxy_maximum()`

Return the minimum or maximum values taken by abs(X-Y) for integer N in the path. The minimum is 0 or more. If there's maximum then return `undef`.

abs(X-Y) can be interpreted geometrically as the distance away from the X=Y diagonal and measured at right-angles to that line.

```     d=abs(X-Y)  X=Y line
^    /
\  /
\/
/\
/  \
/    \
o      v
/         d=abs(X-Y)```

Paths which visit the X=Y line (or approach it as an infimum) have `absdiffxy_minimum() = 0`. Otherwise `absdiffxy_minimum()` is how close they come to the line.

If the path is entirely below the X=Y line so X>=Y then X-Y>=0 and `absdiffxy_minimum()` is the same as `diffxy_minimum()`. If the path is entirely below the X=Y line then `absdiffxy_minimum()` is `- diffxy_maximum()`.

`\$dsumxy = \$path->dsumxy_minimum()`
`\$dsumxy = \$path->dsumxy_maximum()`
`\$ddiffxy = \$path->ddiffxy_minimum()`
`\$ddiffxy = \$path->ddiffxy_maximum()`

Return the minimum or maximum change dSum or dDiffXY occurring in the path for integer N to N+1. For a multi-arm path the change is N to N+arms so it's the change along the same arm.

`\$rsquared = \$path->rsquared_minimum()`
`\$rsquared = \$path->rsquared_maximum()`

Return the minimum or maximum Rsquared = X^2+Y^2 reached by integer N values in the path. If there's no minimum or maximum then return `undef`.

Rsquared is always >= 0 so it always has a minimum. The minimum will be more than 0 for paths which don't include the origin X=0,Y=0.

RSquared generally has no maximum since the paths usually extend infinitely in some direction. `rsquared_maximum()` returns `undef` in that case.

`(\$dx,\$dy) = \$path->dir_minimum_dxdy()`
`(\$dx,\$dy) = \$path->dir_maximum_dxdy()`

Return a vector which is the minimum or maximum angle taken by a step integer N to N+1, or for a multi-arm path N to N+arms so it's the change along the same arm. Directions are reckoned anti-clockwise around from the X axis.

```                  |  *  dX=2,dY=2
dX=-1,dY=1  * | /
\|/
------+----*  dX=1,dY=0
|
|
* dX=0,dY=-1```

A path which is always goes N,S,E,W such as the `SquareSpiral` has minimum East dX=1,dY=0 and maximum South dX=0,dY=-1.

Paths which go diagonally may have different limits. For example the `KnightSpiral` goes in 2x1 steps and so has minimum East-North-East dX=2,dY=1 and maximum East-South-East dX=2,dY=-1.

If the path has directions approaching 360 degrees then `dir_maximum_dxdy()` is 0,0 which should be taken to mean a full circle as a supremum. For example `MultipleRings`.

If the path only ever goes East then the maximum is East dX=1,dY=0, and the minimum the same. This isn't particularly interesting, but arises for example in the `Columns` path height=0.

`\$bool = \$path->turn_any_left()`
`\$bool = \$path->turn_any_right()`
`\$bool = \$path->turn_any_straight()`

Return true if the path turns left, right, or straight (which includes 180deg reverse) at any integer N.

```                N+1 left

N-1  --------  N  -->   N+1 straight

N+1 right```

A line from N-1 to N is a current direction and the turn at N is then whether point N+1 is to the left or right of that line. Directly along the line is straight, and so is anything directly behind as a reverse. This is the turn style of Math::NumSeq::PlanePathTurn.

`\$str = \$path->figure()`

Return a string name of the figure (shape) intended to be drawn at each `\$n` position. This is currently either

```    "square"     side 1 centred on \$x,\$y
"circle"     diameter 1 centred on \$x,\$y```

Of course this is only a suggestion since PlanePath doesn't draw anything itself. A figure like a diamond for instance can look good too.

## Tree Methods

Some paths are structured like a tree where each N has a parent and possibly some children.

```                 123
/ | \
456 999 458
/        / \
1000    1001 1005```

The N numbering and any relation to X,Y positions varies among the paths. Some are numbered by rows in breadth-first style and some have children with X,Y positions adjacent to their parent, but that shouldn't be assumed, only that there's a parent-child relation down from some set of root nodes.

`\$bool = \$path->is_tree()`

Return true if `\$path` is a tree.

The various tree methods have empty or `undef` returns on non-tree paths. Often it's enough to check for that from a desired method rather than a separate `is_tree()` check.

`@n_children = \$path->tree_n_children(\$n)`

Return a list of N values which are the child nodes of `\$n`, or return an empty list if `\$n` has no children.

There could be no children either because `\$path` is not a tree or because there's no children at a particular `\$n`.

`\$num = \$path->tree_n_num_children(\$n)`

Return the number of children of `\$n`, or 0 if `\$n` has no children, or `undef` if `\$n < n_start()` (ie. before the start of the path).

If the tree is considered as a directed graph then this is the "out-degree" of `\$n`.

`\$n_parent = \$path->tree_n_parent(\$n)`

Return the parent node of `\$n`, or `undef` if it has no parent.

There is no parent at the root node of the tree, or one of multiple roots, or if `\$path` is not a tree.

`\$n_root = \$path->tree_n_root (\$n)`

Return the N which is the root node of `\$n`. This is the top of the tree as would be found by following `tree_n_parent()` repeatedly.

The return is `undef` if there's no `\$n` point or if `\$path` is not a tree.

`\$depth = \$path->tree_n_to_depth(\$n)`

Return the depth of node `\$n`, or `undef` if there's no point `\$n`. The top of the tree is depth=0, then its children are depth=1, etc.

The depth is a count of how many parent, grandparent, etc, levels are above `\$n`, ie. until reaching `tree_n_to_parent()` returning `undef`. For non-tree paths `tree_n_to_parent()` is always `undef` and `tree_n_to_depth()` is always 0.

`\$n_lo = \$path->tree_depth_to_n(\$depth)`
`\$n_hi = \$path->tree_depth_to_n_end(\$depth)`
`(\$n_lo, \$n_hi) = \$path->tree_depth_to_n_range (\$depth)`

Return the first or last N, or both those N, for tree level `\$depth` in the path. If there's no such `\$depth` or if `\$path` is not a tree then return `undef`, or for `tree_depth_to_n_range()` return an empty list.

The points `\$n_lo` through `\$n_hi` might not necessarily all be at `\$depth`. It's possible for depths to be interleaved or intermixed in the point numbering. But many paths are breadth-wise successive rows and for them `\$n_lo` to `\$n_hi` inclusive is all `\$depth`.

`\$n_hi` can only exist if the row has a finite number of points. That's true of all current paths, but perhaps allowance ought to be made for `\$n_hi` as `undef` or some such if there is no maximum N for some row.

`\$num = \$path->tree_depth_to_width (\$depth)`

Return the number of points at `\$depth` in the tree. If there's no such `\$depth` or `\$path` is not a tree then return `undef`.

`\$height = \$path->tree_n_to_subheight(\$n)`

Return the height of the sub-tree starting at `\$n`, or `undef` if infinite. The height of a tree is the longest distance down to a leaf node. For example,

```    ...                      N     subheight
\                     ---    ---------
6    7   8            0       undef
\    \ /             1       undef
3    4   5          2         2
\    \ /           3       undef
1    2            4         1
\  /             5         0
0             ...```

At N=0 and all of the left side the tree continues infinitely so the sub-height there is `undef` for infinite. For N=2 the sub-height is 2 because the longest path down is 2 levels (to N=7 or N=8). For a leaf node such as N=5 the sub-height is 0.

## Tree Descriptive Methods

`\$num = \$path->tree_num_roots()`

Return the number of root nodes in `\$path`. If `\$path` is not a tree then return 0. Many tree paths have a single root and for them the return is 1.

`@n_list = \$path->tree_root_n_list()`

Return a list of the N values which are the root nodes in `\$path`. If `\$path` is not a tree then this is an empty list. There are `tree_num_roots()` many return values.

`\$num = \$path->tree_num_children_minimum()`
`\$num = \$path->tree_num_children_maximum()`
`@nums = \$path->tree_num_children_list()`

Return the possible number of children of the nodes of `\$path`, either the minimum, the maximum, or a list of all possible numbers of children.

For `tree_num_children_list()` the list of values is in increasing order, so the first value is `tree_num_children_minimum()` and the last is `tree_num_children_maximum()`.

`\$bool = \$path->tree_any_leaf()`

Return true if there are any leaf nodes in the tree, meaning any N for which `tree_n_num_children()` is 0.

This is the same as `tree_num_children_minimum()==0` since if NumChildren=0 occurs then there are leaf nodes.

Some trees may have no leaf nodes, for example in the complete binary tree of `RationalsTree` every node always has 2 children.

## Level Methods

`level = \$path->n_to_level(\$n)`

Return the replication level containing `\$n`. The first level is 0.

`(\$n_lo,\$n_hi) = \$path->level_to_n_range(\$level)`

Return the range of N values, inclusive, which comprise a self-similar replication level in `\$path`. If `\$path` has no notion of such levels then return an empty list.

```    my (\$n_lo, \$n_hi) = \$path->level_to_n_range(6)
or print "no levels in this path";```

For example the `DragonCurve` has levels running `0` to `2**\$level`, or the `HilbertCurve` is `0` to `4**\$level - 1`. Most levels are powers like this. A power `2**\$level` is a "vertex" style whereas `2**\$level - 1` is a "centre" style. The difference is generally whether the X,Y points represent vertices of the object's segments as opposed to centres or midpoints.

## Parameter Methods

`\$aref = Math::PlanePath::Foo->parameter_info_array()`
`@list = Math::PlanePath::Foo->parameter_info_list()`

Return an arrayref of list describing the parameters taken by a given class. This meant to help making widgets etc for user interaction in a GUI. Each element is a hashref

```    {
name        =>    parameter key arg for new()
share_key   =>    string, or undef
type        =>    string "integer","boolean","enum" etc
default     =>    value
minimum     =>    number, or undef
maximum     =>    number, or undef
width       =>    integer, suggested display size
choices     =>    for enum, an arrayref
}```

`type` is a string, one of

```    "integer"
"enum"
"boolean"
"string"
"filename"```

"filename" is separate from "string" since it might require subtly different handling to reach Perl as a byte string, whereas a "string" type might in principle take Perl wide chars.

For "enum" the `choices` field is the possible values, such as

```    { name => "flavour",
type => "enum",
choices => ["strawberry","chocolate"],
}```

`minimum` and/or `maximum` are omitted if there's no hard limit on the parameter.

`share_key` is designed to indicate when parameters from different `PlanePath` classes can done by a single control widget in a GUI etc. Normally the `name` is enough, but when the same name has slightly different meanings in different classes a `share_key` allows the same meanings to be matched up.

`\$hashref = Math::PlanePath::Foo->parameter_info_hash()`

Return a hashref mapping parameter names `\$info->{'name'}` to their `\$info` records.

```    { wider => { name => "wider",
type => "integer",
...
},
}```

# GENERAL CHARACTERISTICS

The classes are mostly based on integer `\$n` positions and those designed for a square grid turn an integer `\$n` into integer `\$x,\$y`. Usually they give in-between positions for fractional `\$n` too. Classes not on a square grid but instead giving fractional X,Y such as `SacksSpiral` and `VogelFloret` are designed for a unit circle at each `\$n` but they too can give in-between positions on request.

All X,Y positions are calculated by separate `n_to_xy()` calls. To follow a path use successive `\$n` values starting from `\$path->n_start()`.

```    foreach my \$n (\$path->n_start .. 100) {
my (\$x,\$y) = \$path->n_to_xy(\$n);
print "\$n  \$x,\$y\n";
}```

The separate `n_to_xy()` calls were motivated by plotting just some N points of a path, such as just the primes or the perfect squares. Successive positions in paths could perhaps be done more efficiently in an iterator style. Paths with a quadratic "step" are not much worse than a `sqrt()` to break N into a segment and offset, but the self-similar paths which chop N into digits of some radix could increment instead of recalculate.

If interested only in a particular rectangle or similar region then iterating has the disadvantage that it may stray outside the target region for a long time, making an iterator much less useful than it seems. For wild paths it can be better to apply `xy_to_n()` by rows or similar across the desired region.

Math::NumSeq::PlanePathCoord etc offer the PlanePath coordinates, directions, turns, etc as sequences. The iterator forms there simply make repeated calls to `n_to_xy()` etc.

## Scaling and Orientation

The paths generally make a first move to the right and go anti-clockwise around from the X axis, unless there's some more natural orientation. Anti-clockwise is the usual direction for mathematical spirals.

There's no parameters for scaling, offset or reflection as those things are thought better left to a general coordinate transformer, for example to expand or invert for display. Some easy transformations can be had just from the X,Y with

```    -X,Y        flip horizontally (mirror image)
X,-Y        flip vertically (across the X axis)

-Y,X        rotate +90 degrees  (anti-clockwise)
Y,-X        rotate -90 degrees  (clockwise)
-X,-Y       rotate 180 degrees```

Flip vertically makes spirals go clockwise instead of anti-clockwise, or a flip horizontally the same but starting on the left at the negative X axis. See "Triangular Lattice" below for 60 degree rotations of the triangular grid paths too.

The Rows and Columns paths are exceptions to the rule of not having rotated versions of paths. They began as ways to pass in width and height as generic parameters and let the path use the one or the other.

For scaling and shifting see for example Transform::Canvas, and to rotate as well see Geometry::AffineTransform.

## Loop Step

The paths can be characterized by how much longer each loop or repetition is than the preceding one. For example each cycle around the `SquareSpiral` is 8 more N points than the preceding.

```      Step        Path
----        ----
0       Rows, Columns (fixed widths)
1       Diagonals
2/2      DiagonalsOctant (2 rows for +2)
2       SacksSpiral, PyramidSides, Corner, PyramidRows (default)
4       DiamondSpiral, AztecDiamondRings, Staircase
4/2      CellularRule54, CellularRule57,
DiagonalsAlternating (2 rows for +4)
5       PentSpiral, PentSpiralSkewed
6       HexSpiral, HexSpiralSkewed, MPeaks,
MultipleRings (default)
6/2      CellularRule190 (2 rows for +6)
6.28     ArchimedeanChords (approaching 2*pi),
FilledRings (average 2*pi)
7       HeptSpiralSkewed
8       SquareSpiral, PyramidSpiral
16/2      StaircaseAlternating (up and back for +16)
9       TriangleSpiral, TriangleSpiralSkewed
12       AnvilSpiral
16       OctagramSpiral, ToothpickSpiral
19.74     TheodorusSpiral (approaching 2*pi^2)
32/4      KnightSpiral (4 loops 2-wide for +32)
64       DiamondArms (each arm)
72       GreekKeySpiral
128       SquareArms (each arm)
128/4      CretanLabyrinth (4 loops for +128)
216       HexArms (each arm)

totient     CoprimeColumns, DiagonalRationals
numdivisors DivisibleColumns
various     CellularRule

parameter   MultipleRings, PyramidRows```

The step determines which quadratic number sequences make straight lines. For example the gap between successive perfect squares increases by 2 each time (4 to 9 is +5, 9 to 16 is +7, 16 to 25 is +9, etc), so the perfect squares make a straight line in the paths of step 2.

In general straight lines on stepped paths are quadratics

`   N = a*k^2 + b*k + c    where a=step/2`

The polygonal numbers are like this, with the (step+2)-gonal numbers making a straight line on a "step" path. For example the 7-gonals (heptagonals) are 5/2*k^2-3/2*k and make a straight line on the step=5 `PentSpiral`. Or the 8-gonal octagonal numbers 6/2*k^2-4/2*k on the step=6 `HexSpiral`.

There are various interesting properties of primes in quadratic progressions. Some quadratics seem to have more primes than others. For example see "Lucky Numbers of Euler" in Math::PlanePath::PyramidSides. Many quadratics have no primes at all, or none above a certain point, either trivially if always a multiple of 2 etc, or by a more sophisticated reasoning. See "Step 3 Pentagonals" in Math::PlanePath::PyramidRows for a factorization on the roots making a no-primes gap.

A 4*step path splits a straight line in two, so for example the perfect squares are a straight line on the step=2 "Corner" path, and then on the step=8 `SquareSpiral` they instead fall on two lines (lower left and upper right). In the bigger step there's one line of the even squares (2k)^2 == 4*k^2 and another of the odd squares (2k+1)^2. The gap between successive even squares increases by 8 each time and likewise between odd squares.

## Self-Similar Powers

The self-similar patterns such as `PeanoCurve` generally have a base pattern which repeats at powers N=base^level or squares N=(base*base)^level. Or some multiple or relationship to such a power for things like `KochPeaks` and `GosperIslands`.

```    Base          Path
----          ----
2         HilbertCurve, HilbertSides, HilbertSpiral,
ZOrderCurve (default), GrayCode (default),
BetaOmega, AR2W2Curve, HIndexing,
ImaginaryBase (default), ImaginaryHalf (default),
SierpinskiCurve, SierpinskiCurveStair,
CubicBase (default) CornerReplicate,
ComplexMinus (default), ComplexPlus (default),
ComplexRevolving, DragonCurve, DragonRounded,
DragonMidpoint, AlternatePaper, AlternatePaperMidpoint,
CCurve, DigitGroups (default), PowerArray (default)
3         PeanoCurve (default), WunderlichSerpentine (default),
WunderlichMeander, KochelCurve,
GosperIslands, GosperSide
TerdragonCurve, TerdragonRounded, TerdragonMidpoint,
AlternateTerdragon,
UlamWarburton, UlamWarburtonQuarter (each level)
4         KochCurve, KochPeaks, KochSnowflakes, KochSquareflakes,
LTiling,
5         QuintetCurve, QuintetCentres, QuintetReplicate,
DekkingCurve, DekkingCentres, CincoCurve,
R5DragonCurve, R5DragonMidpoint
7         Flowsnake, FlowsnakeCentres, GosperReplicate
9         SquareReplicate
Fibonacci   FibonacciWordFractal, WythoffArray
parameter   PeanoCurve, WunderlichSerpentine, ZOrderCurve, GrayCode,
ImaginaryBase, ImaginaryHalf, CubicBase, ComplexPlus,
ComplexMinus, DigitGroups, PowerArray```

Many number sequences plotted on these self-similar paths tend to be fairly random, or merely show the tiling or path layout rather than much about the number sequence. Sequences related to the base can make holes or patterns picking out parts of the path. For example numbers without a particular digit (or digits) in the relevant base show up as holes. See for example "Power of 2 Values" in Math::PlanePath::ZOrderCurve.

## Triangular Lattice

Some paths are on triangular or "A2" lattice points like

```      *---*---*---*---*---*
/ \ / \ / \ / \ / \ /
*---*---*---*---*---*
\ / \ / \ / \ / \ / \
*---*---*---*---*---*
/ \ / \ / \ / \ / \ /
*---*---*---*---*---*
\ / \ / \ / \ / \ / \
*---*---*---*---*---*
/ \ / \ / \ / \ / \ /
*---*---*---*---*---*```

This is done in integer X,Y on a square grid by using every second square and offsetting alternate rows. This means sum X+Y even, ie. X,Y either both even or both odd, not of opposite parity.

```    . * . * . * . * . * . *
* . * . * . * . * . * .
. * . * . * . * . * . *
* . * . * . * . * . * .
. * . * . * . * . * . *
* . * . * . * . * . * .```

The X axis the and diagonals X=Y and X=-Y divide the plane into six equal parts in this grid.

```       X=-Y     X=Y
\     /
\   /
\ /
----------------- X=0
/ \
/   \
/     \```

The diagonal X=3*Y is the middle of the first sixth, representing a twelfth of the plane.

The resulting triangles are flatter than they should be. The triangle base is width=2 and top is height=1, whereas it would be height=sqrt(3) for an equilateral triangle. That sqrt(3) factor can be applied if desired,

```    X, Y*sqrt(3)          side length 2

X/2, Y*sqrt(3)/2      side length 1```

Integer Y values have the advantage of fitting pixels on the usual kind of raster computer screen, and not losing precision in floating point results.

If doing a general-purpose coordinate rotation then be sure to apply the sqrt(3) scale factor before rotating or the result will be skewed. 60 degree rotations can be made within the integer X,Y coordinates directly as follows, all giving integer X,Y results.

```    ( X-3Y)/2, ( X+Y)/2     rotate +60   (anti-clockwise)
( X+3Y)/2, (-X+Y)/2     rotate -60   (clockwise)
(-X-3Y)/2, ( X-Y)/2     rotate +120
(-X+3Y)/2, (-X-Y)/2     rotate -120
-X,-Y                   rotate 180

(X+3Y)/2, (X-Y)/2       mirror across the X=3*Y twelfth (30deg)```

The sqrt(3) factor can be worked into a hypotenuse radial distance calculation as follows if comparing distances from the origin.

`    hypot = sqrt(X*X + 3*Y*Y)`

See for instance `TriangularHypot` which is triangular points ordered by this radial distance.

# FORMULAS

The formulas section in the POD of each class describes some of the calculations. This might be of interest even if the code is not.

## Triangular Calculations

For a triangular lattice the rotation formulas above allow calculations to be done in the rectangular X,Y coordinates which are the inputs and outputs of the PlanePath functions. Another way is to number vertically on a 60 degree angle with coordinates i,j,

```          ...
*   *   *      2
*   *   *       1
*   *   *      j=0
i=0  1   2```

These coordinates are sometimes used for hexagonal grids in board games etc. Using this internally can simplify rotations a little,

```    -j, i+j         rotate +60   (anti-clockwise)
i+j, -i         rotate -60   (clockwise)
-i-j, i         rotate +120
j, -i-j         rotate -120
-i, -j          rotate 180```

Conversions between i,j and the rectangular X,Y are

```    X = 2*i + j         i = (X-Y)/2
Y = j               j = Y```

A third coordinate k at a +120 degrees angle can be used too,

```     k=0  k=1 k=2
*   *   *
*   *   *
*   *   *
0   1   2```

This is redundant in that it doesn't number anything i,j alone can't already, but it has the advantage of turning rotations into just sign changes and swaps,

```    -k, i, j        rotate +60
j, k, -i        rotate -60
-j, -k, i       rotate +120
k, -i, -j       rotate -120
-i, -j, -k      rotate 180```

The conversions between i,j,k and the rectangular X,Y are like the i,j above but with k worked in too.

```    X = 2i + j - k        i = (X-Y)/2        i = (X+Y)/2
Y = j + k             j = Y         or   j = 0
k = 0              k = Y```

## N to dX,dY -- Fractional

`n_to_dxdy()` is the change from N to N+1, and is designed both for integer N and fractional N. For fractional N it can be convenient to calculate a dX,dY at floor(N) and at floor(N)+1 and then combine the two in proportion to frac(N).

```                     int+2
|
|
N+1    \
/|       |
/ |       |
/  |       | frac
/   |       |
/    |       |
/     |      /
int-----N------int+1
this_dX  dX,dY     next_dX
this_dY            next_dY

|-------|------|
frac   1-frac

int = int(N)
frac = N - int    0 <= frac < 1

this_dX,this_dY  at int
next_dX,next_dY  at int+1

at fractional N
dX = this_dX * (1-frac) + next_dX * frac
dY = this_dY * (1-frac) + next_dY * frac```

This is combination of this_dX,this_dY and next_dX,next_dY in proportion to the distances from positions N to int+1 and from int+1 to N+1.

The formulas can be rearranged to

```    dX = this_dX + frac*(next_dX - this_dX)
dY = this_dY + frac*(next_dY - this_dY)```

which is like dX,dY at the integer position plus fractional part of a turn or change to the next dX,dY.

## N to dX,dY -- Self-Similar

For most of the self-similar paths such as `HilbertCurve` the change dX,dY is determined by following the state table transitions down through either all digits of N, or to the last non-9 digit, ie. drop any low digits equal to radix-1.

Generally paths which are the edges of some tiling use all digits, and those which are the centres of a tiling stop at the lowest non-9. This can be seen for example in the `DekkingCurve` using all digits, whereas its `DekkingCentres` variant stops at the lowest non-24.

Perhaps this all-digits vs low-non-9 even characterizes path style as edges or centres of a tiling, when a path is specified in some way that a tiling is not quite obvious.

# SUBCLASSING

The mandatory methods for a PlanePath subclass are

```    n_to_xy()
xy_to_n()
xy_to_n_list()     if multiple N's map to an X,Y
rect_to_n_range()```

It sometimes happens that one of `n_to_xy()` or `xy_to_n()` is easier than the other but both should be implemented.

`n_to_xy()` should do something sensible on fractional N. The suggestion is to make it an X,Y proportionally between integer N positions. It can be along a straight line or an arc as best suits the path. A straight line can be done simply by two calculations of the surrounding integer points, until it's clear how to work the fraction into the code directly.

`xy_to_n_list()` has a base implementation calling plain `xy_to_n()` to give a single N at X,Y. If a path has multiple Ns at an X,Y (eg. `DragonCurve`) then it should implement `xy_to_n_list()` to return all those Ns and also implement a plain `xy_to_n()` returning the first of them.

`rect_to_n_range()` can initially be any convenient over-estimate. It should give N big enough that from there onwards all points are sure to be beyond the given X,Y rectangle.

The following descriptive methods have base implementations

```    n_start()           1
class_x_negative()  \ 1, so whole plane
class_y_negative()  /
x_negative()        calls class_x_negative()
y_negative()        calls class_x_negative()
x_negative_at_n()   undef \ as for no negatives
y_negative_at_n()   undef /```

The base `n_start()` starts at N=1. Paths which treat N as digits of some radix or where there's self-similar replication are often best started from N=0 instead since doing so puts nice powers-of-2 etc on the axes or diagonals.

`    use constant n_start => 0;    # digit or replication style`

Paths which use only parts of the plane should define `class_x_negative()` and/or `class_y_negative()` to false. For example if only the first quadrant X>=0,Y>=0 then

```    use constant class_x_negative => 0;
use constant class_y_negative => 0;```

If negativeness varies with path parameters then `x_negative()` and/or `y_negative()` follow those parameters and the `class_()` forms are whether any set of parameters ever gives negative.

The following methods have base implementations calling `n_to_xy()`. A subclass can implement them directly if they can be done more efficiently.

```    n_to_dxdy()           calls n_to_xy() twice
n_to_rsquared()       calls n_to_xy()

`SacksSpiral` is an example of an easy `n_to_rsquared()`. `TheodorusSpiral` is only slightly trickier. Unless a path has some sort of easy X^2+Y^2 then it might as well let the base implementation call `n_to_xy()`.

The way `n_to_dxdy()` supports fractional N can be a little tricky. One way is to calculate dX,dY on the integer N below and above and combine as described in "N to dX,dY -- Fractional". For some paths the calculation of turn or direction at ceil(N) can be worked into a calculation of the direction at floor(N) so not much more work.

The following methods have base implementations calling `xy_to_n()`. A subclass might implement them directly if it can be done more efficiently.

```    xy_is_visited()          defined(xy_to_n(\$x,\$y))
xyxy_to_n()              \
xyxy_to_n_either()       | calling xy_to_n_list()
xyxy_to_n_list()         |
xyxy_to_n_list_either()  /```

Paths such as `SquareSpiral` which fill the plane have `xy_is_visited()` always true, so for them

`    use constant xy_is_visited => 1;`

For a tree path the following methods are mandatory

```    tree_n_parent()
tree_n_children()
tree_n_to_depth()
tree_depth_to_n()
tree_num_children_list()
tree_n_to_subheight()```

The other tree methods have base implementations,

`is_tree()`

Checks for `n_start()` having non-zero `tree_n_to_num_children()`. Usually this suffices, expecting `n_start()` to be a root node and to have some children.

`tree_n_num_children()`

Calls `tree_n_children()` and counts the number of return values. Many trees can count the children with less work than calculating outright, for example `RationalsTree` is simply always 2 for N>=Nstart.

`tree_depth_to_n_end()`

Calls `tree_depth_to_n(\$depth+1)-1`. This assumes that the depth level ends where the next begins. This is true for the various breadth-wise tree traversals, but anything interleaved etc will need its own implementation.

`tree_depth_to_n_range()`

Calls `tree_depth_to_n()` and `tree_depth_to_n_end()`. For some paths the row start and end, or start and width, might be calculated together more efficiently.

`tree_depth_to_width()`

Returns `tree_depth_to_n_end() - tree_depth_to_n() + 1`. This suits breadth-wise style paths where all points at `\$depth` are in a contiguous block. Any path not like that will need its own `tree_depth_to_width()`.

`tree_num_children_minimum()`, `tree_num_children_maximum()`

Return the first and last values of `tree_num_children_list()` as the minimum and maximum.

`tree_any_leaf()`

Calls `tree_num_children_minimum()`. If the minimum `num_children` is 0 then there's leaf nodes.

math-image, displaying various sequences on these paths.

examples/numbers.pl, to print all the paths.

## Other Ways To Do It

PerlMagick (module Image::Magick) demo scripts lsys.pl and tree.pl

http://user42.tuxfamily.org/math-planepath/index.html

http://user42.tuxfamily.org/math-planepath/gallery.html