camlib.py 117 KB

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