camlib.py 133 KB

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