camlib.py 107 KB

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