-
Notifications
You must be signed in to change notification settings - Fork 0
/
svgfig.py
3678 lines (2979 loc) · 148 KB
/
svgfig.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
# svgfig.py copyright (C) 2008 Jim Pivarski <[email protected]>
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
# Full licence is in the file COPYING and at http://www.gnu.org/copyleft/gpl.html
import re, codecs, os, platform, copy, itertools, math, cmath, random, sys, copy
_epsilon = 1e-5
if sys.version_info >= (3,0):
long = int
basestring = (str,bytes)
# Fix Python 2.x.
try:
UNICODE_EXISTS = bool(type(unicode))
except NameError:
unicode = lambda s: str(s)
if re.search("windows", platform.system(), re.I):
try:
import _winreg
_default_directory = _winreg.QueryValueEx(_winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\Current Version\Explorer\Shell Folders"), "Desktop")[0]
# tmpdir = _winreg.QueryValueEx(_winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Environment"), "TEMP")[0]
# if tmpdir[0:13] != "%USERPROFILE%":
# tmpdir = os.path.expanduser("~") + tmpdir[13:]
except:
_default_directory = os.path.expanduser("~") + os.sep + "Desktop"
_default_fileName = "tmp.svg"
_hacks = {}
_hacks["inkscape-text-vertical-shift"] = False
def rgb(r, g, b, maximum=1.):
"""Create an SVG color string "#xxyyzz" from r, g, and b.
r,g,b = 0 is black and r,g,b = maximum is white.
"""
return "#%02x%02x%02x" % (max(0, min(r*255./maximum, 255)),
max(0, min(g*255./maximum, 255)),
max(0, min(b*255./maximum, 255)))
def attr_preprocess(attr):
attrCopy = attr.copy()
for name in attr.keys():
name_colon = re.sub("__", ":", name)
if name_colon != name:
attrCopy[name_colon] = attrCopy[name]
del attrCopy[name]
name = name_colon
name_dash = re.sub("_", "-", name)
if name_dash != name:
attrCopy[name_dash] = attrCopy[name]
del attrCopy[name]
name = name_dash
return attrCopy
class SVG:
"""A tree representation of an SVG image or image fragment.
SVG(t, sub, sub, sub..., attribute=value)
t required SVG type name
sub optional list nested SVG elements or text/Unicode
attribute=value pairs optional keywords SVG attributes
In attribute names, "__" becomes ":" and "_" becomes "-".
SVG in XML
<g id="mygroup" fill="blue">
<rect x="1" y="1" width="2" height="2" />
<rect x="3" y="3" width="2" height="2" />
</g>
SVG in Python
>>> svg = SVG("g", SVG("rect", x=1, y=1, width=2, height=2), \
... SVG("rect", x=3, y=3, width=2, height=2), \
... id="mygroup", fill="blue")
Sub-elements and attributes may be accessed through tree-indexing:
>>> svg = SVG("text", SVG("tspan", "hello there"), stroke="none", fill="black")
>>> svg[0]
<tspan (1 sub) />
>>> svg[0, 0]
'hello there'
>>> svg["fill"]
'black'
Iteration is depth-first:
>>> svg = SVG("g", SVG("g", SVG("line", x1=0, y1=0, x2=1, y2=1)), \
... SVG("text", SVG("tspan", "hello again")))
...
>>> for ti, s in svg:
... print ti, repr(s)
...
(0,) <g (1 sub) />
(0, 0) <line x2=1 y1=0 x1=0 y2=1 />
(0, 0, 'x2') 1
(0, 0, 'y1') 0
(0, 0, 'x1') 0
(0, 0, 'y2') 1
(1,) <text (1 sub) />
(1, 0) <tspan (1 sub) />
(1, 0, 0) 'hello again'
Use "print" to navigate:
>>> print svg
None <g (2 sub) />
[0] <g (1 sub) />
[0, 0] <line x2=1 y1=0 x1=0 y2=1 />
[1] <text (1 sub) />
[1, 0] <tspan (1 sub) />
"""
def __init__(self, *t_sub, **attr):
if len(t_sub) == 0:
raise TypeError( "SVG element must have a t (SVG type)")
# first argument is t (SVG type)
self.t = t_sub[0]
# the rest are sub-elements
self.sub = list(t_sub[1:])
# keyword arguments are attributes
# need to preprocess to handle differences between SVG and Python syntax
self.attr = attr_preprocess(attr)
def __getitem__(self, ti):
"""Index is a list that descends tree, returning a sub-element if
it ends with a number and an attribute if it ends with a string."""
obj = self
if isinstance(ti, (list, tuple)):
for i in ti[:-1]:
obj = obj[i]
ti = ti[-1]
if isinstance(ti, (int, long, slice)):
return obj.sub[ti]
else:
return obj.attr[ti]
def __setitem__(self, ti, value):
"""Index is a list that descends tree, returning a sub-element if
it ends with a number and an attribute if it ends with a string."""
obj = self
if isinstance(ti, (list, tuple)):
for i in ti[:-1]:
obj = obj[i]
ti = ti[-1]
if isinstance(ti, (int, long, slice)):
obj.sub[ti] = value
else:
obj.attr[ti] = value
def __delitem__(self, ti):
"""Index is a list that descends tree, returning a sub-element if
it ends with a number and an attribute if it ends with a string."""
obj = self
if isinstance(ti, (list, tuple)):
for i in ti[:-1]:
obj = obj[i]
ti = ti[-1]
if isinstance(ti, (int, long, slice)):
del obj.sub[ti]
else:
del obj.attr[ti]
def __contains__(self, value):
"""x in svg == True iff x is an attribute in svg."""
return value in self.attr
def __eq__(self, other):
"""x == y iff x represents the same SVG as y."""
if id(self) == id(other):
return True
return (isinstance(other, SVG) and
self.t == other.t and self.sub == other.sub and self.attr == other.attr)
def __ne__(self, other):
"""x != y iff x does not represent the same SVG as y."""
return not (self == other)
def append(self, x):
"""Appends x to the list of sub-elements (drawn last, overlaps
other primitives)."""
self.sub.append(x)
def prepend(self, x):
"""Prepends x to the list of sub-elements (drawn first may be
overlapped by other primitives)."""
self.sub[0:0] = [x]
def extend(self, x):
"""Extends list of sub-elements by a list x."""
self.sub.extend(x)
def clone(self, shallow=False):
"""Deep copy of SVG tree. Set shallow=True for a shallow copy."""
if shallow:
return copy.copy(self)
else:
return copy.deepcopy(self)
### nested class
class SVGDepthIterator:
"""Manages SVG iteration."""
def __init__(self, svg, ti, depth_limit):
self.svg = svg
self.ti = ti
self.shown = False
self.depth_limit = depth_limit
def __iter__(self):
return self
def next(self):
if not self.shown:
self.shown = True
if self.ti != ():
return self.ti, self.svg
if not isinstance(self.svg, SVG):
raise StopIteration
if self.depth_limit is not None and len(self.ti) >= self.depth_limit:
raise StopIteration
if "iterators" not in self.__dict__:
self.iterators = []
for i, s in enumerate(self.svg.sub):
self.iterators.append(self.__class__(s, self.ti + (i,), self.depth_limit))
for k, s in self.svg.attr.items():
self.iterators.append(self.__class__(s, self.ti + (k,), self.depth_limit))
self.iterators = itertools.chain(*self.iterators)
return self.iterators.next()
### end nested class
def depth_first(self, depth_limit=None):
"""Returns a depth-first generator over the SVG. If depth_limit
is a number, stop recursion at that depth."""
return self.SVGDepthIterator(self, (), depth_limit)
def breadth_first(self, depth_limit=None):
"""Not implemented yet. Any ideas on how to do it?
Returns a breadth-first generator over the SVG. If depth_limit
is a number, stop recursion at that depth."""
raise NotImplementedError( "Got an algorithm for breadth-first searching a tree without effectively copying the tree?")
def __iter__(self):
return self.depth_first()
def items(self, sub=True, attr=True, text=True):
"""Get a recursively-generated list of tree-index, sub-element/attribute pairs.
If sub == False, do not show sub-elements.
If attr == False, do not show attributes.
If text == False, do not show text/Unicode sub-elements.
"""
output = []
for ti, s in self:
show = False
if isinstance(ti[-1], (int, long)):
if isinstance(s, basestring):
show = text
else:
show = sub
else:
show = attr
if show:
output.append((ti, s))
return output
def keys(self, sub=True, attr=True, text=True):
"""Get a recursively-generated list of tree-indexes.
If sub == False, do not show sub-elements.
If attr == False, do not show attributes.
If text == False, do not show text/Unicode sub-elements.
"""
return [ti for ti, s in self.items(sub, attr, text)]
def values(self, sub=True, attr=True, text=True):
"""Get a recursively-generated list of sub-elements and attributes.
If sub == False, do not show sub-elements.
If attr == False, do not show attributes.
If text == False, do not show text/Unicode sub-elements.
"""
return [s for ti, s in self.items(sub, attr, text)]
def __repr__(self):
return self.xml(depth_limit=0)
def __str__(self):
"""Print (actually, return a string of) the tree in a form useful for browsing."""
return self.tree(sub=True, attr=False, text=False)
def tree(self, depth_limit=None, sub=True, attr=True, text=True, tree_width=20, obj_width=80):
"""Print (actually, return a string of) the tree in a form useful for browsing.
If depth_limit == a number, stop recursion at that depth.
If sub == False, do not show sub-elements.
If attr == False, do not show attributes.
If text == False, do not show text/Unicode sub-elements.
tree_width is the number of characters reserved for printing tree indexes.
obj_width is the number of characters reserved for printing sub-elements/attributes.
"""
output = []
line = "%s %s" % (("%%-%ds" % tree_width) % repr(None),
("%%-%ds" % obj_width) % (repr(self))[0:obj_width])
output.append(line)
for ti, s in self.depth_first(depth_limit):
show = False
if isinstance(ti[-1], (int, long)):
if isinstance(s, basestring):
show = text
else:
show = sub
else:
show = attr
if show:
line = "%s %s" % (("%%-%ds" % tree_width) % repr(list(ti)),
("%%-%ds" % obj_width) % (" "*len(ti) + repr(s))[0:obj_width])
output.append(line)
return "\n".join(output)
def xml(self, indent=u" ", newl=u"\n", depth_limit=None, depth=0):
"""Get an XML representation of the SVG.
indent string used for indenting
newl string used for newlines
If depth_limit == a number, stop recursion at that depth.
depth starting depth (not useful for users)
print svg.xml()
"""
attrstr = []
for n, v in self.attr.items():
if isinstance(v, dict):
v = u"; ".join([u"%s:%s" % (ni, vi) for ni, vi in v.items()])
elif isinstance(v, (list, tuple)):
v = u", ".join(v)
attrstr.append(u" %s=%s" % (n, repr(v)))
attrstr = u"".join(attrstr)
if len(self.sub) == 0:
return u"%s<%s%s />" % (indent * depth, self.t, attrstr)
if depth_limit is None or depth_limit > depth:
substr = []
for s in self.sub:
if isinstance(s, SVG):
substr.append(s.xml(indent, newl, depth_limit, depth + 1) + newl)
elif isinstance(s, basestring):
substr.append(u"%s%s%s" % (indent * (depth + 1), s, newl))
else:
substr.append("%s%s%s" % (indent * (depth + 1), repr(s), newl))
substr = u"".join(substr)
return u"%s<%s%s>%s%s%s</%s>" % (indent * depth, self.t, attrstr, newl, substr, indent * depth, self.t)
else:
return u"%s<%s (%d sub)%s />" % (indent * depth, self.t, len(self.sub), attrstr)
def standalone_xml(self, indent=u" ", newl=u"\n", encoding=u"utf-8"):
"""Get an XML representation of the SVG that can be saved/rendered.
indent string used for indenting
newl string used for newlines
"""
if self.t == "svg":
top = self
else:
top = canvas(self)
return u"""\
<?xml version="1.0" encoding="%s" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
""" % encoding + (u"".join(top.__standalone_xml(indent, newl))) # end of return statement
def __standalone_xml(self, indent, newl):
output = [u"<%s" % self.t]
for n, v in self.attr.items():
if isinstance(v, dict):
v = u"; ".join([u"%s:%s" % (ni, vi) for ni, vi in v.items()])
elif isinstance(v, (list, tuple)):
v = u", ".join(v)
output.append(u' %s="%s"' % (n, v))
if len(self.sub) == 0:
output.append(u" />%s%s" % (newl, newl))
return output
elif self.t == "text" or self.t == "tspan" or self.t == "style":
output.append(u">")
else:
output.append(u">%s%s" % (newl, newl))
for s in self.sub:
if isinstance(s, SVG):
output.extend(s.__standalone_xml(indent, newl))
else:
output.append(unicode(s))
if self.t == "tspan":
output.append(u"</%s>" % self.t)
else:
output.append(u"</%s>%s%s" % (self.t, newl, newl))
return output
def interpret_fileName(self, fileName=None):
if fileName is None:
fileName = _default_fileName
if re.search("windows", platform.system(), re.I) and not os.path.isabs(fileName):
fileName = _default_directory + os.sep + fileName
return fileName
def save(self, fileName=None, encoding="utf-8", compresslevel=None):
"""Save to a file for viewing. Note that svg.save() overwrites the file named _default_fileName.
fileName default=None note that _default_fileName will be overwritten if
no fileName is specified. If the extension
is ".svgz" or ".gz", the output will be gzipped
encoding default="utf-8" file encoding
compresslevel default=None if a number, the output will be gzipped with that
compression level (1-9, 1 being fastest and 9 most
thorough)
"""
fileName = self.interpret_fileName(fileName)
if compresslevel is not None or re.search(r"\.svgz$", fileName, re.I) or re.search(r"\.gz$", fileName, re.I):
import gzip
if compresslevel is None:
f = gzip.GzipFile(fileName, "w")
else:
f = gzip.GzipFile(fileName, "w", compresslevel)
f = codecs.EncodedFile(f, "utf-8", encoding)
f.write(self.standalone_xml(encoding=encoding))
f.close()
else:
f = codecs.open(fileName, "w", encoding=encoding)
f.write(self.standalone_xml(encoding=encoding))
f.close()
def inkview(self, fileName=None, encoding="utf-8"):
"""View in "inkview", assuming that program is available on your system.
fileName default=None note that any file named _default_fileName will be
overwritten if no fileName is specified. If the extension
is ".svgz" or ".gz", the output will be gzipped
encoding default="utf-8" file encoding
"""
fileName = self.interpret_fileName(fileName)
self.save(fileName, encoding)
os.spawnvp(os.P_NOWAIT, "inkview", ("inkview", fileName))
def inkscape(self, fileName=None, encoding="utf-8"):
"""View in "inkscape", assuming that program is available on your system.
fileName default=None note that any file named _default_fileName will be
overwritten if no fileName is specified. If the extension
is ".svgz" or ".gz", the output will be gzipped
encoding default="utf-8" file encoding
"""
fileName = self.interpret_fileName(fileName)
self.save(fileName, encoding)
os.spawnvp(os.P_NOWAIT, "inkscape", ("inkscape", fileName))
def firefox(self, fileName=None, encoding="utf-8"):
"""View in "firefox", assuming that program is available on your system.
fileName default=None note that any file named _default_fileName will be
overwritten if no fileName is specified. If the extension
is ".svgz" or ".gz", the output will be gzipped
encoding default="utf-8" file encoding
"""
fileName = self.interpret_fileName(fileName)
self.save(fileName, encoding)
os.spawnvp(os.P_NOWAIT, "firefox", ("firefox", fileName))
######################################################################
_canvas_defaults = {"width": "400px",
"height": "400px",
"viewBox": "0 0 100 100",
"xmlns": "http://www.w3.org/2000/svg",
"xmlns:xlink": "http://www.w3.org/1999/xlink",
"version": "1.1",
"style": {"stroke": "black",
"fill": "none",
"stroke-width": "0.5pt",
"stroke-linejoin": "round",
"text-anchor": "middle",
},
"font-family": ["Helvetica", "Arial", "FreeSans", "Sans", "sans", "sans-serif"],
}
def canvas(*sub, **attr):
"""Creates a top-level SVG object, allowing the user to control the
image size and aspect ratio.
canvas(sub, sub, sub..., attribute=value)
sub optional list nested SVG elements or text/Unicode
attribute=value pairs optional keywords SVG attributes
Default attribute values:
width "400px"
height "400px"
viewBox "0 0 100 100"
xmlns "http://www.w3.org/2000/svg"
xmlns:xlink "http://www.w3.org/1999/xlink"
version "1.1"
style "stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoin:round; text-anchor:middle"
font-family "Helvetica,Arial,FreeSans?,Sans,sans,sans-serif"
"""
attributes = dict(_canvas_defaults)
attributes.update(attr)
if sub is None or sub == ():
return SVG("svg", **attributes)
else:
return SVG("svg", *sub, **attributes)
def canvas_outline(*sub, **attr):
"""Same as canvas(), but draws an outline around the drawable area,
so that you know how close your image is to the edges."""
svg = canvas(*sub, **attr)
match = re.match(r"[, \t]*([0-9e.+\-]+)[, \t]+([0-9e.+\-]+)[, \t]+([0-9e.+\-]+)[, \t]+([0-9e.+\-]+)[, \t]*", svg["viewBox"])
if match is None:
raise ValueError( "canvas viewBox is incorrectly formatted")
x, y, width, height = [float(x) for x in match.groups()]
svg.prepend(SVG("rect", x=x, y=y, width=width, height=height, stroke="none", fill="cornsilk"))
svg.append(SVG("rect", x=x, y=y, width=width, height=height, stroke="black", fill="none"))
return svg
def template(fileName, svg, replaceme="REPLACEME"):
"""Loads an SVG image from a file, replacing instances of
<REPLACEME /> with a given svg object.
fileName required name of the template SVG
svg required SVG object for replacement
replaceme default="REPLACEME" fake SVG element to be replaced by the given object
>>> print load("template.svg")
None <svg (2 sub) style=u'stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoi
[0] <rect height=u'100' width=u'100' stroke=u'none' y=u'0' x=u'0' fill=u'yellow'
[1] <REPLACEME />
>>>
>>> print template("template.svg", SVG("circle", cx=50, cy=50, r=30))
None <svg (2 sub) style=u'stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoi
[0] <rect height=u'100' width=u'100' stroke=u'none' y=u'0' x=u'0' fill=u'yellow'
[1] <circle cy=50 cx=50 r=30 />
"""
output = load(fileName)
for ti, s in output:
if isinstance(s, SVG) and s.t == replaceme:
output[ti] = svg
return output
######################################################################
def load(fileName):
"""Loads an SVG image from a file."""
return load_stream(file(fileName))
def load_stream(stream):
"""Loads an SVG image from a stream (can be a string or a file object)."""
from xml.sax import handler, make_parser
from xml.sax.handler import feature_namespaces, feature_external_ges, feature_external_pes
class ContentHandler(handler.ContentHandler):
def __init__(self):
self.stack = []
self.output = None
self.all_whitespace = re.compile(r"^\s*$")
def startElement(self, name, attr):
s = SVG(name)
s.attr = dict(attr.items())
if len(self.stack) > 0:
last = self.stack[-1]
last.sub.append(s)
self.stack.append(s)
def characters(self, ch):
if not isinstance(ch, basestring) or self.all_whitespace.match(ch) is None:
if len(self.stack) > 0:
last = self.stack[-1]
if len(last.sub) > 0 and isinstance(last.sub[-1], basestring):
last.sub[-1] = last.sub[-1] + "\n" + ch
else:
last.sub.append(ch)
def endElement(self, name):
if len(self.stack) > 0:
last = self.stack[-1]
if (isinstance(last, SVG) and last.t == "style" and
"type" in last.attr and last.attr["type"] == "text/css" and
len(last.sub) == 1 and isinstance(last.sub[0], basestring)):
last.sub[0] = "<![CDATA[\n" + last.sub[0] + "]]>"
self.output = self.stack.pop()
ch = ContentHandler()
parser = make_parser()
parser.setContentHandler(ch)
parser.setFeature(feature_namespaces, 0)
parser.setFeature(feature_external_ges, 0)
parser.parse(stream)
return ch.output
######################################################################
def set_func_name(f, name):
"""try to patch the function name string into a function object"""
try:
f.func_name = name
except TypeError:
# py 2.3 raises: TypeError: readonly attribute
pass
def totrans(expr, vars=("x", "y"), globals=None, locals=None):
"""Converts to a coordinate transformation (a function that accepts
two arguments and returns two values).
expr required a string expression or a function
of two real or one complex value
vars default=("x", "y") independent variable names; a singleton
("z",) is interpreted as complex
globals default=None dict of global variables
locals default=None dict of local variables
"""
if locals is None:
locals = {} # python 2.3's eval() won't accept None
if callable(expr):
if expr.func_code.co_argcount == 2:
return expr
elif expr.func_code.co_argcount == 1:
split = lambda z: (z.real, z.imag)
output = lambda x, y: split(expr(x + y*1j))
set_func_name(output, expr.func_name)
return output
else:
raise TypeError( "must be a function of 2 or 1 variables")
if len(vars) == 2:
g = math.__dict__
if globals is not None:
g.update(globals)
output = eval("lambda %s, %s: (%s)" % (vars[0], vars[1], expr), g, locals)
set_func_name(output, "%s,%s -> %s" % (vars[0], vars[1], expr))
return output
elif len(vars) == 1:
g = cmath.__dict__
if globals is not None:
g.update(globals)
output = eval("lambda %s: (%s)" % (vars[0], expr), g, locals)
split = lambda z: (z.real, z.imag)
output2 = lambda x, y: split(output(x + y*1j))
set_func_name(output2, "%s -> %s" % (vars[0], expr))
return output2
else:
raise TypeError( "vars must have 2 or 1 elements")
def window(xmin, xmax, ymin, ymax, x=0, y=0, width=100, height=100,
xlogbase=None, ylogbase=None, minusInfinity=-1000, flipx=False, flipy=True):
"""Creates and returns a coordinate transformation (a function that
accepts two arguments and returns two values) that transforms from
(xmin, ymin), (xmax, ymax)
to
(x, y), (x + width, y + height).
xlogbase, ylogbase default=None, None if a number, transform
logarithmically with given base
minusInfinity default=-1000 what to return if
log(0 or negative) is attempted
flipx default=False if true, reverse the direction of x
flipy default=True if true, reverse the direction of y
(When composing windows, be sure to set flipy=False.)
"""
if flipx:
ox1 = x + width
ox2 = x
else:
ox1 = x
ox2 = x + width
if flipy:
oy1 = y + height
oy2 = y
else:
oy1 = y
oy2 = y + height
ix1 = xmin
iy1 = ymin
ix2 = xmax
iy2 = ymax
if xlogbase is not None and (ix1 <= 0. or ix2 <= 0.):
raise ValueError ("x range incompatible with log scaling: (%g, %g)" % (ix1, ix2))
if ylogbase is not None and (iy1 <= 0. or iy2 <= 0.):
raise ValueError ("y range incompatible with log scaling: (%g, %g)" % (iy1, iy2))
def maybelog(t, it1, it2, ot1, ot2, logbase):
if t <= 0.:
return minusInfinity
else:
return ot1 + 1.*(math.log(t, logbase) - math.log(it1, logbase))/(math.log(it2, logbase) - math.log(it1, logbase)) * (ot2 - ot1)
xlogstr, ylogstr = "", ""
if xlogbase is None:
xfunc = lambda x: ox1 + 1.*(x - ix1)/(ix2 - ix1) * (ox2 - ox1)
else:
xfunc = lambda x: maybelog(x, ix1, ix2, ox1, ox2, xlogbase)
xlogstr = " xlog=%g" % xlogbase
if ylogbase is None:
yfunc = lambda y: oy1 + 1.*(y - iy1)/(iy2 - iy1) * (oy2 - oy1)
else:
yfunc = lambda y: maybelog(y, iy1, iy2, oy1, oy2, ylogbase)
ylogstr = " ylog=%g" % ylogbase
output = lambda x, y: (xfunc(x), yfunc(y))
set_func_name(output, "(%g, %g), (%g, %g) -> (%g, %g), (%g, %g)%s%s" % (
ix1, ix2, iy1, iy2, ox1, ox2, oy1, oy2, xlogstr, ylogstr))
return output
def rotate(angle, cx=0, cy=0):
"""Creates and returns a coordinate transformation which rotates
around (cx,cy) by "angle" degrees."""
angle *= math.pi/180.
return lambda x, y: (cx + math.cos(angle)*(x - cx) - math.sin(angle)*(y - cy), cy + math.sin(angle)*(x - cx) + math.cos(angle)*(y - cy))
class Fig:
"""Stores graphics primitive objects and applies a single coordinate
transformation to them. To compose coordinate systems, nest Fig
objects.
Fig(obj, obj, obj..., trans=function)
obj optional list a list of drawing primitives
trans default=None a coordinate transformation function
>>> fig = Fig(Line(0,0,1,1), Rect(0.2,0.2,0.8,0.8), trans="2*x, 2*y")
>>> print fig.SVG().xml()
<g>
<path d='M0 0L2 2' />
<path d='M0.4 0.4L1.6 0.4ZL1.6 1.6ZL0.4 1.6ZL0.4 0.4ZZ' />
</g>
>>> print Fig(fig, trans="x/2., y/2.").SVG().xml()
<g>
<path d='M0 0L1 1' />
<path d='M0.2 0.2L0.8 0.2ZL0.8 0.8ZL0.2 0.8ZL0.2 0.2ZZ' />
</g>
"""
def __repr__(self):
if self.trans is None:
return "<Fig (%d items)>" % len(self.d)
elif isinstance(self.trans, basestring):
return "<Fig (%d items) x,y -> %s>" % (len(self.d), self.trans)
else:
return "<Fig (%d items) %s>" % (len(self.d), self.trans.func_name)
def __init__(self, *d, **kwds):
self.d = list(d)
defaults = {"trans": None, }
defaults.update(kwds)
kwds = defaults
self.trans = kwds["trans"]; del kwds["trans"]
if len(kwds) != 0:
raise TypeError ("Fig() got unexpected keyword arguments %s" % kwds.keys())
def SVG(self, trans=None):
"""Apply the transformation "trans" and return an SVG object.
Coordinate transformations in nested Figs will be composed.
"""
if trans is None:
trans = self.trans
if isinstance(trans, basestring):
trans = totrans(trans)
output = SVG("g")
for s in self.d:
if isinstance(s, SVG):
output.append(s)
elif isinstance(s, Fig):
strans = s.trans
if isinstance(strans, basestring):
strans = totrans(strans)
if trans is None:
subtrans = strans
elif strans is None:
subtrans = trans
else:
subtrans = lambda x, y: trans(*strans(x, y))
output.sub += s.SVG(subtrans).sub
elif s is None:
pass
else:
output.append(s.SVG(trans))
return output
class Plot:
"""Acts like Fig, but draws a coordinate axis. You also need to supply plot ranges.
Plot(xmin, xmax, ymin, ymax, obj, obj, obj..., keyword options...)
xmin, xmax required minimum and maximum x values (in the objs' coordinates)
ymin, ymax required minimum and maximum y values (in the objs' coordinates)
obj optional list drawing primitives
keyword options keyword list options defined below
The following are keyword options, with their default values:
trans None transformation function
x, y 5, 5 upper-left corner of the Plot in SVG coordinates
width, height 90, 90 width and height of the Plot in SVG coordinates
flipx, flipy False, True flip the sign of the coordinate axis
minusInfinity -1000 if an axis is logarithmic and an object is plotted at 0 or
a negative value, -1000 will be used as a stand-in for NaN
atx, aty 0, 0 the place where the coordinate axes cross
xticks -10 request ticks according to the standard tick specification
(see help(Ticks))
xminiticks True request miniticks according to the standard minitick
specification
xlabels True request tick labels according to the standard tick label
specification
xlogbase None if a number, the axis and transformation are logarithmic
with ticks at the given base (10 being the most common)
(same for y)
arrows None if a new identifier, create arrow markers and draw them
at the ends of the coordinate axes
text_attr {} a dictionary of attributes for label text
axis_attr {} a dictionary of attributes for the axis lines
"""
def __repr__(self):
if self.trans is None:
return "<Plot (%d items)>" % len(self.d)
else:
return "<Plot (%d items) %s>" % (len(self.d), self.trans.func_name)
def __init__(self, xmin, xmax, ymin, ymax, *d, **kwds):
self.xmin, self.xmax, self.ymin, self.ymax = xmin, xmax, ymin, ymax
self.d = list(d)
defaults = {"trans": None,
"x": 5, "y": 5, "width": 90, "height": 90,
"flipx": False, "flipy": True,
"minusInfinity": -1000,
"atx": 0, "xticks": -10, "xminiticks": True, "xlabels": True, "xlogbase": None,
"aty": 0, "yticks": -10, "yminiticks": True, "ylabels": True, "ylogbase": None,
"arrows": None,
"text_attr": {}, "axis_attr": {},
}
defaults.update(kwds)
kwds = defaults
self.trans = kwds["trans"]; del kwds["trans"]
self.x = kwds["x"]; del kwds["x"]
self.y = kwds["y"]; del kwds["y"]
self.width = kwds["width"]; del kwds["width"]
self.height = kwds["height"]; del kwds["height"]
self.flipx = kwds["flipx"]; del kwds["flipx"]
self.flipy = kwds["flipy"]; del kwds["flipy"]
self.minusInfinity = kwds["minusInfinity"]; del kwds["minusInfinity"]
self.atx = kwds["atx"]; del kwds["atx"]
self.xticks = kwds["xticks"]; del kwds["xticks"]
self.xminiticks = kwds["xminiticks"]; del kwds["xminiticks"]
self.xlabels = kwds["xlabels"]; del kwds["xlabels"]
self.xlogbase = kwds["xlogbase"]; del kwds["xlogbase"]
self.aty = kwds["aty"]; del kwds["aty"]
self.yticks = kwds["yticks"]; del kwds["yticks"]
self.yminiticks = kwds["yminiticks"]; del kwds["yminiticks"]
self.ylabels = kwds["ylabels"]; del kwds["ylabels"]
self.ylogbase = kwds["ylogbase"]; del kwds["ylogbase"]
self.arrows = kwds["arrows"]; del kwds["arrows"]
self.text_attr = kwds["text_attr"]; del kwds["text_attr"]
self.axis_attr = kwds["axis_attr"]; del kwds["axis_attr"]
if len(kwds) != 0:
raise TypeError ("Plot() got unexpected keyword arguments %s" % kwds.keys())
def SVG(self, trans=None):
"""Apply the transformation "trans" and return an SVG object."""
if trans is None:
trans = self.trans
if isinstance(trans, basestring):
trans = totrans(trans)
self.last_window = window(self.xmin, self.xmax, self.ymin, self.ymax,
x=self.x, y=self.y, width=self.width, height=self.height,
xlogbase=self.xlogbase, ylogbase=self.ylogbase,
minusInfinity=self.minusInfinity, flipx=self.flipx, flipy=self.flipy)
d = ([Axes(self.xmin, self.xmax, self.ymin, self.ymax, self.atx, self.aty,
self.xticks, self.xminiticks, self.xlabels, self.xlogbase,
self.yticks, self.yminiticks, self.ylabels, self.ylogbase,
self.arrows, self.text_attr, **self.axis_attr)]
+ self.d)
return Fig(Fig(*d, **{"trans": trans})).SVG(self.last_window)
class Frame:
text_defaults = {"stroke": "none", "fill": "black", "font-size": 5, }
axis_defaults = {}
tick_length = 1.5
minitick_length = 0.75
text_xaxis_offset = 1.
text_yaxis_offset = 2.
text_xtitle_offset = 6.
text_ytitle_offset = 12.
def __repr__(self):
return "<Frame (%d items)>" % len(self.d)
def __init__(self, xmin, xmax, ymin, ymax, *d, **kwds):
"""Acts like Fig, but draws a coordinate frame around the data. You also need to supply plot ranges.
Frame(xmin, xmax, ymin, ymax, obj, obj, obj..., keyword options...)
xmin, xmax required minimum and maximum x values (in the objs' coordinates)
ymin, ymax required minimum and maximum y values (in the objs' coordinates)
obj optional list drawing primitives
keyword options keyword list options defined below
The following are keyword options, with their default values:
x, y 20, 5 upper-left corner of the Frame in SVG coordinates
width, height 75, 80 width and height of the Frame in SVG coordinates
flipx, flipy False, True flip the sign of the coordinate axis
minusInfinity -1000 if an axis is logarithmic and an object is plotted at 0 or
a negative value, -1000 will be used as a stand-in for NaN
xtitle None if a string, label the x axis
xticks -10 request ticks according to the standard tick specification
(see help(Ticks))
xminiticks True request miniticks according to the standard minitick
specification