-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathcamlib.py
4075 lines (3339 loc) · 141 KB
/
camlib.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
############################################################
# FlatCAM: 2D Post-processing for Manufacturing #
# http://flatcam.org #
# Author: Juan Pablo Caram (c) #
# Date: 2/5/2014 #
# MIT Licence #
############################################################
#from __future__ import division
#from scipy import optimize
#import traceback
from cStringIO import StringIO
from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
transpose
from numpy.linalg import solve, norm
import re
import sys
import traceback
from decimal import Decimal
import collections
import numpy as np
#from scipy.spatial import Delaunay, KDTree
from rtree import index as rtindex
# See: http://toblerity.org/shapely/manual.html
from shapely.geometry import Polygon, LineString, Point, LinearRing
from shapely.geometry import MultiPoint, MultiPolygon
from shapely.geometry import box as shply_box
from shapely.ops import cascaded_union
import shapely.affinity as affinity
from shapely.wkt import loads as sloads
from shapely.wkt import dumps as sdumps
from shapely.geometry.base import BaseGeometry
# Used for solid polygons in Matplotlib
# from descartes.patch import PolygonPatch
import simplejson as json
# TODO: Commented for FlatCAM packaging with cx_freeze
import xml.etree.ElementTree as ET
from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
import itertools
from svgparse import *
import logging
log = logging.getLogger('base2')
log.setLevel(logging.DEBUG)
# log.setLevel(logging.WARNING)
# log.setLevel(logging.INFO)
formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
class ParseError(Exception):
pass
class Geometry(object):
"""
Base geometry class.
"""
defaults = {
"init_units": 'in'
}
def __init__(self):
# Units (in or mm)
self.units = Geometry.defaults["init_units"]
# Final geometry: MultiPolygon or list (of geometry constructs)
self.solid_geometry = None
# Attributes to be included in serialization
self.ser_attrs = ['units', 'solid_geometry']
# Flattened geometry (list of paths only)
self.flat_geometry = []
def add_circle(self, origin, radius):
"""
Adds a circle to the object.
:param origin: Center of the circle.
:param radius: Radius of the circle.
:return: None
"""
# TODO: Decide what solid_geometry is supposed to be and how we append to it.
if self.solid_geometry is None:
self.solid_geometry = []
if type(self.solid_geometry) is list:
self.solid_geometry.append(Point(origin).buffer(radius))
return
try:
self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius))
except:
#print "Failed to run union on polygons."
log.error("Failed to run union on polygons.")
raise
def add_polygon(self, points):
"""
Adds a polygon to the object (by union)
:param points: The vertices of the polygon.
:return: None
"""
if self.solid_geometry is None:
self.solid_geometry = []
if type(self.solid_geometry) is list:
self.solid_geometry.append(Polygon(points))
return
try:
self.solid_geometry = self.solid_geometry.union(Polygon(points))
except:
#print "Failed to run union on polygons."
log.error("Failed to run union on polygons.")
raise
def add_polyline(self, points):
"""
Adds a polyline to the object (by union)
:param points: The vertices of the polyline.
:return: None
"""
if self.solid_geometry is None:
self.solid_geometry = []
if type(self.solid_geometry) is list:
self.solid_geometry.append(LineString(points))
return
try:
self.solid_geometry = self.solid_geometry.union(LineString(points))
except:
#print "Failed to run union on polygons."
log.error("Failed to run union on polylines.")
raise
def is_empty(self):
if isinstance(self.solid_geometry, BaseGeometry):
return self.solid_geometry.is_empty
if isinstance(self.solid_geometry, list):
return len(self.solid_geometry) == 0
raise Exception("self.solid_geometry is neither BaseGeometry or list.")
def subtract_polygon(self, points):
"""
Subtract polygon from the given object. This only operates on the paths in the original geometry, i.e. it converts polygons into paths.
:param points: The vertices of the polygon.
:return: none
"""
if self.solid_geometry is None:
self.solid_geometry = []
#pathonly should be allways True, otherwise polygons are not subtracted
flat_geometry = self.flatten(pathonly=True)
log.debug("%d paths" % len(flat_geometry))
polygon=Polygon(points)
toolgeo=cascaded_union(polygon)
diffs=[]
for target in flat_geometry:
if type(target) == LineString or type(target) == LinearRing:
diffs.append(target.difference(toolgeo))
else:
log.warning("Not implemented.")
self.solid_geometry=cascaded_union(diffs)
def bounds(self):
"""
Returns coordinates of rectangular bounds
of geometry: (xmin, ymin, xmax, ymax).
"""
log.debug("Geometry->bounds()")
if self.solid_geometry is None:
log.debug("solid_geometry is None")
return 0, 0, 0, 0
if type(self.solid_geometry) is list:
# TODO: This can be done faster. See comment from Shapely mailing lists.
if len(self.solid_geometry) == 0:
log.debug('solid_geometry is empty []')
return 0, 0, 0, 0
return cascaded_union(self.solid_geometry).bounds
else:
return self.solid_geometry.bounds
def find_polygon(self, point, geoset=None):
"""
Find an object that object.contains(Point(point)) in
poly, which can can be iterable, contain iterable of, or
be itself an implementer of .contains().
:param poly: See description
:return: Polygon containing point or None.
"""
if geoset is None:
geoset = self.solid_geometry
try: # Iterable
for sub_geo in geoset:
p = self.find_polygon(point, geoset=sub_geo)
if p is not None:
return p
except TypeError: # Non-iterable
try: # Implements .contains()
if geoset.contains(Point(point)):
return geoset
except AttributeError: # Does not implement .contains()
return None
return None
def get_interiors(self, geometry=None):
interiors = []
if geometry is None:
geometry = self.solid_geometry
## If iterable, expand recursively.
try:
for geo in geometry:
interiors.extend(self.get_interiors(geometry=geo))
## Not iterable, get the exterior if polygon.
except TypeError:
if type(geometry) == Polygon:
interiors.extend(geometry.interiors)
return interiors
def get_exteriors(self, geometry=None):
"""
Returns all exteriors of polygons in geometry. Uses
``self.solid_geometry`` if geometry is not provided.
:param geometry: Shapely type or list or list of list of such.
:return: List of paths constituting the exteriors
of polygons in geometry.
"""
exteriors = []
if geometry is None:
geometry = self.solid_geometry
## If iterable, expand recursively.
try:
for geo in geometry:
exteriors.extend(self.get_exteriors(geometry=geo))
## Not iterable, get the exterior if polygon.
except TypeError:
if type(geometry) == Polygon:
exteriors.append(geometry.exterior)
return exteriors
def flatten(self, geometry=None, reset=True, pathonly=False):
"""
Creates a list of non-iterable linear geometry objects.
Polygons are expanded into its exterior and interiors if specified.
Results are placed in self.flat_geoemtry
:param geometry: Shapely type or list or list of list of such.
:param reset: Clears the contents of self.flat_geometry.
:param pathonly: Expands polygons into linear elements.
"""
if geometry is None:
geometry = self.solid_geometry
if reset:
self.flat_geometry = []
## If iterable, expand recursively.
try:
for geo in geometry:
self.flatten(geometry=geo,
reset=False,
pathonly=pathonly)
## Not iterable, do the actual indexing and add.
except TypeError:
if pathonly and type(geometry) == Polygon:
self.flat_geometry.append(geometry.exterior)
self.flatten(geometry=geometry.interiors,
reset=False,
pathonly=True)
else:
self.flat_geometry.append(geometry)
return self.flat_geometry
# def make2Dstorage(self):
#
# self.flatten()
#
# def get_pts(o):
# pts = []
# if type(o) == Polygon:
# g = o.exterior
# pts += list(g.coords)
# for i in o.interiors:
# pts += list(i.coords)
# else:
# pts += list(o.coords)
# return pts
#
# storage = FlatCAMRTreeStorage()
# storage.get_points = get_pts
# for shape in self.flat_geometry:
# storage.insert(shape)
# return storage
# def flatten_to_paths(self, geometry=None, reset=True):
# """
# Creates a list of non-iterable linear geometry elements and
# indexes them in rtree.
#
# :param geometry: Iterable geometry
# :param reset: Wether to clear (True) or append (False) to self.flat_geometry
# :return: self.flat_geometry, self.flat_geometry_rtree
# """
#
# if geometry is None:
# geometry = self.solid_geometry
#
# if reset:
# self.flat_geometry = []
#
# ## If iterable, expand recursively.
# try:
# for geo in geometry:
# self.flatten_to_paths(geometry=geo, reset=False)
#
# ## Not iterable, do the actual indexing and add.
# except TypeError:
# if type(geometry) == Polygon:
# g = geometry.exterior
# self.flat_geometry.append(g)
#
# ## Add first and last points of the path to the index.
# self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
# self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
#
# for interior in geometry.interiors:
# g = interior
# self.flat_geometry.append(g)
# self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
# self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
# else:
# g = geometry
# self.flat_geometry.append(g)
# self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
# self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
#
# return self.flat_geometry, self.flat_geometry_rtree
def isolation_geometry(self, offset):
"""
Creates contours around geometry at a given
offset distance.
:param offset: Offset distance.
:type offset: float
:return: The buffered geometry.
:rtype: Shapely.MultiPolygon or Shapely.Polygon
"""
return self.solid_geometry.buffer(offset)
def import_svg(self, filename, flip=True):
"""
Imports shapes from an SVG file into the object's geometry.
:param filename: Path to the SVG file.
:type filename: str
:return: None
"""
# Parse into list of shapely objects
svg_tree = ET.parse(filename)
svg_root = svg_tree.getroot()
# Change origin to bottom left
# h = float(svg_root.get('height'))
# w = float(svg_root.get('width'))
h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
geos = getsvggeo(svg_root)
if flip:
geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
# Add to object
if self.solid_geometry is None:
self.solid_geometry = []
if type(self.solid_geometry) is list:
self.solid_geometry.append(cascaded_union(geos))
else: # It's shapely geometry
self.solid_geometry = cascaded_union([self.solid_geometry,
cascaded_union(geos)])
return
def size(self):
"""
Returns (width, height) of rectangular
bounds of geometry.
"""
if self.solid_geometry is None:
log.warning("Solid_geometry not computed yet.")
return 0
bounds = self.bounds()
return bounds[2] - bounds[0], bounds[3] - bounds[1]
def get_empty_area(self, boundary=None):
"""
Returns the complement of self.solid_geometry within
the given boundary polygon. If not specified, it defaults to
the rectangular bounding box of self.solid_geometry.
"""
if boundary is None:
boundary = self.solid_geometry.envelope
return boundary.difference(self.solid_geometry)
@staticmethod
def clear_polygon(polygon, tooldia, overlap=0.15):
"""
Creates geometry inside a polygon for a tool to cover
the whole area.
This algorithm shrinks the edges of the polygon and takes
the resulting edges as toolpaths.
:param polygon: Polygon to clear.
:param tooldia: Diameter of the tool.
:param overlap: Overlap of toolpasses.
:return:
"""
log.debug("camlib.clear_polygon()")
assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
"Expected a Polygon or MultiPolygon, got %s" % type(polygon)
## The toolpaths
# Index first and last points in paths
def get_pts(o):
return [o.coords[0], o.coords[-1]]
geoms = FlatCAMRTreeStorage()
geoms.get_points = get_pts
# Can only result in a Polygon or MultiPolygon
current = polygon.buffer(-tooldia / 2.0)
# current can be a MultiPolygon
try:
for p in current:
geoms.insert(p.exterior)
for i in p.interiors:
geoms.insert(i)
# Not a Multipolygon. Must be a Polygon
except TypeError:
geoms.insert(current.exterior)
for i in current.interiors:
geoms.insert(i)
while True:
# Can only result in a Polygon or MultiPolygon
current = current.buffer(-tooldia * (1 - overlap))
if current.area > 0:
# current can be a MultiPolygon
try:
for p in current:
geoms.insert(p.exterior)
for i in p.interiors:
geoms.insert(i)
# Not a Multipolygon. Must be a Polygon
except TypeError:
geoms.insert(current.exterior)
for i in current.interiors:
geoms.insert(i)
else:
break
# Optimization: Reduce lifts
log.debug("Reducing tool lifts...")
geoms = Geometry.paint_connect(geoms, polygon, tooldia)
return geoms
@staticmethod
def clear_polygon2(polygon, tooldia, seedpoint=None, overlap=0.15):
"""
Creates geometry inside a polygon for a tool to cover
the whole area.
This algorithm starts with a seed point inside the polygon
and draws circles around it. Arcs inside the polygons are
valid cuts. Finalizes by cutting around the inside edge of
the polygon.
:param polygon: Shapely.geometry.Polygon
:param tooldia: Diameter of the tool
:param seedpoint: Shapely.geometry.Point or None
:param overlap: Tool fraction overlap bewteen passes
:return: List of toolpaths covering polygon.
"""
log.debug("camlib.clear_polygon2()")
# Current buffer radius
radius = tooldia / 2 * (1 - overlap)
## The toolpaths
# Index first and last points in paths
def get_pts(o):
return [o.coords[0], o.coords[-1]]
geoms = FlatCAMRTreeStorage()
geoms.get_points = get_pts
# Path margin
path_margin = polygon.buffer(-tooldia / 2)
# Estimate good seedpoint if not provided.
if seedpoint is None:
seedpoint = path_margin.representative_point()
# Grow from seed until outside the box. The polygons will
# never have an interior, so take the exterior LinearRing.
while 1:
path = Point(seedpoint).buffer(radius).exterior
path = path.intersection(path_margin)
# Touches polygon?
if path.is_empty:
break
else:
#geoms.append(path)
#geoms.insert(path)
# path can be a collection of paths.
try:
for p in path:
geoms.insert(p)
except TypeError:
geoms.insert(path)
radius += tooldia * (1 - overlap)
# Clean inside edges of the original polygon
outer_edges = [x.exterior for x in autolist(polygon.buffer(-tooldia / 2))]
inner_edges = []
for x in autolist(polygon.buffer(-tooldia / 2)): # Over resulting polygons
for y in x.interiors: # Over interiors of each polygon
inner_edges.append(y)
#geoms += outer_edges + inner_edges
for g in outer_edges + inner_edges:
geoms.insert(g)
# Optimization connect touching paths
# log.debug("Connecting paths...")
# geoms = Geometry.path_connect(geoms)
# Optimization: Reduce lifts
log.debug("Reducing tool lifts...")
geoms = Geometry.paint_connect(geoms, polygon, tooldia)
return geoms
def scale(self, factor):
"""
Scales all of the object's geometry by a given factor. Override
this method.
:param factor: Number by which to scale.
:type factor: float
:return: None
:rtype: None
"""
return
def offset(self, vect):
"""
Offset the geometry by the given vector. Override this method.
:param vect: (x, y) vector by which to offset the object.
:type vect: tuple
:return: None
"""
return
@staticmethod
def paint_connect(storage, boundary, tooldia, max_walk=None):
"""
Connects paths that results in a connection segment that is
within the paint area. This avoids unnecessary tool lifting.
:param storage: Geometry to be optimized.
:type storage: FlatCAMRTreeStorage
:param boundary: Polygon defining the limits of the paintable area.
:type boundary: Polygon
:param max_walk: Maximum allowable distance without lifting tool.
:type max_walk: float or None
:return: Optimized geometry.
:rtype: FlatCAMRTreeStorage
"""
# If max_walk is not specified, the maximum allowed is
# 10 times the tool diameter
max_walk = max_walk or 10 * tooldia
# Assuming geolist is a flat list of flat elements
## Index first and last points in paths
def get_pts(o):
return [o.coords[0], o.coords[-1]]
# storage = FlatCAMRTreeStorage()
# storage.get_points = get_pts
#
# for shape in geolist:
# if shape is not None: # TODO: This shouldn't have happened.
# # Make LlinearRings into linestrings otherwise
# # When chaining the coordinates path is messed up.
# storage.insert(LineString(shape))
# #storage.insert(shape)
## Iterate over geometry paths getting the nearest each time.
#optimized_paths = []
optimized_paths = FlatCAMRTreeStorage()
optimized_paths.get_points = get_pts
path_count = 0
current_pt = (0, 0)
pt, geo = storage.nearest(current_pt)
storage.remove(geo)
geo = LineString(geo)
current_pt = geo.coords[-1]
try:
while True:
path_count += 1
#log.debug("Path %d" % path_count)
pt, candidate = storage.nearest(current_pt)
storage.remove(candidate)
candidate = LineString(candidate)
# If last point in geometry is the nearest
# then reverse coordinates.
# but prefer the first one if last == first
if pt != candidate.coords[0] and pt == candidate.coords[-1]:
candidate.coords = list(candidate.coords)[::-1]
# Straight line from current_pt to pt.
# Is the toolpath inside the geometry?
walk_path = LineString([current_pt, pt])
walk_cut = walk_path.buffer(tooldia / 2)
if walk_cut.within(boundary) and walk_path.length < max_walk:
#log.debug("Walk to path #%d is inside. Joining." % path_count)
# Completely inside. Append...
geo.coords = list(geo.coords) + list(candidate.coords)
# try:
# last = optimized_paths[-1]
# last.coords = list(last.coords) + list(geo.coords)
# except IndexError:
# optimized_paths.append(geo)
else:
# Have to lift tool. End path.
#log.debug("Path #%d not within boundary. Next." % path_count)
#optimized_paths.append(geo)
optimized_paths.insert(geo)
geo = candidate
current_pt = geo.coords[-1]
# Next
#pt, geo = storage.nearest(current_pt)
except StopIteration: # Nothing left in storage.
#pass
optimized_paths.insert(geo)
return optimized_paths
@staticmethod
def path_connect(storage, origin=(0, 0)):
"""
:return: None
"""
log.debug("path_connect()")
## Index first and last points in paths
def get_pts(o):
return [o.coords[0], o.coords[-1]]
#
# storage = FlatCAMRTreeStorage()
# storage.get_points = get_pts
#
# for shape in pathlist:
# if shape is not None: # TODO: This shouldn't have happened.
# storage.insert(shape)
path_count = 0
pt, geo = storage.nearest(origin)
storage.remove(geo)
#optimized_geometry = [geo]
optimized_geometry = FlatCAMRTreeStorage()
optimized_geometry.get_points = get_pts
#optimized_geometry.insert(geo)
try:
while True:
path_count += 1
#print "geo is", geo
_, left = storage.nearest(geo.coords[0])
#print "left is", left
# If left touches geo, remove left from original
# storage and append to geo.
if type(left) == LineString:
if left.coords[0] == geo.coords[0]:
storage.remove(left)
geo.coords = list(geo.coords)[::-1] + list(left.coords)
continue
if left.coords[-1] == geo.coords[0]:
storage.remove(left)
geo.coords = list(left.coords) + list(geo.coords)
continue
if left.coords[0] == geo.coords[-1]:
storage.remove(left)
geo.coords = list(geo.coords) + list(left.coords)
continue
if left.coords[-1] == geo.coords[-1]:
storage.remove(left)
geo.coords = list(geo.coords) + list(left.coords)[::-1]
continue
_, right = storage.nearest(geo.coords[-1])
#print "right is", right
# If right touches geo, remove left from original
# storage and append to geo.
if type(right) == LineString:
if right.coords[0] == geo.coords[-1]:
storage.remove(right)
geo.coords = list(geo.coords) + list(right.coords)
continue
if right.coords[-1] == geo.coords[-1]:
storage.remove(right)
geo.coords = list(geo.coords) + list(right.coords)[::-1]
continue
if right.coords[0] == geo.coords[0]:
storage.remove(right)
geo.coords = list(geo.coords)[::-1] + list(right.coords)
continue
if right.coords[-1] == geo.coords[0]:
storage.remove(right)
geo.coords = list(left.coords) + list(geo.coords)
continue
# right is either a LinearRing or it does not connect
# to geo (nothing left to connect to geo), so we continue
# with right as geo.
storage.remove(right)
if type(right) == LinearRing:
optimized_geometry.insert(right)
else:
# Cannot exteng geo any further. Put it away.
optimized_geometry.insert(geo)
# Continue with right.
geo = right
except StopIteration: # Nothing found in storage.
optimized_geometry.insert(geo)
#print path_count
log.debug("path_count = %d" % path_count)
return optimized_geometry
def convert_units(self, units):
"""
Converts the units of the object to ``units`` by scaling all
the geometry appropriately. This call ``scale()``. Don't call
it again in descendents.
:param units: "IN" or "MM"
:type units: str
:return: Scaling factor resulting from unit change.
:rtype: float
"""
log.debug("Geometry.convert_units()")
if units.upper() == self.units.upper():
return 1.0
if units.upper() == "MM":
factor = 25.4
elif units.upper() == "IN":
factor = 1 / 25.4
else:
log.error("Unsupported units: %s" % str(units))
return 1.0
self.units = units
self.scale(factor)
return factor
def to_dict(self):
"""
Returns a respresentation of the object as a dictionary.
Attributes to include are listed in ``self.ser_attrs``.
:return: A dictionary-encoded copy of the object.
:rtype: dict
"""
d = {}
for attr in self.ser_attrs:
d[attr] = getattr(self, attr)
return d
def from_dict(self, d):
"""
Sets object's attributes from a dictionary.
Attributes to include are listed in ``self.ser_attrs``.
This method will look only for only and all the
attributes in ``self.ser_attrs``. They must all
be present. Use only for deserializing saved
objects.
:param d: Dictionary of attributes to set in the object.
:type d: dict
:return: None
"""
for attr in self.ser_attrs:
setattr(self, attr, d[attr])
def union(self):
"""
Runs a cascaded union on the list of objects in
solid_geometry.
:return: None
"""
self.solid_geometry = [cascaded_union(self.solid_geometry)]
def export_svg(self, scale_factor=0.00):
"""
Exports the Gemoetry Object as a SVG Element
:return: SVG Element
"""
# Make sure we see a Shapely Geometry class and not a list
geom = cascaded_union(self.flatten())
# scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
# If 0 or less which is invalid then default to 0.05
# This value appears to work for zooming, and getting the output svg line width
# to match that viewed on screen with FlatCam
if scale_factor <= 0:
scale_factor = 0.05
# Convert to a SVG
svg_elem = geom.svg(scale_factor=scale_factor)
return svg_elem
def mirror(self, axis, point):
"""
Mirrors the object around a specified axis passign through
the given point.
:param axis: "X" or "Y" indicates around which axis to mirror.
:type axis: str
:param point: [x, y] point belonging to the mirror axis.
:type point: list
:return: None
"""
px, py = point
xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
## solid_geometry ???
# It's a cascaded union of objects.
self.solid_geometry = affinity.scale(self.solid_geometry,
xscale, yscale, origin=(px, py))
class ApertureMacro:
"""
Syntax of aperture macros.
<AM command>: AM<Aperture macro name>*<Macro content>
<Macro content>: {{<Variable definition>*}{<Primitive>*}}
<Variable definition>: $K=<Arithmetic expression>
<Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
<Modifier>: $M|< Arithmetic expression>
<Comment>: 0 <Text>
"""
## Regular expressions
am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
am2_re = re.compile(r'(.*)%$')
amcomm_re = re.compile(r'^0(.*)')
amprim_re = re.compile(r'^[1-9].*')
amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
def __init__(self, name=None):
self.name = name
self.raw = ""
## These below are recomputed for every aperture
## definition, in other words, are temporary variables.
self.primitives = []
self.locvars = {}
self.geometry = None
def to_dict(self):
"""
Returns the object in a serializable form. Only the name and
raw are required.
:return: Dictionary representing the object. JSON ready.
:rtype: dict
"""
return {
'name': self.name,
'raw': self.raw
}
def from_dict(self, d):
"""
Populates the object from a serial representation created
with ``self.to_dict()``.
:param d: Serial representation of an ApertureMacro object.
:return: None
"""
for attr in ['name', 'raw']:
setattr(self, attr, d[attr])
def parse_content(self):
"""
Creates numerical lists for all primitives in the aperture
macro (in ``self.raw``) by replacing all variables by their
values iteratively and evaluating expressions. Results
are stored in ``self.primitives``.
:return: None
"""
# Cleanup
self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
self.primitives = []
# Separate parts
parts = self.raw.split('*')
#### Every part in the macro ####
for part in parts:
### Comments. Ignored.