camlib.py 106 KB

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