camlib.py 140 KB

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