camlib.py 127 KB

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