camlib.py 107 KB

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