# Copyright 2010, 2011, 2012, 2013, 2014 Kevin Ryde
# This file is part of MathPlanePath.
#
# MathPlanePath is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later
# version.
#
# MathPlanePath is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with MathPlanePath. If not, see .
# Maybe:
#
# ($x,$y) = $path>xy_start() x,y at n_start
# $bool = $path>is_tree()
# ($depth,$offset) = $path>tree_n_to_depth_and_offset
#
# $bool = $path>rect_to_n_range_is_always_exact()
# $bool = $path>tree_n_to_subheight_is_infinite()
# identifying the infinite spines only
#
# tree_n_ordered_children() $n and undefs
# SierpinskiTree,ToothpickTree left and right
# OneOfEight 3 from horiz, 5 from diag
#
# gcdxy_minimum
# gcdxy_maximum
# productxy_minimum
# trsquared_minimum
# trsquared_minimum
#
# level_to_n_range() 0 to 2^k1 centres
# 0 to 2^k dragon segments
# ring_to_n_range() 2^(k1) to 2^k1 koch peaks
# ($x1,$y1, $x2,$y2) = n_to_rect($n) integer points
# ($s1,$s1, $d2,$d2) = n_to_diamond($n) integer points
# cf fractional part Diagonals outside integer area
# n_to_figure_boundary
# n_to_hull_boundary
# n_to_hull_area
# n_to_enclosed_area
# n_to_enclosed_boundary
# n_to_right_enclosed_boundary
# n_to_left_enclosed_boundary
# $path>xy_integer() if X,Y both all integer
# $path>x_integer() if X all integer
# $path>y_integer() if Y all integer
# $path>xy_integer_n_start
#
# xy_all_coprime() xy_coprime() gcd(X,Y)=1 always
# xy_all_divisible() X divisible by Y
# xy_any_even
# xy_any_odd
# xy_all_even
# xy_all_odd
# xy_parity_minimum() X+Y mod 2
# xy_parity_maximum() X+Y mod 2
# xy_parity "even" "odd" "both"
# xy_hexlattice_type "centred" "side_horiz"
# xy_triangular_lattice "", "even", "odd
#
# lattice_type square,triangular,triangular_odd,pentagonal,fractional
# $path>xy_any_odd() xy_odd() xy_all_odd()
# $path>xy_any_even() xy_even() xy_all_even()
#
# $path>turn_any_left
# $path>turn_any_right
# $path>turn_any_straight
# $path>n_to_turn_lsr
# $path>n_to_dir4
# $path>n_to_turn4
# $path>n_to_turn6
# $path>n_to_turn8
# $path>n_to_ddist
# $path>n_to_drsquared
# $path>xy_to_dir4_list
# $path>xy_to_dxdy_list
# $path>xy_to_n_list_maxcount
# $path>xy_to_n_list_maxnum
# $path>xy_to_n_list_maximum
# $path>xy_next_in_rect($x,$y, $x1,$y1,$x2,$y2)
# return ($x,$y) or empty
# $path>xy_to_dxdy() or dxdy_list if multiple maybe
#
# xy_unique_n_start
# figures_disjoint
# figures_disjoint_n_start
# separate
# unoverlapped
#
# Math::PlanePath::Base::Generic
# divrem
# divrem_mutate
#
#
package Math::PlanePath;
use 5.004;
use strict;
use vars '$VERSION';
$VERSION = 116;
# uncomment this to run the ### lines
# use Smart::Comments;
# defaults
use constant figure => 'square';
use constant default_n_start => 1;
sub n_start {
my ($self) = @_;
if (ref $self && defined $self>{'n_start'}) {
return $self>{'n_start'};
} else {
return $self>default_n_start;
}
}
sub arms_count {
my ($self) = @_;
return $self>{'arms'}  1;
}
use constant class_x_negative => 1;
use constant class_y_negative => 1;
sub x_negative { $_[0]>class_x_negative }
sub y_negative { $_[0]>class_y_negative }
use constant x_negative_at_n => undef;
use constant y_negative_at_n => undef;
use constant n_frac_discontinuity => undef;
use constant parameter_info_array => [];
sub parameter_info_list {
return @{$_[0]>parameter_info_array};
}
# x_negative(),y_negative() existed before x_minimum(),y_minimum(), so
# default x_minimum(),y_minimum() from those.
sub x_minimum {
my ($self) = @_;
return ($self>x_negative ? undef : 0);
}
sub y_minimum {
my ($self) = @_;
return ($self>y_negative ? undef : 0);
}
use constant x_maximum => undef;
use constant y_maximum => undef;
sub sumxy_minimum {
my ($self) = @_;
### PlanePath sumxy_minimum() ...
if (defined (my $x_minimum = $self>x_minimum)
&& defined (my $y_minimum = $self>y_minimum)) {
### $x_minimum
### $y_minimum
return $x_minimum + $y_minimum;
}
return undef;
}
use constant sumxy_maximum => undef;
sub sumabsxy_minimum {
my ($self) = @_;
my $x_minimum = $self>x_minimum;
my $y_minimum = $self>y_minimum;
if (defined $x_minimum && $x_minimum >= 0
&& defined $y_minimum && $y_minimum >= 0) {
# X>=0 and Y>=0 so abs(X)+abs(Y) == X+Y
return $self>sumxy_minimum;
}
return _max($x_minimum0,0) + _max($y_minimum0,0);
}
use constant sumabsxy_maximum => undef;
use constant diffxy_minimum => undef;
#
# If the path is confined to the fourth quadrant, so X>=something and
# Y<=something then a minimum XY exists. But fourthquadrantonly path is
# unusual, so don't bother with code checking that.
# sub diffxy_minimum {
# my ($self) = @_;
# if (defined (my $y_maximum = $self>y_maximum)
# && defined (my $x_minimum = $self>x_minimum)) {
# return $x_minimum  $y_maximum;
# } else {
# return undef;
# }
# }
# If the path is confined to the second quadrant, so X<=something and
# Y>=something, then has a maximum XY. Presume that the x_maximum() and
# y_minimum() occur together.
#
sub diffxy_maximum {
my ($self) = @_;
if (defined (my $y_minimum = $self>y_minimum)
&& defined (my $x_max = $self>x_maximum)) {
return $x_max  $y_minimum;
} else {
return undef;
}
}
# absdiffxy = abs(XY)
sub absdiffxy_minimum {
my ($self) = @_;
# if XY all one sign, so XY>=0 or XY<=0, then abs(XY) from that
my $m;
if (defined($m = $self>diffxy_minimum) && $m >= 0) {
return $m;
}
if (defined($m = $self>diffxy_maximum) && $m <= 0) {
return  $m;
}
return 0;
}
sub absdiffxy_maximum {
my ($self) = @_;
# if XY constrained so min<=XY<=max then max abs(XY) one of the two ends
if (defined (my $min = $self>diffxy_minimum)
&& defined (my $max = $self>diffxy_maximum)) {
return _max(abs($min),abs($max));
}
return undef;
}
# experimental default from x_minimum(),y_minimum()
# FIXME: should use absx_minimum, absy_minimum, for paths outside first quadrant
sub rsquared_minimum {
my ($self) = @_;
# The X and Y each closest to the origin. This assumes that point is
# actually visited, but is likely to be close.
my $x_minimum = $self>x_minimum;
my $x_maximum = $self>x_maximum;
my $y_minimum = $self>y_minimum;
my $y_maximum = $self>y_maximum;
my $x = (( defined $x_minimum && $x_minimum) > 0 ? $x_minimum
: (defined $x_maximum && $x_maximum) < 0 ? $x_maximum
: 0);
my $y = (( defined $y_minimum && $y_minimum) > 0 ? $y_minimum
: (defined $y_maximum && $y_maximum) < 0 ? $y_maximum
: 0);
return ($x*$x + $y*$y);
# # Maybe initial point $self>n_to_xy($self>n_start)) as the default,
# # but that's not the minimum on "wider" paths.
# return 0;
}
use constant rsquared_maximum => undef;
sub gcdxy_minimum {
my ($self) = @_;
### gcdxy_minimum(): "visited=".($self>xy_is_visited(0,0)0)
return ($self>xy_is_visited(0,0)
? 0 # gcd(0,0)=0
: 1); # any other has gcd>=1
}
use constant gcdxy_maximum => undef;
#
use constant dir_minimum_dxdy => (1,0); # East
use constant dir_maximum_dxdy => (0,0); # supremum all angles
use constant dx_minimum => undef;
use constant dy_minimum => undef;
use constant dx_maximum => undef;
use constant dy_maximum => undef;
#
# =item C<$n = $pathE_UNDOCUMENTED__dxdy_list_at_n()>
#
# Return the N at which all possible dX,dY will have been seen. If there is
# not a finite set of possible dX,dY steps then return C.
#
use constant _UNDOCUMENTED__dxdy_list => (); # default empty for not a finite list
use constant _UNDOCUMENTED__dxdy_list_at_n => undef; # maybe dxdy_at_n()
use constant _UNDOCUMENTED__dxdy_list_three => (2,0, # E
1,1, # NW
1,1); # SW
use constant _UNDOCUMENTED__dxdy_list_six => (2,0, # E
1,1, # NE
1,1, # NW
2,0, # W
1,1, # SW
1,1); # SE
use constant _UNDOCUMENTED__dxdy_list_eight => (1,0, # E
1,1, # NE
0,1, # N
1,1, # NW
1,0, # W
1,1, # SW
0,1, # S
1,1); # SE
sub absdx_minimum {
my ($self) = @_;
# If dX>=0 then abs(dX)=dX always and absdx_minimum()==dx_minimum().
# This happens for column style paths like CoprimeColumns.
# dX>0 is only for line paths so not very interesting.
if (defined (my $dx_minimum = $self>dx_minimum)) {
if ($dx_minimum >= 0) { return $dx_minimum; }
}
return 0;
}
sub absdx_maximum {
my ($self) = @_;
if (defined (my $dx_minimum = $self>dx_minimum)
&& defined (my $dx_maximum = $self>dx_maximum)) {
return _max(abs($dx_minimum),abs($dx_maximum));
}
return undef;
}
sub absdy_minimum {
my ($self) = @_;
# if dY>=0 then abs(dY)=dY always and absdy_minimum()==dy_minimum()
if (defined (my $dy_minimum = $self>dy_minimum)) {
if ($dy_minimum >= 0) { return $dy_minimum; }
}
return 0;
}
sub absdy_maximum {
my ($self) = @_;
if (defined (my $dy_minimum = $self>dy_minimum)
&& defined (my $dy_maximum = $self>dy_maximum)) {
return _max(abs($dy_minimum),abs($dy_maximum));
} else {
return undef;
}
}
use constant dsumxy_minimum => undef;
use constant dsumxy_maximum => undef;
use constant ddiffxy_minimum => undef;
use constant ddiffxy_maximum => undef;
#
sub new {
my $class = shift;
return bless { @_ }, $class;
}
{
my %parameter_info_hash;
sub parameter_info_hash {
my ($class_or_self) = @_;
my $class = (ref $class_or_self  $class_or_self);
return ($parameter_info_hash{$class}
= { map { $_>{'name'} => $_ }
$class_or_self>parameter_info_list });
}
}
sub xy_to_n_list {
### xy_to_n_list() ...
if (defined (my $n = shift>xy_to_n(@_))) {
### $n
return $n;
}
### empty ...
return;
}
sub xy_is_visited {
my ($self, $x, $y) = @_;
### xy_is_visited(): "$x,$y is ndefined=".defined($self>xy_to_n($x,$y))
return defined($self>xy_to_n($x,$y));
}
sub n_to_dxdy {
my ($self, $n) = @_;
### n_to_dxdy(): $n
my ($x,$y) = $self>n_to_xy ($n)
or return;
my ($next_x,$next_y) = $self>n_to_xy ($n + $self>arms_count)
or return;
### points: "$x,$y $next_x,$next_y"
return ($next_x  $x,
$next_y  $y);
}
sub n_to_rsquared {
my ($self, $n) = @_;
my ($x,$y) = $self>n_to_xy($n) or return undef;
return $x*$x + $y*$y;
}
sub n_to_radius {
my ($self, $n) = @_;
my $rsquared = $self>n_to_rsquared($n);
return (defined $rsquared ? sqrt($rsquared) : undef);
}
#
# tree
sub is_tree {
my ($self) = @_;
return $self>tree_n_num_children($self>n_start);
}
use constant tree_n_parent => undef; # default always no parent
use constant tree_n_children => (); # default no children
sub tree_n_num_children {
my ($self, $n) = @_;
if ($n >= $self>n_start) {
my @n_list = $self>tree_n_children($n);
return scalar(@n_list);
} else {
return undef;
}
}
# For nontrees n_num_children() always returns 0 so that's the single
# return here.
use constant tree_num_children_list => (0);
sub tree_num_children_minimum {
my ($self) = @_;
return ($self>tree_num_children_list)[0];
}
sub tree_num_children_maximum {
my ($self) = @_;
return ($self>tree_num_children_list)[1];
}
sub tree_any_leaf {
my ($self) = @_;
return ($self>tree_num_children_minimum == 0);
}
use constant tree_n_to_subheight => 0; # default all leaf node
use constant tree_n_to_depth => undef;
use constant tree_depth_to_n => undef;
sub tree_depth_to_n_end {
my ($self, $depth) = @_;
if ($depth >= 0
&& defined (my $n = $self>tree_depth_to_n($depth+1))) {
return $n1;
} else {
return undef;
}
}
sub tree_depth_to_n_range {
my ($self, $depth) = @_;
if (defined (my $n = $self>tree_depth_to_n($depth))
&& defined (my $n_end = $self>tree_depth_to_n_end($depth))) {
return ($n, $n_end);
}
return;
}
sub tree_depth_to_width {
my ($self, $depth) = @_;
if (defined (my $n = $self>tree_depth_to_n($depth))
&& defined (my $n_end = $self>tree_depth_to_n_end($depth))) {
return $n_end  $n + 1;
}
return undef;
}
sub tree_num_roots {
my ($self) = @_;
my @root_n_list = $self>tree_root_n_list;
return scalar(@root_n_list);
}
sub tree_root_n_list {
my ($self) = @_;
my $n_start = $self>n_start;
my @ret;
for (my $n = $n_start; ; $n++) {
# stop on finding a nonroot (has a parent), or a nontree path has no
# children at all
if (defined($self>tree_n_parent($n))
 ! $self>tree_n_num_children($n)) {
last;
}
push @ret, $n;
}
return @ret;
}
# Generic search upwards. Not fast, but works with past Toothpick or
# anything slack which doesn't have own tree_n_root(). When only one root
# there's no search.
sub tree_n_root {
my ($self, $n) = @_;
my $num_roots = $self>tree_num_roots;
if ($num_roots == 0) {
return undef; # not a tree
}
my $n_start = $self>n_start;
unless ($n >= $n_start) { # and warn if $n==undef
return undef; # inf or NaN
}
if ($num_roots == 1) {
return $n_start; # only one root, no search
}
for (;;) {
my $n_parent = $self>tree_n_parent($n);
if (! defined $n_parent) {
return $n; # found root
}
unless ($n_parent < $n) {
return undef; # +inf or something bad not making progress
}
$n = $n_parent;
}
}
# Generic search for where no more children.
# But must watch out for infinite lets, and might also watch out for
# rounding or overflow.
#
# sub path_tree_n_to_subheight {
# my ($path, $n) = @_;
# ### path_tree_n_to_subheight(): "$n"
#
# if (is_infinite($n)) {
# return $n;
# }
# my $max = $path>tree_n_to_depth($n) + 10;
# my @n = ($n);
# my $height = 0;
# do {
# @n = map {$path>tree_n_children($_)} @n
# or return $height;
# $height++;
# } while (@n && $height < $max);
#
# ### height infinite ...
# return undef;
# }
#
# shared internals
sub _max {
my $max = 0;
foreach my $i (1 .. $#_) {
if ($_[$i] > $_[$max]) {
$max = $i;
}
}
return $_[$max];
}
sub _min {
my $min = 0;
foreach my $i (1 .. $#_) {
if ($_[$i] < $_[$min]) {
$min = $i;
}
}
return $_[$min];
}
use Math::PlanePath::Base::Generic 'round_nearest';
sub _rect_for_first_quadrant {
my ($self, $x1,$y1, $x2,$y2) = @_;
$x1 = round_nearest($x1);
$y1 = round_nearest($y1);
$x2 = round_nearest($x2);
$y2 = round_nearest($y2);
($x1,$x2) = ($x2,$x1) if $x1 > $x2;
($y1,$y2) = ($y2,$y1) if $y1 > $y2;
if ($x2 < 0  $y2 < 0) {
return;
}
return ($x1,$y1, $x2,$y2);
}
# return ($quotient, $remainder)
sub _divrem {
my ($n, $d) = @_;
if (ref $n && $n>isa('Math::BigInt')) {
my ($quot,$rem) = $n>copy>bdiv($d);
if (! ref $d  $d < 1_000_000) {
$rem = $rem>numify; # plain remainder if fits
}
return ($quot, $rem);
}
my $rem = $n % $d;
return (int(($n$rem)/$d), # exact division stays in UV
$rem);
}
# return $remainder, modify $n
# the scalar $_[0] is modified, but if it's a BigInt then a new BigInt is made
# and stored there, the bigint value is not changed
sub _divrem_mutate {
my $d = $_[1];
my $rem;
if (ref $_[0] && $_[0]>isa('Math::BigInt')) {
($_[0], $rem) = $_[0]>copy>bdiv($d); # quot,rem in array context
if (! ref $d  $d < 1_000_000) {
return $rem>numify; # plain remainder if fits
}
} else {
$rem = $_[0] % $d;
$_[0] = int(($_[0]$rem)/$d); # exact division stays in UV
}
return $rem;
}
1;
__END__
=for stopwords PlanePath Ryde MathPlanePath MathPlanePathToothpick 7gonals 8gonal (step+2)gonal heptagonals octagonals bignum multiarm eg PerlMagick NaN NaNs subclasses incrementing arrayref hashref filename enum radix ie dX dY dX,dY Rsquared radix SUBCLASSING Ns onwards supremum radix radix1 octant dSum dDiffXY RSquared
=head1 NAME
Math::PlanePath  points on a path through the 2D plane
=head1 SYNOPSIS
use Math::PlanePath;
# only a base class, see the subclasses for actual operation
=head1 DESCRIPTION
This is a base class for some mathematical paths which map an integer
position C<$n> to and from coordinates C<$x,$y> in the 2D plane.
The current classes include the following. The intention is that any
C is a PlanePath, and supporting base classes or
related things are further down like C.
=for my_pod list begin
SquareSpiral foursided spiral
PyramidSpiral square base pyramid
TriangleSpiral equilateral triangle spiral
TriangleSpiralSkewed equilateral skewed for compactness
DiamondSpiral foursided spiral, looping faster
PentSpiral fivesided spiral
PentSpiralSkewed fivesided spiral, compact
HexSpiral sixsided spiral
HexSpiralSkewed sixsided spiral skewed for compactness
HeptSpiralSkewed sevensided spiral, compact
AnvilSpiral anvil shape
OctagramSpiral eight pointed star
KnightSpiral an infinite knight's tour
CretanLabyrinth 7circuit extended infinitely
SquareArms fourarm square spiral
DiamondArms fourarm diamond spiral
AztecDiamondRings foursided rings
HexArms sixarm 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
PeanoCurve 3x3 selfsimilar quadrant
WunderlichSerpentine transpose parts of PeanoCurve
HilbertCurve 2x2 selfsimilar quadrant
HilbertSpiral 2x2 selfsimilar wholeplane
ZOrderCurve replicating Z shapes
GrayCode Gray code splits
WunderlichMeander 3x3 "R" pattern quadrant
BetaOmega 2x2 selfsimilar halfplane
AR2W2Curve 2x2 selfsimilar of four parts
KochelCurve 3x3 selfsimilar of two parts
DekkingCurve 5x5 selfsimilar, edges
DekkingCentres 5x5 selfsimilar, centres
CincoCurve 5x5 selfsimilar
ImaginaryBase replicate in four directions
ImaginaryHalf halfplane replicate three directions
CubicBase replicate in three directions
SquareReplicate 3x3 replicating squares
CornerReplicate 2x2 replicating "U"
LTiling selfsimlar L shapes
DigitGroups digits grouped by zeros
FibonacciWordFractal turns by Fibonacci word bits
Flowsnake selfsimilar hexagonal tile traversal
FlowsnakeCentres likewise but centres of hexagons
GosperReplicate selfsimilar hexagonal tiling
GosperIslands concentric island rings
GosperSide single side or radial
QuintetCurve selfsimilar "+" traversal
QuintetCentres likewise but centres of squares
QuintetReplicate selfsimilar "+" 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
R5DragonCurve radix5 dragon curve
R5DragonMidpoint radix5 dragon curve midpoints
CCurve "C" curve
ComplexPlus base i+realpart
ComplexMinus base irealpart, including twindragon
ComplexRevolving revolving base i+1
SierpinskiCurve selfsimilar righttriangles
SierpinskiCurveStair selfsimilar righttriangles, stairstep
HIndexing selfsimilar righttriangles, squared up
KochCurve replicating triangular notches
KochPeaks two replicating notches
KochSnowflakes concentric notched 3sided rings
KochSquareflakes concentric notched 4sided rings
QuadricCurve eight segment zigzag
QuadricIslands rings of those zigzags
SierpinskiTriangle selfsimilar triangle by rows
SierpinskiArrowhead selfsimilar triangle connectedly
SierpinskiArrowheadCentres likewise but centres of triangles
Rows fixedwidth rows
Columns fixedheight 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 45degree 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 quarterplane
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 in the MathPlanePath sources for a sample
printout of numbers from selected paths or all paths.
=head2 Number Types
The C<$n> and C<$x,$y> parameters can be either integers or floating point.
The paths are meant to do something sensible with fractions but expect
roundingoff for big floating point exponents.
Floating point infinities (when available) give NaN or infinite returns of
some kind (some unspecified kind as yet). C on negative infinity
is an empty return, the same as other negative C<$n>.
Floating point NaNs (when available) give NaN, infinite, or empty/undef
returns, but again of some unspecified kind as yet.
Many 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 C of Perl 5.8 or higher for C<**>
exponentiation operator.
For reference, an C input as C<$n>, C<$x>, C<$y>, etc, is meant to
provoke an uninitialized value warning when warnings are enabled, but
currently it doesn't croak etc. Perhaps that will change, but the warning
at least prevents bad inputs going unnoticed.
=head1 FUNCTIONS
In the following C is one of the various subclasses, see the list above
and under L.
=head2 Constructor
=over 4
=item C<$path = Math::PlanePath::FooEnew (key=Evalue, ...)>
Create and return a new path object. Optional key/value parameters may
control aspects of the object.
=back
=head2 Coordinate Methods
=over
=item C<($x,$y) = $pathEn_to_xy ($n)>
Return X,Y coordinates of point C<$n> on the path. If there's no point
C<$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 C<$pathEn_start()> below, though some will give a
position for N=0 or N=0.5 too.
=item C<($dx,$dy) = $pathEn_to_dxdy ($n)>
Return the change in X and Y going from point C<$n> to point C<$n+1>, or for
paths with multiple arms from C<$n> to C<$n+$arms_count> (thus advancing one
point along the arm of C<$n>).
+ $n+1 == $next_x,$next_y
^

 $dx = $next_x  $x
