-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvegesvgplot.py
executable file
·3877 lines (2527 loc) · 101 KB
/
vegesvgplot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# vegesvgplot.py
# http://pastebin.com/6Aek3Exm
#-------------------------------------------------------------------------------
u'''VegeSVGPlot, a Python SVG plotting and maths module for vegetables
Description:
The VegeSVGPlot module is a collection of simple mathematics, geometry
and SVG output functions. The module makes it easy to write simple Python
scripts to produce 2D graphical output such as function plots.
Author:
Daniel Neville (Blancmange), [email protected]
Copyright:
None
Licence:
Public domain
INDEX
Imports
Shape constants:
Pt_Break
Pt_Anchor
Pt_Control
PtCmdWithCoordsSet
PtCmdSet
Legendre–Gauss quadrature tables:
LGQWeights25
LGQAbscissae25
Exceptions:
Error
tIndentTracker:
__init__([IndentUnitStr], [StartingLevel], [LineTerminator])
__call__(*StringArgs)
Clone()
StepIn([LevelIncrement])
StepOut([LevelDecrement])
LineTerminator
IndentUnitStr
Level
LIStr
tAffineMtx:
__init__(Origin, BasisVectors)
__repr__()
MultV(Vector)
MultVectors(Vectors)
MultAM(AM)
B
T
Affine matrix creation functions:
AffineMtxTS(Translation, Scale)
AffineMtxTRS2D(Translation, Angle, Scale)
Affine2DMatrices(Origin, X)
Utility functions:
ValidatedRange(ARange, Length)
MergedDictionary(Original, Patch)
Save(Data, FileName)
Array access functions:
ArrayDimensions(MDArray)
NewArray(Dimensions, Value)
CopyArray(Source, [CopyDepth])
At(MDArray, Indices)
SetAt(MDArray, Indices, Value)
EnumerateArray(MDArray, [Depth])
Basic vector functions:
VZeros(n)
VOnes(n)
VStdBasis(Dimensions, Index, [Scale])
VDim(A, n)
VAug(A, x)
VMajorAxis(A)
VNeg(A)
VSum(A, B...)
VDiff(A, B)
VSchur(A, B...)
VDot(A, B)
VLengthSquared(A)
VLength(A)
VManhattan(A)
VScaled(A, scale)
VNormalised(A)
VPerp(A)
VRevPerp(A)
VCrossProduct(A, B)
VCrossProduct4D(A, B, C)
VScalarTripleProduct(A, B, C)
VVectorTripleProduct(A, B, C)
VProjectionOnto(Axis, Vector)
VDiagonalMAV(Diagonals)
VTransposedMAV(BasisVectors)
VRectToPol(A)
VPolToRect(DistanceAngle)
VLerp(A, B, Progress)
Mathematical functions:
BinomialCoefficient(n, k)
BinomialRow(n)
NextBinomialRow(Row)
ApproxSaggita(ArcLength, ChordLength)
LGQIntegral25(Interval, Fn, InitalParams, FinalParams)
IntegralFunctionOfPLF(Vertices, C=0.0)
EvaluatePQF(PQF, x)
EvaluateInvPQF(PQF, y)
Linear intersection functions:
LineParameter(Point, Line)
XInterceptOfLine(Line)
UnitXToLineIntersection(Line2)
LineToLineIntersectionPoint(Line1, Line2)
LineToLineIntersection(Line1, Line2)
Bézier functions:
CubicBezierArcHandleLength(AngleSweep)
BezierPoint(Curve, t)
BezierPAT(Curve, t)
SplitBezier(Curve, t)
BezierDerivative(Curve)
ManhattanBezierDeviance(Curve)
BezierLength(Curve, [Interval])
Bézier intersection functions:
UnitXToBezierIntersections(Curve, [Tolerance])
LineToBezierIntersections(Line, Curve, [Tolerance])
Shape functions:
ShapeDim(Shape, n)
ShapeFromVertices(Vertices, Order)
ShapePoints(Shape, [Range])
ShapeSubpathRanges(Shape)
ShapeCurveRanges(Shape, [Range])
ShapeLength(Shape)
LineToShapeIntersections(Line, Shape, [Tolerance])
TransformedShape(AM, Shape)
PiecewiseArc(Centre, Radius, AngleRange, NumPieces)
Output formatting functions:
MaxDP(x, n)
GFListStr(L)
GFTupleStr(T)
HTMLEscaped(Text)
AttrMarkup(Attributes, PrependSpace)
ProgressColourStr(Progress, [Opacity])
SVG functions:
SVGStart(IT, Title, [SVGAttributes])
SVGEnd(IT)
SVGPathDataSegments(ShapePoints)
SVGPath(IT, ShapePoints, [Attributes])
SVGText(IT, Position, Text, [Attributes])
SVGGroup(IT, [Attributes])
SVGGroupEnd(IT)
SVGGrid(IT, Grid)
'''
#-------------------------------------------------------------------------------
# Imports
#-------------------------------------------------------------------------------
import math
from math import (
pi, sqrt, hypot, sin, cos, tan, asin, acos, atan, atan2, radians, degrees,
floor, ceil
)
#-------------------------------------------------------------------------------
# Shape constants
#
# A “Shape” is a list of (PointType, Point) pairs intended to represent paths
# in the matter of Postscript or SVG but in a way which allows a path segment
# to be very easily reversed.
#
#-------------------------------------------------------------------------------
Pt_Break = 0
Pt_Anchor = 1
Pt_Control = 2
PtCmdWithCoordsSet = set([Pt_Anchor, Pt_Control])
PtCmdSet = set([Pt_Break, Pt_Anchor, Pt_Control])
#-------------------------------------------------------------------------------
# Legendre–Gauss quadrature tables
#
# The following tables were adapted from Mike "Pomax" Kamermans’s tables,
# which were computed to 295 decimal places and given for orders up to 64.
#
#-------------------------------------------------------------------------------
# Legendre–Gauss quadrature weights for
# the 25th order Legendre polynomial
LGQWeights25 = [
0.1222424429903100416889595189458515058351, # −12
0.1222424429903100416889595189458515058351, # +12
0.1194557635357847722281781265129010473902, # −11
0.1194557635357847722281781265129010473902, # +11
0.1148582591457116483393255458695558086409, # −10
0.1148582591457116483393255458695558086409, # +10
0.1085196244742636531160939570501166193401, # −9
0.1085196244742636531160939570501166193401, # +9
0.1005359490670506442022068903926858269885, # −8
0.1005359490670506442022068903926858269885, # +8
0.0910282619829636498114972207028916533810, # −7
0.0910282619829636498114972207028916533810, # +7
0.0801407003350010180132349596691113022902, # −6
0.0801407003350010180132349596691113022902, # +6
0.0680383338123569172071871856567079685547, # −5
0.0680383338123569172071871856567079685547, # +5
0.0549046959758351919259368915404733241601, # −4
0.0549046959758351919259368915404733241601, # +4
0.0409391567013063126556234877116459536608, # −3
0.0409391567013063126556234877116459536608, # +3
0.0263549866150321372619018152952991449360, # −2
0.0263549866150321372619018152952991449360, # +2
0.0113937985010262879479029641132347736033, # −1
0.0113937985010262879479029641132347736033, # +1
0.1231760537267154512039028730790501424382 # 0
]
# Legendre–Gauss quadrature abscissae (x-values)
# for the 25th order Legendre polynomial
LGQAbscissae25 = [
-0.1228646926107103963873598188080368055322, # −12
0.1228646926107103963873598188080368055322, # +12
-0.2438668837209884320451903627974515864056, # −11
0.2438668837209884320451903627974515864056, # +11
-0.3611723058093878377358217301276406674221, # −10
0.3611723058093878377358217301276406674221, # +10
-0.4730027314457149605221821150091920413318, # −9
0.4730027314457149605221821150091920413318, # +9
-0.5776629302412229677236898416126540673957, # −8
0.5776629302412229677236898416126540673957, # +8
-0.6735663684734683644851206332476221758834, # −7
0.6735663684734683644851206332476221758834, # +7
-0.7592592630373576305772828652043609763875, # −6
0.7592592630373576305772828652043609763875, # +6
-0.8334426287608340014210211086935695694610, # −5
0.8334426287608340014210211086935695694610, # +5
-0.8949919978782753688510420067828049541746, # −4
0.8949919978782753688510420067828049541746, # +4
-0.9429745712289743394140111696584705319052, # −3
0.9429745712289743394140111696584705319052, # +3
-0.9766639214595175114983153864795940677454, # −2
0.9766639214595175114983153864795940677454, # +2
-0.9955569697904980979087849468939016172576, # −1
0.9955569697904980979087849468939016172576, # +1
0 # 0
]
#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class Error (Exception):
pass;
#-------------------------------------------------------------------------------
# tIndentTracker
#-------------------------------------------------------------------------------
class tIndentTracker (object):
u'''Keeper of current indentation levels for text output
Functions which output strings of nicely indented markup can be made
especially easy to use when an object like this keeps track of the
current indenting level and the caller’s preference for the character
or string used for indenting.
The default method returns indented and line-terminated text given one
or more string arguments, one argument per line of text. (Use the “*”
list or tuple unpacking operator to work with lists or tuples.)
For convenience when writing custom markup, the LIStr field may
be used to begin each line of output.
Functions which produce markup which imply a change in indentation
level should update both the Level and LIStr fields.
Methods:
__init__([IndentUnitStr], [StartingLevel], [LineTerminator])
__call__(*StringArgs)
Clone()
StepIn([LevelIncrement])
StepOut([LevelDecrement])
Fields:
IndentUnitStr
LineTerminator
Level
LIStr
'''
#-----------------------------------------------------------------------------
def __init__(self, IndentUnitStr=' ', StartingLevel=0, LineTerminator='\n'):
u'''Construct a keeper for the current indentation level for text output.
All three arguments are optional.
IndentUnitStr is the string used for each level of indentation.
This string is typically two spaces (to emulate the em-square of
typography), four spaces or a tab control character.
StartingLevel, which defaults to zero, sets the current indentation
level.
LineTerminator is the character or string appended to each string
argument supplied to the default method, a function which returns
indented and line-terminated text.
'''
self.IndentUnitStr = IndentUnitStr
self.LineTerminator = LineTerminator
self.Level = StartingLevel
self.LIStr = IndentUnitStr * StartingLevel
#-----------------------------------------------------------------------------
def __call__(self, *StringArgs):
u'''Return a block of text with lines indented and terminated.
Each argument is taken to be a line of text which is to be indented
at the current level and terminated with LineTerminator. If a list
or tuple of strings is to be processed, use the list or tuple unpacking
operator “*”.
'''
IndentedLines = []
for Line in StringArgs:
ILine = Line.rstrip()
if len(Line) > 0:
ILine = self.LIStr + ILine
IndentedLines.append(ILine)
Result = self.LineTerminator.join(IndentedLines) + self.LineTerminator
return Result
#-----------------------------------------------------------------------------
def Clone(self):
u'''Create a clone of this tIndentTracker instance.
A clone is handy for temporarily going into deeper nesting levels when
the supplied tIndentTracker instance must be treated as immutable.
'''
Result = tIndentTracker()
# Return an exact copy, even if it is internally inconsistent.
# The user probably knows what they’re doing.
Result.IndentUnitStr = self.IndentUnitStr
Result.LineTerminator = self.LineTerminator
Result.Level = self.StartingLevel
Result.LIStr = self.LIStr
return Result
#-----------------------------------------------------------------------------
def StepIn(self, LevelIncrement=1):
u'''Increase the indentation level.
The fields Level and the convenience string LIStr are updated.
'''
self.Level += LevelIncrement
self.LIStr = self.IndentUnitStr * max(0, self.Level)
#-----------------------------------------------------------------------------
def StepOut(self, LevelDecrement=1):
u'''Decrease the indentation level.
The fields Level and the convenience string LIStr are updated.
'''
self.Level -= LevelDecrement
self.LIStr = self.IndentUnitStr * max(0, self.Level)
#-----------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# tAffineMtx
#-------------------------------------------------------------------------------
class tAffineMtx (object):
u'''Affine matrix for transforming non-homogeneous vectors
An affine matrix is the usual square transformation matrix augmented
with a translation vector. Thus uniform and non-uniform scaling,
shearing, rotation and translation transformations can be combined
in any order. Using the convention that vectors are written as columns,
an affine matrix is like a homogeneous matrix without the bottom row and
is used to transform non-homogeneous vectors or other affine matrices.
Methods:
__init__(Origin, BasisVectors)
__repr__()
MultV(Vector)
MultVectors(Vectors)
MultAM(AM)
Fields:
B - Basis vectors (rotation, scaling, skewing)
T - Translation (Local origin)
'''
#-----------------------------------------------------------------------------
def __init__(self, Origin, BasisVectors):
u'''Construct an affine matrix.
The origin is loaded into the translation part and is measured in terms
of the reference frame outside the local frame constructed by the basis
vectors and the origin.
'''
self.B = tuple(tuple(Bi) for Bi in BasisVectors)
self.T = tuple(Origin)
#-----------------------------------------------------------------------------
def __repr__(self):
u'''Return a Python code string representation of this affine matrix.'''
Name = self.__class__.__name__
return Name + '(' + repr(self.T) + ', ' + repr(self.B) + ')'
#-----------------------------------------------------------------------------
def MultV(self, Vector):
u'''Return a vector transformed by this matrix.
The vector is permitted to have a number of dimensions that differ to
the number of basis vectors represented in the affine matrix. Excess
basis vectors or excess vector components are ignored.
If the vector is None or has a length of zero, the vector is returned
untransformed. This behaviour is convenient for processing Shapes, which
may include items like (Pt_Break, None).
'''
if (Vector is not None) and (len(Vector) > 0):
Result = self.T
for i, Basis in enumerate(self.B):
if i < len(Vector):
Result = VSum(Result, VScaled(Basis, Vector[i]))
else:
Result = Vector
return Result
#-----------------------------------------------------------------------------
def MultVectors(self, Vectors):
u'''Return a tuple of vectors transformed by this affine matrix.
The vectors are each permitted to have a number of dimensions
different to the number of basis vectors represented in the
affine matrix. Excess basis vectors or excess vector components
are ignored.
Any vector that is None or has a length of zero is appears in
the result untransformed.
'''
Result = []
for V in Vectors:
if (V is not None) and (len(V) > 0):
VPrime = self.T
for i, Basis in enumerate(self.B):
if i < len(V):
VPrime = VSum(VPrime, VScaled(Basis, V[i]))
else:
VPrime = V
Result.append(VPrime)
Result = tuple(Result)
return Result
#-----------------------------------------------------------------------------
def MultAM(self, AM):
u'''Return the product of this and a second affine matrix.
When the resulting affine matrix is applied to vertices, the effect is as
if the second matrix was applied first and the first matrix applied last.
From the point of view of nested transformed reference frames in the manner
of SVG and OpenGL, the transformations are nested in left-to-right order.
Considering the vectors to be transformed as column vectors, the nesting of
reference frames is performed by postmultiplying the current affine matrix
with successive (affine) transformation matrices. The composite matrix is
then premultiplied to each vector to be transformed.
'''
d = len(self.T)
dr = range(d)
B1t = VTransposedMAV(self.B)
T1 = self.T
B2 = AM.B
T2 = AM.T
BasisVectors = tuple(tuple(VDot(B1t[j], B2[i]) for j in dr) for i in dr)
Traslation = tuple(VDot(B1t[j], T2) + T1[j] for j in DimRange)
return tAffineMtx(Translation, BasisVectors)
#-----------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Affine matrix creation functions
#-------------------------------------------------------------------------------
def AffineMtxTS(Translation, Scale):
u'''Return an affine matrix given a translation and a scale.
When the tAffineMtx returned is applied to vertices, the translation
is performed last. From the point of view of transformed reference
frames in the manner of SVG and OpenGL, the translation is performed
first.
The dimension of the resulting affine matrix is made to match the
dimension of Translation, which defines a local origin relative to
the origin of the ambient frame.
If Scale is or contains only a single number, the scaling is uniform.
If Scale is a list or tuple, say, the scaling can be different for
each axis. Negative scales are permissible. Excess scale components
are ignored and unspecified scale components are assumed to be 1.0.
'''
#-----------------------------------------------------------------------------
d = len(Translation)
dr = range(d)
if hasattr(Scale, '__iter__'):
S = tuple(Scale)[:d]
S += (1.0,) * max(0, d - len(S))
else:
S = (Scale,) * d
BasisVectors = VDiagonalMAV(S)
return tAffineMtx(Translation, BasisVectors)
#-------------------------------------------------------------------------------
def AffineMtxTRS2D(Translation, Angle, Scale):
u'''Return an affine matrix given a translation, rotation angle and a scale.
Translation must be a vector of at least two dimensions, More dimensions
are permitted but the rotation is performed only in the plane of the first
two.
Angle is measured in radians from the +x axis to the +y axis of the ambient
frame.
The transformation is applied to vectors in the order scaling, rotation
and translation. From the point of view of nested reference frames in
the manner of OpenGL and SCG, the order of nested transformations is
translation, rotation and scaling.
'''
d = len(Translation)
AM = AffineMtxTS(Translation, Scale)
c = cos(Angle)
s = sin(Angle)
xs = AM.B[0][0]
ys = AM.B[1][1]
B = ((xs * c, xs * s), (ys * -s, ys * c))
return tAffineMtx(AM.T, B)
#-------------------------------------------------------------------------------
def Affine2DMatrices(Origin, X):
u'''Create matrices for mapping a line in 2D space to (0,0)–(1,0) and back.
The line’s endpoints lie at Origin and Origin + X. This function gives the
scale, rotation and translation necessary to map the line onto the x-axis
between 0 and 1, thus aiding quick intersection and rejection tests.
The result is in the form (M, InvM) where:
M is the affine matrix to transform points so Line maps to (0,0)–(1,0) and
InvM restores points from the UnitX frame back to the original frame.
If the vector X is too small, an overflow or a divide-by-zero exception
may be raised.
'''
Y = VPerp(X)
# The scale to use in forming the inverse matrix’s basis vectors is
# is the inverse square of the length of the X basis vector, not just
# the inverse length. This is because the lengths of the basis vectors
# of one matrix must be the reciprocals of those of the other.
# ‖(‖X‖⁻²X)‖ × ‖X‖ = 1.
s2 = 1.0 / VLengthSquared(X)
MX = (s2 * X[0], s2 * Y[0])
MY = (s2 * X[1], s2 * Y[1])
MT = (
-(MX[0] * Origin[0] + MY[0] * Origin[1]),
-(MX[1] * Origin[0] + MY[1] * Origin[1]),
)
M = tAffineMtx(MT, (MX, MY))
InvM = tAffineMtx(Origin, (X, Y))
return (M, InvM)
#-------------------------------------------------------------------------------
# Utility functions
#-------------------------------------------------------------------------------
def ValidatedRange(ARange, Length):
u'''Return a validated range for a given array length.
The validated range may have a span of zero and it may lie at the end of
a zero-based array (at an index of Length). It will, however, be sure to
not be reversed or include intervals beyond either end of the array.
if ARange is None, the range (0, Length) is returned. This behaviour
makes it convenient to use this function on optional range arguments.
'''
if ARange is None:
Start, End = (0, Length)
else:
Start, End = ARange
Start = min(Length, Start) if Start >= 0 else max(0, Length + Start)
End = min(Length, End) if End >= 0 else Length + End
End = max(Start, End)
return (Start, End)
#-------------------------------------------------------------------------------
def MergedDictionary(Original, Patch):
u'''Return the union of two Python dictionaries.
In the case of a key appearing in both dictionaries, Patch takes
precedence over Original.
For the convenience of easily providing defaults or immutable
attributes to HTML or SVG tags, either argument may be None.
In any case, the result is a (shallow) copy.
'''
if Original is not None:
if Patch is not None:
return dict(list(Original.items()) + list(Patch.items()))
else:
return dict(Original)
else:
if Patch is not None:
return dict(Patch)
else:
return dict()
#-------------------------------------------------------------------------------
def Save(Data, FileName):
u'''Save data to a new file.
Data is usually a string. If a file with the given name already exists,
it is overwritten.
If the string is a Unicode string, it should be encoded:
Save(Data.encode('utf_8'), FileName)
Encoding will fail if Data is a non-Unicode string which contains a
character outside of the 7-bit ASCII range. This can easily occur
when an ordinary byte string contains a Latin-1 character such as
the times symbol (“×”, code 215). Take care to prefix non-ASCII
string constants with “u”.
'''
f = open(FileName, 'wb')
try:
f.write(Data)
finally:
f.close()
#-------------------------------------------------------------------------------
# Array access functions
#-------------------------------------------------------------------------------
def ArrayDimensions(MDArray):
u'''Measure the size of the array in each dimension.
If the given array is three dimensional and indexed with subscripts
[0…5][0…7][0…2], the result will be (6, 8, 3).
The array, which in Python is really an array of arrays if it is
multidimensional, is assumed to be linear, rectangular, cuboid or
similarly regular for higher dimensions.
An empty array has a dimension of zero.
'''
Result = []
Axis = MDArray
while hasattr(Axis, '__iter__'):
Result.append(len(Axis))
if len(Axis) < 1:
break
Axis = Axis[0]
Result = tuple(Result)
return Result
#-------------------------------------------------------------------------------
def NewArray(Dimensions, Value):
u'''Return a new array of the given dimensions, filled with a given value.
Dimensions may either be a tuple or a list. When creating one-dimensional
arrays, remember that the tuple or list constructor is needed around a
bare integer and that the syntax for a one-element tuple has a comma to
distinguish a tuple from an parenthesised number.
NewArray((5,), 42) = [42, 42, 42, 42, 42]
'''
n = len(Dimensions)
if n < 2:
Result = [Value] * Dimensions[0]
else:
Result = []
for i in range(Dimensions[0]):
Result.append(NewArray(Dimensions[1:], Value))
return Result
#-------------------------------------------------------------------------------
def CopyArray(Source, CopyDepth=None):
u'''Create an arbitrarily deep copy of an array.
If CopyDepth is 0, the result is another reference to the same array,
not a copy. If CopyDepth is 1, a shallow copy is made. Higher values of
CopyDepth result in deeper copies. This allows one to create separately
mutable multidimensional arrays to refer to objects shared between them.
Negative values for CopyDepth work in the manner of negative slice
indices in python: A value of -1, for example, causes the entries of
the final dimension to be shared.
If CopyDepth is None (the default), the result will be a completely
distinct copy.
The behaviour of this function with CopyDepth set to None is subtly
different to that for negative values of CopyDepth. A value of -1
or lower causes the ArrayDimensions() function to be invoked. The
measurement then makes the assumption of the array being regular
important.
This function cannot be used with arrays which contain circular
references.
'''
#-----------------------------------------------------------------------------
def CopyArray_Recursive(Source, d):
if d == 0 or not hasattr(Source, '__iter__'):
Result = Source
elif d == 1:
Result = [x for x in Source]
else:
Result = [CopyArray_Recursive(x, d - 1) for x in Source]
return Result
#-----------------------------------------------------------------------------
if CopyDepth is None:
d = -1
else:
d = CopyDepth
if d < 0:
d = max(0, len(ArrayDimensions(Source)) + d)
return CopyArray_Recursive(Source, d)
#-------------------------------------------------------------------------------
def At(MDArray, Indices):
u'''Return an array element of the given indices.
An array element that would be accessed as A[3][1][0], say, can
be accessed as At(A, (3, 1, 0)) or as At(A, X) where X = (3, 1, 0).
This is handy for writing code that is agnostic in regard to the
number of dimensions being used.
Remember that Indices must be a tuple, a list or something similar
and that the Python syntax for a single-element tuple is “(x,)”.
'''
Result = MDArray
for i in Indices:
Result = Result[i]
return Result
#-------------------------------------------------------------------------------
def SetAt(MDArray, Indices, Value):
u'''Set an array element at the given indices.
An array element that would be set with the statement A[1][5][2] = x,
say, can be set with SetAt(A, Pos, x) where Pos is (1, 5, 2).
Remember that Indices must be a tuple, a list or something similar
and that the Python syntax for a single-element tuple is “(x,)”.
'''
Target = MDArray
for i in Indices[:-1]:
Target = Target[i]
Target[Indices[-1]] = Value
#-------------------------------------------------------------------------------
def EnumerateArray(MDArray, Depth=None):
u'''Enumerate the indices and the elements of a multidimensional array.
The result is a generator which can be used in the following manner:
for Pos, Element in EnumerateArray(MDArray):
...
Pos is a tuple of the indices required to access the array using At
(reading) or SetAt (writing). Element is already set to At(MDArray, Pos).
Depth, an optional argument in the constructor, allows the traversal
to be restricted to the major dimensions. In the manner of Python
array indices, Depth may be given a negative value.
A value of -1 for Depth causes all but the last dimension to be
traversed. This can be handy for efficiently updating the contents
of a multidimensional array. If Depth is zero, the enumeration yields
nothing.
'''
Dim = ArrayDimensions(MDArray)
if Depth is None:
d = len(Dim)
else:
d = Depth
if d < 0:
d += len(Dim)
Dim = Dim[:d]