camlib.py 142 KB

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