camlib.py 127 KB

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