camlib.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  9. from matplotlib.figure import Figure
  10. import re
  11. # See: http://toblerity.org/shapely/manual.html
  12. from shapely.geometry import Polygon, LineString, Point, LinearRing
  13. from shapely.geometry import MultiPoint, MultiPolygon
  14. from shapely.geometry import box as shply_box
  15. from shapely.ops import cascaded_union
  16. import shapely.affinity as affinity
  17. from shapely.wkt import loads as sloads
  18. from shapely.wkt import dumps as sdumps
  19. from shapely.geometry.base import BaseGeometry
  20. # Used for solid polygons in Matplotlib
  21. from descartes.patch import PolygonPatch
  22. import simplejson as json
  23. # TODO: Commented for FlatCAM packaging with cx_freeze
  24. #from matplotlib.pyplot import plot
  25. class Geometry(object):
  26. def __init__(self):
  27. # Units (in or mm)
  28. self.units = 'in'
  29. # Final geometry: MultiPolygon
  30. self.solid_geometry = None
  31. # Attributes to be included in serialization
  32. self.ser_attrs = ['units', 'solid_geometry']
  33. def isolation_geometry(self, offset):
  34. """
  35. Creates contours around geometry at a given
  36. offset distance.
  37. :param offset: Offset distance.
  38. :type offset: float
  39. :return: The buffered geometry.
  40. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  41. """
  42. return self.solid_geometry.buffer(offset)
  43. def bounds(self):
  44. """
  45. Returns coordinates of rectangular bounds
  46. of geometry: (xmin, ymin, xmax, ymax).
  47. """
  48. if self.solid_geometry is None:
  49. print "Warning: solid_geometry not computed yet."
  50. return (0, 0, 0, 0)
  51. if type(self.solid_geometry) == list:
  52. # TODO: This can be done faster. See comment from Shapely mailing lists.
  53. return cascaded_union(self.solid_geometry).bounds
  54. else:
  55. return self.solid_geometry.bounds
  56. def size(self):
  57. """
  58. Returns (width, height) of rectangular
  59. bounds of geometry.
  60. """
  61. if self.solid_geometry is None:
  62. print "Warning: solid_geometry not computed yet."
  63. return 0
  64. bounds = self.bounds()
  65. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  66. def get_empty_area(self, boundary=None):
  67. """
  68. Returns the complement of self.solid_geometry within
  69. the given boundary polygon. If not specified, it defaults to
  70. the rectangular bounding box of self.solid_geometry.
  71. """
  72. if boundary is None:
  73. boundary = self.solid_geometry.envelope
  74. return boundary.difference(self.solid_geometry)
  75. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  76. """
  77. Creates geometry inside a polygon for a tool to cover
  78. the whole area.
  79. """
  80. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  81. while True:
  82. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  83. if polygon.area > 0:
  84. poly_cuts.append(polygon)
  85. else:
  86. break
  87. return poly_cuts
  88. def scale(self, factor):
  89. """
  90. Scales all of the object's geometry by a given factor. Override
  91. this method.
  92. :param factor: Number by which to scale.
  93. :type factor: float
  94. :return: None
  95. :rtype: None
  96. """
  97. return
  98. def offset(self, vect):
  99. """
  100. Offset the geometry by the given vector. Override this method.
  101. :param vect: (x, y) vector by which to offset the object.
  102. :type vect: tuple
  103. :return: None
  104. """
  105. return
  106. def convert_units(self, units):
  107. """
  108. Converts the units of the object to ``units`` by scaling all
  109. the geometry appropriately. This call ``scale()``. Don't call
  110. it again in descendents.
  111. :param units: "IN" or "MM"
  112. :type units: str
  113. :return: Scaling factor resulting from unit change.
  114. :rtype: float
  115. """
  116. print "Geometry.convert_units()"
  117. if units.upper() == self.units.upper():
  118. return 1.0
  119. if units.upper() == "MM":
  120. factor = 25.4
  121. elif units.upper() == "IN":
  122. factor = 1/25.4
  123. else:
  124. print "Unsupported units:", units
  125. return 1.0
  126. self.units = units
  127. self.scale(factor)
  128. return factor
  129. def to_dict(self):
  130. """
  131. Returns a respresentation of the object as a dictionary.
  132. Attributes to include are listed in ``self.ser_attrs``.
  133. :return: A dictionary-encoded copy of the object.
  134. :rtype: dict
  135. """
  136. d = {}
  137. for attr in self.ser_attrs:
  138. d[attr] = getattr(self, attr)
  139. return d
  140. def from_dict(self, d):
  141. """
  142. Sets object's attributes from a dictionary.
  143. Attributes to include are listed in ``self.ser_attrs``.
  144. This method will look only for only and all the
  145. attributes in ``self.ser_attrs``. They must all
  146. be present. Use only for deserializing saved
  147. objects.
  148. :param d: Dictionary of attributes to set in the object.
  149. :type d: dict
  150. :return: None
  151. """
  152. for attr in self.ser_attrs:
  153. setattr(self, attr, d[attr])
  154. class ApertureMacro:
  155. ## Regular expressions
  156. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  157. am2_re = re.compile(r'(.*)%$')
  158. amcomm_re = re.compile(r'^0(.*)')
  159. amprim_re = re.compile(r'^[1-9].*')
  160. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  161. def __init__(self, name=None):
  162. self.name = name
  163. self.raw = ""
  164. ## These below are recomputed for every aperture
  165. ## definition, in other words, are temporary variables.
  166. self.primitives = []
  167. self.locvars = {}
  168. self.geometry = None
  169. def to_dict(self):
  170. """
  171. Returns the object in a serializable form. Only the name and
  172. raw are required.
  173. :return: Dictionary representing the object. JSON ready.
  174. :rtype: dict
  175. """
  176. return {
  177. 'name': self.name,
  178. 'raw': self.raw
  179. }
  180. def from_dict(self, d):
  181. """
  182. Populates the object from a serial representation created
  183. with ``self.to_dict()``.
  184. :param d: Serial representation of an ApertureMacro object.
  185. :return: None
  186. """
  187. for attr in ['name', 'raw']:
  188. setattr(self, attr, d[attr])
  189. def parse_content(self):
  190. """
  191. Creates numerical lists for all primitives in the aperture
  192. macro (in ``self.raw``) by replacing all variables by their
  193. values iteratively and evaluating expressions. Results
  194. are stored in ``self.primitives``.
  195. :return: None
  196. """
  197. # Cleanup
  198. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  199. self.primitives = []
  200. # Separate parts
  201. parts = self.raw.split('*')
  202. #### Every part in the macro ####
  203. for part in parts:
  204. ### Comments. Ignored.
  205. match = ApertureMacro.amcomm_re.search(part)
  206. if match:
  207. continue
  208. ### Variables
  209. # These are variables defined locally inside the macro. They can be
  210. # numerical constant or defind in terms of previously define
  211. # variables, which can be defined locally or in an aperture
  212. # definition. All replacements ocurr here.
  213. match = ApertureMacro.amvar_re.search(part)
  214. if match:
  215. var = match.group(1)
  216. val = match.group(2)
  217. # Replace variables in value
  218. for v in self.locvars:
  219. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  220. # Make all others 0
  221. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  222. # Change x with *
  223. val = re.sub(r'[xX]', "*", val)
  224. # Eval() and store.
  225. self.locvars[var] = eval(val)
  226. continue
  227. ### Primitives
  228. # Each is an array. The first identifies the primitive, while the
  229. # rest depend on the primitive. All are strings representing a
  230. # number and may contain variable definition. The values of these
  231. # variables are defined in an aperture definition.
  232. match = ApertureMacro.amprim_re.search(part)
  233. if match:
  234. ## Replace all variables
  235. for v in self.locvars:
  236. part = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  237. # Make all others 0
  238. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  239. # Change x with *
  240. part = re.sub(r'[xX]', "*", part)
  241. ## Store
  242. elements = part.split(",")
  243. self.primitives.append([eval(x) for x in elements])
  244. continue
  245. print "WARNING: Unknown syntax of aperture macro part:", part
  246. def append(self, data):
  247. """
  248. Appends a string to the raw macro.
  249. :param data: Part of the macro.
  250. :type data: str
  251. :return: None
  252. """
  253. self.raw += data
  254. @staticmethod
  255. def default2zero(n, mods):
  256. """
  257. Pads the ``mods`` list with zeros resulting in an
  258. list of length n.
  259. :param n: Length of the resulting list.
  260. :type n: int
  261. :param mods: List to be padded.
  262. :type mods: list
  263. :return: Zero-padded list.
  264. :rtype: list
  265. """
  266. x = [0.0]*n
  267. na = len(mods)
  268. x[0:na] = mods
  269. return x
  270. @staticmethod
  271. def make_circle(mods):
  272. """
  273. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  274. :return:
  275. """
  276. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  277. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  278. @staticmethod
  279. def make_vectorline(mods):
  280. """
  281. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  282. rotation angle around origin in degrees)
  283. :return:
  284. """
  285. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  286. line = LineString([(xs, ys), (xe, ye)])
  287. box = line.buffer(width/2, cap_style=2)
  288. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  289. return {"pol": int(pol), "geometry": box_rotated}
  290. @staticmethod
  291. def make_centerline(mods):
  292. """
  293. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  294. rotation angle around origin in degrees)
  295. :return:
  296. """
  297. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  298. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  299. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  300. return {"pol": int(pol), "geometry": box_rotated}
  301. @staticmethod
  302. def make_lowerleftline(mods):
  303. """
  304. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  305. rotation angle around origin in degrees)
  306. :return:
  307. """
  308. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  309. box = shply_box(x, y, x+width, y+height)
  310. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  311. return {"pol": int(pol), "geometry": box_rotated}
  312. @staticmethod
  313. def make_outline(mods):
  314. """
  315. :param mods:
  316. :return:
  317. """
  318. pol = mods[0]
  319. n = mods[1]
  320. points = [(0, 0)]*(n+1)
  321. for i in range(n+1):
  322. points[i] = mods[2*i + 2:2*i + 4]
  323. angle = mods[2*n + 4]
  324. poly = Polygon(points)
  325. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  326. return {"pol": int(pol), "geometry": poly_rotated}
  327. @staticmethod
  328. def make_polygon(mods):
  329. """
  330. Note: Specs indicate that rotation is only allowed if the center
  331. (x, y) == (0, 0). I will tolerate breaking this rule.
  332. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  333. diameter of circumscribed circle >=0, rotation angle around origin)
  334. :return:
  335. """
  336. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  337. points = [(0, 0)]*nverts
  338. for i in range(nverts):
  339. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  340. y + 0.5 * dia * sin(2*pi * i/nverts))
  341. poly = Polygon(points)
  342. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  343. return {"pol": int(pol), "geometry": poly_rotated}
  344. @staticmethod
  345. def make_moire(mods):
  346. """
  347. Note: Specs indicate that rotation is only allowed if the center
  348. (x, y) == (0, 0). I will tolerate breaking this rule.
  349. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  350. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  351. angle around origin in degrees)
  352. :return:
  353. """
  354. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  355. r = dia/2 - thickness/2
  356. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  357. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  358. i = 1 # Number of rings created so far
  359. ## If the ring does not have an interior it means that it is
  360. ## a disk. Then stop.
  361. while len(ring.interiors) > 0 and i < nrings:
  362. r -= thickness + gap
  363. if r <= 0:
  364. break
  365. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  366. result = cascaded_union([result, ring])
  367. i += 1
  368. ## Crosshair
  369. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  370. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  371. result = cascaded_union([result, hor, ver])
  372. return {"pol": 1, "geometry": result}
  373. @staticmethod
  374. def make_thermal(mods):
  375. """
  376. Note: Specs indicate that rotation is only allowed if the center
  377. (x, y) == (0, 0). I will tolerate breaking this rule.
  378. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  379. gap-thickness, rotation angle around origin]
  380. :return:
  381. """
  382. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  383. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  384. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  385. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  386. thermal = ring.difference(hline.union(vline))
  387. return {"pol": 1, "geometry": thermal}
  388. def make_geometry(self, modifiers):
  389. """
  390. Runs the macro for the given modifiers and generates
  391. the corresponding geometry.
  392. :param modifiers: Modifiers (parameters) for this macro
  393. :type modifiers: list
  394. """
  395. ## Primitive makers
  396. makers = {
  397. "1": ApertureMacro.make_circle,
  398. "2": ApertureMacro.make_vectorline,
  399. "20": ApertureMacro.make_vectorline,
  400. "21": ApertureMacro.make_centerline,
  401. "22": ApertureMacro.make_lowerleftline,
  402. "4": ApertureMacro.make_outline,
  403. "5": ApertureMacro.make_polygon,
  404. "6": ApertureMacro.make_moire,
  405. "7": ApertureMacro.make_thermal
  406. }
  407. ## Store modifiers as local variables
  408. modifiers = modifiers or []
  409. modifiers = [float(m) for m in modifiers]
  410. self.locvars = {}
  411. for i in range(0, len(modifiers)):
  412. self.locvars[str(i+1)] = modifiers[i]
  413. ## Parse
  414. self.primitives = [] # Cleanup
  415. self.geometry = None
  416. self.parse_content()
  417. ## Make the geometry
  418. for primitive in self.primitives:
  419. # Make the primitive
  420. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  421. # Add it (according to polarity)
  422. if self.geometry is None and prim_geo['pol'] == 1:
  423. self.geometry = prim_geo['geometry']
  424. continue
  425. if prim_geo['pol'] == 1:
  426. self.geometry = self.geometry.union(prim_geo['geometry'])
  427. continue
  428. if prim_geo['pol'] == 0:
  429. self.geometry = self.geometry.difference(prim_geo['geometry'])
  430. continue
  431. return self.geometry
  432. class Gerber (Geometry):
  433. """
  434. **ATTRIBUTES**
  435. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  436. The values are dictionaries key/value pairs which describe the aperture. The
  437. type key is always present and the rest depend on the key:
  438. +-----------+-----------------------------------+
  439. | Key | Value |
  440. +===========+===================================+
  441. | type | (str) "C", "R", "O", "P", or "AP" |
  442. +-----------+-----------------------------------+
  443. | others | Depend on ``type`` |
  444. +-----------+-----------------------------------+
  445. * ``paths`` (list): A path is described by a line an aperture that follows that
  446. line. Each paths[i] is a dictionary:
  447. +------------+------------------------------------------------+
  448. | Key | Value |
  449. +============+================================================+
  450. | linestring | (Shapely.LineString) The actual path. |
  451. +------------+------------------------------------------------+
  452. | aperture | (str) The key for an aperture in apertures. |
  453. +------------+------------------------------------------------+
  454. * ``flashes`` (list): Flashes are single-point strokes of an aperture. Each
  455. is a dictionary:
  456. +------------+------------------------------------------------+
  457. | Key | Value |
  458. +============+================================================+
  459. | loc | (Point) Shapely Point indicating location. |
  460. +------------+------------------------------------------------+
  461. | aperture | (str) The key for an aperture in apertures. |
  462. +------------+------------------------------------------------+
  463. * ``regions`` (list): Are surfaces defined by a polygon (Shapely.Polygon),
  464. which have an exterior and zero or more interiors. An aperture is also
  465. associated with a region. Each is a dictionary:
  466. +------------+-----------------------------------------------------+
  467. | Key | Value |
  468. +============+=====================================================+
  469. | polygon | (Shapely.Polygon) The polygon defining the region. |
  470. +------------+-----------------------------------------------------+
  471. | aperture | (str) The key for an aperture in apertures. |
  472. +------------+-----------------------------------------------------+
  473. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  474. that can be instanciated with different parameters in an aperture
  475. definition. See ``apertures`` above. The key is the name of the macro,
  476. and the macro itself, the value, is a ``Aperture_Macro`` object.
  477. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  478. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  479. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  480. *buffering* (or thickening) the ``paths`` with the aperture. These are
  481. generated from ``paths`` in ``buffer_paths()``.
  482. **USAGE**::
  483. g = Gerber()
  484. g.parse_file(filename)
  485. g.create_geometry()
  486. do_something(s.solid_geometry)
  487. """
  488. def __init__(self):
  489. """
  490. The constructor takes no parameters. Use ``gerber.parse_files()``
  491. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  492. :return: Gerber object
  493. :rtype: Gerber
  494. """
  495. # Initialize parent
  496. Geometry.__init__(self)
  497. # Number format
  498. self.int_digits = 3
  499. """Number of integer digits in Gerber numbers. Used during parsing."""
  500. self.frac_digits = 4
  501. """Number of fraction digits in Gerber numbers. Used during parsing."""
  502. ## Gerber elements ##
  503. # Apertures {'id':{'type':chr,
  504. # ['size':float], ['width':float],
  505. # ['height':float]}, ...}
  506. self.apertures = {}
  507. # Paths [{'linestring':LineString, 'aperture':str}]
  508. self.paths = []
  509. # Buffered Paths [Polygon]
  510. # Paths transformed into Polygons by
  511. # offsetting the aperture size/2
  512. self.buffered_paths = []
  513. # Polygon regions [{'polygon':Polygon, 'aperture':str}]
  514. self.regions = []
  515. # Flashes [{'loc':[float,float], 'aperture':str}]
  516. self.flashes = []
  517. # Geometry from flashes
  518. self.flash_geometry = []
  519. # Aperture Macros
  520. # TODO: Make sure these can be serialized
  521. self.aperture_macros = {}
  522. # Attributes to be included in serialization
  523. # Always append to it because it carries contents
  524. # from Geometry.
  525. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures', 'paths',
  526. 'buffered_paths', 'regions', 'flashes',
  527. 'flash_geometry', 'aperture_macros']
  528. #### Parser patterns ####
  529. # FS - Format Specification
  530. # The format of X and Y must be the same!
  531. # L-omit leading zeros, T-omit trailing zeros
  532. # A-absolute notation, I-incremental notation
  533. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  534. # Mode (IN/MM)
  535. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  536. # Comment G04|G4
  537. self.comm_re = re.compile(r'^G0?4(.*)$')
  538. # AD - Aperture definition
  539. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z0-9]*)(?:,(.*))?\*%$')
  540. # AM - Aperture Macro
  541. # Beginning of macro (Ends with *%):
  542. self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  543. # Tool change
  544. # May begin with G54 but that is deprecated
  545. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  546. # G01 - Linear interpolation plus flashes
  547. # Operation code (D0x) missing is deprecated... oh well I will support it.
  548. self.lin_re = re.compile(r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0?([123]))?\*$')
  549. self.setlin_re = re.compile(r'^(?:G0?1)\*')
  550. # G02/3 - Circular interpolation
  551. # 2-clockwise, 3-counterclockwise
  552. self.circ_re = re.compile(r'^(?:G0?([23]))?(?:X(-?\d+))?(?:Y(-?\d+))' +
  553. '?(?:I(-?\d+))?(?:J(-?\d+))?D0([12])\*$')
  554. # G01/2/3 Occurring without coordinates
  555. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  556. # Single D74 or multi D75 quadrant for circular interpolation
  557. self.quad_re = re.compile(r'^G7([45])\*$')
  558. # Region mode on
  559. # In region mode, D01 starts a region
  560. # and D02 ends it. A new region can be started again
  561. # with D01. All contours must be closed before
  562. # D02 or G37.
  563. self.regionon_re = re.compile(r'^G36\*$')
  564. # Region mode off
  565. # Will end a region and come off region mode.
  566. # All contours must be closed before D02 or G37.
  567. self.regionoff_re = re.compile(r'^G37\*$')
  568. # End of file
  569. self.eof_re = re.compile(r'^M02\*')
  570. # IP - Image polarity
  571. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  572. # LP - Level polarity
  573. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  574. # Units (OBSOLETE)
  575. self.units_re = re.compile(r'^G7([01])\*$')
  576. # Absolute/Relative G90/1 (OBSOLETE)
  577. self.absrel_re = re.compile(r'^G9([01])\*$')
  578. # Aperture macros
  579. self.am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  580. self.am2_re = re.compile(r'(.*)%$')
  581. # TODO: This is bad.
  582. self.steps_per_circ = 40
  583. def scale(self, factor):
  584. """
  585. Scales the objects' geometry on the XY plane by a given factor.
  586. These are:
  587. * ``buffered_paths``
  588. * ``flash_geometry``
  589. * ``solid_geometry``
  590. * ``regions``
  591. NOTE:
  592. Does not modify the data used to create these elements. If these
  593. are recreated, the scaling will be lost. This behavior was modified
  594. because of the complexity reached in this class.
  595. :param factor: Number by which to scale.
  596. :type factor: float
  597. :rtype : None
  598. """
  599. # ## Apertures
  600. # # List of the non-dimension aperture parameters
  601. # nonDimensions = ["type", "nVertices", "rotation"]
  602. # for apid in self.apertures:
  603. # for param in self.apertures[apid]:
  604. # if param not in nonDimensions: # All others are dimensions.
  605. # print "Tool:", apid, "Parameter:", param
  606. # self.apertures[apid][param] *= factor
  607. #
  608. # ## Paths
  609. # for path in self.paths:
  610. # path['linestring'] = affinity.scale(path['linestring'],
  611. # factor, factor, origin=(0, 0))
  612. #
  613. # ## Flashes
  614. # for fl in self.flashes:
  615. # fl['loc'] = affinity.scale(fl['loc'], factor, factor, origin=(0, 0))
  616. ## Regions
  617. for reg in self.regions:
  618. reg['polygon'] = affinity.scale(reg['polygon'], factor, factor,
  619. origin=(0, 0))
  620. ## Flashes
  621. for flash in self.flash_geometry:
  622. flash = affinity.scale(flash, factor, factor, origin=(0, 0))
  623. ## Buffered paths
  624. for bp in self.buffered_paths:
  625. bp = affinity.scale(bp, factor, factor, origin=(0, 0))
  626. ## solid_geometry ???
  627. # It's a cascaded union of objects.
  628. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  629. factor, origin=(0, 0))
  630. # # Now buffered_paths, flash_geometry and solid_geometry
  631. # self.create_geometry()
  632. def offset(self, vect):
  633. """
  634. Offsets the objects' geometry on the XY plane by a given vector.
  635. These are:
  636. * ``buffered_paths``
  637. * ``flash_geometry``
  638. * ``solid_geometry``
  639. * ``regions``
  640. NOTE:
  641. Does not modify the data used to create these elements. If these
  642. are recreated, the scaling will be lost. This behavior was modified
  643. because of the complexity reached in this class.
  644. :param vect: (x, y) offset vector.
  645. :type vect: tuple
  646. :return: None
  647. """
  648. dx, dy = vect
  649. # ## Paths
  650. # for path in self.paths:
  651. # path['linestring'] = affinity.translate(path['linestring'],
  652. # xoff=dx, yoff=dy)
  653. #
  654. # ## Flashes
  655. # for fl in self.flashes:
  656. # fl['loc'] = affinity.translate(fl['loc'], xoff=dx, yoff=dy)
  657. ## Regions
  658. for reg in self.regions:
  659. reg['polygon'] = affinity.translate(reg['polygon'],
  660. xoff=dx, yoff=dy)
  661. ## Buffered paths
  662. for bp in self.buffered_paths:
  663. bp = affinity.translate(bp, xoff=dx, yoff=dy)
  664. ## Flash geometry
  665. for fl in self.flash_geometry:
  666. fl = affinity.translate(fl, xoff=dx, yoff=dy)
  667. ## Solid geometry
  668. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  669. # # Now buffered_paths, flash_geometry and solid_geometry
  670. # self.create_geometry()
  671. def mirror(self, axis, point):
  672. """
  673. Mirrors the object around a specified axis passign through
  674. the given point. What is affected:
  675. * ``buffered_paths``
  676. * ``flash_geometry``
  677. * ``solid_geometry``
  678. * ``regions``
  679. NOTE:
  680. Does not modify the data used to create these elements. If these
  681. are recreated, the scaling will be lost. This behavior was modified
  682. because of the complexity reached in this class.
  683. :param axis: "X" or "Y" indicates around which axis to mirror.
  684. :type axis: str
  685. :param point: [x, y] point belonging to the mirror axis.
  686. :type point: list
  687. :return: None
  688. """
  689. px, py = point
  690. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  691. # ## Paths
  692. # for path in self.paths:
  693. # path['linestring'] = affinity.scale(path['linestring'], xscale, yscale,
  694. # origin=(px, py))
  695. #
  696. # ## Flashes
  697. # for fl in self.flashes:
  698. # fl['loc'] = affinity.scale(fl['loc'], xscale, yscale, origin=(px, py))
  699. ## Regions
  700. for reg in self.regions:
  701. reg['polygon'] = affinity.scale(reg['polygon'], xscale, yscale,
  702. origin=(px, py))
  703. ## Flashes
  704. for flash in self.flash_geometry:
  705. flash = affinity.scale(flash, xscale, yscale, origin=(px, py))
  706. ## Buffered paths
  707. for bp in self.buffered_paths:
  708. bp = affinity.scale(bp, xscale, yscale, origin=(px, py))
  709. ## solid_geometry ???
  710. # It's a cascaded union of objects.
  711. self.solid_geometry = affinity.scale(self.solid_geometry,
  712. xscale, yscale, origin=(px, py))
  713. # # Now buffered_paths, flash_geometry and solid_geometry
  714. # self.create_geometry()
  715. def fix_regions(self):
  716. """
  717. Overwrites the region polygons with fixed
  718. versions if found to be invalid (according to Shapely).
  719. :return: None
  720. """
  721. for region in self.regions:
  722. if not region['polygon'].is_valid:
  723. region['polygon'] = region['polygon'].buffer(0)
  724. def buffer_paths(self):
  725. """
  726. This is part of the parsing process. "Thickens" the paths
  727. by their appertures. This will only work for circular appertures.
  728. :return: None
  729. """
  730. self.buffered_paths = []
  731. for path in self.paths:
  732. try:
  733. width = self.apertures[path["aperture"]]["size"]
  734. self.buffered_paths.append(path["linestring"].buffer(width/2))
  735. except KeyError:
  736. print "ERROR: Failed to buffer path: ", path
  737. print "Apertures: ", self.apertures
  738. def aperture_parse(self, apertureId, apertureType, apParameters):
  739. """
  740. Parse gerber aperture definition into dictionary of apertures.
  741. The following kinds and their attributes are supported:
  742. * *Circular (C)*: size (float)
  743. * *Rectangle (R)*: width (float), height (float)
  744. * *Obround (O)*: width (float), height (float).
  745. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  746. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  747. :param apertureId: Id of the aperture being defined.
  748. :param apertureType: Type of the aperture.
  749. :param apParameters: Parameters of the aperture.
  750. :type apertureId: str
  751. :type apertureType: str
  752. :type apParameters: str
  753. :return: Identifier of the aperture.
  754. :rtype: str
  755. """
  756. # Found some Gerber with a leading zero in the aperture id and the
  757. # referenced it without the zero, so this is a hack to handle that.
  758. apid = str(int(apertureId))
  759. try: # Could be empty for aperture macros
  760. paramList = apParameters.split('X')
  761. except:
  762. paramList = None
  763. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  764. self.apertures[apid] = {"type": "C",
  765. "size": float(paramList[0])}
  766. return apid
  767. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  768. self.apertures[apid] = {"type": "R",
  769. "width": float(paramList[0]),
  770. "height": float(paramList[1])}
  771. return apid
  772. if apertureType == "O": # Obround
  773. self.apertures[apid] = {"type": "O",
  774. "width": float(paramList[0]),
  775. "height": float(paramList[1])}
  776. return apid
  777. if apertureType == "P": # Polygon (regular)
  778. self.apertures[apid] = {"type": "P",
  779. "diam": float(paramList[0]),
  780. "nVertices": int(paramList[1])}
  781. if len(paramList) >= 3:
  782. self.apertures[apid]["rotation"] = float(paramList[2])
  783. return apid
  784. if apertureType in self.aperture_macros:
  785. self.apertures[apid] = {"type": "AM",
  786. "macro": self.aperture_macros[apertureType],
  787. "modifiers": paramList}
  788. return apid
  789. print "WARNING: Aperture not implemented:", apertureType
  790. return None
  791. def parse_file(self, filename):
  792. """
  793. Calls Gerber.parse_lines() with array of lines
  794. read from the given file.
  795. :param filename: Gerber file to parse.
  796. :type filename: str
  797. :return: None
  798. """
  799. gfile = open(filename, 'r')
  800. gstr = gfile.readlines()
  801. gfile.close()
  802. self.parse_lines(gstr)
  803. def parse_lines(self, glines):
  804. """
  805. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  806. ``self.flashes``, ``self.regions`` and ``self.units``.
  807. :param glines: Gerber code as list of strings, each element being
  808. one line of the source file.
  809. :type glines: list
  810. :return: None
  811. :rtype: None
  812. """
  813. path = [] # Coordinates of the current path, each is [x, y]
  814. last_path_aperture = None
  815. current_aperture = None
  816. # 1,2 or 3 from "G01", "G02" or "G03"
  817. current_interpolation_mode = None
  818. # 1 or 2 from "D01" or "D02"
  819. # Note this is to support deprecated Gerber not putting
  820. # an operation code at the end of every coordinate line.
  821. current_operation_code = None
  822. # Current coordinates
  823. current_x = None
  824. current_y = None
  825. # Absolute or Relative/Incremental coordinates
  826. absolute = True
  827. # How to interpret circular interpolation: SINGLE or MULTI
  828. quadrant_mode = None
  829. # Indicates we are parsing an aperture macro
  830. current_macro = None
  831. #### Parsing starts here ####
  832. line_num = 0
  833. for gline in glines:
  834. line_num += 1
  835. ### Aperture Macros
  836. # Having this at the beggining will slow things down
  837. # but macros can have complicated statements than could
  838. # be caught by other ptterns.
  839. if current_macro is None: # No macro started yet
  840. match = self.am1_re.search(gline)
  841. # Start macro if match, else not an AM, carry on.
  842. if match:
  843. current_macro = match.group(1)
  844. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  845. if match.group(2): # Append
  846. self.aperture_macros[current_macro].append(match.group(2))
  847. if match.group(3): # Finish macro
  848. #self.aperture_macros[current_macro].parse_content()
  849. current_macro = None
  850. continue
  851. else: # Continue macro
  852. match = self.am2_re.search(gline)
  853. if match: # Finish macro
  854. self.aperture_macros[current_macro].append(match.group(1))
  855. #self.aperture_macros[current_macro].parse_content()
  856. current_macro = None
  857. else: # Append
  858. self.aperture_macros[current_macro].append(gline)
  859. continue
  860. ### G01 - Linear interpolation plus flashes
  861. # Operation code (D0x) missing is deprecated... oh well I will support it.
  862. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  863. match = self.lin_re.search(gline)
  864. if match:
  865. # Dxx alone?
  866. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  867. # try:
  868. # current_operation_code = int(match.group(4))
  869. # except:
  870. # pass # A line with just * will match too.
  871. # continue
  872. # NOTE: Letting it continue allows it to react to the
  873. # operation code.
  874. # Parse coordinates
  875. if match.group(2) is not None:
  876. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  877. if match.group(3) is not None:
  878. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  879. # Parse operation code
  880. if match.group(4) is not None:
  881. current_operation_code = int(match.group(4))
  882. # Pen down: add segment
  883. if current_operation_code == 1:
  884. path.append([current_x, current_y])
  885. last_path_aperture = current_aperture
  886. # Pen up: finish path
  887. elif current_operation_code == 2:
  888. if len(path) > 1:
  889. if last_path_aperture is None:
  890. print "Warning: No aperture defined for curent path. (%d)" % line_num
  891. self.paths.append({"linestring": LineString(path),
  892. "aperture": last_path_aperture})
  893. path = [[current_x, current_y]] # Start new path
  894. # Flash
  895. elif current_operation_code == 3:
  896. self.flashes.append({"loc": Point([current_x, current_y]),
  897. "aperture": current_aperture})
  898. continue
  899. ### G02/3 - Circular interpolation
  900. # 2-clockwise, 3-counterclockwise
  901. match = self.circ_re.search(gline)
  902. if match:
  903. mode, x, y, i, j, d = match.groups()
  904. try:
  905. x = parse_gerber_number(x, self.frac_digits)
  906. except:
  907. x = current_x
  908. try:
  909. y = parse_gerber_number(y, self.frac_digits)
  910. except:
  911. y = current_y
  912. try:
  913. i = parse_gerber_number(i, self.frac_digits)
  914. except:
  915. i = 0
  916. try:
  917. j = parse_gerber_number(j, self.frac_digits)
  918. except:
  919. j = 0
  920. if quadrant_mode is None:
  921. print "ERROR: Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num
  922. print gline
  923. continue
  924. if mode is None and current_interpolation_mode not in [2, 3]:
  925. print "ERROR: Found arc without circular interpolation mode defined. (%d)" % line_num
  926. print gline
  927. continue
  928. elif mode is not None:
  929. current_interpolation_mode = int(mode)
  930. # Set operation code if provided
  931. if d is not None:
  932. current_operation_code = int(d)
  933. # Nothing created! Pen Up.
  934. if current_operation_code == 2:
  935. print "Warning: Arc with D2. (%d)" % line_num
  936. if len(path) > 1:
  937. if last_path_aperture is None:
  938. print "Warning: No aperture defined for curent path. (%d)" % line_num
  939. self.paths.append({"linestring": LineString(path),
  940. "aperture": last_path_aperture})
  941. current_x = x
  942. current_y = y
  943. path = [[current_x, current_y]] # Start new path
  944. continue
  945. # Flash should not happen here
  946. if current_operation_code == 3:
  947. print "ERROR: Trying to flash within arc. (%d)" % line_num
  948. continue
  949. if quadrant_mode == 'MULTI':
  950. center = [i + current_x, j + current_y]
  951. radius = sqrt(i**2 + j**2)
  952. start = arctan2(-j, -i)
  953. stop = arctan2(-center[1] + y, -center[0] + x)
  954. arcdir = [None, None, "cw", "ccw"]
  955. this_arc = arc(center, radius, start, stop,
  956. arcdir[current_interpolation_mode],
  957. self.steps_per_circ)
  958. # Last point in path is current point
  959. current_x = this_arc[-1][0]
  960. current_y = this_arc[-1][1]
  961. # Append
  962. path += this_arc
  963. last_path_aperture = current_aperture
  964. continue
  965. if quadrant_mode == 'SINGLE':
  966. print "Warning: Single quadrant arc are not implemented yet. (%d)" % line_num
  967. ### G74/75* - Single or multiple quadrant arcs
  968. match = self.quad_re.search(gline)
  969. if match:
  970. if match.group(1) == '4':
  971. quadrant_mode = 'SINGLE'
  972. else:
  973. quadrant_mode = 'MULTI'
  974. continue
  975. ### G37* - End region
  976. if self.regionoff_re.search(gline):
  977. # Only one path defines region?
  978. if len(path) < 3:
  979. print "ERROR: Path contains less than 3 points:"
  980. print path
  981. print "Line (%d): " % line_num, gline
  982. path = []
  983. continue
  984. # For regions we may ignore an aperture that is None
  985. self.regions.append({"polygon": Polygon(path),
  986. "aperture": last_path_aperture})
  987. #path = []
  988. path = [[current_x, current_y]] # Start new path
  989. continue
  990. ### Aperture definitions %ADD...
  991. match = self.ad_re.search(gline)
  992. if match:
  993. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  994. continue
  995. ### G01/2/3* - Interpolation mode change
  996. # Can occur along with coordinates and operation code but
  997. # sometimes by itself (handled here).
  998. # Example: G01*
  999. match = self.interp_re.search(gline)
  1000. if match:
  1001. current_interpolation_mode = int(match.group(1))
  1002. continue
  1003. ### Tool/aperture change
  1004. # Example: D12*
  1005. match = self.tool_re.search(gline)
  1006. if match:
  1007. current_aperture = match.group(1)
  1008. continue
  1009. ### Number format
  1010. # Example: %FSLAX24Y24*%
  1011. # TODO: This is ignoring most of the format. Implement the rest.
  1012. match = self.fmt_re.search(gline)
  1013. if match:
  1014. absolute = {'A': True, 'I': False}
  1015. self.int_digits = int(match.group(3))
  1016. self.frac_digits = int(match.group(4))
  1017. continue
  1018. ### Mode (IN/MM)
  1019. # Example: %MOIN*%
  1020. match = self.mode_re.search(gline)
  1021. if match:
  1022. self.units = match.group(1)
  1023. continue
  1024. ### Units (G70/1) OBSOLETE
  1025. match = self.units_re.search(gline)
  1026. if match:
  1027. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1028. continue
  1029. ### Absolute/relative coordinates G90/1 OBSOLETE
  1030. match = self.absrel_re.search(gline)
  1031. if match:
  1032. absolute = {'0': True, '1': False}[match.group(1)]
  1033. continue
  1034. #### Ignored lines
  1035. ## Comments
  1036. match = self.comm_re.search(gline)
  1037. if match:
  1038. continue
  1039. ## EOF
  1040. match = self.eof_re.search(gline)
  1041. if match:
  1042. continue
  1043. ### Line did not match any pattern. Warn user.
  1044. print "WARNING: Line ignored (%d):" % line_num, gline
  1045. if len(path) > 1:
  1046. # EOF, create shapely LineString if something still in path
  1047. self.paths.append({"linestring": LineString(path),
  1048. "aperture": last_path_aperture})
  1049. def do_flashes(self):
  1050. """
  1051. Creates geometry for Gerber flashes (aperture on a single point).
  1052. """
  1053. self.flash_geometry = []
  1054. for flash in self.flashes:
  1055. try:
  1056. aperture = self.apertures[flash['aperture']]
  1057. except KeyError:
  1058. print "ERROR: Trying to flash with unknown aperture: ", flash['aperture']
  1059. continue
  1060. if aperture['type'] == 'C': # Circles
  1061. #circle = Point(flash['loc']).buffer(aperture['size']/2)
  1062. circle = flash['loc'].buffer(aperture['size']/2)
  1063. self.flash_geometry.append(circle)
  1064. continue
  1065. if aperture['type'] == 'R': # Rectangles
  1066. loc = flash['loc'].coords[0]
  1067. width = aperture['width']
  1068. height = aperture['height']
  1069. minx = loc[0] - width/2
  1070. maxx = loc[0] + width/2
  1071. miny = loc[1] - height/2
  1072. maxy = loc[1] + height/2
  1073. rectangle = shply_box(minx, miny, maxx, maxy)
  1074. self.flash_geometry.append(rectangle)
  1075. continue
  1076. if aperture['type'] == 'O': # Obround
  1077. loc = flash['loc'].coords[0]
  1078. width = aperture['width']
  1079. height = aperture['height']
  1080. if width > height:
  1081. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1082. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1083. c1 = p1.buffer(height*0.5)
  1084. c2 = p2.buffer(height*0.5)
  1085. else:
  1086. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1087. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1088. c1 = p1.buffer(width*0.5)
  1089. c2 = p2.buffer(width*0.5)
  1090. obround = cascaded_union([c1, c2]).convex_hull
  1091. self.flash_geometry.append(obround)
  1092. continue
  1093. if aperture['type'] == 'P': # Regular polygon
  1094. loc = flash['loc'].coords[0]
  1095. diam = aperture['diam']
  1096. n_vertices = aperture['nVertices']
  1097. points = []
  1098. for i in range(0, n_vertices):
  1099. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1100. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1101. points.append((x, y))
  1102. ply = Polygon(points)
  1103. if 'rotation' in aperture:
  1104. ply = affinity.rotate(ply, aperture['rotation'])
  1105. self.flash_geometry.append(ply)
  1106. continue
  1107. if aperture['type'] == 'AM': # Aperture Macro
  1108. loc = flash['loc'].coords[0]
  1109. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1110. flash_geo_final = affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1111. self.flash_geometry.append(flash_geo_final)
  1112. continue
  1113. print "WARNING: Aperture type %s not implemented" % (aperture['type'])
  1114. def create_geometry(self):
  1115. """
  1116. Geometry from a Gerber file is made up entirely of polygons.
  1117. Every stroke (linear or circular) has an aperture which gives
  1118. it thickness. Additionally, aperture strokes have non-zero area,
  1119. and regions naturally do as well.
  1120. :rtype : None
  1121. :return: None
  1122. """
  1123. self.buffer_paths()
  1124. self.fix_regions()
  1125. self.do_flashes()
  1126. self.solid_geometry = cascaded_union(self.buffered_paths +
  1127. [poly['polygon'] for poly in self.regions] +
  1128. self.flash_geometry)
  1129. def get_bounding_box(self, margin=0.0, rounded=False):
  1130. """
  1131. Creates and returns a rectangular polygon bounding at a distance of
  1132. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1133. can optionally have rounded corners of radius equal to margin.
  1134. :param margin: Distance to enlarge the rectangular bounding
  1135. box in both positive and negative, x and y axes.
  1136. :type margin: float
  1137. :param rounded: Wether or not to have rounded corners.
  1138. :type rounded: bool
  1139. :return: The bounding box.
  1140. :rtype: Shapely.Polygon
  1141. """
  1142. bbox = self.solid_geometry.envelope.buffer(margin)
  1143. if not rounded:
  1144. bbox = bbox.envelope
  1145. return bbox
  1146. class Excellon(Geometry):
  1147. """
  1148. *ATTRIBUTES*
  1149. * ``tools`` (dict): The key is the tool name and the value is
  1150. a dictionary specifying the tool:
  1151. ================ ====================================
  1152. Key Value
  1153. ================ ====================================
  1154. C Diameter of the tool
  1155. Others Not supported (Ignored).
  1156. ================ ====================================
  1157. * ``drills`` (list): Each is a dictionary:
  1158. ================ ====================================
  1159. Key Value
  1160. ================ ====================================
  1161. point (Shapely.Point) Where to drill
  1162. tool (str) A key in ``tools``
  1163. ================ ====================================
  1164. """
  1165. def __init__(self):
  1166. """
  1167. The constructor takes no parameters.
  1168. :return: Excellon object.
  1169. :rtype: Excellon
  1170. """
  1171. Geometry.__init__(self)
  1172. self.tools = {}
  1173. self.drills = []
  1174. # Trailing "T" or leading "L"
  1175. self.zeros = ""
  1176. # Attributes to be included in serialization
  1177. # Always append to it because it carries contents
  1178. # from Geometry.
  1179. self.ser_attrs += ['tools', 'drills', 'zeros']
  1180. #### Patterns ####
  1181. # Regex basics:
  1182. # ^ - beginning
  1183. # $ - end
  1184. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1185. # M48 - Beggining of Part Program Header
  1186. self.hbegin_re = re.compile(r'^M48$')
  1187. # M95 or % - End of Part Program Header
  1188. # NOTE: % has different meaning in the body
  1189. self.hend_re = re.compile(r'^(?:M95|%)$')
  1190. # FMAT Excellon format
  1191. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1192. # Number format and units
  1193. # INCH uses 6 digits
  1194. # METRIC uses 5/6
  1195. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1196. # Tool definition/parameters (?= is look-ahead
  1197. # NOTE: This might be an overkill!
  1198. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1199. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1200. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1201. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1202. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1203. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1204. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1205. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1206. # Tool select
  1207. # Can have additional data after tool number but
  1208. # is ignored if present in the header.
  1209. # Warning: This will match toolset_re too.
  1210. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1211. self.toolsel_re = re.compile(r'^T(\d+)')
  1212. # Comment
  1213. self.comm_re = re.compile(r'^;(.*)$')
  1214. # Absolute/Incremental G90/G91
  1215. self.absinc_re = re.compile(r'^G9([01])$')
  1216. # Modes of operation
  1217. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1218. self.modes_re = re.compile(r'^G0([012345])')
  1219. # Measuring mode
  1220. # 1-metric, 2-inch
  1221. self.meas_re = re.compile(r'^M7([12])$')
  1222. # Coordinates
  1223. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1224. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1225. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1226. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1227. # R - Repeat hole (# times, X offset, Y offset)
  1228. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1229. # Various stop/pause commands
  1230. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1231. def parse_file(self, filename):
  1232. """
  1233. Reads the specified file as array of lines as
  1234. passes it to ``parse_lines()``.
  1235. :param filename: The file to be read and parsed.
  1236. :type filename: str
  1237. :return: None
  1238. """
  1239. efile = open(filename, 'r')
  1240. estr = efile.readlines()
  1241. efile.close()
  1242. self.parse_lines(estr)
  1243. def parse_lines(self, elines):
  1244. """
  1245. Main Excellon parser.
  1246. :param elines: List of strings, each being a line of Excellon code.
  1247. :type elines: list
  1248. :return: None
  1249. """
  1250. # State variables
  1251. current_tool = ""
  1252. in_header = False
  1253. current_x = None
  1254. current_y = None
  1255. i = 0 # Line number
  1256. for eline in elines:
  1257. i += 1
  1258. ## Header Begin/End ##
  1259. if self.hbegin_re.search(eline):
  1260. in_header = True
  1261. continue
  1262. if self.hend_re.search(eline):
  1263. in_header = False
  1264. continue
  1265. #### Body ####
  1266. if not in_header:
  1267. ## Tool change ##
  1268. match = self.toolsel_re.search(eline)
  1269. if match:
  1270. current_tool = str(int(match.group(1)))
  1271. continue
  1272. ## Coordinates without period ##
  1273. match = self.coordsnoperiod_re.search(eline)
  1274. if match:
  1275. try:
  1276. x = float(match.group(1))/10000
  1277. current_x = x
  1278. except TypeError:
  1279. x = current_x
  1280. try:
  1281. y = float(match.group(2))/10000
  1282. current_y = y
  1283. except TypeError:
  1284. y = current_y
  1285. if x is None or y is None:
  1286. print "ERROR: Missing coordinates"
  1287. continue
  1288. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1289. continue
  1290. ## Coordinates with period ##
  1291. match = self.coordsperiod_re.search(eline)
  1292. if match:
  1293. try:
  1294. x = float(match.group(1))
  1295. current_x = x
  1296. except TypeError:
  1297. x = current_x
  1298. try:
  1299. y = float(match.group(2))
  1300. current_y = y
  1301. except TypeError:
  1302. y = current_y
  1303. if x is None or y is None:
  1304. print "ERROR: Missing coordinates"
  1305. continue
  1306. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1307. continue
  1308. #### Header ####
  1309. if in_header:
  1310. ## Tool definitions ##
  1311. match = self.toolset_re.search(eline)
  1312. if match:
  1313. name = str(int(match.group(1)))
  1314. spec = {
  1315. "C": float(match.group(2)),
  1316. # "F": float(match.group(3)),
  1317. # "S": float(match.group(4)),
  1318. # "B": float(match.group(5)),
  1319. # "H": float(match.group(6)),
  1320. # "Z": float(match.group(7))
  1321. }
  1322. self.tools[name] = spec
  1323. continue
  1324. ## Units and number format ##
  1325. match = self.units_re.match(eline)
  1326. if match:
  1327. self.zeros = match.group(2) # "T" or "L"
  1328. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1329. continue
  1330. print "WARNING: Line ignored:", eline
  1331. def create_geometry(self):
  1332. """
  1333. Creates circles of the tool diameter at every point
  1334. specified in ``self.drills``.
  1335. :return: None
  1336. """
  1337. self.solid_geometry = []
  1338. for drill in self.drills:
  1339. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1340. tooldia = self.tools[drill['tool']]['C']
  1341. poly = drill['point'].buffer(tooldia/2.0)
  1342. self.solid_geometry.append(poly)
  1343. def scale(self, factor):
  1344. """
  1345. Scales geometry on the XY plane in the object by a given factor.
  1346. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1347. :param factor: Number by which to scale the object.
  1348. :type factor: float
  1349. :return: None
  1350. :rtype: NOne
  1351. """
  1352. # Drills
  1353. for drill in self.drills:
  1354. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1355. self.create_geometry()
  1356. def offset(self, vect):
  1357. """
  1358. Offsets geometry on the XY plane in the object by a given vector.
  1359. :param vect: (x, y) offset vector.
  1360. :type vect: tuple
  1361. :return: None
  1362. """
  1363. dx, dy = vect
  1364. # Drills
  1365. for drill in self.drills:
  1366. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1367. # Recreate geometry
  1368. self.create_geometry()
  1369. def mirror(self, axis, point):
  1370. """
  1371. :param axis: "X" or "Y" indicates around which axis to mirror.
  1372. :type axis: str
  1373. :param point: [x, y] point belonging to the mirror axis.
  1374. :type point: list
  1375. :return: None
  1376. """
  1377. px, py = point
  1378. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1379. # Modify data
  1380. for drill in self.drills:
  1381. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1382. # Recreate geometry
  1383. self.create_geometry()
  1384. def convert_units(self, units):
  1385. factor = Geometry.convert_units(self, units)
  1386. # Tools
  1387. for tname in self.tools:
  1388. self.tools[tname]["C"] *= factor
  1389. self.create_geometry()
  1390. return factor
  1391. class CNCjob(Geometry):
  1392. """
  1393. Represents work to be done by a CNC machine.
  1394. *ATTRIBUTES*
  1395. * ``gcode_parsed`` (list): Each is a dictionary:
  1396. ===================== =========================================
  1397. Key Value
  1398. ===================== =========================================
  1399. geom (Shapely.LineString) Tool path (XY plane)
  1400. kind (string) "AB", A is "T" (travel) or
  1401. "C" (cut). B is "F" (fast) or "S" (slow).
  1402. ===================== =========================================
  1403. """
  1404. def __init__(self, units="in", kind="generic", z_move=0.1,
  1405. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  1406. Geometry.__init__(self)
  1407. self.kind = kind
  1408. self.units = units
  1409. self.z_cut = z_cut
  1410. self.z_move = z_move
  1411. self.feedrate = feedrate
  1412. self.tooldia = tooldia
  1413. self.unitcode = {"IN": "G20", "MM": "G21"}
  1414. self.pausecode = "G04 P1"
  1415. self.feedminutecode = "G94"
  1416. self.absolutecode = "G90"
  1417. self.gcode = ""
  1418. self.input_geometry_bounds = None
  1419. self.gcode_parsed = None
  1420. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1421. # Attributes to be included in serialization
  1422. # Always append to it because it carries contents
  1423. # from Geometry.
  1424. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1425. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1426. 'steps_per_circ']
  1427. def convert_units(self, units):
  1428. factor = Geometry.convert_units(self, units)
  1429. print "CNCjob.convert_units()"
  1430. self.z_cut *= factor
  1431. self.z_move *= factor
  1432. self.feedrate *= factor
  1433. self.tooldia *= factor
  1434. return factor
  1435. def generate_from_excellon(self, exobj):
  1436. """
  1437. Generates G-code for drilling from Excellon object.
  1438. self.gcode becomes a list, each element is a
  1439. different job for each tool in the excellon code.
  1440. """
  1441. self.kind = "drill"
  1442. self.gcode = []
  1443. t = "G00 X%.4fY%.4f\n"
  1444. down = "G01 Z%.4f\n" % self.z_cut
  1445. up = "G01 Z%.4f\n" % self.z_move
  1446. for tool in exobj.tools:
  1447. points = []
  1448. for drill in exobj.drill:
  1449. if drill['tool'] == tool:
  1450. points.append(drill['point'])
  1451. gcode = self.unitcode[self.units.upper()] + "\n"
  1452. gcode += self.absolutecode + "\n"
  1453. gcode += self.feedminutecode + "\n"
  1454. gcode += "F%.2f\n" % self.feedrate
  1455. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1456. gcode += "M03\n" # Spindle start
  1457. gcode += self.pausecode + "\n"
  1458. for point in points:
  1459. gcode += t % point
  1460. gcode += down + up
  1461. gcode += t % (0, 0)
  1462. gcode += "M05\n" # Spindle stop
  1463. self.gcode.append(gcode)
  1464. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1465. """
  1466. Creates gcode for this object from an Excellon object
  1467. for the specified tools.
  1468. :param exobj: Excellon object to process
  1469. :type exobj: Excellon
  1470. :param tools: Comma separated tool names
  1471. :type: tools: str
  1472. :return: None
  1473. :rtype: None
  1474. """
  1475. print "Creating CNC Job from Excellon..."
  1476. if tools == "all":
  1477. tools = [tool for tool in exobj.tools]
  1478. else:
  1479. tools = [x.strip() for x in tools.split(",")]
  1480. tools = filter(lambda i: i in exobj.tools, tools)
  1481. print "Tools are:", tools
  1482. points = []
  1483. for drill in exobj.drills:
  1484. if drill['tool'] in tools:
  1485. points.append(drill['point'])
  1486. print "Found %d drills." % len(points)
  1487. #self.kind = "drill"
  1488. self.gcode = []
  1489. t = "G00 X%.4fY%.4f\n"
  1490. down = "G01 Z%.4f\n" % self.z_cut
  1491. up = "G01 Z%.4f\n" % self.z_move
  1492. gcode = self.unitcode[self.units.upper()] + "\n"
  1493. gcode += self.absolutecode + "\n"
  1494. gcode += self.feedminutecode + "\n"
  1495. gcode += "F%.2f\n" % self.feedrate
  1496. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1497. gcode += "M03\n" # Spindle start
  1498. gcode += self.pausecode + "\n"
  1499. for point in points:
  1500. x, y = point.coords.xy
  1501. gcode += t % (x[0], y[0])
  1502. gcode += down + up
  1503. gcode += t % (0, 0)
  1504. gcode += "M05\n" # Spindle stop
  1505. self.gcode = gcode
  1506. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1507. """
  1508. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1509. :param geometry: Geometry defining the toolpath
  1510. :type geometry: Geometry
  1511. :param append: Wether to append to self.gcode or re-write it.
  1512. :type append: bool
  1513. :param tooldia: If given, sets the tooldia property but does
  1514. not affect the process in any other way.
  1515. :type tooldia: bool
  1516. :param tolerance: All points in the simplified object will be within the
  1517. tolerance distance of the original geometry.
  1518. :return: None
  1519. :rtype: None
  1520. """
  1521. if tooldia is not None:
  1522. self.tooldia = tooldia
  1523. self.input_geometry_bounds = geometry.bounds()
  1524. if not append:
  1525. self.gcode = ""
  1526. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1527. self.gcode += self.absolutecode + "\n"
  1528. self.gcode += self.feedminutecode + "\n"
  1529. self.gcode += "F%.2f\n" % self.feedrate
  1530. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1531. self.gcode += "M03\n" # Spindle start
  1532. self.gcode += self.pausecode + "\n"
  1533. for geo in geometry.solid_geometry:
  1534. if type(geo) == Polygon:
  1535. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1536. continue
  1537. if type(geo) == LineString or type(geo) == LinearRing:
  1538. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1539. continue
  1540. if type(geo) == Point:
  1541. self.gcode += self.point2gcode(geo)
  1542. continue
  1543. if type(geo) == MultiPolygon:
  1544. for poly in geo:
  1545. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1546. continue
  1547. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  1548. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1549. self.gcode += "G00 X0Y0\n"
  1550. self.gcode += "M05\n" # Spindle stop
  1551. def pre_parse(self, gtext):
  1552. """
  1553. Separates parts of the G-Code text into a list of dictionaries.
  1554. Used by ``self.gcode_parse()``.
  1555. :param gtext: A single string with g-code
  1556. """
  1557. # Units: G20-inches, G21-mm
  1558. units_re = re.compile(r'^G2([01])')
  1559. # TODO: This has to be re-done
  1560. gcmds = []
  1561. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1562. for line in lines:
  1563. # Clean up
  1564. line = line.strip()
  1565. # Remove comments
  1566. # NOTE: Limited to 1 bracket pair
  1567. op = line.find("(")
  1568. cl = line.find(")")
  1569. #if op > -1 and cl > op:
  1570. if cl > op > -1:
  1571. #comment = line[op+1:cl]
  1572. line = line[:op] + line[(cl+1):]
  1573. # Units
  1574. match = units_re.match(line)
  1575. if match:
  1576. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1577. # Parse GCode
  1578. # 0 4 12
  1579. # G01 X-0.007 Y-0.057
  1580. # --> codes_idx = [0, 4, 12]
  1581. codes = "NMGXYZIJFP"
  1582. codes_idx = []
  1583. i = 0
  1584. for ch in line:
  1585. if ch in codes:
  1586. codes_idx.append(i)
  1587. i += 1
  1588. n_codes = len(codes_idx)
  1589. if n_codes == 0:
  1590. continue
  1591. # Separate codes in line
  1592. parts = []
  1593. for p in range(n_codes-1):
  1594. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1595. parts.append(line[codes_idx[-1]:].strip())
  1596. # Separate codes from values
  1597. cmds = {}
  1598. for part in parts:
  1599. cmds[part[0]] = float(part[1:])
  1600. gcmds.append(cmds)
  1601. return gcmds
  1602. def gcode_parse(self):
  1603. """
  1604. G-Code parser (from self.gcode). Generates dictionary with
  1605. single-segment LineString's and "kind" indicating cut or travel,
  1606. fast or feedrate speed.
  1607. """
  1608. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1609. # Results go here
  1610. geometry = []
  1611. # TODO: Merge into single parser?
  1612. gobjs = self.pre_parse(self.gcode)
  1613. # Last known instruction
  1614. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1615. # Current path: temporary storage until tool is
  1616. # lifted or lowered.
  1617. path = [(0, 0)]
  1618. # Process every instruction
  1619. for gobj in gobjs:
  1620. ## Changing height
  1621. if 'Z' in gobj:
  1622. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1623. print "WARNING: Non-orthogonal motion: From", current
  1624. print " To:", gobj
  1625. current['Z'] = gobj['Z']
  1626. # Store the path into geometry and reset path
  1627. if len(path) > 1:
  1628. geometry.append({"geom": LineString(path),
  1629. "kind": kind})
  1630. path = [path[-1]] # Start with the last point of last path.
  1631. if 'G' in gobj:
  1632. current['G'] = int(gobj['G'])
  1633. if 'X' in gobj or 'Y' in gobj:
  1634. if 'X' in gobj:
  1635. x = gobj['X']
  1636. else:
  1637. x = current['X']
  1638. if 'Y' in gobj:
  1639. y = gobj['Y']
  1640. else:
  1641. y = current['Y']
  1642. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1643. if current['Z'] > 0:
  1644. kind[0] = 'T'
  1645. if current['G'] > 0:
  1646. kind[1] = 'S'
  1647. arcdir = [None, None, "cw", "ccw"]
  1648. if current['G'] in [0, 1]: # line
  1649. path.append((x, y))
  1650. if current['G'] in [2, 3]: # arc
  1651. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1652. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1653. start = arctan2(-gobj['J'], -gobj['I'])
  1654. stop = arctan2(-center[1]+y, -center[0]+x)
  1655. path += arc(center, radius, start, stop,
  1656. arcdir[current['G']],
  1657. self.steps_per_circ)
  1658. # Update current instruction
  1659. for code in gobj:
  1660. current[code] = gobj[code]
  1661. # There might not be a change in height at the
  1662. # end, therefore, see here too if there is
  1663. # a final path.
  1664. if len(path) > 1:
  1665. geometry.append({"geom": LineString(path),
  1666. "kind": kind})
  1667. self.gcode_parsed = geometry
  1668. return geometry
  1669. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1670. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1671. # alpha={"T": 0.3, "C": 1.0}):
  1672. # """
  1673. # Creates a Matplotlib figure with a plot of the
  1674. # G-code job.
  1675. # """
  1676. # if tooldia is None:
  1677. # tooldia = self.tooldia
  1678. #
  1679. # fig = Figure(dpi=dpi)
  1680. # ax = fig.add_subplot(111)
  1681. # ax.set_aspect(1)
  1682. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1683. # ax.set_xlim(xmin-margin, xmax+margin)
  1684. # ax.set_ylim(ymin-margin, ymax+margin)
  1685. #
  1686. # if tooldia == 0:
  1687. # for geo in self.gcode_parsed:
  1688. # linespec = '--'
  1689. # linecolor = color[geo['kind'][0]][1]
  1690. # if geo['kind'][0] == 'C':
  1691. # linespec = 'k-'
  1692. # x, y = geo['geom'].coords.xy
  1693. # ax.plot(x, y, linespec, color=linecolor)
  1694. # else:
  1695. # for geo in self.gcode_parsed:
  1696. # poly = geo['geom'].buffer(tooldia/2.0)
  1697. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1698. # edgecolor=color[geo['kind'][0]][1],
  1699. # alpha=alpha[geo['kind'][0]], zorder=2)
  1700. # ax.add_patch(patch)
  1701. #
  1702. # return fig
  1703. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1704. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1705. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1706. """
  1707. Plots the G-code job onto the given axes.
  1708. :param axes: Matplotlib axes on which to plot.
  1709. :param tooldia: Tool diameter.
  1710. :param dpi: Not used!
  1711. :param margin: Not used!
  1712. :param color: Color specification.
  1713. :param alpha: Transparency specification.
  1714. :param tool_tolerance: Tolerance when drawing the toolshape.
  1715. :return: None
  1716. """
  1717. if tooldia is None:
  1718. tooldia = self.tooldia
  1719. if tooldia == 0:
  1720. for geo in self.gcode_parsed:
  1721. linespec = '--'
  1722. linecolor = color[geo['kind'][0]][1]
  1723. if geo['kind'][0] == 'C':
  1724. linespec = 'k-'
  1725. x, y = geo['geom'].coords.xy
  1726. axes.plot(x, y, linespec, color=linecolor)
  1727. else:
  1728. for geo in self.gcode_parsed:
  1729. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1730. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1731. edgecolor=color[geo['kind'][0]][1],
  1732. alpha=alpha[geo['kind'][0]], zorder=2)
  1733. axes.add_patch(patch)
  1734. def create_geometry(self):
  1735. # TODO: This takes forever. Too much data?
  1736. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1737. def polygon2gcode(self, polygon, tolerance=0):
  1738. """
  1739. Creates G-Code for the exterior and all interior paths
  1740. of a polygon.
  1741. :param polygon: A Shapely.Polygon
  1742. :type polygon: Shapely.Polygon
  1743. :param tolerance: All points in the simplified object will be within the
  1744. tolerance distance of the original geometry.
  1745. :type tolerance: float
  1746. :return: G-code to cut along polygon.
  1747. :rtype: str
  1748. """
  1749. if tolerance > 0:
  1750. target_polygon = polygon.simplify(tolerance)
  1751. else:
  1752. target_polygon = polygon
  1753. gcode = ""
  1754. t = "G0%d X%.4fY%.4f\n"
  1755. path = list(target_polygon.exterior.coords) # Polygon exterior
  1756. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1757. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1758. for pt in path[1:]:
  1759. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1760. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1761. for ints in target_polygon.interiors: # Polygon interiors
  1762. path = list(ints.coords)
  1763. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1764. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1765. for pt in path[1:]:
  1766. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1767. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1768. return gcode
  1769. def linear2gcode(self, linear, tolerance=0):
  1770. """
  1771. Generates G-code to cut along the linear feature.
  1772. :param linear: The path to cut along.
  1773. :type: Shapely.LinearRing or Shapely.Linear String
  1774. :param tolerance: All points in the simplified object will be within the
  1775. tolerance distance of the original geometry.
  1776. :type tolerance: float
  1777. :return: G-code to cut alon the linear feature.
  1778. :rtype: str
  1779. """
  1780. if tolerance > 0:
  1781. target_linear = linear.simplify(tolerance)
  1782. else:
  1783. target_linear = linear
  1784. gcode = ""
  1785. t = "G0%d X%.4fY%.4f\n"
  1786. path = list(target_linear.coords)
  1787. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1788. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1789. for pt in path[1:]:
  1790. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1791. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1792. return gcode
  1793. def point2gcode(self, point):
  1794. # TODO: This is not doing anything.
  1795. gcode = ""
  1796. t = "G0%d X%.4fY%.4f\n"
  1797. path = list(point.coords)
  1798. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1799. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1800. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1801. def scale(self, factor):
  1802. """
  1803. Scales all the geometry on the XY plane in the object by the
  1804. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  1805. not altered.
  1806. :param factor: Number by which to scale the object.
  1807. :type factor: float
  1808. :return: None
  1809. :rtype: None
  1810. """
  1811. for g in self.gcode_parsed:
  1812. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  1813. self.create_geometry()
  1814. def offset(self, vect):
  1815. """
  1816. Offsets all the geometry on the XY plane in the object by the
  1817. given vector.
  1818. :param vect: (x, y) offset vector.
  1819. :type vect: tuple
  1820. :return: None
  1821. """
  1822. dx, dy = vect
  1823. for g in self.gcode_parsed:
  1824. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  1825. self.create_geometry()
  1826. # def get_bounds(geometry_set):
  1827. # xmin = Inf
  1828. # ymin = Inf
  1829. # xmax = -Inf
  1830. # ymax = -Inf
  1831. #
  1832. # #print "Getting bounds of:", str(geometry_set)
  1833. # for gs in geometry_set:
  1834. # try:
  1835. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  1836. # xmin = min([xmin, gxmin])
  1837. # ymin = min([ymin, gymin])
  1838. # xmax = max([xmax, gxmax])
  1839. # ymax = max([ymax, gymax])
  1840. # except:
  1841. # print "DEV WARNING: Tried to get bounds of empty geometry."
  1842. #
  1843. # return [xmin, ymin, xmax, ymax]
  1844. def get_bounds(geometry_list):
  1845. xmin = Inf
  1846. ymin = Inf
  1847. xmax = -Inf
  1848. ymax = -Inf
  1849. #print "Getting bounds of:", str(geometry_set)
  1850. for gs in geometry_list:
  1851. try:
  1852. gxmin, gymin, gxmax, gymax = gs.bounds()
  1853. xmin = min([xmin, gxmin])
  1854. ymin = min([ymin, gymin])
  1855. xmax = max([xmax, gxmax])
  1856. ymax = max([ymax, gymax])
  1857. except:
  1858. print "DEV WARNING: Tried to get bounds of empty geometry."
  1859. return [xmin, ymin, xmax, ymax]
  1860. def arc(center, radius, start, stop, direction, steps_per_circ):
  1861. """
  1862. Creates a list of point along the specified arc.
  1863. :param center: Coordinates of the center [x, y]
  1864. :type center: list
  1865. :param radius: Radius of the arc.
  1866. :type radius: float
  1867. :param start: Starting angle in radians
  1868. :type start: float
  1869. :param stop: End angle in radians
  1870. :type stop: float
  1871. :param direction: Orientation of the arc, "CW" or "CCW"
  1872. :type direction: string
  1873. :param steps_per_circ: Number of straight line segments to
  1874. represent a circle.
  1875. :type steps_per_circ: int
  1876. :return: The desired arc, as list of tuples
  1877. :rtype: list
  1878. """
  1879. # TODO: Resolution should be established by fraction of total length, not angle.
  1880. da_sign = {"cw": -1.0, "ccw": 1.0}
  1881. points = []
  1882. if direction == "ccw" and stop <= start:
  1883. stop += 2*pi
  1884. if direction == "cw" and stop >= start:
  1885. stop -= 2*pi
  1886. angle = abs(stop - start)
  1887. #angle = stop-start
  1888. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  1889. delta_angle = da_sign[direction]*angle*1.0/steps
  1890. for i in range(steps+1):
  1891. theta = start + delta_angle*i
  1892. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  1893. return points
  1894. def clear_poly(poly, tooldia, overlap=0.1):
  1895. """
  1896. Creates a list of Shapely geometry objects covering the inside
  1897. of a Shapely.Polygon. Use for removing all the copper in a region
  1898. or bed flattening.
  1899. :param poly: Target polygon
  1900. :type poly: Shapely.Polygon
  1901. :param tooldia: Diameter of the tool
  1902. :type tooldia: float
  1903. :param overlap: Fraction of the tool diameter to overlap
  1904. in each pass.
  1905. :type overlap: float
  1906. :return: list of Shapely.Polygon
  1907. :rtype: list
  1908. """
  1909. poly_cuts = [poly.buffer(-tooldia/2.0)]
  1910. while True:
  1911. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  1912. if poly.area > 0:
  1913. poly_cuts.append(poly)
  1914. else:
  1915. break
  1916. return poly_cuts
  1917. def find_polygon(poly_set, point):
  1918. """
  1919. Return the first polygon in the list of polygons poly_set
  1920. that contains the given point.
  1921. """
  1922. p = Point(point)
  1923. for poly in poly_set:
  1924. if poly.contains(p):
  1925. return poly
  1926. return None
  1927. def to_dict(obj):
  1928. """
  1929. Makes a Shapely geometry object into serializeable form.
  1930. :param obj: Shapely geometry.
  1931. :type obj: BaseGeometry
  1932. :return: Dictionary with serializable form if ``obj`` was
  1933. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  1934. """
  1935. if isinstance(obj, ApertureMacro):
  1936. return {
  1937. "__class__": "ApertureMacro",
  1938. "__inst__": obj.to_dict()
  1939. }
  1940. if isinstance(obj, BaseGeometry):
  1941. return {
  1942. "__class__": "Shply",
  1943. "__inst__": sdumps(obj)
  1944. }
  1945. return obj
  1946. def dict2obj(d):
  1947. """
  1948. Default deserializer.
  1949. :param d: Serializable dictionary representation of an object
  1950. to be reconstructed.
  1951. :return: Reconstructed object.
  1952. """
  1953. if '__class__' in d and '__inst__' in d:
  1954. if d['__class__'] == "Shply":
  1955. return sloads(d['__inst__'])
  1956. if d['__class__'] == "ApertureMacro":
  1957. am = ApertureMacro()
  1958. am.from_dict(d['__inst__'])
  1959. return am
  1960. return d
  1961. else:
  1962. return d
  1963. def plotg(geo):
  1964. try:
  1965. _ = iter(geo)
  1966. except:
  1967. geo = [geo]
  1968. for g in geo:
  1969. if type(g) == Polygon:
  1970. x, y = g.exterior.coords.xy
  1971. plot(x, y)
  1972. for ints in g.interiors:
  1973. x, y = ints.coords.xy
  1974. plot(x, y)
  1975. continue
  1976. if type(g) == LineString or type(g) == LinearRing:
  1977. x, y = g.coords.xy
  1978. plot(x, y)
  1979. continue
  1980. if type(g) == Point:
  1981. x, y = g.coords.xy
  1982. plot(x, y, 'o')
  1983. continue
  1984. try:
  1985. _ = iter(g)
  1986. plotg(g)
  1987. except:
  1988. print "Cannot plot:", str(type(g))
  1989. continue
  1990. def parse_gerber_number(strnumber, frac_digits):
  1991. """
  1992. Parse a single number of Gerber coordinates.
  1993. :param strnumber: String containing a number in decimal digits
  1994. from a coordinate data block, possibly with a leading sign.
  1995. :type strnumber: str
  1996. :param frac_digits: Number of digits used for the fractional
  1997. part of the number
  1998. :type frac_digits: int
  1999. :return: The number in floating point.
  2000. :rtype: float
  2001. """
  2002. return int(strnumber)*(10**(-frac_digits))
  2003. def parse_gerber_coords(gstr, int_digits, frac_digits):
  2004. """
  2005. Parse Gerber coordinates
  2006. :param gstr: Line of G-Code containing coordinates.
  2007. :type gstr: str
  2008. :param int_digits: Number of digits in integer part of a number.
  2009. :type int_digits: int
  2010. :param frac_digits: Number of digits in frac_digits part of a number.
  2011. :type frac_digits: int
  2012. :return: [x, y] coordinates.
  2013. :rtype: list
  2014. """
  2015. global gerbx, gerby
  2016. xindex = gstr.find("X")
  2017. yindex = gstr.find("Y")
  2018. index = gstr.find("D")
  2019. if xindex == -1:
  2020. x = gerbx
  2021. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  2022. elif yindex == -1:
  2023. y = gerby
  2024. x = int(gstr[(xindex+1):index])*(10**(-frac_digits))
  2025. else:
  2026. x = int(gstr[(xindex+1):yindex])*(10**(-frac_digits))
  2027. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  2028. gerbx = x
  2029. gerby = y
  2030. return [x, y]