camlib.py 142 KB

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