+ $n == $x,$y $dy = $next_y  $y
C<$n> can be fractional and in that case the dX,dY is from that fractional
C<$n> position to C<$n+1> (or C<$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 C is the difference C<$dx=$next_x$x,
$dy=$next_y$y>. Currently for most paths it's merely two C
calls to calculate the two points, but some paths can calculate a dX,dY with
a little less work.
=item C<$rsquared = $pathEn_to_radius ($n)>
=item C<$rsquared = $pathEn_to_rsquared ($n)>
Return the radial distance R=sqrt(X^2+Y^2) of point C<$n>, or the radius
squared R^2=X^2+Y^2. If there's no point C<$n> then the return is C.
For a few paths these might be calculated with less work than C.
For example the C is simply R^2=N, or the C path
with its default step=6 has an integer radius for integer C<$n> whereas
C<$x,$y> are fractional (and so inexact).
=item C<$n = $pathExy_to_n ($x,$y)>
Return the N point number at coordinates C<$x,$y>. If there's nothing at
C<$x,$y> then return C.
my $n = $path>xy_to_n(20,20);
if (! defined $n) {
next; # nothing at this X,Y
}
C<$x> and C<$y> can be fractional and the path classes will give an integer
C<$n> which contains C<$x,$y> within a unit square, circle, or intended
figure centred on the integer C<$n>.
For paths which completely fill the plane there's always an C<$n> to return,
but for the spreadout paths an C<$x,$y> position may fall in between (no
C<$n> close enough) and give C.
=item C<@n_list = $pathExy_to_n_list ($x,$y)>
Return a list of N point numbers at coordinates C<$x,$y>. If there's
nothing at C<$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
C and C have multiple N's and this method
returns all of them.
=item C<$bool = $pathExy_is_visited ($x,$y)>
Return true if C<$x,$y> is visited. This is equivalent to
defined($path>xy_to_n($x,$y))
Some paths cover the plane and for them C is always true.
For others it might be less work to test a point than to calculate its
C<$n>.
=item C<($n_lo, $n_hi) = $pathErect_to_n_range ($x1,$y1, $x2,$y2)>
Return a range of N values covering or exceeding a rectangle with corners at
C<$x1>,C<$y1> and C<$x2>,C<$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 overestimate 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 C<$n_lo> and C<$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.
C<$n_hi> is usually no more than an extra partial row, revolution, or
selfsimilar level. C<$n_lo> might be merely the starting
C<$pathEn_start()>, which is fine if the origin is in the desired
rectangle but away from the origin might actually start higher.
C<$x1>,C<$y1> and C<$x2>,C<$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 C<$n_lo=1>, C<$n_hi=0> (which makes a C do no loops).
But C may not always notice there's no points in the
rectangle and might instead return some overestimate.
=back
=head2 Descriptive Methods
=over
=item C<$n = $pathEn_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
C parameter to control the numbering.
Some classes have secret dubious undocumented support for N values below
this start (zero or negative), but C is the intended starting
point.
=item C<$f = $pathEn_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 C<$f> is 0.5. Or C<$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 C. 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.
=item C<$arms = $pathEarms_count()>
Return the number of arms in a "multiarm" path.
For example in C this is 4 and each arm increments in turn, so
the first arm is N=1,5,9,13,etc starting from C<$pathEn_start()> and
incrementing by 4 each time.
=item C<$bool = $pathEx_negative()>
=item C<$bool = $pathEy_negative()>
Return true if the path extends into negative X coordinates and/or negative
Y coordinates respectively.
=item C<$bool = Math::PlanePath::FooEclass_x_negative()>
=item C<$bool = Math::PlanePath::FooEclass_y_negative()>
=item C<$bool = $pathEclass_x_negative()>
=item C<$bool = $pathEclass_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.
=item C<$n = $pathEx_negative_at_n()>
=item C<$n = $pathEy_negative_at_n()>
Return the integer N where X or Y respectively first goes negative, or
return C if it does not go negative (C or
C respectively is false).
=item C<$x = $pathEx_minimum()>
=item C<$y = $pathEy_minimum()>
=item C<$x = $pathEx_maximum()>
=item C<$y = $pathEy_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 C.
=item C<$dx = $pathEdx_minimum()>
=item C<$dx = $pathEdx_maximum()>
=item C<$dy = $pathEdy_minimum()>
=item C<$dy = $pathEdy_maximum()>
Return the minimum or maximum change dX, dY occurring in the path for
integer N to N+1. For a multiarm path the change is N to N+arms so it's
the change along the same arm.
Various paths which go by rows have nondecreasing Y. For them
C is 0.
=cut
# =item C<@dxdy_list = $pathEdxdy_list()>
#
# If C<$path> has a finite set of dX,dY steps then return them as a list.
# If C<$path> has an infinite set of dX,dY steps then return an empty list.
#
# $dx1,$dy1, $dx2,$dy2, $dx3,$dy3, ...
#
# The points are returned in order of angle around starting from East
# (dXE0,dY=0), and by increasing length among those of the same angle. If
# dX=0,dY=0 occurs (which it doesn't in any current path) then that would be
# first in the return list.
=pod
=item C<$adx = $pathEabsdx_minimum()>
=item C<$adx = $pathEabsdx_maximum()>
=item C<$ady = $pathEabsdy_minimum()>
=item C<$ady = $pathEabsdy_maximum()>
Return the minimum or maximum change abs(dX) or abs(dY) occurring in the
path for integer N to N+1. For a multiarm path the change is N to N+arms
so it's the change along the same arm.
C is simply max(dXmax,dXmin), the biggest change either
positive or negative. C similarly.
C is 0 if dX=0 occurs anywhere in the path, which means any
vertical step. If X always changes then C will be
something bigger than 0. C likewise 0 if any horizontal
dY=0, or bigger if Y always changes.
=item C<$sum = $pathEsumxy_minimum()>
=item C<$sum = $pathEsumxy_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
C.
S=X+Y is an antidiagonal. A path which is always right and above some
antidiagonal 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
=item C<$sum = $pathEsumabsxy_minimum()>
=item C<$sum = $pathEsumabsxy_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 C.
SumAbs=abs(X)+abs(Y) is sometimes called the "taxicab" or "Manhatten"
distance, being how far to travel through a squaregrid city to get to X,Y.
C is then how close to the origin the path extends.
SumAbs can also be interpreted geometrically as numbering the antidiagonals
of the quadrant containing X,Y, which is equivalent to asking which diamond
shape X,Y falls on. C is then the smallest such diamond
reached by the path.

/\ SumAbs = which diamond X,Y falls on
/  \
/  \
o
\  /
\  /
\/

=item C<$diffxy = $pathEdiffxy_minimum()>
=item C<$diffxy = $pathEdiffxy_maximum()>
Return the minimum or maximum values taken by coordinate difference XY
reached by integer N values in the path. If there's no minimum or maximum
then return C.
D=XY is a leading diagonal. A path which is always right and below such a
diagonal has a minimum, for example C. A path which is always
left and above some diagonal has a maximum D=XY. For example various
wedgelike paths such as C in its default step=2, and "upper
octant" paths have a maximum.
/ D=XY
Path always below  /
has maximum D=XY /
o
/
/  Path always above
/ has minimum D=XY
=item C<$absdiffxy = $pathEabsdiffxy_minimum()>
=item C<$absdiffxy = $pathEabsdiffxy_maximum()>
Return the minimum or maximum values taken by abs(XY) for integer N in the
path. The minimum is 0 or more. If there's maximum then return C.
abs(XY) can be interpreted geometrically as the distance away from the X=Y
diagonal and measured at rightangles to that line.
d=abs(XY) X=Y line
^ /
\ /
\/
/\
/ \
/ \
o v
/ d=abs(XY)
Paths which visit the X=Y line (or approach it as an infimum) have
C. Otherwise C is how close
they come to the line.
If the path is entirely below the X=Y line so XE=Y then XY>=0 and
C is the same as C. If the path is
entirely below the X=Y line then C is
S>.
=item C<$dsumxy = $pathEdsumxy_minimum()>
=item C<$dsumxy = $pathEdsumxy_maximum()>
=item C<$ddiffxy = $pathEddiffxy_minimum()>
=item C<$ddiffxy = $pathEddiffxy_maximum()>
Return the minimum or maximum change dSum or dDiffXY occurring in the path
for integer N to N+1. For a multiarm path the change is N to N+arms so
it's the change along the same arm.
=item C<$rsquared = $pathErsquared_minimum()>
=item C<$rsquared = $pathErsquared_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 C.
Rsquared is always E= 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. C returns C in that case.
=cut
# =item C<$gcd = $pathEgcdxy_minimum()>
#
# =item C<$gcd = $pathEgcdxy_maximum()>
#
# Return the minimum or maximum GCD(X,Y) reached by integer N values in the
# path. If there's no minimum or maximum then return C.
#
# C is always 0 or more since the sign of X and Y is ignored
# for taking the GCD. GCD(0,0)=0 is the only GCD=0. X!=0 or Y!=0 gives
# GCD(X,Y)E0. So the minimum is 0 if X=0,Y=0 is visited and E0 if
# not.
#
# C is usually C since there's no limit to the GCD.
# Paths such as C where X,Y have no common factor have
# C returning 1.
=pod
=item C<($dx,$dy) = $pathEdir_minimum_dxdy()>
=item C<($dx,$dy) = $pathEdir_maximum_dxdy()>
Return a vector which is the minimum or maximum angle taken by a step
integer N to N+1, or for a multiarm path N to N+arms so it's the change
along the same arm. Directions are reckoned anticlockwise 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 C 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
C goes in 2x1 steps and so has minimum EastNorthEast
dX=2,dY=1 and maximum EastSouthEast dX=2,dY=1.
If the path has directions approaching 360 degrees then
C is 0,0 which should be taken to mean a full circle as
a supremum. For example C.
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 C path height=0.
=item C<$str = $pathEfigure()>
Return a string name of the figure (shape) intended to be drawn at each
C<$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.
=back
=head2 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 breadthfirst style and some have children with
X,Y positions adjacent to their parent, but that shouldn't be assumed, only
that there's a parentchild relation down from some set of root nodes.
=over
=item C<$bool = $pathEis_tree()>
Return true if C<$path> is a tree.
The various tree methods have empty or C returns on nontree paths.
Often it's enough to check for that from a desired method rather than a
separate C check.
=item C<@n_children = $pathEtree_n_children($n)>
Return a list of N values which are the child nodes of C<$n>, or return an
empty list if C<$n> has no children.
There could be no children either because C<$path> is not a tree or because
there's no children at a particular C<$n>.
=item C<$num = $pathEtree_n_num_children($n)>
Return the number of children of C<$n>, or 0 if C<$n> has no children, or
C if S n_start()>> (ie. before the start of the path).
If the tree is considered as a directed graph then this is the "outdegree"
of C<$n>.
=item C<$n_parent = $pathEtree_n_parent($n)>
Return the parent node of C<$n>, or C if it has no parent.
There is no parent at the root node of the tree, or one of multiple roots,
or if C<$path> is not a tree.
=item C<$n_root = $pathEtree_n_root ($n)>
Return the N which is the root node of C<$n>. This is the top of the tree
as would be found by following C repeatedly.
The return is C if there's no C<$n> point or if C<$path> is not a
tree.
=item C<$depth = $pathEtree_n_to_depth($n)>
Return the depth of node C<$n>, or C if there's no point C<$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
C<$n>, ie. until reaching C returning C. For
nontree paths C is always C and
C is always 0.
=item C<$n_lo = $pathEtree_depth_to_n($depth)>
=item C<$n_hi = $pathEtree_depth_to_n_end($depth)>
=item C<($n_lo, $n_hi) = $pathEtree_depth_to_n_range ($depth)>
Return the first or last N, or both those N, for tree level C<$depth> in the
path. If there's no such C<$depth> or if C<$path> is not a tree then return
C, or for C return an empty list.
The points C<$n_lo> through C<$n_hi> might not necessarily all be at
C<$depth>. It's possible for depths to be interleaved or intermixed in the
point numbering. But many paths are breadthwise successive rows and for
them C<$n_lo> to C<$n_hi> inclusive is all C<$depth>.
C<$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
C<$n_hi> as C or some such if there is no maximum N for some row.
=item C<$num = $pathEtree_depth_to_width ($depth)>
Return the number of points at C<$depth> in the tree. If there's no such
C<$depth> or C<$path> is not a tree then return C.
=item C<$height = $pathEtree_n_to_subheight($n)>
Return the height of the subtree starting at C<$n>, or C 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
subheight there is C for infinite. For N=2 the subheight 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 subheight is 0.
=back
=head2 Tree Descriptive Methods
=over
=item C<$num = $pathEtree_num_roots()>
Return the number of root nodes in C<$path>. If C<$path> is not a tree then
return 0. Many tree paths have a single root and for them the return is 1.
=item C<@n_list = $pathEtree_root_n_list()>
Return a list of the N values which are the root nodes in C<$path>. If
C<$path> is not a tree then this is an empty list. There are
C many return values.
=item C<$num = $pathEtree_num_children_minimum()>
=item C<$num = $pathEtree_num_children_maximum()>
=item C<@nums = $pathEtree_num_children_list()>
Return the possible number of children of the nodes of C<$path>, either the
minimum, the maximum, or a list of all possible numbers of children.
For C the list of values is in increasing order,
so the first value is C and the last is
C.
=item C<$bool = $pathEtree_any_leaf()>
Return true if there are any leaf nodes in the tree, meaning any N for which
C is 0.
This is the same as C 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 C every node always has 2 children.
=back
=head2 Parameter Methods
=over
=item C<$aref = Math::PlanePath::FooEparameter_info_array()>
=item C<@list = Math::PlanePath::FooEparameter_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
description => human readable string
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
}
C 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 C field is the possible values, such as
{ name => "flavour",
type => "enum",
choices => ["strawberry","chocolate"],
}
C and/or C are omitted if there's no hard limit on the
parameter.
C is designed to indicate when parameters from different
C classes can done by a single control widget in a GUI etc.
Normally the C is enough, but when the same name has slightly
different meanings in different classes a C allows the same
meanings to be matched up.
=item C<$hashref = Math::PlanePath::FooEparameter_info_hash()>
Return a hashref mapping parameter names C<$infoE{'name'}> to their
C<$info> records.
{ wider => { name => "wider",
type => "integer",
...
},
}
=back
=head1 GENERAL CHARACTERISTICS
The classes are mostly based on integer C<$n> positions and those designed
for a square grid turn an integer C<$n> into integer C<$x,$y>. Usually they
give inbetween positions for fractional C<$n> too. Classes not on a square
grid but instead giving fractional X,Y such as C and
C are designed for a unit circle at each C<$n> but they too can
give inbetween positions on request.
All X,Y positions are calculated by separate C calls. To follow
a path use successive C<$n> values starting from C<$pathEn_start()>.
foreach my $n ($path>n_start .. 100) {
my ($x,$y) = $path>n_to_xy($n);
print "$n $x,$y\n";
}
The separate C 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
C to break N into a segment and offset, but the selfsimilar 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 C by rows or similar across
the desired region.
L etc offer the PlanePath coordinates,
directions, turns, etc as sequences. The iterator forms there simply make
repeated calls to C etc.
=head2 Scaling and Orientation
The paths generally make a first move to the right and go anticlockwise
around from the X axis, unless there's some more natural orientation.
Anticlockwise 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 (anticlockwise)
Y,X rotate 90 degrees (clockwise)
X,Y rotate 180 degrees
Flip vertically makes spirals go clockwise instead of anticlockwise, or a
flip horizontally the same but starting on the left at the negative X axis.
See L 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 L, and to rotate
as well see L.
=head2 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 C
is 8 more N points than the preceding.
=for my_pod step begin
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
5.65 PixelRings (average about 4*sqrt(2))
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 2wide 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
=for my_pod step end
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 7gonals (heptagonals)
are 5/2*k^23/2*k and make a straight line on the step=5 C. Or
the 8gonal octagonal numbers 6/2*k^24/2*k on the step=6 C.
There are various interesting properties of primes in quadratic
progressions. Some quadratics seem to have more primes than others. For
example see L. 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 L for a
factorization on the roots making a noprimes 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 C 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.
=head2 SelfSimilar Powers
The selfsimilar patterns such as C 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
C and C.
=for my_pod base begin
Base Path
 
