camlib.py 104 KB

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