camlib.py 100 KB

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