camlib.py 107 KB

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