2 HilbertCurve, HilbertSpiral, ZOrderCurve (default),
GrayCode (default), BetaOmega, AR2W2Curve,
SierpinskiCurve, HIndexing, SierpinskiCurveStair,
ImaginaryBase (default), ImaginaryHalf (default),
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
SierpinskiTriangle, SierpinskiArrowhead,
SierpinskiArrowheadCentres,
TerdragonCurve, TerdragonRounded, TerdragonMidpoint,
UlamWarburton, UlamWarburtonQuarter (each level)
4 KochCurve, KochPeaks, KochSnowflakes, KochSquareflakes,
LTiling,
5 QuintetCurve, QuintetCentres, QuintetReplicate,
DekkingCurve, DekkingCentres, CincoCurve,
R5DragonCurve, R5DragonMidpoint
7 Flowsnake, FlowsnakeCentres, GosperReplicate
8 QuadricCurve, QuadricIslands
9 SquareReplicate
Fibonacci FibonacciWordFractal, WythoffArray
parameter PeanoCurve, WunderlichSerpentine, ZOrderCurve, GrayCode,
ImaginaryBase, ImaginaryHalf, CubicBase, ComplexPlus,
ComplexMinus, DigitGroups, PowerArray
=for my_pod base end
Many number sequences plotted on these selfsimilar 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
L.
=head2 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 generalpurpose 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.
(X3Y)/2, (Y+X)/2 rotate +60 (anticlockwise)
(X+3Y)/2, (YX)/2 rotate 60 (clockwise)
(X+3Y)/2, (XY)/2 rotate +120
(3YX)/2, (X+Y)/2 rotate 120
X,Y rotate 180
(X+3Y)/2, (XY)/2 mirror across the X=3*Y twelfth line
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 C which is triangular points ordered by
this radial distance.
=head1 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.
=head2 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 (anticlockwise)
i+j, i rotate 60 (clockwise)
ij, i rotate +120
j, ij rotate 120
i, j rotate 180
Conversions between i,j and the rectangular X,Y are
X = 2*i + j i = (XY)/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 = (XY)/2 i = (X+Y)/2
Y = j + k j = Y or j = 0
k = 0 k = Y
=head2 N to dX,dY  Fractional
C 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
/  
/  
/  /
intNint+1
this_dX dX,dY next_dX
this_dY next_dY

