camlib.py 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. #from __future__ import division
  9. import traceback
  10. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  11. transpose
  12. from numpy.linalg import solve, norm
  13. from matplotlib.figure import Figure
  14. import re
  15. import collections
  16. import numpy as np
  17. import matplotlib
  18. #import matplotlib.pyplot as plt
  19. #from scipy.spatial import Delaunay, KDTree
  20. from rtree import index as rtindex
  21. # See: http://toblerity.org/shapely/manual.html
  22. from shapely.geometry import Polygon, LineString, Point, LinearRing
  23. from shapely.geometry import MultiPoint, MultiPolygon
  24. from shapely.geometry import box as shply_box
  25. from shapely.ops import cascaded_union
  26. import shapely.affinity as affinity
  27. from shapely.wkt import loads as sloads
  28. from shapely.wkt import dumps as sdumps
  29. from shapely.geometry.base import BaseGeometry
  30. # Used for solid polygons in Matplotlib
  31. from descartes.patch import PolygonPatch
  32. import simplejson as json
  33. # TODO: Commented for FlatCAM packaging with cx_freeze
  34. from matplotlib.pyplot import plot, subplot
  35. import logging
  36. log = logging.getLogger('base2')
  37. log.setLevel(logging.DEBUG)
  38. #log.setLevel(logging.WARNING)
  39. #log.setLevel(logging.INFO)
  40. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  41. handler = logging.StreamHandler()
  42. handler.setFormatter(formatter)
  43. log.addHandler(handler)
  44. class ParseError(Exception):
  45. pass
  46. class Geometry(object):
  47. """
  48. Base geometry class.
  49. """
  50. defaults = {
  51. "init_units": 'in'
  52. }
  53. def __init__(self):
  54. # Units (in or mm)
  55. self.units = Geometry.defaults["init_units"]
  56. # Final geometry: MultiPolygon or list (of geometry constructs)
  57. self.solid_geometry = None
  58. # Attributes to be included in serialization
  59. self.ser_attrs = ['units', 'solid_geometry']
  60. # Flattened geometry (list of paths only)
  61. self.flat_geometry = []
  62. def add_circle(self, origin, radius):
  63. """
  64. Adds a circle to the object.
  65. :param origin: Center of the circle.
  66. :param radius: Radius of the circle.
  67. :return: None
  68. """
  69. # TODO: Decide what solid_geometry is supposed to be and how we append to it.
  70. if self.solid_geometry is None:
  71. self.solid_geometry = []
  72. if type(self.solid_geometry) is list:
  73. self.solid_geometry.append(Point(origin).buffer(radius))
  74. return
  75. try:
  76. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius))
  77. except:
  78. #print "Failed to run union on polygons."
  79. log.error("Failed to run union on polygons.")
  80. raise
  81. def add_polygon(self, points):
  82. """
  83. Adds a polygon to the object (by union)
  84. :param points: The vertices of the polygon.
  85. :return: None
  86. """
  87. if self.solid_geometry is None:
  88. self.solid_geometry = []
  89. if type(self.solid_geometry) is list:
  90. self.solid_geometry.append(Polygon(points))
  91. return
  92. try:
  93. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  94. except:
  95. #print "Failed to run union on polygons."
  96. log.error("Failed to run union on polygons.")
  97. raise
  98. def bounds(self):
  99. """
  100. Returns coordinates of rectangular bounds
  101. of geometry: (xmin, ymin, xmax, ymax).
  102. """
  103. log.debug("Geometry->bounds()")
  104. if self.solid_geometry is None:
  105. log.debug("solid_geometry is None")
  106. return 0, 0, 0, 0
  107. if type(self.solid_geometry) is list:
  108. # TODO: This can be done faster. See comment from Shapely mailing lists.
  109. if len(self.solid_geometry) == 0:
  110. log.debug('solid_geometry is empty []')
  111. return 0, 0, 0, 0
  112. return cascaded_union(self.solid_geometry).bounds
  113. else:
  114. return self.solid_geometry.bounds
  115. def find_polygon(self, point, geoset=None):
  116. """
  117. Find an object that object.contains(Point(point)) in
  118. poly, which can can be iterable, contain iterable of, or
  119. be itself an implementer of .contains().
  120. :param poly: See description
  121. :return: Polygon containing point or None.
  122. """
  123. if geoset is None:
  124. geoset = self.solid_geometry
  125. try: # Iterable
  126. for sub_geo in geoset:
  127. p = self.find_polygon(point, geoset=sub_geo)
  128. if p is not None:
  129. return p
  130. except TypeError: # Non-iterable
  131. try: # Implements .contains()
  132. if geoset.contains(Point(point)):
  133. return geoset
  134. except AttributeError: # Does not implement .contains()
  135. return None
  136. return None
  137. def flatten(self, geometry=None, reset=True, pathonly=False):
  138. """
  139. Creates a list of non-iterable linear geometry objects.
  140. Polygons are expanded into its exterior and interiors if specified.
  141. Results are placed in self.flat_geoemtry
  142. :param geometry: Shapely type or list or list of list of such.
  143. :param reset: Clears the contents of self.flat_geometry.
  144. :param pathonly: Expands polygons into linear elements.
  145. """
  146. if geometry is None:
  147. geometry = self.solid_geometry
  148. if reset:
  149. self.flat_geometry = []
  150. ## If iterable, expand recursively.
  151. try:
  152. for geo in geometry:
  153. self.flatten(geometry=geo,
  154. reset=False,
  155. pathonly=pathonly)
  156. ## Not iterable, do the actual indexing and add.
  157. except TypeError:
  158. if pathonly and type(geometry) == Polygon:
  159. self.flat_geometry.append(geometry.exterior)
  160. self.flatten(geometry=geometry.interiors,
  161. reset=False,
  162. pathonly=True)
  163. else:
  164. self.flat_geometry.append(geometry)
  165. return self.flat_geometry
  166. # def make2Dstorage(self):
  167. #
  168. # self.flatten()
  169. #
  170. # def get_pts(o):
  171. # pts = []
  172. # if type(o) == Polygon:
  173. # g = o.exterior
  174. # pts += list(g.coords)
  175. # for i in o.interiors:
  176. # pts += list(i.coords)
  177. # else:
  178. # pts += list(o.coords)
  179. # return pts
  180. #
  181. # storage = FlatCAMRTreeStorage()
  182. # storage.get_points = get_pts
  183. # for shape in self.flat_geometry:
  184. # storage.insert(shape)
  185. # return storage
  186. # def flatten_to_paths(self, geometry=None, reset=True):
  187. # """
  188. # Creates a list of non-iterable linear geometry elements and
  189. # indexes them in rtree.
  190. #
  191. # :param geometry: Iterable geometry
  192. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  193. # :return: self.flat_geometry, self.flat_geometry_rtree
  194. # """
  195. #
  196. # if geometry is None:
  197. # geometry = self.solid_geometry
  198. #
  199. # if reset:
  200. # self.flat_geometry = []
  201. #
  202. # ## If iterable, expand recursively.
  203. # try:
  204. # for geo in geometry:
  205. # self.flatten_to_paths(geometry=geo, reset=False)
  206. #
  207. # ## Not iterable, do the actual indexing and add.
  208. # except TypeError:
  209. # if type(geometry) == Polygon:
  210. # g = geometry.exterior
  211. # self.flat_geometry.append(g)
  212. #
  213. # ## Add first and last points of the path to the index.
  214. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  215. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  216. #
  217. # for interior in geometry.interiors:
  218. # g = interior
  219. # self.flat_geometry.append(g)
  220. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  221. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  222. # else:
  223. # g = geometry
  224. # self.flat_geometry.append(g)
  225. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  226. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  227. #
  228. # return self.flat_geometry, self.flat_geometry_rtree
  229. def isolation_geometry(self, offset):
  230. """
  231. Creates contours around geometry at a given
  232. offset distance.
  233. :param offset: Offset distance.
  234. :type offset: float
  235. :return: The buffered geometry.
  236. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  237. """
  238. return self.solid_geometry.buffer(offset)
  239. def is_empty(self):
  240. if self.solid_geometry is None:
  241. return True
  242. if type(self.solid_geometry) is list and len(self.solid_geometry) == 0:
  243. return True
  244. return False
  245. def size(self):
  246. """
  247. Returns (width, height) of rectangular
  248. bounds of geometry.
  249. """
  250. if self.solid_geometry is None:
  251. log.warning("Solid_geometry not computed yet.")
  252. return 0
  253. bounds = self.bounds()
  254. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  255. def get_empty_area(self, boundary=None):
  256. """
  257. Returns the complement of self.solid_geometry within
  258. the given boundary polygon. If not specified, it defaults to
  259. the rectangular bounding box of self.solid_geometry.
  260. """
  261. if boundary is None:
  262. boundary = self.solid_geometry.envelope
  263. return boundary.difference(self.solid_geometry)
  264. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  265. """
  266. Creates geometry inside a polygon for a tool to cover
  267. the whole area.
  268. This algorithm shrinks the edges of the polygon and takes
  269. the resulting edges as toolpaths.
  270. :param polygon: Polygon to clear.
  271. :param tooldia: Diameter of the tool.
  272. :param overlap: Overlap of toolpasses.
  273. :return:
  274. """
  275. poly_cuts = [polygon.buffer(-tooldia / 2.0)]
  276. while True:
  277. polygon = poly_cuts[-1].buffer(-tooldia * (1 - overlap))
  278. if polygon.area > 0:
  279. poly_cuts.append(polygon)
  280. else:
  281. break
  282. return poly_cuts
  283. def clear_polygon2(self, polygon, tooldia, seedpoint=None, overlap=0.15):
  284. """
  285. Creates geometry inside a polygon for a tool to cover
  286. the whole area.
  287. This algorithm starts with a seed point inside the polygon
  288. and draws circles around it. Arcs inside the polygons are
  289. valid cuts. Finalizes by cutting around the inside edge of
  290. the polygon.
  291. :param polygon:
  292. :param tooldia:
  293. :param seedpoint:
  294. :param overlap:
  295. :return:
  296. """
  297. # Current buffer radius
  298. radius = tooldia / 2 * (1 - overlap)
  299. # The toolpaths
  300. geoms = []
  301. # Path margin
  302. path_margin = polygon.buffer(-tooldia / 2)
  303. # Estimate good seedpoint if not provided.
  304. if seedpoint is None:
  305. seedpoint = path_margin.representative_point()
  306. # Grow from seed until outside the box.
  307. while 1:
  308. path = Point(seedpoint).buffer(radius).exterior
  309. path = path.intersection(path_margin)
  310. # Touches polygon?
  311. if path.is_empty:
  312. break
  313. else:
  314. geoms.append(path)
  315. radius += tooldia * (1 - overlap)
  316. # Clean edges
  317. outer_edges = [x.exterior for x in autolist(polygon.buffer(-tooldia / 2))]
  318. inner_edges = []
  319. for x in autolist(polygon.buffer(-tooldia / 2)): # Over resulting polygons
  320. for y in x.interiors: # Over interiors of each polygon
  321. inner_edges.append(y)
  322. geoms += outer_edges + inner_edges
  323. # Optimization: Join paths
  324. # TODO: Re-architecture?
  325. # log.debug("Simplifying paths...")
  326. g = Geometry()
  327. g.solid_geometry = geoms
  328. # g.path_connect()
  329. #return g.flat_geometry
  330. g.flatten(pathonly=True)
  331. # Optimization: Reduce lifts
  332. log.debug("Reducing tool lifts...")
  333. p = self.paint_connect(g.flat_geometry, polygon, tooldia)
  334. return p
  335. #return geoms
  336. def scale(self, factor):
  337. """
  338. Scales all of the object's geometry by a given factor. Override
  339. this method.
  340. :param factor: Number by which to scale.
  341. :type factor: float
  342. :return: None
  343. :rtype: None
  344. """
  345. return
  346. def offset(self, vect):
  347. """
  348. Offset the geometry by the given vector. Override this method.
  349. :param vect: (x, y) vector by which to offset the object.
  350. :type vect: tuple
  351. :return: None
  352. """
  353. return
  354. @staticmethod
  355. def paint_connect(geolist, boundary, tooldia):
  356. """
  357. Connects paths that results in a connection segment that is
  358. within the paint area. This avoids unnecessary tool lifting.
  359. :return:
  360. """
  361. # Assuming geolist is a flat list of flat elements
  362. ## Index first and last points in paths
  363. def get_pts(o):
  364. return [o.coords[0], o.coords[-1]]
  365. storage = FlatCAMRTreeStorage()
  366. storage.get_points = get_pts
  367. for shape in geolist:
  368. if shape is not None: # TODO: This shouldn't have happened.
  369. # Make LlinearRings into linestrings otherwise
  370. # When chaining the coordinates path is messed up.
  371. storage.insert(LineString(shape))
  372. #storage.insert(shape)
  373. ## Iterate over geometry paths getting the nearest each time.
  374. optimized_paths = []
  375. path_count = 0
  376. current_pt = (0, 0)
  377. pt, geo = storage.nearest(current_pt)
  378. try:
  379. while True:
  380. path_count += 1
  381. log.debug("Path %d" % path_count)
  382. # Remove before modifying, otherwise
  383. # deletion will fail.
  384. storage.remove(geo)
  385. # If last point in geometry is the nearest
  386. # then reverse coordinates.
  387. if list(pt) == list(geo.coords[-1]):
  388. geo.coords = list(geo.coords)[::-1]
  389. # Straight line from current_pt to pt.
  390. # Is the toolpath inside the geometry?
  391. jump = LineString([current_pt, pt]).buffer(tooldia / 2)
  392. if jump.within(boundary):
  393. log.debug("Jump to path #%d is inside. Joining." % path_count)
  394. # Completely inside. Append...
  395. try:
  396. last = optimized_paths[-1]
  397. last.coords = list(last.coords) + list(geo.coords)
  398. except IndexError:
  399. optimized_paths.append(geo)
  400. else:
  401. # Have to lift tool. End path.
  402. log.debug("Path #%d not within boundary. Next." % path_count)
  403. optimized_paths.append(geo)
  404. current_pt = geo.coords[-1]
  405. # Next
  406. pt, geo = storage.nearest(current_pt)
  407. except StopIteration: # Nothing left in storage.
  408. pass
  409. return optimized_paths
  410. @staticmethod
  411. def path_connect(pathlist, origin=(0, 0)):
  412. """
  413. Simplifies a list of paths by joining those whose ends touch.
  414. The list of paths of generated from the geometry.flatten()
  415. method which writes to geometry.flat_geometry. This list
  416. if overwritten by this method with the optimized result.
  417. :return: None
  418. """
  419. ## Index first and last points in paths
  420. def get_pts(o):
  421. return [o.coords[0], o.coords[-1]]
  422. storage = FlatCAMRTreeStorage()
  423. storage.get_points = get_pts
  424. for shape in pathlist:
  425. if shape is not None: # TODO: This shouldn't have happened.
  426. storage.insert(shape)
  427. path_count = 0
  428. pt, geo = storage.nearest(origin)
  429. storage.remove(geo)
  430. optimized_geometry = [geo]
  431. try:
  432. while True:
  433. path_count += 1
  434. print "geo is", geo
  435. _, left = storage.nearest(geo.coords[0])
  436. print "left is", left
  437. if type(left) == LineString:
  438. if left.coords[0] == geo.coords[0]:
  439. storage.remove(left)
  440. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  441. continue
  442. if left.coords[-1] == geo.coords[0]:
  443. storage.remove(left)
  444. geo.coords = list(left.coords) + list(geo.coords)
  445. continue
  446. if left.coords[0] == geo.coords[-1]:
  447. storage.remove(left)
  448. geo.coords = list(geo.coords) + list(left.coords)
  449. continue
  450. if left.coords[-1] == geo.coords[-1]:
  451. storage.remove(left)
  452. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  453. continue
  454. _, right = storage.nearest(geo.coords[-1])
  455. print "right is", right
  456. if type(right) == LineString:
  457. if right.coords[0] == geo.coords[-1]:
  458. storage.remove(right)
  459. geo.coords = list(geo.coords) + list(right.coords)
  460. continue
  461. if right.coords[-1] == geo.coords[-1]:
  462. storage.remove(right)
  463. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  464. continue
  465. if right.coords[0] == geo.coords[0]:
  466. storage.remove(right)
  467. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  468. continue
  469. if right.coords[-1] == geo.coords[0]:
  470. storage.remove(right)
  471. geo.coords = list(left.coords) + list(geo.coords)
  472. continue
  473. # No matches on either end
  474. #optimized_geometry.append(geo)
  475. optimized_geometry.append(right)
  476. storage.remove(right)
  477. geo = right
  478. print "stored right, now geo<-right"
  479. # Next
  480. #_, geo = storage.nearest(geo.coords[0])
  481. #optimized_geometry.append(geo)
  482. except StopIteration: # Nothing found in storage.
  483. pass
  484. print path_count
  485. #self.flat_geometry = optimized_geometry
  486. return optimized_geometry
  487. def convert_units(self, units):
  488. """
  489. Converts the units of the object to ``units`` by scaling all
  490. the geometry appropriately. This call ``scale()``. Don't call
  491. it again in descendents.
  492. :param units: "IN" or "MM"
  493. :type units: str
  494. :return: Scaling factor resulting from unit change.
  495. :rtype: float
  496. """
  497. log.debug("Geometry.convert_units()")
  498. if units.upper() == self.units.upper():
  499. return 1.0
  500. if units.upper() == "MM":
  501. factor = 25.4
  502. elif units.upper() == "IN":
  503. factor = 1/25.4
  504. else:
  505. log.error("Unsupported units: %s" % str(units))
  506. return 1.0
  507. self.units = units
  508. self.scale(factor)
  509. return factor
  510. def to_dict(self):
  511. """
  512. Returns a respresentation of the object as a dictionary.
  513. Attributes to include are listed in ``self.ser_attrs``.
  514. :return: A dictionary-encoded copy of the object.
  515. :rtype: dict
  516. """
  517. d = {}
  518. for attr in self.ser_attrs:
  519. d[attr] = getattr(self, attr)
  520. return d
  521. def from_dict(self, d):
  522. """
  523. Sets object's attributes from a dictionary.
  524. Attributes to include are listed in ``self.ser_attrs``.
  525. This method will look only for only and all the
  526. attributes in ``self.ser_attrs``. They must all
  527. be present. Use only for deserializing saved
  528. objects.
  529. :param d: Dictionary of attributes to set in the object.
  530. :type d: dict
  531. :return: None
  532. """
  533. for attr in self.ser_attrs:
  534. setattr(self, attr, d[attr])
  535. def union(self):
  536. """
  537. Runs a cascaded union on the list of objects in
  538. solid_geometry.
  539. :return: None
  540. """
  541. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  542. class ApertureMacro:
  543. """
  544. Syntax of aperture macros.
  545. <AM command>: AM<Aperture macro name>*<Macro content>
  546. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  547. <Variable definition>: $K=<Arithmetic expression>
  548. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  549. <Modifier>: $M|< Arithmetic expression>
  550. <Comment>: 0 <Text>
  551. """
  552. ## Regular expressions
  553. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  554. am2_re = re.compile(r'(.*)%$')
  555. amcomm_re = re.compile(r'^0(.*)')
  556. amprim_re = re.compile(r'^[1-9].*')
  557. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  558. def __init__(self, name=None):
  559. self.name = name
  560. self.raw = ""
  561. ## These below are recomputed for every aperture
  562. ## definition, in other words, are temporary variables.
  563. self.primitives = []
  564. self.locvars = {}
  565. self.geometry = None
  566. def to_dict(self):
  567. """
  568. Returns the object in a serializable form. Only the name and
  569. raw are required.
  570. :return: Dictionary representing the object. JSON ready.
  571. :rtype: dict
  572. """
  573. return {
  574. 'name': self.name,
  575. 'raw': self.raw
  576. }
  577. def from_dict(self, d):
  578. """
  579. Populates the object from a serial representation created
  580. with ``self.to_dict()``.
  581. :param d: Serial representation of an ApertureMacro object.
  582. :return: None
  583. """
  584. for attr in ['name', 'raw']:
  585. setattr(self, attr, d[attr])
  586. def parse_content(self):
  587. """
  588. Creates numerical lists for all primitives in the aperture
  589. macro (in ``self.raw``) by replacing all variables by their
  590. values iteratively and evaluating expressions. Results
  591. are stored in ``self.primitives``.
  592. :return: None
  593. """
  594. # Cleanup
  595. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  596. self.primitives = []
  597. # Separate parts
  598. parts = self.raw.split('*')
  599. #### Every part in the macro ####
  600. for part in parts:
  601. ### Comments. Ignored.
  602. match = ApertureMacro.amcomm_re.search(part)
  603. if match:
  604. continue
  605. ### Variables
  606. # These are variables defined locally inside the macro. They can be
  607. # numerical constant or defind in terms of previously define
  608. # variables, which can be defined locally or in an aperture
  609. # definition. All replacements ocurr here.
  610. match = ApertureMacro.amvar_re.search(part)
  611. if match:
  612. var = match.group(1)
  613. val = match.group(2)
  614. # Replace variables in value
  615. for v in self.locvars:
  616. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  617. # Make all others 0
  618. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  619. # Change x with *
  620. val = re.sub(r'[xX]', "*", val)
  621. # Eval() and store.
  622. self.locvars[var] = eval(val)
  623. continue
  624. ### Primitives
  625. # Each is an array. The first identifies the primitive, while the
  626. # rest depend on the primitive. All are strings representing a
  627. # number and may contain variable definition. The values of these
  628. # variables are defined in an aperture definition.
  629. match = ApertureMacro.amprim_re.search(part)
  630. if match:
  631. ## Replace all variables
  632. for v in self.locvars:
  633. part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  634. # Make all others 0
  635. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  636. # Change x with *
  637. part = re.sub(r'[xX]', "*", part)
  638. ## Store
  639. elements = part.split(",")
  640. self.primitives.append([eval(x) for x in elements])
  641. continue
  642. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  643. def append(self, data):
  644. """
  645. Appends a string to the raw macro.
  646. :param data: Part of the macro.
  647. :type data: str
  648. :return: None
  649. """
  650. self.raw += data
  651. @staticmethod
  652. def default2zero(n, mods):
  653. """
  654. Pads the ``mods`` list with zeros resulting in an
  655. list of length n.
  656. :param n: Length of the resulting list.
  657. :type n: int
  658. :param mods: List to be padded.
  659. :type mods: list
  660. :return: Zero-padded list.
  661. :rtype: list
  662. """
  663. x = [0.0] * n
  664. na = len(mods)
  665. x[0:na] = mods
  666. return x
  667. @staticmethod
  668. def make_circle(mods):
  669. """
  670. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  671. :return:
  672. """
  673. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  674. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  675. @staticmethod
  676. def make_vectorline(mods):
  677. """
  678. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  679. rotation angle around origin in degrees)
  680. :return:
  681. """
  682. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  683. line = LineString([(xs, ys), (xe, ye)])
  684. box = line.buffer(width/2, cap_style=2)
  685. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  686. return {"pol": int(pol), "geometry": box_rotated}
  687. @staticmethod
  688. def make_centerline(mods):
  689. """
  690. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  691. rotation angle around origin in degrees)
  692. :return:
  693. """
  694. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  695. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  696. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  697. return {"pol": int(pol), "geometry": box_rotated}
  698. @staticmethod
  699. def make_lowerleftline(mods):
  700. """
  701. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  702. rotation angle around origin in degrees)
  703. :return:
  704. """
  705. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  706. box = shply_box(x, y, x+width, y+height)
  707. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  708. return {"pol": int(pol), "geometry": box_rotated}
  709. @staticmethod
  710. def make_outline(mods):
  711. """
  712. :param mods:
  713. :return:
  714. """
  715. pol = mods[0]
  716. n = mods[1]
  717. points = [(0, 0)]*(n+1)
  718. for i in range(n+1):
  719. points[i] = mods[2*i + 2:2*i + 4]
  720. angle = mods[2*n + 4]
  721. poly = Polygon(points)
  722. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  723. return {"pol": int(pol), "geometry": poly_rotated}
  724. @staticmethod
  725. def make_polygon(mods):
  726. """
  727. Note: Specs indicate that rotation is only allowed if the center
  728. (x, y) == (0, 0). I will tolerate breaking this rule.
  729. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  730. diameter of circumscribed circle >=0, rotation angle around origin)
  731. :return:
  732. """
  733. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  734. points = [(0, 0)]*nverts
  735. for i in range(nverts):
  736. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  737. y + 0.5 * dia * sin(2*pi * i/nverts))
  738. poly = Polygon(points)
  739. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  740. return {"pol": int(pol), "geometry": poly_rotated}
  741. @staticmethod
  742. def make_moire(mods):
  743. """
  744. Note: Specs indicate that rotation is only allowed if the center
  745. (x, y) == (0, 0). I will tolerate breaking this rule.
  746. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  747. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  748. angle around origin in degrees)
  749. :return:
  750. """
  751. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  752. r = dia/2 - thickness/2
  753. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  754. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  755. i = 1 # Number of rings created so far
  756. ## If the ring does not have an interior it means that it is
  757. ## a disk. Then stop.
  758. while len(ring.interiors) > 0 and i < nrings:
  759. r -= thickness + gap
  760. if r <= 0:
  761. break
  762. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  763. result = cascaded_union([result, ring])
  764. i += 1
  765. ## Crosshair
  766. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  767. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  768. result = cascaded_union([result, hor, ver])
  769. return {"pol": 1, "geometry": result}
  770. @staticmethod
  771. def make_thermal(mods):
  772. """
  773. Note: Specs indicate that rotation is only allowed if the center
  774. (x, y) == (0, 0). I will tolerate breaking this rule.
  775. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  776. gap-thickness, rotation angle around origin]
  777. :return:
  778. """
  779. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  780. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  781. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  782. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  783. thermal = ring.difference(hline.union(vline))
  784. return {"pol": 1, "geometry": thermal}
  785. def make_geometry(self, modifiers):
  786. """
  787. Runs the macro for the given modifiers and generates
  788. the corresponding geometry.
  789. :param modifiers: Modifiers (parameters) for this macro
  790. :type modifiers: list
  791. """
  792. ## Primitive makers
  793. makers = {
  794. "1": ApertureMacro.make_circle,
  795. "2": ApertureMacro.make_vectorline,
  796. "20": ApertureMacro.make_vectorline,
  797. "21": ApertureMacro.make_centerline,
  798. "22": ApertureMacro.make_lowerleftline,
  799. "4": ApertureMacro.make_outline,
  800. "5": ApertureMacro.make_polygon,
  801. "6": ApertureMacro.make_moire,
  802. "7": ApertureMacro.make_thermal
  803. }
  804. ## Store modifiers as local variables
  805. modifiers = modifiers or []
  806. modifiers = [float(m) for m in modifiers]
  807. self.locvars = {}
  808. for i in range(0, len(modifiers)):
  809. self.locvars[str(i+1)] = modifiers[i]
  810. ## Parse
  811. self.primitives = [] # Cleanup
  812. self.geometry = None
  813. self.parse_content()
  814. ## Make the geometry
  815. for primitive in self.primitives:
  816. # Make the primitive
  817. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  818. # Add it (according to polarity)
  819. if self.geometry is None and prim_geo['pol'] == 1:
  820. self.geometry = prim_geo['geometry']
  821. continue
  822. if prim_geo['pol'] == 1:
  823. self.geometry = self.geometry.union(prim_geo['geometry'])
  824. continue
  825. if prim_geo['pol'] == 0:
  826. self.geometry = self.geometry.difference(prim_geo['geometry'])
  827. continue
  828. return self.geometry
  829. class Gerber (Geometry):
  830. """
  831. **ATTRIBUTES**
  832. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  833. The values are dictionaries key/value pairs which describe the aperture. The
  834. type key is always present and the rest depend on the key:
  835. +-----------+-----------------------------------+
  836. | Key | Value |
  837. +===========+===================================+
  838. | type | (str) "C", "R", "O", "P", or "AP" |
  839. +-----------+-----------------------------------+
  840. | others | Depend on ``type`` |
  841. +-----------+-----------------------------------+
  842. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  843. that can be instanciated with different parameters in an aperture
  844. definition. See ``apertures`` above. The key is the name of the macro,
  845. and the macro itself, the value, is a ``Aperture_Macro`` object.
  846. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  847. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  848. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  849. *buffering* (or thickening) the ``paths`` with the aperture. These are
  850. generated from ``paths`` in ``buffer_paths()``.
  851. **USAGE**::
  852. g = Gerber()
  853. g.parse_file(filename)
  854. g.create_geometry()
  855. do_something(s.solid_geometry)
  856. """
  857. defaults = {
  858. "steps_per_circle": 40
  859. }
  860. def __init__(self, steps_per_circle=None):
  861. """
  862. The constructor takes no parameters. Use ``gerber.parse_files()``
  863. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  864. :return: Gerber object
  865. :rtype: Gerber
  866. """
  867. # Initialize parent
  868. Geometry.__init__(self)
  869. self.solid_geometry = Polygon()
  870. # Number format
  871. self.int_digits = 3
  872. """Number of integer digits in Gerber numbers. Used during parsing."""
  873. self.frac_digits = 4
  874. """Number of fraction digits in Gerber numbers. Used during parsing."""
  875. ## Gerber elements ##
  876. # Apertures {'id':{'type':chr,
  877. # ['size':float], ['width':float],
  878. # ['height':float]}, ...}
  879. self.apertures = {}
  880. # Aperture Macros
  881. self.aperture_macros = {}
  882. # Attributes to be included in serialization
  883. # Always append to it because it carries contents
  884. # from Geometry.
  885. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  886. 'aperture_macros', 'solid_geometry']
  887. #### Parser patterns ####
  888. # FS - Format Specification
  889. # The format of X and Y must be the same!
  890. # L-omit leading zeros, T-omit trailing zeros
  891. # A-absolute notation, I-incremental notation
  892. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  893. # Mode (IN/MM)
  894. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  895. # Comment G04|G4
  896. self.comm_re = re.compile(r'^G0?4(.*)$')
  897. # AD - Aperture definition
  898. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.]*)(?:,(.*))?\*%$')
  899. # AM - Aperture Macro
  900. # Beginning of macro (Ends with *%):
  901. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  902. # Tool change
  903. # May begin with G54 but that is deprecated
  904. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  905. # G01... - Linear interpolation plus flashes with coordinates
  906. # Operation code (D0x) missing is deprecated... oh well I will support it.
  907. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  908. # Operation code alone, usually just D03 (Flash)
  909. self.opcode_re = re.compile(r'^D0?([123])\*$')
  910. # G02/3... - Circular interpolation with coordinates
  911. # 2-clockwise, 3-counterclockwise
  912. # Operation code (D0x) missing is deprecated... oh well I will support it.
  913. # Optional start with G02 or G03, optional end with D01 or D02 with
  914. # optional coordinates but at least one in any order.
  915. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))' +
  916. '?(?=.*I(-?\d+))?(?=.*J(-?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  917. # G01/2/3 Occurring without coordinates
  918. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  919. # Single D74 or multi D75 quadrant for circular interpolation
  920. self.quad_re = re.compile(r'^G7([45])\*$')
  921. # Region mode on
  922. # In region mode, D01 starts a region
  923. # and D02 ends it. A new region can be started again
  924. # with D01. All contours must be closed before
  925. # D02 or G37.
  926. self.regionon_re = re.compile(r'^G36\*$')
  927. # Region mode off
  928. # Will end a region and come off region mode.
  929. # All contours must be closed before D02 or G37.
  930. self.regionoff_re = re.compile(r'^G37\*$')
  931. # End of file
  932. self.eof_re = re.compile(r'^M02\*')
  933. # IP - Image polarity
  934. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  935. # LP - Level polarity
  936. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  937. # Units (OBSOLETE)
  938. self.units_re = re.compile(r'^G7([01])\*$')
  939. # Absolute/Relative G90/1 (OBSOLETE)
  940. self.absrel_re = re.compile(r'^G9([01])\*$')
  941. # Aperture macros
  942. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  943. self.am2_re = re.compile(r'(.*)%$')
  944. # How to discretize a circle.
  945. self.steps_per_circ = steps_per_circle or Gerber.defaults['steps_per_circle']
  946. def scale(self, factor):
  947. """
  948. Scales the objects' geometry on the XY plane by a given factor.
  949. These are:
  950. * ``buffered_paths``
  951. * ``flash_geometry``
  952. * ``solid_geometry``
  953. * ``regions``
  954. NOTE:
  955. Does not modify the data used to create these elements. If these
  956. are recreated, the scaling will be lost. This behavior was modified
  957. because of the complexity reached in this class.
  958. :param factor: Number by which to scale.
  959. :type factor: float
  960. :rtype : None
  961. """
  962. ## solid_geometry ???
  963. # It's a cascaded union of objects.
  964. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  965. factor, origin=(0, 0))
  966. # # Now buffered_paths, flash_geometry and solid_geometry
  967. # self.create_geometry()
  968. def offset(self, vect):
  969. """
  970. Offsets the objects' geometry on the XY plane by a given vector.
  971. These are:
  972. * ``buffered_paths``
  973. * ``flash_geometry``
  974. * ``solid_geometry``
  975. * ``regions``
  976. NOTE:
  977. Does not modify the data used to create these elements. If these
  978. are recreated, the scaling will be lost. This behavior was modified
  979. because of the complexity reached in this class.
  980. :param vect: (x, y) offset vector.
  981. :type vect: tuple
  982. :return: None
  983. """
  984. dx, dy = vect
  985. ## Solid geometry
  986. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  987. def mirror(self, axis, point):
  988. """
  989. Mirrors the object around a specified axis passign through
  990. the given point. What is affected:
  991. * ``buffered_paths``
  992. * ``flash_geometry``
  993. * ``solid_geometry``
  994. * ``regions``
  995. NOTE:
  996. Does not modify the data used to create these elements. If these
  997. are recreated, the scaling will be lost. This behavior was modified
  998. because of the complexity reached in this class.
  999. :param axis: "X" or "Y" indicates around which axis to mirror.
  1000. :type axis: str
  1001. :param point: [x, y] point belonging to the mirror axis.
  1002. :type point: list
  1003. :return: None
  1004. """
  1005. px, py = point
  1006. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1007. ## solid_geometry ???
  1008. # It's a cascaded union of objects.
  1009. self.solid_geometry = affinity.scale(self.solid_geometry,
  1010. xscale, yscale, origin=(px, py))
  1011. def aperture_parse(self, apertureId, apertureType, apParameters):
  1012. """
  1013. Parse gerber aperture definition into dictionary of apertures.
  1014. The following kinds and their attributes are supported:
  1015. * *Circular (C)*: size (float)
  1016. * *Rectangle (R)*: width (float), height (float)
  1017. * *Obround (O)*: width (float), height (float).
  1018. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  1019. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  1020. :param apertureId: Id of the aperture being defined.
  1021. :param apertureType: Type of the aperture.
  1022. :param apParameters: Parameters of the aperture.
  1023. :type apertureId: str
  1024. :type apertureType: str
  1025. :type apParameters: str
  1026. :return: Identifier of the aperture.
  1027. :rtype: str
  1028. """
  1029. # Found some Gerber with a leading zero in the aperture id and the
  1030. # referenced it without the zero, so this is a hack to handle that.
  1031. apid = str(int(apertureId))
  1032. try: # Could be empty for aperture macros
  1033. paramList = apParameters.split('X')
  1034. except:
  1035. paramList = None
  1036. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  1037. self.apertures[apid] = {"type": "C",
  1038. "size": float(paramList[0])}
  1039. return apid
  1040. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  1041. self.apertures[apid] = {"type": "R",
  1042. "width": float(paramList[0]),
  1043. "height": float(paramList[1]),
  1044. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1045. return apid
  1046. if apertureType == "O": # Obround
  1047. self.apertures[apid] = {"type": "O",
  1048. "width": float(paramList[0]),
  1049. "height": float(paramList[1]),
  1050. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1051. return apid
  1052. if apertureType == "P": # Polygon (regular)
  1053. self.apertures[apid] = {"type": "P",
  1054. "diam": float(paramList[0]),
  1055. "nVertices": int(paramList[1]),
  1056. "size": float(paramList[0])} # Hack
  1057. if len(paramList) >= 3:
  1058. self.apertures[apid]["rotation"] = float(paramList[2])
  1059. return apid
  1060. if apertureType in self.aperture_macros:
  1061. self.apertures[apid] = {"type": "AM",
  1062. "macro": self.aperture_macros[apertureType],
  1063. "modifiers": paramList}
  1064. return apid
  1065. log.warning("Aperture not implemented: %s" % str(apertureType))
  1066. return None
  1067. def parse_file(self, filename, follow=False):
  1068. """
  1069. Calls Gerber.parse_lines() with array of lines
  1070. read from the given file.
  1071. :param filename: Gerber file to parse.
  1072. :type filename: str
  1073. :param follow: If true, will not create polygons, just lines
  1074. following the gerber path.
  1075. :type follow: bool
  1076. :return: None
  1077. """
  1078. gfile = open(filename, 'r')
  1079. gstr = gfile.readlines()
  1080. gfile.close()
  1081. self.parse_lines(gstr, follow=follow)
  1082. def parse_lines(self, glines, follow=False):
  1083. """
  1084. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  1085. ``self.flashes``, ``self.regions`` and ``self.units``.
  1086. :param glines: Gerber code as list of strings, each element being
  1087. one line of the source file.
  1088. :type glines: list
  1089. :param follow: If true, will not create polygons, just lines
  1090. following the gerber path.
  1091. :type follow: bool
  1092. :return: None
  1093. :rtype: None
  1094. """
  1095. # Coordinates of the current path, each is [x, y]
  1096. path = []
  1097. # Polygons are stored here until there is a change in polarity.
  1098. # Only then they are combined via cascaded_union and added or
  1099. # subtracted from solid_geometry. This is ~100 times faster than
  1100. # applyng a union for every new polygon.
  1101. poly_buffer = []
  1102. last_path_aperture = None
  1103. current_aperture = None
  1104. # 1,2 or 3 from "G01", "G02" or "G03"
  1105. current_interpolation_mode = None
  1106. # 1 or 2 from "D01" or "D02"
  1107. # Note this is to support deprecated Gerber not putting
  1108. # an operation code at the end of every coordinate line.
  1109. current_operation_code = None
  1110. # Current coordinates
  1111. current_x = None
  1112. current_y = None
  1113. # Absolute or Relative/Incremental coordinates
  1114. # Not implemented
  1115. absolute = True
  1116. # How to interpret circular interpolation: SINGLE or MULTI
  1117. quadrant_mode = None
  1118. # Indicates we are parsing an aperture macro
  1119. current_macro = None
  1120. # Indicates the current polarity: D-Dark, C-Clear
  1121. current_polarity = 'D'
  1122. # If a region is being defined
  1123. making_region = False
  1124. #### Parsing starts here ####
  1125. line_num = 0
  1126. gline = ""
  1127. try:
  1128. for gline in glines:
  1129. line_num += 1
  1130. ### Cleanup
  1131. gline = gline.strip(' \r\n')
  1132. #log.debug("%3s %s" % (line_num, gline))
  1133. ### Aperture Macros
  1134. # Having this at the beggining will slow things down
  1135. # but macros can have complicated statements than could
  1136. # be caught by other patterns.
  1137. if current_macro is None: # No macro started yet
  1138. match = self.am1_re.search(gline)
  1139. # Start macro if match, else not an AM, carry on.
  1140. if match:
  1141. log.info("Starting macro. Line %d: %s" % (line_num, gline))
  1142. current_macro = match.group(1)
  1143. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  1144. if match.group(2): # Append
  1145. self.aperture_macros[current_macro].append(match.group(2))
  1146. if match.group(3): # Finish macro
  1147. #self.aperture_macros[current_macro].parse_content()
  1148. current_macro = None
  1149. log.info("Macro complete in 1 line.")
  1150. continue
  1151. else: # Continue macro
  1152. log.info("Continuing macro. Line %d." % line_num)
  1153. match = self.am2_re.search(gline)
  1154. if match: # Finish macro
  1155. log.info("End of macro. Line %d." % line_num)
  1156. self.aperture_macros[current_macro].append(match.group(1))
  1157. #self.aperture_macros[current_macro].parse_content()
  1158. current_macro = None
  1159. else: # Append
  1160. self.aperture_macros[current_macro].append(gline)
  1161. continue
  1162. ### G01 - Linear interpolation plus flashes
  1163. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1164. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  1165. match = self.lin_re.search(gline)
  1166. if match:
  1167. # Dxx alone?
  1168. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  1169. # try:
  1170. # current_operation_code = int(match.group(4))
  1171. # except:
  1172. # pass # A line with just * will match too.
  1173. # continue
  1174. # NOTE: Letting it continue allows it to react to the
  1175. # operation code.
  1176. # Parse coordinates
  1177. if match.group(2) is not None:
  1178. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  1179. if match.group(3) is not None:
  1180. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  1181. # Parse operation code
  1182. if match.group(4) is not None:
  1183. current_operation_code = int(match.group(4))
  1184. # Pen down: add segment
  1185. if current_operation_code == 1:
  1186. path.append([current_x, current_y])
  1187. last_path_aperture = current_aperture
  1188. elif current_operation_code == 2:
  1189. if len(path) > 1:
  1190. ## --- BUFFERED ---
  1191. if making_region:
  1192. geo = Polygon(path)
  1193. else:
  1194. if last_path_aperture is None:
  1195. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1196. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  1197. #log.debug("Line %d: Setting aperture to %s before buffering." % (line_num, last_path_aperture))
  1198. if follow:
  1199. geo = LineString(path)
  1200. else:
  1201. geo = LineString(path).buffer(width / 2)
  1202. poly_buffer.append(geo)
  1203. path = [[current_x, current_y]] # Start new path
  1204. # Flash
  1205. elif current_operation_code == 3:
  1206. # --- BUFFERED ---
  1207. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  1208. self.apertures[current_aperture])
  1209. poly_buffer.append(flash)
  1210. continue
  1211. ### G02/3 - Circular interpolation
  1212. # 2-clockwise, 3-counterclockwise
  1213. match = self.circ_re.search(gline)
  1214. if match:
  1215. arcdir = [None, None, "cw", "ccw"]
  1216. mode, x, y, i, j, d = match.groups()
  1217. try:
  1218. x = parse_gerber_number(x, self.frac_digits)
  1219. except:
  1220. x = current_x
  1221. try:
  1222. y = parse_gerber_number(y, self.frac_digits)
  1223. except:
  1224. y = current_y
  1225. try:
  1226. i = parse_gerber_number(i, self.frac_digits)
  1227. except:
  1228. i = 0
  1229. try:
  1230. j = parse_gerber_number(j, self.frac_digits)
  1231. except:
  1232. j = 0
  1233. if quadrant_mode is None:
  1234. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  1235. log.error(gline)
  1236. continue
  1237. if mode is None and current_interpolation_mode not in [2, 3]:
  1238. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  1239. log.error(gline)
  1240. continue
  1241. elif mode is not None:
  1242. current_interpolation_mode = int(mode)
  1243. # Set operation code if provided
  1244. if d is not None:
  1245. current_operation_code = int(d)
  1246. # Nothing created! Pen Up.
  1247. if current_operation_code == 2:
  1248. log.warning("Arc with D2. (%d)" % line_num)
  1249. if len(path) > 1:
  1250. if last_path_aperture is None:
  1251. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1252. # --- BUFFERED ---
  1253. width = self.apertures[last_path_aperture]["size"]
  1254. buffered = LineString(path).buffer(width / 2)
  1255. poly_buffer.append(buffered)
  1256. current_x = x
  1257. current_y = y
  1258. path = [[current_x, current_y]] # Start new path
  1259. continue
  1260. # Flash should not happen here
  1261. if current_operation_code == 3:
  1262. log.error("Trying to flash within arc. (%d)" % line_num)
  1263. continue
  1264. if quadrant_mode == 'MULTI':
  1265. center = [i + current_x, j + current_y]
  1266. radius = sqrt(i ** 2 + j ** 2)
  1267. start = arctan2(-j, -i) # Start angle
  1268. # Numerical errors might prevent start == stop therefore
  1269. # we check ahead of time. This should result in a
  1270. # 360 degree arc.
  1271. if current_x == x and current_y == y:
  1272. stop = start
  1273. else:
  1274. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1275. this_arc = arc(center, radius, start, stop,
  1276. arcdir[current_interpolation_mode],
  1277. self.steps_per_circ)
  1278. # Last point in path is current point
  1279. current_x = this_arc[-1][0]
  1280. current_y = this_arc[-1][1]
  1281. # Append
  1282. path += this_arc
  1283. last_path_aperture = current_aperture
  1284. continue
  1285. if quadrant_mode == 'SINGLE':
  1286. center_candidates = [
  1287. [i + current_x, j + current_y],
  1288. [-i + current_x, j + current_y],
  1289. [i + current_x, -j + current_y],
  1290. [-i + current_x, -j + current_y]
  1291. ]
  1292. valid = False
  1293. log.debug("I: %f J: %f" % (i, j))
  1294. for center in center_candidates:
  1295. radius = sqrt(i ** 2 + j ** 2)
  1296. # Make sure radius to start is the same as radius to end.
  1297. radius2 = sqrt((center[0] - x) ** 2 + (center[1] - y) ** 2)
  1298. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1299. continue # Not a valid center.
  1300. # Correct i and j and continue as with multi-quadrant.
  1301. i = center[0] - current_x
  1302. j = center[1] - current_y
  1303. start = arctan2(-j, -i) # Start angle
  1304. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1305. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1306. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1307. (current_x, current_y, center[0], center[1], x, y))
  1308. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1309. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  1310. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  1311. if angle <= (pi + 1e-6) / 2:
  1312. log.debug("########## ACCEPTING ARC ############")
  1313. this_arc = arc(center, radius, start, stop,
  1314. arcdir[current_interpolation_mode],
  1315. self.steps_per_circ)
  1316. current_x = this_arc[-1][0]
  1317. current_y = this_arc[-1][1]
  1318. path += this_arc
  1319. last_path_aperture = current_aperture
  1320. valid = True
  1321. break
  1322. if valid:
  1323. continue
  1324. else:
  1325. log.warning("Invalid arc in line %d." % line_num)
  1326. ### Operation code alone
  1327. # Operation code alone, usually just D03 (Flash)
  1328. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1329. match = self.opcode_re.search(gline)
  1330. if match:
  1331. current_operation_code = int(match.group(1))
  1332. if current_operation_code == 3:
  1333. ## --- Buffered ---
  1334. try:
  1335. log.debug("Bare op-code %d." % current_operation_code)
  1336. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1337. # self.apertures[current_aperture])
  1338. flash = Gerber.create_flash_geometry(Point(current_x, current_y),
  1339. self.apertures[current_aperture])
  1340. poly_buffer.append(flash)
  1341. except IndexError:
  1342. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1343. continue
  1344. ### G74/75* - Single or multiple quadrant arcs
  1345. match = self.quad_re.search(gline)
  1346. if match:
  1347. if match.group(1) == '4':
  1348. quadrant_mode = 'SINGLE'
  1349. else:
  1350. quadrant_mode = 'MULTI'
  1351. continue
  1352. ### G36* - Begin region
  1353. if self.regionon_re.search(gline):
  1354. if len(path) > 1:
  1355. # Take care of what is left in the path
  1356. ## --- Buffered ---
  1357. width = self.apertures[last_path_aperture]["size"]
  1358. geo = LineString(path).buffer(width/2)
  1359. poly_buffer.append(geo)
  1360. path = [path[-1]]
  1361. making_region = True
  1362. continue
  1363. ### G37* - End region
  1364. if self.regionoff_re.search(gline):
  1365. making_region = False
  1366. # Only one path defines region?
  1367. # This can happen if D02 happened before G37 and
  1368. # is not and error.
  1369. if len(path) < 3:
  1370. # print "ERROR: Path contains less than 3 points:"
  1371. # print path
  1372. # print "Line (%d): " % line_num, gline
  1373. # path = []
  1374. #path = [[current_x, current_y]]
  1375. continue
  1376. # For regions we may ignore an aperture that is None
  1377. # self.regions.append({"polygon": Polygon(path),
  1378. # "aperture": last_path_aperture})
  1379. # --- Buffered ---
  1380. region = Polygon(path)
  1381. if not region.is_valid:
  1382. region = region.buffer(0)
  1383. poly_buffer.append(region)
  1384. path = [[current_x, current_y]] # Start new path
  1385. continue
  1386. ### Aperture definitions %ADD...
  1387. match = self.ad_re.search(gline)
  1388. if match:
  1389. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1390. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1391. continue
  1392. ### G01/2/3* - Interpolation mode change
  1393. # Can occur along with coordinates and operation code but
  1394. # sometimes by itself (handled here).
  1395. # Example: G01*
  1396. match = self.interp_re.search(gline)
  1397. if match:
  1398. current_interpolation_mode = int(match.group(1))
  1399. continue
  1400. ### Tool/aperture change
  1401. # Example: D12*
  1402. match = self.tool_re.search(gline)
  1403. if match:
  1404. current_aperture = match.group(1)
  1405. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1406. log.debug(self.apertures[current_aperture])
  1407. # Take care of the current path with the previous tool
  1408. if len(path) > 1:
  1409. # --- Buffered ----
  1410. width = self.apertures[last_path_aperture]["size"]
  1411. geo = LineString(path).buffer(width / 2)
  1412. poly_buffer.append(geo)
  1413. path = [path[-1]]
  1414. continue
  1415. ### Polarity change
  1416. # Example: %LPD*% or %LPC*%
  1417. # If polarity changes, creates geometry from current
  1418. # buffer, then adds or subtracts accordingly.
  1419. match = self.lpol_re.search(gline)
  1420. if match:
  1421. if len(path) > 1 and current_polarity != match.group(1):
  1422. # --- Buffered ----
  1423. width = self.apertures[last_path_aperture]["size"]
  1424. geo = LineString(path).buffer(width / 2)
  1425. poly_buffer.append(geo)
  1426. path = [path[-1]]
  1427. # --- Apply buffer ---
  1428. # If added for testing of bug #83
  1429. # TODO: Remove when bug fixed
  1430. if len(poly_buffer) > 0:
  1431. if current_polarity == 'D':
  1432. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1433. else:
  1434. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1435. poly_buffer = []
  1436. current_polarity = match.group(1)
  1437. continue
  1438. ### Number format
  1439. # Example: %FSLAX24Y24*%
  1440. # TODO: This is ignoring most of the format. Implement the rest.
  1441. match = self.fmt_re.search(gline)
  1442. if match:
  1443. absolute = {'A': True, 'I': False}
  1444. self.int_digits = int(match.group(3))
  1445. self.frac_digits = int(match.group(4))
  1446. continue
  1447. ### Mode (IN/MM)
  1448. # Example: %MOIN*%
  1449. match = self.mode_re.search(gline)
  1450. if match:
  1451. self.units = match.group(1)
  1452. continue
  1453. ### Units (G70/1) OBSOLETE
  1454. match = self.units_re.search(gline)
  1455. if match:
  1456. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1457. continue
  1458. ### Absolute/relative coordinates G90/1 OBSOLETE
  1459. match = self.absrel_re.search(gline)
  1460. if match:
  1461. absolute = {'0': True, '1': False}[match.group(1)]
  1462. continue
  1463. #### Ignored lines
  1464. ## Comments
  1465. match = self.comm_re.search(gline)
  1466. if match:
  1467. continue
  1468. ## EOF
  1469. match = self.eof_re.search(gline)
  1470. if match:
  1471. continue
  1472. ### Line did not match any pattern. Warn user.
  1473. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1474. if len(path) > 1:
  1475. # EOF, create shapely LineString if something still in path
  1476. ## --- Buffered ---
  1477. width = self.apertures[last_path_aperture]["size"]
  1478. geo = LineString(path).buffer(width/2)
  1479. poly_buffer.append(geo)
  1480. # --- Apply buffer ---
  1481. if current_polarity == 'D':
  1482. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1483. else:
  1484. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1485. except Exception, err:
  1486. #print traceback.format_exc()
  1487. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1488. raise
  1489. @staticmethod
  1490. def create_flash_geometry(location, aperture):
  1491. log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1492. if type(location) == list:
  1493. location = Point(location)
  1494. if aperture['type'] == 'C': # Circles
  1495. return location.buffer(aperture['size'] / 2)
  1496. if aperture['type'] == 'R': # Rectangles
  1497. loc = location.coords[0]
  1498. width = aperture['width']
  1499. height = aperture['height']
  1500. minx = loc[0] - width / 2
  1501. maxx = loc[0] + width / 2
  1502. miny = loc[1] - height / 2
  1503. maxy = loc[1] + height / 2
  1504. return shply_box(minx, miny, maxx, maxy)
  1505. if aperture['type'] == 'O': # Obround
  1506. loc = location.coords[0]
  1507. width = aperture['width']
  1508. height = aperture['height']
  1509. if width > height:
  1510. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1511. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1512. c1 = p1.buffer(height * 0.5)
  1513. c2 = p2.buffer(height * 0.5)
  1514. else:
  1515. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1516. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1517. c1 = p1.buffer(width * 0.5)
  1518. c2 = p2.buffer(width * 0.5)
  1519. return cascaded_union([c1, c2]).convex_hull
  1520. if aperture['type'] == 'P': # Regular polygon
  1521. loc = location.coords[0]
  1522. diam = aperture['diam']
  1523. n_vertices = aperture['nVertices']
  1524. points = []
  1525. for i in range(0, n_vertices):
  1526. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1527. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1528. points.append((x, y))
  1529. ply = Polygon(points)
  1530. if 'rotation' in aperture:
  1531. ply = affinity.rotate(ply, aperture['rotation'])
  1532. return ply
  1533. if aperture['type'] == 'AM': # Aperture Macro
  1534. loc = location.coords[0]
  1535. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1536. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1537. return None
  1538. def create_geometry(self):
  1539. """
  1540. Geometry from a Gerber file is made up entirely of polygons.
  1541. Every stroke (linear or circular) has an aperture which gives
  1542. it thickness. Additionally, aperture strokes have non-zero area,
  1543. and regions naturally do as well.
  1544. :rtype : None
  1545. :return: None
  1546. """
  1547. # self.buffer_paths()
  1548. #
  1549. # self.fix_regions()
  1550. #
  1551. # self.do_flashes()
  1552. #
  1553. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1554. # [poly['polygon'] for poly in self.regions] +
  1555. # self.flash_geometry)
  1556. def get_bounding_box(self, margin=0.0, rounded=False):
  1557. """
  1558. Creates and returns a rectangular polygon bounding at a distance of
  1559. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1560. can optionally have rounded corners of radius equal to margin.
  1561. :param margin: Distance to enlarge the rectangular bounding
  1562. box in both positive and negative, x and y axes.
  1563. :type margin: float
  1564. :param rounded: Wether or not to have rounded corners.
  1565. :type rounded: bool
  1566. :return: The bounding box.
  1567. :rtype: Shapely.Polygon
  1568. """
  1569. bbox = self.solid_geometry.envelope.buffer(margin)
  1570. if not rounded:
  1571. bbox = bbox.envelope
  1572. return bbox
  1573. class Excellon(Geometry):
  1574. """
  1575. *ATTRIBUTES*
  1576. * ``tools`` (dict): The key is the tool name and the value is
  1577. a dictionary specifying the tool:
  1578. ================ ====================================
  1579. Key Value
  1580. ================ ====================================
  1581. C Diameter of the tool
  1582. Others Not supported (Ignored).
  1583. ================ ====================================
  1584. * ``drills`` (list): Each is a dictionary:
  1585. ================ ====================================
  1586. Key Value
  1587. ================ ====================================
  1588. point (Shapely.Point) Where to drill
  1589. tool (str) A key in ``tools``
  1590. ================ ====================================
  1591. """
  1592. defaults = {
  1593. "zeros": "L"
  1594. }
  1595. def __init__(self, zeros=None):
  1596. """
  1597. The constructor takes no parameters.
  1598. :return: Excellon object.
  1599. :rtype: Excellon
  1600. """
  1601. Geometry.__init__(self)
  1602. self.tools = {}
  1603. self.drills = []
  1604. ## IN|MM -> Units are inherited from Geometry
  1605. #self.units = units
  1606. # Trailing "T" or leading "L" (default)
  1607. #self.zeros = "T"
  1608. self.zeros = zeros or self.defaults["zeros"]
  1609. # Attributes to be included in serialization
  1610. # Always append to it because it carries contents
  1611. # from Geometry.
  1612. self.ser_attrs += ['tools', 'drills', 'zeros']
  1613. #### Patterns ####
  1614. # Regex basics:
  1615. # ^ - beginning
  1616. # $ - end
  1617. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1618. # M48 - Beggining of Part Program Header
  1619. self.hbegin_re = re.compile(r'^M48$')
  1620. # M95 or % - End of Part Program Header
  1621. # NOTE: % has different meaning in the body
  1622. self.hend_re = re.compile(r'^(?:M95|%)$')
  1623. # FMAT Excellon format
  1624. # Ignored in the parser
  1625. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  1626. # Number format and units
  1627. # INCH uses 6 digits
  1628. # METRIC uses 5/6
  1629. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1630. # Tool definition/parameters (?= is look-ahead
  1631. # NOTE: This might be an overkill!
  1632. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1633. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1634. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1635. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1636. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1637. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1638. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1639. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1640. # Tool select
  1641. # Can have additional data after tool number but
  1642. # is ignored if present in the header.
  1643. # Warning: This will match toolset_re too.
  1644. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1645. self.toolsel_re = re.compile(r'^T(\d+)')
  1646. # Comment
  1647. self.comm_re = re.compile(r'^;(.*)$')
  1648. # Absolute/Incremental G90/G91
  1649. self.absinc_re = re.compile(r'^G9([01])$')
  1650. # Modes of operation
  1651. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1652. self.modes_re = re.compile(r'^G0([012345])')
  1653. # Measuring mode
  1654. # 1-metric, 2-inch
  1655. self.meas_re = re.compile(r'^M7([12])$')
  1656. # Coordinates
  1657. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1658. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1659. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1660. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1661. # R - Repeat hole (# times, X offset, Y offset)
  1662. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1663. # Various stop/pause commands
  1664. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1665. # Parse coordinates
  1666. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  1667. def parse_file(self, filename):
  1668. """
  1669. Reads the specified file as array of lines as
  1670. passes it to ``parse_lines()``.
  1671. :param filename: The file to be read and parsed.
  1672. :type filename: str
  1673. :return: None
  1674. """
  1675. efile = open(filename, 'r')
  1676. estr = efile.readlines()
  1677. efile.close()
  1678. self.parse_lines(estr)
  1679. def parse_lines(self, elines):
  1680. """
  1681. Main Excellon parser.
  1682. :param elines: List of strings, each being a line of Excellon code.
  1683. :type elines: list
  1684. :return: None
  1685. """
  1686. # State variables
  1687. current_tool = ""
  1688. in_header = False
  1689. current_x = None
  1690. current_y = None
  1691. #### Parsing starts here ####
  1692. line_num = 0 # Line number
  1693. eline = ""
  1694. try:
  1695. for eline in elines:
  1696. line_num += 1
  1697. #log.debug("%3d %s" % (line_num, str(eline)))
  1698. ### Cleanup lines
  1699. eline = eline.strip(' \r\n')
  1700. ## Header Begin (M48) ##
  1701. if self.hbegin_re.search(eline):
  1702. in_header = True
  1703. continue
  1704. ## Header End ##
  1705. if self.hend_re.search(eline):
  1706. in_header = False
  1707. continue
  1708. ## Alternative units format M71/M72
  1709. # Supposed to be just in the body (yes, the body)
  1710. # but some put it in the header (PADS for example).
  1711. # Will detect anywhere. Occurrence will change the
  1712. # object's units.
  1713. match = self.meas_re.match(eline)
  1714. if match:
  1715. self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  1716. log.debug(" Units: %s" % self.units)
  1717. continue
  1718. #### Body ####
  1719. if not in_header:
  1720. ## Tool change ##
  1721. match = self.toolsel_re.search(eline)
  1722. if match:
  1723. current_tool = str(int(match.group(1)))
  1724. log.debug("Tool change: %s" % current_tool)
  1725. continue
  1726. ## Coordinates without period ##
  1727. match = self.coordsnoperiod_re.search(eline)
  1728. if match:
  1729. try:
  1730. #x = float(match.group(1))/10000
  1731. x = self.parse_number(match.group(1))
  1732. current_x = x
  1733. except TypeError:
  1734. x = current_x
  1735. try:
  1736. #y = float(match.group(2))/10000
  1737. y = self.parse_number(match.group(2))
  1738. current_y = y
  1739. except TypeError:
  1740. y = current_y
  1741. if x is None or y is None:
  1742. log.error("Missing coordinates")
  1743. continue
  1744. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1745. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  1746. continue
  1747. ## Coordinates with period: Use literally. ##
  1748. match = self.coordsperiod_re.search(eline)
  1749. if match:
  1750. try:
  1751. x = float(match.group(1))
  1752. current_x = x
  1753. except TypeError:
  1754. x = current_x
  1755. try:
  1756. y = float(match.group(2))
  1757. current_y = y
  1758. except TypeError:
  1759. y = current_y
  1760. if x is None or y is None:
  1761. log.error("Missing coordinates")
  1762. continue
  1763. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1764. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  1765. continue
  1766. #### Header ####
  1767. if in_header:
  1768. ## Tool definitions ##
  1769. match = self.toolset_re.search(eline)
  1770. if match:
  1771. name = str(int(match.group(1)))
  1772. spec = {
  1773. "C": float(match.group(2)),
  1774. # "F": float(match.group(3)),
  1775. # "S": float(match.group(4)),
  1776. # "B": float(match.group(5)),
  1777. # "H": float(match.group(6)),
  1778. # "Z": float(match.group(7))
  1779. }
  1780. self.tools[name] = spec
  1781. log.debug(" Tool definition: %s %s" % (name, spec))
  1782. continue
  1783. ## Units and number format ##
  1784. match = self.units_re.match(eline)
  1785. if match:
  1786. self.zeros = match.group(2) or self.zeros # "T" or "L". Might be empty
  1787. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1788. log.debug(" Units/Format: %s %s" % (self.units, self.zeros))
  1789. continue
  1790. log.warning("Line ignored: %s" % eline)
  1791. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  1792. except Exception as e:
  1793. log.error("PARSING FAILED. Line %d: %s" % (line_num, eline))
  1794. raise
  1795. def parse_number(self, number_str):
  1796. """
  1797. Parses coordinate numbers without period.
  1798. :param number_str: String representing the numerical value.
  1799. :type number_str: str
  1800. :return: Floating point representation of the number
  1801. :rtype: foat
  1802. """
  1803. if self.zeros == "L":
  1804. # With leading zeros, when you type in a coordinate,
  1805. # the leading zeros must always be included. Trailing zeros
  1806. # are unneeded and may be left off. The CNC-7 will automatically add them.
  1807. # r'^[-\+]?(0*)(\d*)'
  1808. # 6 digits are divided by 10^4
  1809. # If less than size digits, they are automatically added,
  1810. # 5 digits then are divided by 10^3 and so on.
  1811. match = self.leadingzeros_re.search(number_str)
  1812. if self.units.lower() == "in":
  1813. return float(number_str) / \
  1814. (10 ** (len(match.group(1)) + len(match.group(2)) - 2))
  1815. else:
  1816. return float(number_str) / \
  1817. (10 ** (len(match.group(1)) + len(match.group(2)) - 3))
  1818. else: # Trailing
  1819. # You must show all zeros to the right of the number and can omit
  1820. # all zeros to the left of the number. The CNC-7 will count the number
  1821. # of digits you typed and automatically fill in the missing zeros.
  1822. if self.units.lower() == "in": # Inches is 00.0000
  1823. return float(number_str) / 10000
  1824. else:
  1825. return float(number_str) / 1000 # Metric is 000.000
  1826. def create_geometry(self):
  1827. """
  1828. Creates circles of the tool diameter at every point
  1829. specified in ``self.drills``.
  1830. :return: None
  1831. """
  1832. self.solid_geometry = []
  1833. for drill in self.drills:
  1834. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1835. tooldia = self.tools[drill['tool']]['C']
  1836. poly = drill['point'].buffer(tooldia / 2.0)
  1837. self.solid_geometry.append(poly)
  1838. def scale(self, factor):
  1839. """
  1840. Scales geometry on the XY plane in the object by a given factor.
  1841. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1842. :param factor: Number by which to scale the object.
  1843. :type factor: float
  1844. :return: None
  1845. :rtype: NOne
  1846. """
  1847. # Drills
  1848. for drill in self.drills:
  1849. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1850. self.create_geometry()
  1851. def offset(self, vect):
  1852. """
  1853. Offsets geometry on the XY plane in the object by a given vector.
  1854. :param vect: (x, y) offset vector.
  1855. :type vect: tuple
  1856. :return: None
  1857. """
  1858. dx, dy = vect
  1859. # Drills
  1860. for drill in self.drills:
  1861. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1862. # Recreate geometry
  1863. self.create_geometry()
  1864. def mirror(self, axis, point):
  1865. """
  1866. :param axis: "X" or "Y" indicates around which axis to mirror.
  1867. :type axis: str
  1868. :param point: [x, y] point belonging to the mirror axis.
  1869. :type point: list
  1870. :return: None
  1871. """
  1872. px, py = point
  1873. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1874. # Modify data
  1875. for drill in self.drills:
  1876. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1877. # Recreate geometry
  1878. self.create_geometry()
  1879. def convert_units(self, units):
  1880. factor = Geometry.convert_units(self, units)
  1881. # Tools
  1882. for tname in self.tools:
  1883. self.tools[tname]["C"] *= factor
  1884. self.create_geometry()
  1885. return factor
  1886. class CNCjob(Geometry):
  1887. """
  1888. Represents work to be done by a CNC machine.
  1889. *ATTRIBUTES*
  1890. * ``gcode_parsed`` (list): Each is a dictionary:
  1891. ===================== =========================================
  1892. Key Value
  1893. ===================== =========================================
  1894. geom (Shapely.LineString) Tool path (XY plane)
  1895. kind (string) "AB", A is "T" (travel) or
  1896. "C" (cut). B is "F" (fast) or "S" (slow).
  1897. ===================== =========================================
  1898. """
  1899. defaults = {
  1900. "zdownrate": None,
  1901. "coordinate_format": "X%.4fY%.4f"
  1902. }
  1903. def __init__(self, units="in", kind="generic", z_move=0.1,
  1904. feedrate=3.0, z_cut=-0.002, tooldia=0.0, zdownrate=None):
  1905. Geometry.__init__(self)
  1906. self.kind = kind
  1907. self.units = units
  1908. self.z_cut = z_cut
  1909. self.z_move = z_move
  1910. self.feedrate = feedrate
  1911. self.tooldia = tooldia
  1912. self.unitcode = {"IN": "G20", "MM": "G21"}
  1913. self.pausecode = "G04 P1"
  1914. self.feedminutecode = "G94"
  1915. self.absolutecode = "G90"
  1916. self.gcode = ""
  1917. self.input_geometry_bounds = None
  1918. self.gcode_parsed = None
  1919. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1920. if zdownrate is not None:
  1921. self.zdownrate = float(zdownrate)
  1922. elif CNCjob.defaults["zdownrate"] is not None:
  1923. self.zdownrate = float(CNCjob.defaults["zdownrate"])
  1924. else:
  1925. self.zdownrate = None
  1926. # Attributes to be included in serialization
  1927. # Always append to it because it carries contents
  1928. # from Geometry.
  1929. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1930. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1931. 'steps_per_circ']
  1932. def convert_units(self, units):
  1933. factor = Geometry.convert_units(self, units)
  1934. log.debug("CNCjob.convert_units()")
  1935. self.z_cut *= factor
  1936. self.z_move *= factor
  1937. self.feedrate *= factor
  1938. self.tooldia *= factor
  1939. return factor
  1940. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1941. """
  1942. Creates gcode for this object from an Excellon object
  1943. for the specified tools.
  1944. :param exobj: Excellon object to process
  1945. :type exobj: Excellon
  1946. :param tools: Comma separated tool names
  1947. :type: tools: str
  1948. :return: None
  1949. :rtype: None
  1950. """
  1951. log.debug("Creating CNC Job from Excellon...")
  1952. if tools == "all":
  1953. tools = [tool for tool in exobj.tools]
  1954. else:
  1955. tools = [x.strip() for x in tools.split(",")]
  1956. tools = filter(lambda i: i in exobj.tools, tools)
  1957. log.debug("Tools are: %s" % str(tools))
  1958. points = []
  1959. for drill in exobj.drills:
  1960. if drill['tool'] in tools:
  1961. points.append(drill['point'])
  1962. log.debug("Found %d drills." % len(points))
  1963. self.gcode = []
  1964. t = "G00 " + CNCjob.defaults["coordinate_format"] + "\n"
  1965. down = "G01 Z%.4f\n" % self.z_cut
  1966. up = "G01 Z%.4f\n" % self.z_move
  1967. gcode = self.unitcode[self.units.upper()] + "\n"
  1968. gcode += self.absolutecode + "\n"
  1969. gcode += self.feedminutecode + "\n"
  1970. gcode += "F%.2f\n" % self.feedrate
  1971. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1972. gcode += "M03\n" # Spindle start
  1973. gcode += self.pausecode + "\n"
  1974. for point in points:
  1975. x, y = point.coords.xy
  1976. gcode += t % (x[0], y[0])
  1977. gcode += down + up
  1978. gcode += t % (0, 0)
  1979. gcode += "M05\n" # Spindle stop
  1980. self.gcode = gcode
  1981. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, tolerance=0):
  1982. """
  1983. Second algorithm to generate from Geometry.
  1984. ALgorithm description:
  1985. ----------------------
  1986. Uses RTree to find the nearest path to follow.
  1987. :param geometry:
  1988. :param append:
  1989. :param tooldia:
  1990. :param tolerance:
  1991. :return: None
  1992. """
  1993. assert isinstance(geometry, Geometry)
  1994. log.debug("generate_from_geometry_2()")
  1995. ## Flatten the geometry
  1996. # Only linear elements (no polygons) remain.
  1997. flat_geometry = geometry.flatten(pathonly=True)
  1998. log.debug("%d paths" % len(flat_geometry))
  1999. ## Index first and last points in paths
  2000. # What points to index.
  2001. def get_pts(o):
  2002. return [o.coords[0], o.coords[-1]]
  2003. # Create the indexed storage.
  2004. storage = FlatCAMRTreeStorage()
  2005. storage.get_points = get_pts
  2006. # Store the geometry
  2007. log.debug("Indexing geometry before generating G-Code...")
  2008. for shape in flat_geometry:
  2009. if shape is not None: # TODO: This shouldn't have happened.
  2010. storage.insert(shape)
  2011. if tooldia is not None:
  2012. self.tooldia = tooldia
  2013. # self.input_geometry_bounds = geometry.bounds()
  2014. if not append:
  2015. self.gcode = ""
  2016. # Initial G-Code
  2017. self.gcode = self.unitcode[self.units.upper()] + "\n"
  2018. self.gcode += self.absolutecode + "\n"
  2019. self.gcode += self.feedminutecode + "\n"
  2020. self.gcode += "F%.2f\n" % self.feedrate
  2021. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  2022. self.gcode += "M03\n" # Spindle start
  2023. self.gcode += self.pausecode + "\n"
  2024. ## Iterate over geometry paths getting the nearest each time.
  2025. log.debug("Starting G-Code...")
  2026. path_count = 0
  2027. current_pt = (0, 0)
  2028. pt, geo = storage.nearest(current_pt)
  2029. try:
  2030. while True:
  2031. path_count += 1
  2032. #print "Current: ", "(%.3f, %.3f)" % current_pt
  2033. # Remove before modifying, otherwise
  2034. # deletion will fail.
  2035. storage.remove(geo)
  2036. # If last point in geometry is the nearest
  2037. # then reverse coordinates.
  2038. if list(pt) == list(geo.coords[-1]):
  2039. geo.coords = list(geo.coords)[::-1]
  2040. # G-code
  2041. # Note: self.linear2gcode() and self.point2gcode() will
  2042. # lower and raise the tool every time.
  2043. if type(geo) == LineString or type(geo) == LinearRing:
  2044. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  2045. elif type(geo) == Point:
  2046. self.gcode += self.point2gcode(geo)
  2047. else:
  2048. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2049. # Delete from index, update current location and continue.
  2050. #rti.delete(hits[0], geo.coords[0])
  2051. #rti.delete(hits[0], geo.coords[-1])
  2052. current_pt = geo.coords[-1]
  2053. # Next
  2054. pt, geo = storage.nearest(current_pt)
  2055. except StopIteration: # Nothing found in storage.
  2056. pass
  2057. log.debug("%s paths traced." % path_count)
  2058. # Finish
  2059. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2060. self.gcode += "G00 X0Y0\n"
  2061. self.gcode += "M05\n" # Spindle stop
  2062. def pre_parse(self, gtext):
  2063. """
  2064. Separates parts of the G-Code text into a list of dictionaries.
  2065. Used by ``self.gcode_parse()``.
  2066. :param gtext: A single string with g-code
  2067. """
  2068. # Units: G20-inches, G21-mm
  2069. units_re = re.compile(r'^G2([01])')
  2070. # TODO: This has to be re-done
  2071. gcmds = []
  2072. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  2073. for line in lines:
  2074. # Clean up
  2075. line = line.strip()
  2076. # Remove comments
  2077. # NOTE: Limited to 1 bracket pair
  2078. op = line.find("(")
  2079. cl = line.find(")")
  2080. #if op > -1 and cl > op:
  2081. if cl > op > -1:
  2082. #comment = line[op+1:cl]
  2083. line = line[:op] + line[(cl+1):]
  2084. # Units
  2085. match = units_re.match(line)
  2086. if match:
  2087. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  2088. # Parse GCode
  2089. # 0 4 12
  2090. # G01 X-0.007 Y-0.057
  2091. # --> codes_idx = [0, 4, 12]
  2092. codes = "NMGXYZIJFP"
  2093. codes_idx = []
  2094. i = 0
  2095. for ch in line:
  2096. if ch in codes:
  2097. codes_idx.append(i)
  2098. i += 1
  2099. n_codes = len(codes_idx)
  2100. if n_codes == 0:
  2101. continue
  2102. # Separate codes in line
  2103. parts = []
  2104. for p in range(n_codes - 1):
  2105. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  2106. parts.append(line[codes_idx[-1]:].strip())
  2107. # Separate codes from values
  2108. cmds = {}
  2109. for part in parts:
  2110. cmds[part[0]] = float(part[1:])
  2111. gcmds.append(cmds)
  2112. return gcmds
  2113. def gcode_parse(self):
  2114. """
  2115. G-Code parser (from self.gcode). Generates dictionary with
  2116. single-segment LineString's and "kind" indicating cut or travel,
  2117. fast or feedrate speed.
  2118. """
  2119. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2120. # Results go here
  2121. geometry = []
  2122. # TODO: Merge into single parser?
  2123. gobjs = self.pre_parse(self.gcode)
  2124. # Last known instruction
  2125. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  2126. # Current path: temporary storage until tool is
  2127. # lifted or lowered.
  2128. path = [(0, 0)]
  2129. # Process every instruction
  2130. for gobj in gobjs:
  2131. ## Changing height
  2132. if 'Z' in gobj:
  2133. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  2134. log.warning("Non-orthogonal motion: From %s" % str(current))
  2135. log.warning(" To: %s" % str(gobj))
  2136. current['Z'] = gobj['Z']
  2137. # Store the path into geometry and reset path
  2138. if len(path) > 1:
  2139. geometry.append({"geom": LineString(path),
  2140. "kind": kind})
  2141. path = [path[-1]] # Start with the last point of last path.
  2142. if 'G' in gobj:
  2143. current['G'] = int(gobj['G'])
  2144. if 'X' in gobj or 'Y' in gobj:
  2145. if 'X' in gobj:
  2146. x = gobj['X']
  2147. else:
  2148. x = current['X']
  2149. if 'Y' in gobj:
  2150. y = gobj['Y']
  2151. else:
  2152. y = current['Y']
  2153. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2154. if current['Z'] > 0:
  2155. kind[0] = 'T'
  2156. if current['G'] > 0:
  2157. kind[1] = 'S'
  2158. arcdir = [None, None, "cw", "ccw"]
  2159. if current['G'] in [0, 1]: # line
  2160. path.append((x, y))
  2161. if current['G'] in [2, 3]: # arc
  2162. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  2163. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  2164. start = arctan2(-gobj['J'], -gobj['I'])
  2165. stop = arctan2(-center[1]+y, -center[0]+x)
  2166. path += arc(center, radius, start, stop,
  2167. arcdir[current['G']],
  2168. self.steps_per_circ)
  2169. # Update current instruction
  2170. for code in gobj:
  2171. current[code] = gobj[code]
  2172. # There might not be a change in height at the
  2173. # end, therefore, see here too if there is
  2174. # a final path.
  2175. if len(path) > 1:
  2176. geometry.append({"geom": LineString(path),
  2177. "kind": kind})
  2178. self.gcode_parsed = geometry
  2179. return geometry
  2180. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  2181. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2182. # alpha={"T": 0.3, "C": 1.0}):
  2183. # """
  2184. # Creates a Matplotlib figure with a plot of the
  2185. # G-code job.
  2186. # """
  2187. # if tooldia is None:
  2188. # tooldia = self.tooldia
  2189. #
  2190. # fig = Figure(dpi=dpi)
  2191. # ax = fig.add_subplot(111)
  2192. # ax.set_aspect(1)
  2193. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  2194. # ax.set_xlim(xmin-margin, xmax+margin)
  2195. # ax.set_ylim(ymin-margin, ymax+margin)
  2196. #
  2197. # if tooldia == 0:
  2198. # for geo in self.gcode_parsed:
  2199. # linespec = '--'
  2200. # linecolor = color[geo['kind'][0]][1]
  2201. # if geo['kind'][0] == 'C':
  2202. # linespec = 'k-'
  2203. # x, y = geo['geom'].coords.xy
  2204. # ax.plot(x, y, linespec, color=linecolor)
  2205. # else:
  2206. # for geo in self.gcode_parsed:
  2207. # poly = geo['geom'].buffer(tooldia/2.0)
  2208. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2209. # edgecolor=color[geo['kind'][0]][1],
  2210. # alpha=alpha[geo['kind'][0]], zorder=2)
  2211. # ax.add_patch(patch)
  2212. #
  2213. # return fig
  2214. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  2215. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2216. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  2217. """
  2218. Plots the G-code job onto the given axes.
  2219. :param axes: Matplotlib axes on which to plot.
  2220. :param tooldia: Tool diameter.
  2221. :param dpi: Not used!
  2222. :param margin: Not used!
  2223. :param color: Color specification.
  2224. :param alpha: Transparency specification.
  2225. :param tool_tolerance: Tolerance when drawing the toolshape.
  2226. :return: None
  2227. """
  2228. path_num = 0
  2229. if tooldia is None:
  2230. tooldia = self.tooldia
  2231. if tooldia == 0:
  2232. for geo in self.gcode_parsed:
  2233. linespec = '--'
  2234. linecolor = color[geo['kind'][0]][1]
  2235. if geo['kind'][0] == 'C':
  2236. linespec = 'k-'
  2237. x, y = geo['geom'].coords.xy
  2238. axes.plot(x, y, linespec, color=linecolor)
  2239. else:
  2240. for geo in self.gcode_parsed:
  2241. path_num += 1
  2242. axes.annotate(str(path_num), xy=geo['geom'].coords[0],
  2243. xycoords='data')
  2244. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  2245. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2246. edgecolor=color[geo['kind'][0]][1],
  2247. alpha=alpha[geo['kind'][0]], zorder=2)
  2248. axes.add_patch(patch)
  2249. def create_geometry(self):
  2250. # TODO: This takes forever. Too much data?
  2251. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2252. def linear2gcode(self, linear, tolerance=0):
  2253. """
  2254. Generates G-code to cut along the linear feature.
  2255. :param linear: The path to cut along.
  2256. :type: Shapely.LinearRing or Shapely.Linear String
  2257. :param tolerance: All points in the simplified object will be within the
  2258. tolerance distance of the original geometry.
  2259. :type tolerance: float
  2260. :return: G-code to cut alon the linear feature.
  2261. :rtype: str
  2262. """
  2263. if tolerance > 0:
  2264. target_linear = linear.simplify(tolerance)
  2265. else:
  2266. target_linear = linear
  2267. gcode = ""
  2268. #t = "G0%d X%.4fY%.4f\n"
  2269. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2270. path = list(target_linear.coords)
  2271. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2272. if self.zdownrate is not None:
  2273. gcode += "F%.2f\n" % self.zdownrate
  2274. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2275. gcode += "F%.2f\n" % self.feedrate
  2276. else:
  2277. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2278. for pt in path[1:]:
  2279. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2280. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2281. return gcode
  2282. def point2gcode(self, point):
  2283. gcode = ""
  2284. #t = "G0%d X%.4fY%.4f\n"
  2285. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2286. path = list(point.coords)
  2287. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2288. if self.zdownrate is not None:
  2289. gcode += "F%.2f\n" % self.zdownrate
  2290. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2291. gcode += "F%.2f\n" % self.feedrate
  2292. else:
  2293. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2294. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2295. return gcode
  2296. def scale(self, factor):
  2297. """
  2298. Scales all the geometry on the XY plane in the object by the
  2299. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2300. not altered.
  2301. :param factor: Number by which to scale the object.
  2302. :type factor: float
  2303. :return: None
  2304. :rtype: None
  2305. """
  2306. for g in self.gcode_parsed:
  2307. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2308. self.create_geometry()
  2309. def offset(self, vect):
  2310. """
  2311. Offsets all the geometry on the XY plane in the object by the
  2312. given vector.
  2313. :param vect: (x, y) offset vector.
  2314. :type vect: tuple
  2315. :return: None
  2316. """
  2317. dx, dy = vect
  2318. for g in self.gcode_parsed:
  2319. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2320. self.create_geometry()
  2321. # def get_bounds(geometry_set):
  2322. # xmin = Inf
  2323. # ymin = Inf
  2324. # xmax = -Inf
  2325. # ymax = -Inf
  2326. #
  2327. # #print "Getting bounds of:", str(geometry_set)
  2328. # for gs in geometry_set:
  2329. # try:
  2330. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2331. # xmin = min([xmin, gxmin])
  2332. # ymin = min([ymin, gymin])
  2333. # xmax = max([xmax, gxmax])
  2334. # ymax = max([ymax, gymax])
  2335. # except:
  2336. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2337. #
  2338. # return [xmin, ymin, xmax, ymax]
  2339. def get_bounds(geometry_list):
  2340. xmin = Inf
  2341. ymin = Inf
  2342. xmax = -Inf
  2343. ymax = -Inf
  2344. #print "Getting bounds of:", str(geometry_set)
  2345. for gs in geometry_list:
  2346. try:
  2347. gxmin, gymin, gxmax, gymax = gs.bounds()
  2348. xmin = min([xmin, gxmin])
  2349. ymin = min([ymin, gymin])
  2350. xmax = max([xmax, gxmax])
  2351. ymax = max([ymax, gymax])
  2352. except:
  2353. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  2354. return [xmin, ymin, xmax, ymax]
  2355. def arc(center, radius, start, stop, direction, steps_per_circ):
  2356. """
  2357. Creates a list of point along the specified arc.
  2358. :param center: Coordinates of the center [x, y]
  2359. :type center: list
  2360. :param radius: Radius of the arc.
  2361. :type radius: float
  2362. :param start: Starting angle in radians
  2363. :type start: float
  2364. :param stop: End angle in radians
  2365. :type stop: float
  2366. :param direction: Orientation of the arc, "CW" or "CCW"
  2367. :type direction: string
  2368. :param steps_per_circ: Number of straight line segments to
  2369. represent a circle.
  2370. :type steps_per_circ: int
  2371. :return: The desired arc, as list of tuples
  2372. :rtype: list
  2373. """
  2374. # TODO: Resolution should be established by maximum error from the exact arc.
  2375. da_sign = {"cw": -1.0, "ccw": 1.0}
  2376. points = []
  2377. if direction == "ccw" and stop <= start:
  2378. stop += 2 * pi
  2379. if direction == "cw" and stop >= start:
  2380. stop -= 2 * pi
  2381. angle = abs(stop - start)
  2382. #angle = stop-start
  2383. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  2384. delta_angle = da_sign[direction] * angle * 1.0 / steps
  2385. for i in range(steps + 1):
  2386. theta = start + delta_angle * i
  2387. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  2388. return points
  2389. def arc2(p1, p2, center, direction, steps_per_circ):
  2390. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  2391. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  2392. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  2393. return arc(center, r, start, stop, direction, steps_per_circ)
  2394. def arc_angle(start, stop, direction):
  2395. if direction == "ccw" and stop <= start:
  2396. stop += 2 * pi
  2397. if direction == "cw" and stop >= start:
  2398. stop -= 2 * pi
  2399. angle = abs(stop - start)
  2400. return angle
  2401. # def find_polygon(poly, point):
  2402. # """
  2403. # Find an object that object.contains(Point(point)) in
  2404. # poly, which can can be iterable, contain iterable of, or
  2405. # be itself an implementer of .contains().
  2406. #
  2407. # :param poly: See description
  2408. # :return: Polygon containing point or None.
  2409. # """
  2410. #
  2411. # if poly is None:
  2412. # return None
  2413. #
  2414. # try:
  2415. # for sub_poly in poly:
  2416. # p = find_polygon(sub_poly, point)
  2417. # if p is not None:
  2418. # return p
  2419. # except TypeError:
  2420. # try:
  2421. # if poly.contains(Point(point)):
  2422. # return poly
  2423. # except AttributeError:
  2424. # return None
  2425. #
  2426. # return None
  2427. def to_dict(obj):
  2428. """
  2429. Makes the following types into serializable form:
  2430. * ApertureMacro
  2431. * BaseGeometry
  2432. :param obj: Shapely geometry.
  2433. :type obj: BaseGeometry
  2434. :return: Dictionary with serializable form if ``obj`` was
  2435. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  2436. """
  2437. if isinstance(obj, ApertureMacro):
  2438. return {
  2439. "__class__": "ApertureMacro",
  2440. "__inst__": obj.to_dict()
  2441. }
  2442. if isinstance(obj, BaseGeometry):
  2443. return {
  2444. "__class__": "Shply",
  2445. "__inst__": sdumps(obj)
  2446. }
  2447. return obj
  2448. def dict2obj(d):
  2449. """
  2450. Default deserializer.
  2451. :param d: Serializable dictionary representation of an object
  2452. to be reconstructed.
  2453. :return: Reconstructed object.
  2454. """
  2455. if '__class__' in d and '__inst__' in d:
  2456. if d['__class__'] == "Shply":
  2457. return sloads(d['__inst__'])
  2458. if d['__class__'] == "ApertureMacro":
  2459. am = ApertureMacro()
  2460. am.from_dict(d['__inst__'])
  2461. return am
  2462. return d
  2463. else:
  2464. return d
  2465. def plotg(geo, solid_poly=False, color="black"):
  2466. try:
  2467. _ = iter(geo)
  2468. except:
  2469. geo = [geo]
  2470. for g in geo:
  2471. if type(g) == Polygon:
  2472. if solid_poly:
  2473. patch = PolygonPatch(g,
  2474. facecolor="#BBF268",
  2475. edgecolor="#006E20",
  2476. alpha=0.75,
  2477. zorder=2)
  2478. ax = subplot(111)
  2479. ax.add_patch(patch)
  2480. else:
  2481. x, y = g.exterior.coords.xy
  2482. plot(x, y, color=color)
  2483. for ints in g.interiors:
  2484. x, y = ints.coords.xy
  2485. plot(x, y, color=color)
  2486. continue
  2487. if type(g) == LineString or type(g) == LinearRing:
  2488. x, y = g.coords.xy
  2489. plot(x, y, color=color)
  2490. continue
  2491. if type(g) == Point:
  2492. x, y = g.coords.xy
  2493. plot(x, y, 'o')
  2494. continue
  2495. try:
  2496. _ = iter(g)
  2497. plotg(g, color=color)
  2498. except:
  2499. log.error("Cannot plot: " + str(type(g)))
  2500. continue
  2501. def parse_gerber_number(strnumber, frac_digits):
  2502. """
  2503. Parse a single number of Gerber coordinates.
  2504. :param strnumber: String containing a number in decimal digits
  2505. from a coordinate data block, possibly with a leading sign.
  2506. :type strnumber: str
  2507. :param frac_digits: Number of digits used for the fractional
  2508. part of the number
  2509. :type frac_digits: int
  2510. :return: The number in floating point.
  2511. :rtype: float
  2512. """
  2513. return int(strnumber) * (10 ** (-frac_digits))
  2514. # def voronoi(P):
  2515. # """
  2516. # Returns a list of all edges of the voronoi diagram for the given input points.
  2517. # """
  2518. # delauny = Delaunay(P)
  2519. # triangles = delauny.points[delauny.vertices]
  2520. #
  2521. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  2522. # long_lines_endpoints = []
  2523. #
  2524. # lineIndices = []
  2525. # for i, triangle in enumerate(triangles):
  2526. # circum_center = circum_centers[i]
  2527. # for j, neighbor in enumerate(delauny.neighbors[i]):
  2528. # if neighbor != -1:
  2529. # lineIndices.append((i, neighbor))
  2530. # else:
  2531. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  2532. # ps = np.array((ps[1], -ps[0]))
  2533. #
  2534. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  2535. # di = middle - triangle[j]
  2536. #
  2537. # ps /= np.linalg.norm(ps)
  2538. # di /= np.linalg.norm(di)
  2539. #
  2540. # if np.dot(di, ps) < 0.0:
  2541. # ps *= -1000.0
  2542. # else:
  2543. # ps *= 1000.0
  2544. #
  2545. # long_lines_endpoints.append(circum_center + ps)
  2546. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  2547. #
  2548. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  2549. #
  2550. # # filter out any duplicate lines
  2551. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  2552. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  2553. # lineIndicesUnique = np.unique(lineIndicesTupled)
  2554. #
  2555. # return vertices, lineIndicesUnique
  2556. #
  2557. #
  2558. # def triangle_csc(pts):
  2559. # rows, cols = pts.shape
  2560. #
  2561. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  2562. # [np.ones((1, rows)), np.zeros((1, 1))]])
  2563. #
  2564. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  2565. # x = np.linalg.solve(A,b)
  2566. # bary_coords = x[:-1]
  2567. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  2568. #
  2569. #
  2570. # def voronoi_cell_lines(points, vertices, lineIndices):
  2571. # """
  2572. # Returns a mapping from a voronoi cell to its edges.
  2573. #
  2574. # :param points: shape (m,2)
  2575. # :param vertices: shape (n,2)
  2576. # :param lineIndices: shape (o,2)
  2577. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  2578. # """
  2579. # kd = KDTree(points)
  2580. #
  2581. # cells = collections.defaultdict(list)
  2582. # for i1, i2 in lineIndices:
  2583. # v1, v2 = vertices[i1], vertices[i2]
  2584. # mid = (v1+v2)/2
  2585. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  2586. # cells[p1Idx].append((i1, i2))
  2587. # cells[p2Idx].append((i1, i2))
  2588. #
  2589. # return cells
  2590. #
  2591. #
  2592. # def voronoi_edges2polygons(cells):
  2593. # """
  2594. # Transforms cell edges into polygons.
  2595. #
  2596. # :param cells: as returned from voronoi_cell_lines
  2597. # :rtype: dict point index -> list of vertex indices which form a polygon
  2598. # """
  2599. #
  2600. # # first, close the outer cells
  2601. # for pIdx, lineIndices_ in cells.items():
  2602. # dangling_lines = []
  2603. # for i1, i2 in lineIndices_:
  2604. # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  2605. # assert 1 <= len(connections) <= 2
  2606. # if len(connections) == 1:
  2607. # dangling_lines.append((i1, i2))
  2608. # assert len(dangling_lines) in [0, 2]
  2609. # if len(dangling_lines) == 2:
  2610. # (i11, i12), (i21, i22) = dangling_lines
  2611. #
  2612. # # determine which line ends are unconnected
  2613. # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  2614. # i11Unconnected = len(connected) == 0
  2615. #
  2616. # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  2617. # i21Unconnected = len(connected) == 0
  2618. #
  2619. # startIdx = i11 if i11Unconnected else i12
  2620. # endIdx = i21 if i21Unconnected else i22
  2621. #
  2622. # cells[pIdx].append((startIdx, endIdx))
  2623. #
  2624. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  2625. # polys = dict()
  2626. # for pIdx, lineIndices_ in cells.items():
  2627. # # get a directed graph which contains both directions and arbitrarily follow one of both
  2628. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  2629. # directedGraphMap = collections.defaultdict(list)
  2630. # for (i1, i2) in directedGraph:
  2631. # directedGraphMap[i1].append(i2)
  2632. # orderedEdges = []
  2633. # currentEdge = directedGraph[0]
  2634. # while len(orderedEdges) < len(lineIndices_):
  2635. # i1 = currentEdge[1]
  2636. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  2637. # nextEdge = (i1, i2)
  2638. # orderedEdges.append(nextEdge)
  2639. # currentEdge = nextEdge
  2640. #
  2641. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  2642. #
  2643. # return polys
  2644. #
  2645. #
  2646. # def voronoi_polygons(points):
  2647. # """
  2648. # Returns the voronoi polygon for each input point.
  2649. #
  2650. # :param points: shape (n,2)
  2651. # :rtype: list of n polygons where each polygon is an array of vertices
  2652. # """
  2653. # vertices, lineIndices = voronoi(points)
  2654. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  2655. # polys = voronoi_edges2polygons(cells)
  2656. # polylist = []
  2657. # for i in xrange(len(points)):
  2658. # poly = vertices[np.asarray(polys[i])]
  2659. # polylist.append(poly)
  2660. # return polylist
  2661. #
  2662. #
  2663. # class Zprofile:
  2664. # def __init__(self):
  2665. #
  2666. # # data contains lists of [x, y, z]
  2667. # self.data = []
  2668. #
  2669. # # Computed voronoi polygons (shapely)
  2670. # self.polygons = []
  2671. # pass
  2672. #
  2673. # def plot_polygons(self):
  2674. # axes = plt.subplot(1, 1, 1)
  2675. #
  2676. # plt.axis([-0.05, 1.05, -0.05, 1.05])
  2677. #
  2678. # for poly in self.polygons:
  2679. # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  2680. # axes.add_patch(p)
  2681. #
  2682. # def init_from_csv(self, filename):
  2683. # pass
  2684. #
  2685. # def init_from_string(self, zpstring):
  2686. # pass
  2687. #
  2688. # def init_from_list(self, zplist):
  2689. # self.data = zplist
  2690. #
  2691. # def generate_polygons(self):
  2692. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  2693. #
  2694. # def normalize(self, origin):
  2695. # pass
  2696. #
  2697. # def paste(self, path):
  2698. # """
  2699. # Return a list of dictionaries containing the parts of the original
  2700. # path and their z-axis offset.
  2701. # """
  2702. #
  2703. # # At most one region/polygon will contain the path
  2704. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  2705. #
  2706. # if len(containing) > 0:
  2707. # return [{"path": path, "z": self.data[containing[0]][2]}]
  2708. #
  2709. # # All region indexes that intersect with the path
  2710. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  2711. #
  2712. # return [{"path": path.intersection(self.polygons[i]),
  2713. # "z": self.data[i][2]} for i in crossing]
  2714. def autolist(obj):
  2715. try:
  2716. _ = iter(obj)
  2717. return obj
  2718. except TypeError:
  2719. return [obj]
  2720. def three_point_circle(p1, p2, p3):
  2721. """
  2722. Computes the center and radius of a circle from
  2723. 3 points on its circumference.
  2724. :param p1: Point 1
  2725. :param p2: Point 2
  2726. :param p3: Point 3
  2727. :return: center, radius
  2728. """
  2729. # Midpoints
  2730. a1 = (p1 + p2) / 2.0
  2731. a2 = (p2 + p3) / 2.0
  2732. # Normals
  2733. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  2734. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  2735. # Params
  2736. T = solve(transpose(array([-b1, b2])), a1 - a2)
  2737. # Center
  2738. center = a1 + b1 * T[0]
  2739. # Radius
  2740. radius = norm(center - p1)
  2741. return center, radius, T[0]
  2742. def distance(pt1, pt2):
  2743. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  2744. class FlatCAMRTree(object):
  2745. def __init__(self):
  2746. # Python RTree Index
  2747. self.rti = rtindex.Index()
  2748. ## Track object-point relationship
  2749. # Each is list of points in object.
  2750. self.obj2points = []
  2751. # Index is index in rtree, value is index of
  2752. # object in obj2points.
  2753. self.points2obj = []
  2754. self.get_points = lambda go: go.coords
  2755. def grow_obj2points(self, idx):
  2756. if len(self.obj2points) > idx:
  2757. # len == 2, idx == 1, ok.
  2758. return
  2759. else:
  2760. # len == 2, idx == 2, need 1 more.
  2761. # range(2, 3)
  2762. for i in range(len(self.obj2points), idx + 1):
  2763. self.obj2points.append([])
  2764. def insert(self, objid, obj):
  2765. self.grow_obj2points(objid)
  2766. self.obj2points[objid] = []
  2767. for pt in self.get_points(obj):
  2768. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  2769. self.obj2points[objid].append(len(self.points2obj))
  2770. self.points2obj.append(objid)
  2771. def remove_obj(self, objid, obj):
  2772. # Use all ptids to delete from index
  2773. for i, pt in enumerate(self.get_points(obj)):
  2774. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  2775. def nearest(self, pt):
  2776. return self.rti.nearest(pt, objects=True).next()
  2777. class FlatCAMRTreeStorage(FlatCAMRTree):
  2778. def __init__(self):
  2779. super(FlatCAMRTreeStorage, self).__init__()
  2780. self.objects = []
  2781. def insert(self, obj):
  2782. self.objects.append(obj)
  2783. super(FlatCAMRTreeStorage, self).insert(len(self.objects) - 1, obj)
  2784. def remove(self, obj):
  2785. # Get index in list
  2786. objidx = self.objects.index(obj)
  2787. # Remove from list
  2788. self.objects[objidx] = None
  2789. # Remove from index
  2790. self.remove_obj(objidx, obj)
  2791. def get_objects(self):
  2792. return (o for o in self.objects if o is not None)
  2793. def nearest(self, pt):
  2794. """
  2795. Returns the nearest matching points and the object
  2796. it belongs to.
  2797. :param pt: Query point.
  2798. :return: (match_x, match_y), Object owner of
  2799. matching point.
  2800. :rtype: tuple
  2801. """
  2802. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  2803. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  2804. # class myO:
  2805. # def __init__(self, coords):
  2806. # self.coords = coords
  2807. #
  2808. #
  2809. # def test_rti():
  2810. #
  2811. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  2812. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  2813. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  2814. #
  2815. # os = [o1, o2]
  2816. #
  2817. # idx = FlatCAMRTree()
  2818. #
  2819. # for o in range(len(os)):
  2820. # idx.insert(o, os[o])
  2821. #
  2822. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  2823. #
  2824. # idx.remove_obj(0, o1)
  2825. #
  2826. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  2827. #
  2828. # idx.remove_obj(1, o2)
  2829. #
  2830. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  2831. #
  2832. #
  2833. # def test_rtis():
  2834. #
  2835. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  2836. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  2837. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  2838. #
  2839. # os = [o1, o2]
  2840. #
  2841. # idx = FlatCAMRTreeStorage()
  2842. #
  2843. # for o in range(len(os)):
  2844. # idx.insert(os[o])
  2845. #
  2846. # #os = None
  2847. # #o1 = None
  2848. # #o2 = None
  2849. #
  2850. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  2851. #
  2852. # idx.remove(idx.nearest((2,0))[1])
  2853. #
  2854. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  2855. #
  2856. # idx.remove(idx.nearest((0,0))[1])
  2857. #
  2858. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]