camlib.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. #from __future__ import division
  9. import traceback
  10. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  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. # Numerical errors might prevent start == stop therefore
  988. # we check ahead of time. This should result in a
  989. # 360 degree arc.
  990. if current_x == x and current_y == y:
  991. stop = start
  992. else:
  993. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  994. this_arc = arc(center, radius, start, stop,
  995. arcdir[current_interpolation_mode],
  996. self.steps_per_circ)
  997. # Last point in path is current point
  998. current_x = this_arc[-1][0]
  999. current_y = this_arc[-1][1]
  1000. # Append
  1001. path += this_arc
  1002. last_path_aperture = current_aperture
  1003. continue
  1004. if quadrant_mode == 'SINGLE':
  1005. center_candidates = [
  1006. [i + current_x, j + current_y],
  1007. [-i + current_x, j + current_y],
  1008. [i + current_x, -j + current_y],
  1009. [-i + current_x, -j + current_y]
  1010. ]
  1011. valid = False
  1012. log.debug("I: %f J: %f" % (i, j))
  1013. for center in center_candidates:
  1014. radius = sqrt(i**2 + j**2)
  1015. # Make sure radius to start is the same as radius to end.
  1016. radius2 = sqrt((center[0] - x)**2 + (center[1] - y)**2)
  1017. if radius2 < radius*0.95 or radius2 > radius*1.05:
  1018. continue # Not a valid center.
  1019. # Correct i and j and continue as with multi-quadrant.
  1020. i = center[0] - current_x
  1021. j = center[1] - current_y
  1022. start = arctan2(-j, -i) # Start angle
  1023. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1024. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1025. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1026. (current_x, current_y, center[0], center[1], x, y))
  1027. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1028. (start*180/pi, stop*180/pi, arcdir[current_interpolation_mode],
  1029. angle*180/pi, pi/2*180/pi, angle <= (pi+1e-6)/2))
  1030. if angle <= (pi+1e-6)/2:
  1031. log.debug("########## ACCEPTING ARC ############")
  1032. this_arc = arc(center, radius, start, stop,
  1033. arcdir[current_interpolation_mode],
  1034. self.steps_per_circ)
  1035. current_x = this_arc[-1][0]
  1036. current_y = this_arc[-1][1]
  1037. path += this_arc
  1038. last_path_aperture = current_aperture
  1039. valid = True
  1040. break
  1041. if valid:
  1042. continue
  1043. else:
  1044. log.warning("Invalid arc in line %d." % line_num)
  1045. ### Operation code alone
  1046. # Operation code alone, usually just D03 (Flash)
  1047. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1048. match = self.opcode_re.search(gline)
  1049. if match:
  1050. current_operation_code = int(match.group(1))
  1051. if current_operation_code == 3:
  1052. ## --- Buffered ---
  1053. try:
  1054. flash = Gerber.create_flash_geometry(Point(path[-1]),
  1055. self.apertures[current_aperture])
  1056. poly_buffer.append(flash)
  1057. except IndexError:
  1058. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1059. continue
  1060. ### G74/75* - Single or multiple quadrant arcs
  1061. match = self.quad_re.search(gline)
  1062. if match:
  1063. if match.group(1) == '4':
  1064. quadrant_mode = 'SINGLE'
  1065. else:
  1066. quadrant_mode = 'MULTI'
  1067. continue
  1068. ### G36* - Begin region
  1069. if self.regionon_re.search(gline):
  1070. if len(path) > 1:
  1071. # Take care of what is left in the path
  1072. ## --- Buffered ---
  1073. width = self.apertures[last_path_aperture]["size"]
  1074. geo = LineString(path).buffer(width/2)
  1075. poly_buffer.append(geo)
  1076. path = [path[-1]]
  1077. making_region = True
  1078. continue
  1079. ### G37* - End region
  1080. if self.regionoff_re.search(gline):
  1081. making_region = False
  1082. # Only one path defines region?
  1083. # This can happen if D02 happened before G37 and
  1084. # is not and error.
  1085. if len(path) < 3:
  1086. # print "ERROR: Path contains less than 3 points:"
  1087. # print path
  1088. # print "Line (%d): " % line_num, gline
  1089. # path = []
  1090. #path = [[current_x, current_y]]
  1091. continue
  1092. # For regions we may ignore an aperture that is None
  1093. # self.regions.append({"polygon": Polygon(path),
  1094. # "aperture": last_path_aperture})
  1095. # --- Buffered ---
  1096. region = Polygon(path)
  1097. if not region.is_valid:
  1098. region = region.buffer(0)
  1099. poly_buffer.append(region)
  1100. path = [[current_x, current_y]] # Start new path
  1101. continue
  1102. ### Aperture definitions %ADD...
  1103. match = self.ad_re.search(gline)
  1104. if match:
  1105. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1106. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1107. continue
  1108. ### G01/2/3* - Interpolation mode change
  1109. # Can occur along with coordinates and operation code but
  1110. # sometimes by itself (handled here).
  1111. # Example: G01*
  1112. match = self.interp_re.search(gline)
  1113. if match:
  1114. current_interpolation_mode = int(match.group(1))
  1115. continue
  1116. ### Tool/aperture change
  1117. # Example: D12*
  1118. match = self.tool_re.search(gline)
  1119. if match:
  1120. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1121. current_aperture = match.group(1)
  1122. # Take care of the current path with the previous tool
  1123. if len(path) > 1:
  1124. # --- Buffered ----
  1125. width = self.apertures[last_path_aperture]["size"]
  1126. geo = LineString(path).buffer(width/2)
  1127. poly_buffer.append(geo)
  1128. path = [path[-1]]
  1129. continue
  1130. ### Polarity change
  1131. # Example: %LPD*% or %LPC*%
  1132. match = self.lpol_re.search(gline)
  1133. if match:
  1134. if len(path) > 1 and current_polarity != match.group(1):
  1135. # --- Buffered ----
  1136. width = self.apertures[last_path_aperture]["size"]
  1137. geo = LineString(path).buffer(width/2)
  1138. poly_buffer.append(geo)
  1139. path = [path[-1]]
  1140. # --- Apply buffer ---
  1141. if current_polarity == 'D':
  1142. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1143. else:
  1144. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1145. poly_buffer = []
  1146. current_polarity = match.group(1)
  1147. continue
  1148. ### Number format
  1149. # Example: %FSLAX24Y24*%
  1150. # TODO: This is ignoring most of the format. Implement the rest.
  1151. match = self.fmt_re.search(gline)
  1152. if match:
  1153. absolute = {'A': True, 'I': False}
  1154. self.int_digits = int(match.group(3))
  1155. self.frac_digits = int(match.group(4))
  1156. continue
  1157. ### Mode (IN/MM)
  1158. # Example: %MOIN*%
  1159. match = self.mode_re.search(gline)
  1160. if match:
  1161. self.units = match.group(1)
  1162. continue
  1163. ### Units (G70/1) OBSOLETE
  1164. match = self.units_re.search(gline)
  1165. if match:
  1166. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1167. continue
  1168. ### Absolute/relative coordinates G90/1 OBSOLETE
  1169. match = self.absrel_re.search(gline)
  1170. if match:
  1171. absolute = {'0': True, '1': False}[match.group(1)]
  1172. continue
  1173. #### Ignored lines
  1174. ## Comments
  1175. match = self.comm_re.search(gline)
  1176. if match:
  1177. continue
  1178. ## EOF
  1179. match = self.eof_re.search(gline)
  1180. if match:
  1181. continue
  1182. ### Line did not match any pattern. Warn user.
  1183. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1184. if len(path) > 1:
  1185. # EOF, create shapely LineString if something still in path
  1186. ## --- Buffered ---
  1187. width = self.apertures[last_path_aperture]["size"]
  1188. geo = LineString(path).buffer(width/2)
  1189. poly_buffer.append(geo)
  1190. # --- Apply buffer ---
  1191. if current_polarity == 'D':
  1192. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1193. else:
  1194. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1195. except Exception, err:
  1196. #print traceback.format_exc()
  1197. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1198. raise
  1199. @staticmethod
  1200. def create_flash_geometry(location, aperture):
  1201. if type(location) == list:
  1202. location = Point(location)
  1203. if aperture['type'] == 'C': # Circles
  1204. return location.buffer(aperture['size']/2)
  1205. if aperture['type'] == 'R': # Rectangles
  1206. loc = location.coords[0]
  1207. width = aperture['width']
  1208. height = aperture['height']
  1209. minx = loc[0] - width/2
  1210. maxx = loc[0] + width/2
  1211. miny = loc[1] - height/2
  1212. maxy = loc[1] + height/2
  1213. return shply_box(minx, miny, maxx, maxy)
  1214. if aperture['type'] == 'O': # Obround
  1215. loc = location.coords[0]
  1216. width = aperture['width']
  1217. height = aperture['height']
  1218. if width > height:
  1219. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1220. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1221. c1 = p1.buffer(height*0.5)
  1222. c2 = p2.buffer(height*0.5)
  1223. else:
  1224. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1225. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1226. c1 = p1.buffer(width*0.5)
  1227. c2 = p2.buffer(width*0.5)
  1228. return cascaded_union([c1, c2]).convex_hull
  1229. if aperture['type'] == 'P': # Regular polygon
  1230. loc = location.coords[0]
  1231. diam = aperture['diam']
  1232. n_vertices = aperture['nVertices']
  1233. points = []
  1234. for i in range(0, n_vertices):
  1235. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1236. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1237. points.append((x, y))
  1238. ply = Polygon(points)
  1239. if 'rotation' in aperture:
  1240. ply = affinity.rotate(ply, aperture['rotation'])
  1241. return ply
  1242. if aperture['type'] == 'AM': # Aperture Macro
  1243. loc = location.coords[0]
  1244. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1245. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1246. return None
  1247. def create_geometry(self):
  1248. """
  1249. Geometry from a Gerber file is made up entirely of polygons.
  1250. Every stroke (linear or circular) has an aperture which gives
  1251. it thickness. Additionally, aperture strokes have non-zero area,
  1252. and regions naturally do as well.
  1253. :rtype : None
  1254. :return: None
  1255. """
  1256. # self.buffer_paths()
  1257. #
  1258. # self.fix_regions()
  1259. #
  1260. # self.do_flashes()
  1261. #
  1262. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1263. # [poly['polygon'] for poly in self.regions] +
  1264. # self.flash_geometry)
  1265. def get_bounding_box(self, margin=0.0, rounded=False):
  1266. """
  1267. Creates and returns a rectangular polygon bounding at a distance of
  1268. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1269. can optionally have rounded corners of radius equal to margin.
  1270. :param margin: Distance to enlarge the rectangular bounding
  1271. box in both positive and negative, x and y axes.
  1272. :type margin: float
  1273. :param rounded: Wether or not to have rounded corners.
  1274. :type rounded: bool
  1275. :return: The bounding box.
  1276. :rtype: Shapely.Polygon
  1277. """
  1278. bbox = self.solid_geometry.envelope.buffer(margin)
  1279. if not rounded:
  1280. bbox = bbox.envelope
  1281. return bbox
  1282. class Excellon(Geometry):
  1283. """
  1284. *ATTRIBUTES*
  1285. * ``tools`` (dict): The key is the tool name and the value is
  1286. a dictionary specifying the tool:
  1287. ================ ====================================
  1288. Key Value
  1289. ================ ====================================
  1290. C Diameter of the tool
  1291. Others Not supported (Ignored).
  1292. ================ ====================================
  1293. * ``drills`` (list): Each is a dictionary:
  1294. ================ ====================================
  1295. Key Value
  1296. ================ ====================================
  1297. point (Shapely.Point) Where to drill
  1298. tool (str) A key in ``tools``
  1299. ================ ====================================
  1300. """
  1301. def __init__(self, zeros="L"):
  1302. """
  1303. The constructor takes no parameters.
  1304. :return: Excellon object.
  1305. :rtype: Excellon
  1306. """
  1307. Geometry.__init__(self)
  1308. self.tools = {}
  1309. self.drills = []
  1310. # Trailing "T" or leading "L" (default)
  1311. #self.zeros = "T"
  1312. self.zeros = zeros
  1313. # Attributes to be included in serialization
  1314. # Always append to it because it carries contents
  1315. # from Geometry.
  1316. self.ser_attrs += ['tools', 'drills', 'zeros']
  1317. #### Patterns ####
  1318. # Regex basics:
  1319. # ^ - beginning
  1320. # $ - end
  1321. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1322. # M48 - Beggining of Part Program Header
  1323. self.hbegin_re = re.compile(r'^M48$')
  1324. # M95 or % - End of Part Program Header
  1325. # NOTE: % has different meaning in the body
  1326. self.hend_re = re.compile(r'^(?:M95|%)$')
  1327. # FMAT Excellon format
  1328. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1329. # Number format and units
  1330. # INCH uses 6 digits
  1331. # METRIC uses 5/6
  1332. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1333. # Tool definition/parameters (?= is look-ahead
  1334. # NOTE: This might be an overkill!
  1335. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1336. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1337. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1338. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1339. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1340. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1341. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1342. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1343. # Tool select
  1344. # Can have additional data after tool number but
  1345. # is ignored if present in the header.
  1346. # Warning: This will match toolset_re too.
  1347. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1348. self.toolsel_re = re.compile(r'^T(\d+)')
  1349. # Comment
  1350. self.comm_re = re.compile(r'^;(.*)$')
  1351. # Absolute/Incremental G90/G91
  1352. self.absinc_re = re.compile(r'^G9([01])$')
  1353. # Modes of operation
  1354. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1355. self.modes_re = re.compile(r'^G0([012345])')
  1356. # Measuring mode
  1357. # 1-metric, 2-inch
  1358. self.meas_re = re.compile(r'^M7([12])$')
  1359. # Coordinates
  1360. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1361. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1362. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1363. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1364. # R - Repeat hole (# times, X offset, Y offset)
  1365. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1366. # Various stop/pause commands
  1367. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1368. # Parse coordinates
  1369. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  1370. def parse_file(self, filename):
  1371. """
  1372. Reads the specified file as array of lines as
  1373. passes it to ``parse_lines()``.
  1374. :param filename: The file to be read and parsed.
  1375. :type filename: str
  1376. :return: None
  1377. """
  1378. efile = open(filename, 'r')
  1379. estr = efile.readlines()
  1380. efile.close()
  1381. self.parse_lines(estr)
  1382. def parse_lines(self, elines):
  1383. """
  1384. Main Excellon parser.
  1385. :param elines: List of strings, each being a line of Excellon code.
  1386. :type elines: list
  1387. :return: None
  1388. """
  1389. # State variables
  1390. current_tool = ""
  1391. in_header = False
  1392. current_x = None
  1393. current_y = None
  1394. #### Parsing starts here ####
  1395. line_num = 0 # Line number
  1396. for eline in elines:
  1397. line_num += 1
  1398. ### Cleanup lines
  1399. eline = eline.strip(' \r\n')
  1400. ## Header Begin/End ##
  1401. if self.hbegin_re.search(eline):
  1402. in_header = True
  1403. continue
  1404. if self.hend_re.search(eline):
  1405. in_header = False
  1406. continue
  1407. #### Body ####
  1408. if not in_header:
  1409. ## Tool change ##
  1410. match = self.toolsel_re.search(eline)
  1411. if match:
  1412. current_tool = str(int(match.group(1)))
  1413. continue
  1414. ## Coordinates without period ##
  1415. match = self.coordsnoperiod_re.search(eline)
  1416. if match:
  1417. try:
  1418. #x = float(match.group(1))/10000
  1419. x = self.parse_number(match.group(1))
  1420. current_x = x
  1421. except TypeError:
  1422. x = current_x
  1423. try:
  1424. #y = float(match.group(2))/10000
  1425. y = self.parse_number(match.group(2))
  1426. current_y = y
  1427. except TypeError:
  1428. y = current_y
  1429. if x is None or y is None:
  1430. log.error("Missing coordinates")
  1431. continue
  1432. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1433. continue
  1434. ## Coordinates with period: Use literally. ##
  1435. match = self.coordsperiod_re.search(eline)
  1436. if match:
  1437. try:
  1438. x = float(match.group(1))
  1439. current_x = x
  1440. except TypeError:
  1441. x = current_x
  1442. try:
  1443. y = float(match.group(2))
  1444. current_y = y
  1445. except TypeError:
  1446. y = current_y
  1447. if x is None or y is None:
  1448. log.error("Missing coordinates")
  1449. continue
  1450. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1451. continue
  1452. #### Header ####
  1453. if in_header:
  1454. ## Tool definitions ##
  1455. match = self.toolset_re.search(eline)
  1456. if match:
  1457. name = str(int(match.group(1)))
  1458. spec = {
  1459. "C": float(match.group(2)),
  1460. # "F": float(match.group(3)),
  1461. # "S": float(match.group(4)),
  1462. # "B": float(match.group(5)),
  1463. # "H": float(match.group(6)),
  1464. # "Z": float(match.group(7))
  1465. }
  1466. self.tools[name] = spec
  1467. continue
  1468. ## Units and number format ##
  1469. match = self.units_re.match(eline)
  1470. if match:
  1471. self.zeros = match.group(2) or self.zeros # "T" or "L". Might be empty
  1472. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1473. continue
  1474. log.warning("Line ignored: %s" % eline)
  1475. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  1476. def parse_number(self, number_str):
  1477. """
  1478. Parses coordinate numbers without period.
  1479. :param number_str: String representing the numerical value.
  1480. :type number_str: str
  1481. :return: Floating point representation of the number
  1482. :rtype: foat
  1483. """
  1484. if self.zeros == "L":
  1485. # With leading zeros, when you type in a coordinate,
  1486. # the leading zeros must always be included. Trailing zeros
  1487. # are unneeded and may be left off. The CNC-7 will automatically add them.
  1488. # r'^[-\+]?(0*)(\d*)'
  1489. # 6 digits are divided by 10^4
  1490. # If less than size digits, they are automatically added,
  1491. # 5 digits then are divided by 10^3 and so on.
  1492. match = self.leadingzeros_re.search(number_str)
  1493. return float(number_str)/(10**(len(match.group(1)) + len(match.group(2)) - 2))
  1494. else: # Trailing
  1495. # You must show all zeros to the right of the number and can omit
  1496. # all zeros to the left of the number. The CNC-7 will count the number
  1497. # of digits you typed and automatically fill in the missing zeros.
  1498. if self.units.lower() == "in": # Inches is 00.0000
  1499. return float(number_str)/10000
  1500. return float(number_str)/1000 # Metric is 000.000
  1501. def create_geometry(self):
  1502. """
  1503. Creates circles of the tool diameter at every point
  1504. specified in ``self.drills``.
  1505. :return: None
  1506. """
  1507. self.solid_geometry = []
  1508. for drill in self.drills:
  1509. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1510. tooldia = self.tools[drill['tool']]['C']
  1511. poly = drill['point'].buffer(tooldia/2.0)
  1512. self.solid_geometry.append(poly)
  1513. def scale(self, factor):
  1514. """
  1515. Scales geometry on the XY plane in the object by a given factor.
  1516. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1517. :param factor: Number by which to scale the object.
  1518. :type factor: float
  1519. :return: None
  1520. :rtype: NOne
  1521. """
  1522. # Drills
  1523. for drill in self.drills:
  1524. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1525. self.create_geometry()
  1526. def offset(self, vect):
  1527. """
  1528. Offsets geometry on the XY plane in the object by a given vector.
  1529. :param vect: (x, y) offset vector.
  1530. :type vect: tuple
  1531. :return: None
  1532. """
  1533. dx, dy = vect
  1534. # Drills
  1535. for drill in self.drills:
  1536. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1537. # Recreate geometry
  1538. self.create_geometry()
  1539. def mirror(self, axis, point):
  1540. """
  1541. :param axis: "X" or "Y" indicates around which axis to mirror.
  1542. :type axis: str
  1543. :param point: [x, y] point belonging to the mirror axis.
  1544. :type point: list
  1545. :return: None
  1546. """
  1547. px, py = point
  1548. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1549. # Modify data
  1550. for drill in self.drills:
  1551. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1552. # Recreate geometry
  1553. self.create_geometry()
  1554. def convert_units(self, units):
  1555. factor = Geometry.convert_units(self, units)
  1556. # Tools
  1557. for tname in self.tools:
  1558. self.tools[tname]["C"] *= factor
  1559. self.create_geometry()
  1560. return factor
  1561. class CNCjob(Geometry):
  1562. """
  1563. Represents work to be done by a CNC machine.
  1564. *ATTRIBUTES*
  1565. * ``gcode_parsed`` (list): Each is a dictionary:
  1566. ===================== =========================================
  1567. Key Value
  1568. ===================== =========================================
  1569. geom (Shapely.LineString) Tool path (XY plane)
  1570. kind (string) "AB", A is "T" (travel) or
  1571. "C" (cut). B is "F" (fast) or "S" (slow).
  1572. ===================== =========================================
  1573. """
  1574. defaults = {
  1575. "zdownrate": None
  1576. }
  1577. def __init__(self, units="in", kind="generic", z_move=0.1,
  1578. feedrate=3.0, z_cut=-0.002, tooldia=0.0, zdownrate=None):
  1579. Geometry.__init__(self)
  1580. self.kind = kind
  1581. self.units = units
  1582. self.z_cut = z_cut
  1583. self.z_move = z_move
  1584. self.feedrate = feedrate
  1585. self.tooldia = tooldia
  1586. self.unitcode = {"IN": "G20", "MM": "G21"}
  1587. self.pausecode = "G04 P1"
  1588. self.feedminutecode = "G94"
  1589. self.absolutecode = "G90"
  1590. self.gcode = ""
  1591. self.input_geometry_bounds = None
  1592. self.gcode_parsed = None
  1593. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1594. if zdownrate is not None:
  1595. self.zdownrate = float(zdownrate)
  1596. elif CNCjob.defaults["zdownrate"] is not None:
  1597. self.zdownrate = float(CNCjob.defaults["zdownrate"])
  1598. else:
  1599. self.zdownrate = None
  1600. # Attributes to be included in serialization
  1601. # Always append to it because it carries contents
  1602. # from Geometry.
  1603. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1604. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1605. 'steps_per_circ']
  1606. # Buffer for linear (No polygons or iterable geometry) elements
  1607. # and their properties.
  1608. self.flat_geometry = []
  1609. # 2D index of self.flat_geometry
  1610. self.flat_geometry_rtree = rtindex.Index()
  1611. # Current insert position to flat_geometry
  1612. self.fg_current_index = 0
  1613. def flatten(self, geo):
  1614. """
  1615. Flattens the input geometry into an array of non-iterable geometry
  1616. elements and indexes into rtree by their first and last coordinate
  1617. pairs.
  1618. :param geo:
  1619. :return:
  1620. """
  1621. try:
  1622. for g in geo:
  1623. self.flatten(g)
  1624. except TypeError: # is not iterable
  1625. self.flat_geometry.append({"path": geo})
  1626. self.flat_geometry_rtree.insert(self.fg_current_index, geo.coords[0])
  1627. self.flat_geometry_rtree.insert(self.fg_current_index, geo.coords[-1])
  1628. self.fg_current_index += 1
  1629. def convert_units(self, units):
  1630. factor = Geometry.convert_units(self, units)
  1631. log.debug("CNCjob.convert_units()")
  1632. self.z_cut *= factor
  1633. self.z_move *= factor
  1634. self.feedrate *= factor
  1635. self.tooldia *= factor
  1636. return factor
  1637. def generate_from_excellon(self, exobj):
  1638. """
  1639. Generates G-code for drilling from Excellon object.
  1640. self.gcode becomes a list, each element is a
  1641. different job for each tool in the excellon code.
  1642. """
  1643. self.kind = "drill"
  1644. self.gcode = []
  1645. t = "G00 X%.4fY%.4f\n"
  1646. down = "G01 Z%.4f\n" % self.z_cut
  1647. up = "G01 Z%.4f\n" % self.z_move
  1648. for tool in exobj.tools:
  1649. points = []
  1650. for drill in exobj.drill:
  1651. if drill['tool'] == tool:
  1652. points.append(drill['point'])
  1653. gcode = self.unitcode[self.units.upper()] + "\n"
  1654. gcode += self.absolutecode + "\n"
  1655. gcode += self.feedminutecode + "\n"
  1656. gcode += "F%.2f\n" % self.feedrate
  1657. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1658. gcode += "M03\n" # Spindle start
  1659. gcode += self.pausecode + "\n"
  1660. for point in points:
  1661. gcode += t % point
  1662. gcode += down + up
  1663. gcode += t % (0, 0)
  1664. gcode += "M05\n" # Spindle stop
  1665. self.gcode.append(gcode)
  1666. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1667. """
  1668. Creates gcode for this object from an Excellon object
  1669. for the specified tools.
  1670. :param exobj: Excellon object to process
  1671. :type exobj: Excellon
  1672. :param tools: Comma separated tool names
  1673. :type: tools: str
  1674. :return: None
  1675. :rtype: None
  1676. """
  1677. log.debug("Creating CNC Job from Excellon...")
  1678. if tools == "all":
  1679. tools = [tool for tool in exobj.tools]
  1680. else:
  1681. tools = [x.strip() for x in tools.split(",")]
  1682. tools = filter(lambda i: i in exobj.tools, tools)
  1683. log.debug("Tools are: %s" % str(tools))
  1684. points = []
  1685. for drill in exobj.drills:
  1686. if drill['tool'] in tools:
  1687. points.append(drill['point'])
  1688. log.debug("Found %d drills." % len(points))
  1689. #self.kind = "drill"
  1690. self.gcode = []
  1691. t = "G00 X%.4fY%.4f\n"
  1692. down = "G01 Z%.4f\n" % self.z_cut
  1693. up = "G01 Z%.4f\n" % self.z_move
  1694. gcode = self.unitcode[self.units.upper()] + "\n"
  1695. gcode += self.absolutecode + "\n"
  1696. gcode += self.feedminutecode + "\n"
  1697. gcode += "F%.2f\n" % self.feedrate
  1698. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1699. gcode += "M03\n" # Spindle start
  1700. gcode += self.pausecode + "\n"
  1701. for point in points:
  1702. x, y = point.coords.xy
  1703. gcode += t % (x[0], y[0])
  1704. gcode += down + up
  1705. gcode += t % (0, 0)
  1706. gcode += "M05\n" # Spindle stop
  1707. self.gcode = gcode
  1708. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1709. """
  1710. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1711. :param geometry: Geometry defining the toolpath
  1712. :type geometry: Geometry
  1713. :param append: Wether to append to self.gcode or re-write it.
  1714. :type append: bool
  1715. :param tooldia: If given, sets the tooldia property but does
  1716. not affect the process in any other way.
  1717. :type tooldia: bool
  1718. :param tolerance: All points in the simplified object will be within the
  1719. tolerance distance of the original geometry.
  1720. :return: None
  1721. :rtype: None
  1722. """
  1723. if tooldia is not None:
  1724. self.tooldia = tooldia
  1725. self.input_geometry_bounds = geometry.bounds()
  1726. if not append:
  1727. self.gcode = ""
  1728. # Initial G-Code
  1729. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1730. self.gcode += self.absolutecode + "\n"
  1731. self.gcode += self.feedminutecode + "\n"
  1732. self.gcode += "F%.2f\n" % self.feedrate
  1733. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  1734. self.gcode += "M03\n" # Spindle start
  1735. self.gcode += self.pausecode + "\n"
  1736. # Iterate over geometry and run individual methods
  1737. # depending on type
  1738. for geo in geometry.solid_geometry:
  1739. if type(geo) == Polygon:
  1740. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1741. continue
  1742. if type(geo) == LineString or type(geo) == LinearRing:
  1743. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1744. continue
  1745. if type(geo) == Point:
  1746. self.gcode += self.point2gcode(geo)
  1747. continue
  1748. if type(geo) == MultiPolygon:
  1749. for poly in geo:
  1750. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1751. continue
  1752. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1753. # Finish
  1754. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1755. self.gcode += "G00 X0Y0\n"
  1756. self.gcode += "M05\n" # Spindle stop
  1757. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, tolerance=0):
  1758. """
  1759. Second algorithm to generate from Geometry.
  1760. :param geometry:
  1761. :param append:
  1762. :param tooldia:
  1763. :param tolerance:
  1764. :return:
  1765. """
  1766. assert isinstance(geometry, Geometry)
  1767. flat_geometry, rtindex = geometry.flatten_to_paths()
  1768. if tooldia is not None:
  1769. self.tooldia = tooldia
  1770. self.input_geometry_bounds = geometry.bounds()
  1771. if not append:
  1772. self.gcode = ""
  1773. # Initial G-Code
  1774. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1775. self.gcode += self.absolutecode + "\n"
  1776. self.gcode += self.feedminutecode + "\n"
  1777. self.gcode += "F%.2f\n" % self.feedrate
  1778. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  1779. self.gcode += "M03\n" # Spindle start
  1780. self.gcode += self.pausecode + "\n"
  1781. # Iterate over geometry and run individual methods
  1782. # depending on type
  1783. # for geo in flat_geometry:
  1784. #
  1785. # if type(geo) == LineString or type(geo) == LinearRing:
  1786. # self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1787. # continue
  1788. #
  1789. # if type(geo) == Point:
  1790. # self.gcode += self.point2gcode(geo)
  1791. # continue
  1792. #
  1793. # log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1794. hits = list(rtindex.nearest((0, 0), 1))
  1795. while len(hits) > 0:
  1796. geo = flat_geometry[hits[0]]
  1797. if type(geo) == LineString or type(geo) == LinearRing:
  1798. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1799. elif type(geo) == Point:
  1800. self.gcode += self.point2gcode(geo)
  1801. else:
  1802. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  1803. start_pt = geo.coords[0]
  1804. stop_pt = geo.coords[-1]
  1805. rtindex.delete(hits[0], start_pt)
  1806. rtindex.delete(hits[0], stop_pt)
  1807. hits = list(rtindex.nearest(stop_pt, 1))
  1808. # Finish
  1809. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1810. self.gcode += "G00 X0Y0\n"
  1811. self.gcode += "M05\n" # Spindle stop
  1812. def pre_parse(self, gtext):
  1813. """
  1814. Separates parts of the G-Code text into a list of dictionaries.
  1815. Used by ``self.gcode_parse()``.
  1816. :param gtext: A single string with g-code
  1817. """
  1818. # Units: G20-inches, G21-mm
  1819. units_re = re.compile(r'^G2([01])')
  1820. # TODO: This has to be re-done
  1821. gcmds = []
  1822. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1823. for line in lines:
  1824. # Clean up
  1825. line = line.strip()
  1826. # Remove comments
  1827. # NOTE: Limited to 1 bracket pair
  1828. op = line.find("(")
  1829. cl = line.find(")")
  1830. #if op > -1 and cl > op:
  1831. if cl > op > -1:
  1832. #comment = line[op+1:cl]
  1833. line = line[:op] + line[(cl+1):]
  1834. # Units
  1835. match = units_re.match(line)
  1836. if match:
  1837. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1838. # Parse GCode
  1839. # 0 4 12
  1840. # G01 X-0.007 Y-0.057
  1841. # --> codes_idx = [0, 4, 12]
  1842. codes = "NMGXYZIJFP"
  1843. codes_idx = []
  1844. i = 0
  1845. for ch in line:
  1846. if ch in codes:
  1847. codes_idx.append(i)
  1848. i += 1
  1849. n_codes = len(codes_idx)
  1850. if n_codes == 0:
  1851. continue
  1852. # Separate codes in line
  1853. parts = []
  1854. for p in range(n_codes-1):
  1855. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1856. parts.append(line[codes_idx[-1]:].strip())
  1857. # Separate codes from values
  1858. cmds = {}
  1859. for part in parts:
  1860. cmds[part[0]] = float(part[1:])
  1861. gcmds.append(cmds)
  1862. return gcmds
  1863. def gcode_parse(self):
  1864. """
  1865. G-Code parser (from self.gcode). Generates dictionary with
  1866. single-segment LineString's and "kind" indicating cut or travel,
  1867. fast or feedrate speed.
  1868. """
  1869. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1870. # Results go here
  1871. geometry = []
  1872. # TODO: Merge into single parser?
  1873. gobjs = self.pre_parse(self.gcode)
  1874. # Last known instruction
  1875. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1876. # Current path: temporary storage until tool is
  1877. # lifted or lowered.
  1878. path = [(0, 0)]
  1879. # Process every instruction
  1880. for gobj in gobjs:
  1881. ## Changing height
  1882. if 'Z' in gobj:
  1883. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1884. log.warning("Non-orthogonal motion: From %s" % str(current))
  1885. log.warning(" To: %s" % str(gobj))
  1886. current['Z'] = gobj['Z']
  1887. # Store the path into geometry and reset path
  1888. if len(path) > 1:
  1889. geometry.append({"geom": LineString(path),
  1890. "kind": kind})
  1891. path = [path[-1]] # Start with the last point of last path.
  1892. if 'G' in gobj:
  1893. current['G'] = int(gobj['G'])
  1894. if 'X' in gobj or 'Y' in gobj:
  1895. if 'X' in gobj:
  1896. x = gobj['X']
  1897. else:
  1898. x = current['X']
  1899. if 'Y' in gobj:
  1900. y = gobj['Y']
  1901. else:
  1902. y = current['Y']
  1903. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1904. if current['Z'] > 0:
  1905. kind[0] = 'T'
  1906. if current['G'] > 0:
  1907. kind[1] = 'S'
  1908. arcdir = [None, None, "cw", "ccw"]
  1909. if current['G'] in [0, 1]: # line
  1910. path.append((x, y))
  1911. if current['G'] in [2, 3]: # arc
  1912. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1913. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1914. start = arctan2(-gobj['J'], -gobj['I'])
  1915. stop = arctan2(-center[1]+y, -center[0]+x)
  1916. path += arc(center, radius, start, stop,
  1917. arcdir[current['G']],
  1918. self.steps_per_circ)
  1919. # Update current instruction
  1920. for code in gobj:
  1921. current[code] = gobj[code]
  1922. # There might not be a change in height at the
  1923. # end, therefore, see here too if there is
  1924. # a final path.
  1925. if len(path) > 1:
  1926. geometry.append({"geom": LineString(path),
  1927. "kind": kind})
  1928. self.gcode_parsed = geometry
  1929. return geometry
  1930. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1931. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1932. # alpha={"T": 0.3, "C": 1.0}):
  1933. # """
  1934. # Creates a Matplotlib figure with a plot of the
  1935. # G-code job.
  1936. # """
  1937. # if tooldia is None:
  1938. # tooldia = self.tooldia
  1939. #
  1940. # fig = Figure(dpi=dpi)
  1941. # ax = fig.add_subplot(111)
  1942. # ax.set_aspect(1)
  1943. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1944. # ax.set_xlim(xmin-margin, xmax+margin)
  1945. # ax.set_ylim(ymin-margin, ymax+margin)
  1946. #
  1947. # if tooldia == 0:
  1948. # for geo in self.gcode_parsed:
  1949. # linespec = '--'
  1950. # linecolor = color[geo['kind'][0]][1]
  1951. # if geo['kind'][0] == 'C':
  1952. # linespec = 'k-'
  1953. # x, y = geo['geom'].coords.xy
  1954. # ax.plot(x, y, linespec, color=linecolor)
  1955. # else:
  1956. # for geo in self.gcode_parsed:
  1957. # poly = geo['geom'].buffer(tooldia/2.0)
  1958. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1959. # edgecolor=color[geo['kind'][0]][1],
  1960. # alpha=alpha[geo['kind'][0]], zorder=2)
  1961. # ax.add_patch(patch)
  1962. #
  1963. # return fig
  1964. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1965. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1966. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1967. """
  1968. Plots the G-code job onto the given axes.
  1969. :param axes: Matplotlib axes on which to plot.
  1970. :param tooldia: Tool diameter.
  1971. :param dpi: Not used!
  1972. :param margin: Not used!
  1973. :param color: Color specification.
  1974. :param alpha: Transparency specification.
  1975. :param tool_tolerance: Tolerance when drawing the toolshape.
  1976. :return: None
  1977. """
  1978. if tooldia is None:
  1979. tooldia = self.tooldia
  1980. if tooldia == 0:
  1981. for geo in self.gcode_parsed:
  1982. linespec = '--'
  1983. linecolor = color[geo['kind'][0]][1]
  1984. if geo['kind'][0] == 'C':
  1985. linespec = 'k-'
  1986. x, y = geo['geom'].coords.xy
  1987. axes.plot(x, y, linespec, color=linecolor)
  1988. else:
  1989. for geo in self.gcode_parsed:
  1990. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1991. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1992. edgecolor=color[geo['kind'][0]][1],
  1993. alpha=alpha[geo['kind'][0]], zorder=2)
  1994. axes.add_patch(patch)
  1995. def create_geometry(self):
  1996. # TODO: This takes forever. Too much data?
  1997. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1998. def polygon2gcode(self, polygon, tolerance=0):
  1999. """
  2000. Creates G-Code for the exterior and all interior paths
  2001. of a polygon.
  2002. :param polygon: A Shapely.Polygon
  2003. :type polygon: Shapely.Polygon
  2004. :param tolerance: All points in the simplified object will be within the
  2005. tolerance distance of the original geometry.
  2006. :type tolerance: float
  2007. :return: G-code to cut along polygon.
  2008. :rtype: str
  2009. """
  2010. if tolerance > 0:
  2011. target_polygon = polygon.simplify(tolerance)
  2012. else:
  2013. target_polygon = polygon
  2014. gcode = ""
  2015. t = "G0%d X%.4fY%.4f\n"
  2016. path = list(target_polygon.exterior.coords) # Polygon exterior
  2017. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2018. if self.zdownrate is not None:
  2019. gcode += "F%.2f\n" % self.zdownrate
  2020. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2021. gcode += "F%.2f\n" % self.feedrate
  2022. else:
  2023. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2024. for pt in path[1:]:
  2025. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2026. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2027. for ints in target_polygon.interiors: # Polygon interiors
  2028. path = list(ints.coords)
  2029. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2030. if self.zdownrate is not None:
  2031. gcode += "F%.2f\n" % self.zdownrate
  2032. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2033. gcode += "F%.2f\n" % self.feedrate
  2034. else:
  2035. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2036. for pt in path[1:]:
  2037. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2038. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2039. return gcode
  2040. def linear2gcode(self, linear, tolerance=0):
  2041. """
  2042. Generates G-code to cut along the linear feature.
  2043. :param linear: The path to cut along.
  2044. :type: Shapely.LinearRing or Shapely.Linear String
  2045. :param tolerance: All points in the simplified object will be within the
  2046. tolerance distance of the original geometry.
  2047. :type tolerance: float
  2048. :return: G-code to cut alon the linear feature.
  2049. :rtype: str
  2050. """
  2051. if tolerance > 0:
  2052. target_linear = linear.simplify(tolerance)
  2053. else:
  2054. target_linear = linear
  2055. gcode = ""
  2056. t = "G0%d X%.4fY%.4f\n"
  2057. path = list(target_linear.coords)
  2058. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2059. if self.zdownrate is not None:
  2060. gcode += "F%.2f\n" % self.zdownrate
  2061. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2062. gcode += "F%.2f\n" % self.feedrate
  2063. else:
  2064. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2065. for pt in path[1:]:
  2066. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2067. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2068. return gcode
  2069. def point2gcode(self, point):
  2070. gcode = ""
  2071. t = "G0%d X%.4fY%.4f\n"
  2072. path = list(point.coords)
  2073. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2074. if self.zdownrate is not None:
  2075. gcode += "F%.2f\n" % self.zdownrate
  2076. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2077. gcode += "F%.2f\n" % self.feedrate
  2078. else:
  2079. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2080. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2081. return gcode
  2082. def scale(self, factor):
  2083. """
  2084. Scales all the geometry on the XY plane in the object by the
  2085. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2086. not altered.
  2087. :param factor: Number by which to scale the object.
  2088. :type factor: float
  2089. :return: None
  2090. :rtype: None
  2091. """
  2092. for g in self.gcode_parsed:
  2093. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2094. self.create_geometry()
  2095. def offset(self, vect):
  2096. """
  2097. Offsets all the geometry on the XY plane in the object by the
  2098. given vector.
  2099. :param vect: (x, y) offset vector.
  2100. :type vect: tuple
  2101. :return: None
  2102. """
  2103. dx, dy = vect
  2104. for g in self.gcode_parsed:
  2105. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2106. self.create_geometry()
  2107. # def get_bounds(geometry_set):
  2108. # xmin = Inf
  2109. # ymin = Inf
  2110. # xmax = -Inf
  2111. # ymax = -Inf
  2112. #
  2113. # #print "Getting bounds of:", str(geometry_set)
  2114. # for gs in geometry_set:
  2115. # try:
  2116. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2117. # xmin = min([xmin, gxmin])
  2118. # ymin = min([ymin, gymin])
  2119. # xmax = max([xmax, gxmax])
  2120. # ymax = max([ymax, gymax])
  2121. # except:
  2122. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2123. #
  2124. # return [xmin, ymin, xmax, ymax]
  2125. def get_bounds(geometry_list):
  2126. xmin = Inf
  2127. ymin = Inf
  2128. xmax = -Inf
  2129. ymax = -Inf
  2130. #print "Getting bounds of:", str(geometry_set)
  2131. for gs in geometry_list:
  2132. try:
  2133. gxmin, gymin, gxmax, gymax = gs.bounds()
  2134. xmin = min([xmin, gxmin])
  2135. ymin = min([ymin, gymin])
  2136. xmax = max([xmax, gxmax])
  2137. ymax = max([ymax, gymax])
  2138. except:
  2139. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  2140. return [xmin, ymin, xmax, ymax]
  2141. def arc(center, radius, start, stop, direction, steps_per_circ):
  2142. """
  2143. Creates a list of point along the specified arc.
  2144. :param center: Coordinates of the center [x, y]
  2145. :type center: list
  2146. :param radius: Radius of the arc.
  2147. :type radius: float
  2148. :param start: Starting angle in radians
  2149. :type start: float
  2150. :param stop: End angle in radians
  2151. :type stop: float
  2152. :param direction: Orientation of the arc, "CW" or "CCW"
  2153. :type direction: string
  2154. :param steps_per_circ: Number of straight line segments to
  2155. represent a circle.
  2156. :type steps_per_circ: int
  2157. :return: The desired arc, as list of tuples
  2158. :rtype: list
  2159. """
  2160. # TODO: Resolution should be established by fraction of total length, not angle.
  2161. da_sign = {"cw": -1.0, "ccw": 1.0}
  2162. points = []
  2163. if direction == "ccw" and stop <= start:
  2164. stop += 2*pi
  2165. if direction == "cw" and stop >= start:
  2166. stop -= 2*pi
  2167. angle = abs(stop - start)
  2168. #angle = stop-start
  2169. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  2170. delta_angle = da_sign[direction]*angle*1.0/steps
  2171. for i in range(steps+1):
  2172. theta = start + delta_angle*i
  2173. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  2174. return points
  2175. def arc_angle(start, stop, direction):
  2176. if direction == "ccw" and stop <= start:
  2177. stop += 2*pi
  2178. if direction == "cw" and stop >= start:
  2179. stop -= 2*pi
  2180. angle = abs(stop - start)
  2181. return angle
  2182. def clear_poly(poly, tooldia, overlap=0.1):
  2183. """
  2184. Creates a list of Shapely geometry objects covering the inside
  2185. of a Shapely.Polygon. Use for removing all the copper in a region
  2186. or bed flattening.
  2187. :param poly: Target polygon
  2188. :type poly: Shapely.Polygon
  2189. :param tooldia: Diameter of the tool
  2190. :type tooldia: float
  2191. :param overlap: Fraction of the tool diameter to overlap
  2192. in each pass.
  2193. :type overlap: float
  2194. :return: list of Shapely.Polygon
  2195. :rtype: list
  2196. """
  2197. poly_cuts = [poly.buffer(-tooldia/2.0)]
  2198. while True:
  2199. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  2200. if poly.area > 0:
  2201. poly_cuts.append(poly)
  2202. else:
  2203. break
  2204. return poly_cuts
  2205. def find_polygon(poly_set, point):
  2206. """
  2207. Return the first polygon in the list of polygons poly_set
  2208. that contains the given point.
  2209. """
  2210. p = Point(point)
  2211. for poly in poly_set:
  2212. if poly.contains(p):
  2213. return poly
  2214. return None
  2215. def to_dict(obj):
  2216. """
  2217. Makes a Shapely geometry object into serializeable form.
  2218. :param obj: Shapely geometry.
  2219. :type obj: BaseGeometry
  2220. :return: Dictionary with serializable form if ``obj`` was
  2221. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  2222. """
  2223. if isinstance(obj, ApertureMacro):
  2224. return {
  2225. "__class__": "ApertureMacro",
  2226. "__inst__": obj.to_dict()
  2227. }
  2228. if isinstance(obj, BaseGeometry):
  2229. return {
  2230. "__class__": "Shply",
  2231. "__inst__": sdumps(obj)
  2232. }
  2233. return obj
  2234. def dict2obj(d):
  2235. """
  2236. Default deserializer.
  2237. :param d: Serializable dictionary representation of an object
  2238. to be reconstructed.
  2239. :return: Reconstructed object.
  2240. """
  2241. if '__class__' in d and '__inst__' in d:
  2242. if d['__class__'] == "Shply":
  2243. return sloads(d['__inst__'])
  2244. if d['__class__'] == "ApertureMacro":
  2245. am = ApertureMacro()
  2246. am.from_dict(d['__inst__'])
  2247. return am
  2248. return d
  2249. else:
  2250. return d
  2251. def plotg(geo):
  2252. try:
  2253. _ = iter(geo)
  2254. except:
  2255. geo = [geo]
  2256. for g in geo:
  2257. if type(g) == Polygon:
  2258. x, y = g.exterior.coords.xy
  2259. plot(x, y)
  2260. for ints in g.interiors:
  2261. x, y = ints.coords.xy
  2262. plot(x, y)
  2263. continue
  2264. if type(g) == LineString or type(g) == LinearRing:
  2265. x, y = g.coords.xy
  2266. plot(x, y)
  2267. continue
  2268. if type(g) == Point:
  2269. x, y = g.coords.xy
  2270. plot(x, y, 'o')
  2271. continue
  2272. try:
  2273. _ = iter(g)
  2274. plotg(g)
  2275. except:
  2276. log.error("Cannot plot: " + str(type(g)))
  2277. continue
  2278. def parse_gerber_number(strnumber, frac_digits):
  2279. """
  2280. Parse a single number of Gerber coordinates.
  2281. :param strnumber: String containing a number in decimal digits
  2282. from a coordinate data block, possibly with a leading sign.
  2283. :type strnumber: str
  2284. :param frac_digits: Number of digits used for the fractional
  2285. part of the number
  2286. :type frac_digits: int
  2287. :return: The number in floating point.
  2288. :rtype: float
  2289. """
  2290. return int(strnumber)*(10**(-frac_digits))
  2291. def voronoi(P):
  2292. """
  2293. Returns a list of all edges of the voronoi diagram for the given input points.
  2294. """
  2295. delauny = Delaunay(P)
  2296. triangles = delauny.points[delauny.vertices]
  2297. circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  2298. long_lines_endpoints = []
  2299. lineIndices = []
  2300. for i, triangle in enumerate(triangles):
  2301. circum_center = circum_centers[i]
  2302. for j, neighbor in enumerate(delauny.neighbors[i]):
  2303. if neighbor != -1:
  2304. lineIndices.append((i, neighbor))
  2305. else:
  2306. ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  2307. ps = np.array((ps[1], -ps[0]))
  2308. middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  2309. di = middle - triangle[j]
  2310. ps /= np.linalg.norm(ps)
  2311. di /= np.linalg.norm(di)
  2312. if np.dot(di, ps) < 0.0:
  2313. ps *= -1000.0
  2314. else:
  2315. ps *= 1000.0
  2316. long_lines_endpoints.append(circum_center + ps)
  2317. lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  2318. vertices = np.vstack((circum_centers, long_lines_endpoints))
  2319. # filter out any duplicate lines
  2320. lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  2321. lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  2322. lineIndicesUnique = np.unique(lineIndicesTupled)
  2323. return vertices, lineIndicesUnique
  2324. def triangle_csc(pts):
  2325. rows, cols = pts.shape
  2326. A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  2327. [np.ones((1, rows)), np.zeros((1, 1))]])
  2328. b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  2329. x = np.linalg.solve(A,b)
  2330. bary_coords = x[:-1]
  2331. return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  2332. def voronoi_cell_lines(points, vertices, lineIndices):
  2333. """
  2334. Returns a mapping from a voronoi cell to its edges.
  2335. :param points: shape (m,2)
  2336. :param vertices: shape (n,2)
  2337. :param lineIndices: shape (o,2)
  2338. :rtype: dict point index -> list of shape (n,2) with vertex indices
  2339. """
  2340. kd = KDTree(points)
  2341. cells = collections.defaultdict(list)
  2342. for i1, i2 in lineIndices:
  2343. v1, v2 = vertices[i1], vertices[i2]
  2344. mid = (v1+v2)/2
  2345. _, (p1Idx, p2Idx) = kd.query(mid, 2)
  2346. cells[p1Idx].append((i1, i2))
  2347. cells[p2Idx].append((i1, i2))
  2348. return cells
  2349. def voronoi_edges2polygons(cells):
  2350. """
  2351. Transforms cell edges into polygons.
  2352. :param cells: as returned from voronoi_cell_lines
  2353. :rtype: dict point index -> list of vertex indices which form a polygon
  2354. """
  2355. # first, close the outer cells
  2356. for pIdx, lineIndices_ in cells.items():
  2357. dangling_lines = []
  2358. for i1, i2 in lineIndices_:
  2359. connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  2360. assert 1 <= len(connections) <= 2
  2361. if len(connections) == 1:
  2362. dangling_lines.append((i1, i2))
  2363. assert len(dangling_lines) in [0, 2]
  2364. if len(dangling_lines) == 2:
  2365. (i11, i12), (i21, i22) = dangling_lines
  2366. # determine which line ends are unconnected
  2367. connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  2368. i11Unconnected = len(connected) == 0
  2369. connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  2370. i21Unconnected = len(connected) == 0
  2371. startIdx = i11 if i11Unconnected else i12
  2372. endIdx = i21 if i21Unconnected else i22
  2373. cells[pIdx].append((startIdx, endIdx))
  2374. # then, form polygons by storing vertex indices in (counter-)clockwise order
  2375. polys = dict()
  2376. for pIdx, lineIndices_ in cells.items():
  2377. # get a directed graph which contains both directions and arbitrarily follow one of both
  2378. directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  2379. directedGraphMap = collections.defaultdict(list)
  2380. for (i1, i2) in directedGraph:
  2381. directedGraphMap[i1].append(i2)
  2382. orderedEdges = []
  2383. currentEdge = directedGraph[0]
  2384. while len(orderedEdges) < len(lineIndices_):
  2385. i1 = currentEdge[1]
  2386. i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  2387. nextEdge = (i1, i2)
  2388. orderedEdges.append(nextEdge)
  2389. currentEdge = nextEdge
  2390. polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  2391. return polys
  2392. def voronoi_polygons(points):
  2393. """
  2394. Returns the voronoi polygon for each input point.
  2395. :param points: shape (n,2)
  2396. :rtype: list of n polygons where each polygon is an array of vertices
  2397. """
  2398. vertices, lineIndices = voronoi(points)
  2399. cells = voronoi_cell_lines(points, vertices, lineIndices)
  2400. polys = voronoi_edges2polygons(cells)
  2401. polylist = []
  2402. for i in xrange(len(points)):
  2403. poly = vertices[np.asarray(polys[i])]
  2404. polylist.append(poly)
  2405. return polylist
  2406. class Zprofile:
  2407. def __init__(self):
  2408. # data contains lists of [x, y, z]
  2409. self.data = []
  2410. # Computed voronoi polygons (shapely)
  2411. self.polygons = []
  2412. pass
  2413. def plot_polygons(self):
  2414. axes = plt.subplot(1, 1, 1)
  2415. plt.axis([-0.05, 1.05, -0.05, 1.05])
  2416. for poly in self.polygons:
  2417. p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  2418. axes.add_patch(p)
  2419. def init_from_csv(self, filename):
  2420. pass
  2421. def init_from_string(self, zpstring):
  2422. pass
  2423. def init_from_list(self, zplist):
  2424. self.data = zplist
  2425. def generate_polygons(self):
  2426. self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  2427. def normalize(self, origin):
  2428. pass
  2429. def paste(self, path):
  2430. """
  2431. Return a list of dictionaries containing the parts of the original
  2432. path and their z-axis offset.
  2433. """
  2434. # At most one region/polygon will contain the path
  2435. containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  2436. if len(containing) > 0:
  2437. return [{"path": path, "z": self.data[containing[0]][2]}]
  2438. # All region indexes that intersect with the path
  2439. crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  2440. return [{"path": path.intersection(self.polygons[i]),
  2441. "z": self.data[i][2]} for i in crossing]