frac 1frac
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 * (1frac) + next_dX * frac
dY = this_dY * (1frac) + 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.
=head2 N to dX,dY  SelfSimilar
For most of the selfsimilar paths such as C the change dX,dY
is determined by following the state table transitions down through either
all digits of N, or to the last non9 digit, ie. drop any low digits equal
to radix1.
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 non9. This can be
seen for example in the C using all digits, whereas its
C variant stops at the lowest non24.
Perhaps this alldigits vs lownon9 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.
=head1 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 C or C is easier than
the other but both should be implemented.
C 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.
C has a base implementation calling plain C to
give a single N at X,Y. If a path has multiple Ns at an X,Y
(eg. C) then it should implement C to return
all those Ns and also implement a plain C returning the first of
them.
C can initially be any convenient overestimate. 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 C starts at N=1. Paths which treat N as digits of some
radix or where there's selfsimilar replication are often best started from
N=0 instead since doing so puts nice powersof2 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 C
and/or C to false. For example if only the first
quadrant XE=0,YE=0 then
use constant class_x_negative => 0;
use constant class_y_negative => 0;
If negativeness varies with path parameters then C and/or
C follow those parameters and the C forms are
whether any set of parameters ever gives negative.
The following methods have base implementations calling C.
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()
n_to_radius() sqrt of n_to_rsquared()
C is an example of an easy C.
C 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
C.
The way C 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 L. 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 method has a base implementation calling C.
A subclass can implement is directly if it can be done more efficiently.
xy_is_visited() defined(xy_to_n($x,$y))
Paths such as C which fill the plane have C
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,
=over
=item C
Checks for C having nonzero C.
Usually this suffices, expecting C to be a root node and to have
some children.
=item C
Calls C and counts the number of return values. Many
trees can count the children with less work than calculating outright, for
example C is simply always 2 for NE=Nstart.
=item C
Calls C. This assumes that the depth level
ends where the next begins. This is true for the various breadthwise tree
traversals, but anything interleaved etc will need its own implementation.
=item C
Calls C and C. For some paths the
row start and end, or start and width, might be calculated together more
efficiently.
=item C
Returns C. This suits
breadthwise style paths where all points at C<$depth> are in a contiguous
block. Any path not like that will need its own C.
=item C, C
Return the first and last values of C as the
minimum and maximum.
=item C
Calls C. If the minimum C is 0
then there's leaf nodes.
=back
=head1 SEE ALSO
=for my_pod see_also begin
L