camlib.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos
  9. from matplotlib.figure import Figure
  10. import re
  11. # See: http://toblerity.org/shapely/manual.html
  12. from shapely.geometry import Polygon, LineString, Point, LinearRing
  13. from shapely.geometry import MultiPoint, MultiPolygon
  14. from shapely.geometry import box as shply_box
  15. from shapely.ops import cascaded_union
  16. import shapely.affinity as affinity
  17. from shapely.wkt import loads as sloads
  18. from shapely.wkt import dumps as sdumps
  19. from shapely.geometry.base import BaseGeometry
  20. # Used for solid polygons in Matplotlib
  21. from descartes.patch import PolygonPatch
  22. import simplejson as json
  23. # TODO: Commented for FlatCAM packaging with cx_freeze
  24. #from matplotlib.pyplot import plot
  25. class Geometry(object):
  26. def __init__(self):
  27. # Units (in or mm)
  28. self.units = 'in'
  29. # Final geometry: MultiPolygon
  30. self.solid_geometry = None
  31. # Attributes to be included in serialization
  32. self.ser_attrs = ['units', 'solid_geometry']
  33. def isolation_geometry(self, offset):
  34. """
  35. Creates contours around geometry at a given
  36. offset distance.
  37. :param offset: Offset distance.
  38. :type offset: float
  39. :return: The buffered geometry.
  40. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  41. """
  42. return self.solid_geometry.buffer(offset)
  43. def bounds(self):
  44. """
  45. Returns coordinates of rectangular bounds
  46. of geometry: (xmin, ymin, xmax, ymax).
  47. """
  48. if self.solid_geometry is None:
  49. print "Warning: solid_geometry not computed yet."
  50. return (0, 0, 0, 0)
  51. if type(self.solid_geometry) == list:
  52. # TODO: This can be done faster. See comment from Shapely mailing lists.
  53. return cascaded_union(self.solid_geometry).bounds
  54. else:
  55. return self.solid_geometry.bounds
  56. def size(self):
  57. """
  58. Returns (width, height) of rectangular
  59. bounds of geometry.
  60. """
  61. if self.solid_geometry is None:
  62. print "Warning: solid_geometry not computed yet."
  63. return 0
  64. bounds = self.bounds()
  65. return (bounds[2]-bounds[0], bounds[3]-bounds[1])
  66. def get_empty_area(self, boundary=None):
  67. """
  68. Returns the complement of self.solid_geometry within
  69. the given boundary polygon. If not specified, it defaults to
  70. the rectangular bounding box of self.solid_geometry.
  71. """
  72. if boundary is None:
  73. boundary = self.solid_geometry.envelope
  74. return boundary.difference(self.solid_geometry)
  75. def clear_polygon(self, polygon, tooldia, overlap=0.15):
  76. """
  77. Creates geometry inside a polygon for a tool to cover
  78. the whole area.
  79. """
  80. poly_cuts = [polygon.buffer(-tooldia/2.0)]
  81. while True:
  82. polygon = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  83. if polygon.area > 0:
  84. poly_cuts.append(polygon)
  85. else:
  86. break
  87. return poly_cuts
  88. def scale(self, factor):
  89. """
  90. Scales all of the object's geometry by a given factor. Override
  91. this method.
  92. :param factor: Number by which to scale.
  93. :type factor: float
  94. :return: None
  95. :rtype: None
  96. """
  97. return
  98. def offset(self, vect):
  99. """
  100. Offset the geometry by the given vector. Override this method.
  101. :param vect: (x, y) vector by which to offset the object.
  102. :type vect: tuple
  103. :return: None
  104. """
  105. return
  106. def convert_units(self, units):
  107. """
  108. Converts the units of the object to ``units`` by scaling all
  109. the geometry appropriately. This call ``scale()``. Don't call
  110. it again in descendents.
  111. :param units: "IN" or "MM"
  112. :type units: str
  113. :return: Scaling factor resulting from unit change.
  114. :rtype: float
  115. """
  116. print "Geometry.convert_units()"
  117. if units.upper() == self.units.upper():
  118. return 1.0
  119. if units.upper() == "MM":
  120. factor = 25.4
  121. elif units.upper() == "IN":
  122. factor = 1/25.4
  123. else:
  124. print "Unsupported units:", units
  125. return 1.0
  126. self.units = units
  127. self.scale(factor)
  128. return factor
  129. def to_dict(self):
  130. """
  131. Returns a respresentation of the object as a dictionary.
  132. Attributes to include are listed in ``self.ser_attrs``.
  133. :return: A dictionary-encoded copy of the object.
  134. :rtype: dict
  135. """
  136. d = {}
  137. for attr in self.ser_attrs:
  138. d[attr] = getattr(self, attr)
  139. return d
  140. def from_dict(self, d):
  141. """
  142. Sets object's attributes from a dictionary.
  143. Attributes to include are listed in ``self.ser_attrs``.
  144. This method will look only for only and all the
  145. attributes in ``self.ser_attrs``. They must all
  146. be present. Use only for deserializing saved
  147. objects.
  148. :param d: Dictionary of attributes to set in the object.
  149. :type d: dict
  150. :return: None
  151. """
  152. for attr in self.ser_attrs:
  153. setattr(self, attr, d[attr])
  154. class ApertureMacro:
  155. ## Regular expressions
  156. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  157. am2_re = re.compile(r'(.*)%$')
  158. amcomm_re = re.compile(r'^0(.*)')
  159. amprim_re = re.compile(r'^[1-9].*')
  160. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  161. def __init__(self, name=None):
  162. self.name = name
  163. self.raw = ""
  164. ## These below are recomputed for every aperture
  165. ## definition, in other words, are temporary variables.
  166. self.primitives = []
  167. self.locvars = {}
  168. self.geometry = None
  169. def to_dict(self):
  170. """
  171. Returns the object in a serializable form. Only the name and
  172. raw are required.
  173. :return: Dictionary representing the object. JSON ready.
  174. :rtype: dict
  175. """
  176. return {
  177. 'name': self.name,
  178. 'raw': self.raw
  179. }
  180. def from_dict(self, d):
  181. """
  182. Populates the object from a serial representation created
  183. with ``self.to_dict()``.
  184. :param d: Serial representation of an ApertureMacro object.
  185. :return: None
  186. """
  187. for attr in ['name', 'raw']:
  188. setattr(self, attr, d[attr])
  189. def parse_content(self):
  190. """
  191. Creates numerical lists for all primitives in the aperture
  192. macro (in ``self.raw``) by replacing all variables by their
  193. values iteratively and evaluating expressions. Results
  194. are stored in ``self.primitives``.
  195. :return: None
  196. """
  197. # Cleanup
  198. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  199. self.primitives = []
  200. # Separate parts
  201. parts = self.raw.split('*')
  202. #### Every part in the macro ####
  203. for part in parts:
  204. ### Comments. Ignored.
  205. match = ApertureMacro.amcomm_re.search(part)
  206. if match:
  207. continue
  208. ### Variables
  209. # These are variables defined locally inside the macro. They can be
  210. # numerical constant or defind in terms of previously define
  211. # variables, which can be defined locally or in an aperture
  212. # definition. All replacements ocurr here.
  213. match = ApertureMacro.amvar_re.search(part)
  214. if match:
  215. var = match.group(1)
  216. val = match.group(2)
  217. # Replace variables in value
  218. for v in self.locvars:
  219. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  220. # Make all others 0
  221. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  222. # Change x with *
  223. val = re.sub(r'[xX]', "*", val)
  224. # Eval() and store.
  225. self.locvars[var] = eval(val)
  226. continue
  227. ### Primitives
  228. # Each is an array. The first identifies the primitive, while the
  229. # rest depend on the primitive. All are strings representing a
  230. # number and may contain variable definition. The values of these
  231. # variables are defined in an aperture definition.
  232. match = ApertureMacro.amprim_re.search(part)
  233. if match:
  234. ## Replace all variables
  235. for v in self.locvars:
  236. part = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  237. # Make all others 0
  238. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  239. # Change x with *
  240. part = re.sub(r'[xX]', "*", part)
  241. ## Store
  242. elements = part.split(",")
  243. self.primitives.append([eval(x) for x in elements])
  244. continue
  245. print "WARNING: Unknown syntax of aperture macro part:", part
  246. def append(self, data):
  247. """
  248. Appends a string to the raw macro.
  249. :param data: Part of the macro.
  250. :type data: str
  251. :return: None
  252. """
  253. self.raw += data
  254. @staticmethod
  255. def default2zero(n, mods):
  256. """
  257. Pads the ``mods`` list with zeros resulting in an
  258. list of length n.
  259. :param n: Length of the resulting list.
  260. :type n: int
  261. :param mods: List to be padded.
  262. :type mods: list
  263. :return: Zero-padded list.
  264. :rtype: list
  265. """
  266. x = [0.0]*n
  267. na = len(mods)
  268. x[0:na] = mods
  269. return x
  270. @staticmethod
  271. def make_circle(mods):
  272. """
  273. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  274. :return:
  275. """
  276. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  277. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  278. @staticmethod
  279. def make_vectorline(mods):
  280. """
  281. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  282. rotation angle around origin in degrees)
  283. :return:
  284. """
  285. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  286. line = LineString([(xs, ys), (xe, ye)])
  287. box = line.buffer(width/2, cap_style=2)
  288. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  289. return {"pol": int(pol), "geometry": box_rotated}
  290. @staticmethod
  291. def make_centerline(mods):
  292. """
  293. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  294. rotation angle around origin in degrees)
  295. :return:
  296. """
  297. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  298. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  299. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  300. return {"pol": int(pol), "geometry": box_rotated}
  301. @staticmethod
  302. def make_lowerleftline(mods):
  303. """
  304. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  305. rotation angle around origin in degrees)
  306. :return:
  307. """
  308. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  309. box = shply_box(x, y, x+width, y+height)
  310. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  311. return {"pol": int(pol), "geometry": box_rotated}
  312. @staticmethod
  313. def make_outline(mods):
  314. """
  315. :param mods:
  316. :return:
  317. """
  318. pol = mods[0]
  319. n = mods[1]
  320. points = [(0, 0)]*(n+1)
  321. for i in range(n+1):
  322. points[i] = mods[2*i + 2:2*i + 4]
  323. angle = mods[2*n + 4]
  324. poly = Polygon(points)
  325. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  326. return {"pol": int(pol), "geometry": poly_rotated}
  327. @staticmethod
  328. def make_polygon(mods):
  329. """
  330. Note: Specs indicate that rotation is only allowed if the center
  331. (x, y) == (0, 0). I will tolerate breaking this rule.
  332. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  333. diameter of circumscribed circle >=0, rotation angle around origin)
  334. :return:
  335. """
  336. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  337. points = [(0, 0)]*nverts
  338. for i in range(nverts):
  339. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  340. y + 0.5 * dia * sin(2*pi * i/nverts))
  341. poly = Polygon(points)
  342. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  343. return {"pol": int(pol), "geometry": poly_rotated}
  344. @staticmethod
  345. def make_moire(mods):
  346. """
  347. Note: Specs indicate that rotation is only allowed if the center
  348. (x, y) == (0, 0). I will tolerate breaking this rule.
  349. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  350. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  351. angle around origin in degrees)
  352. :return:
  353. """
  354. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  355. r = dia/2 - thickness/2
  356. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  357. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  358. i = 1 # Number of rings created so far
  359. ## If the ring does not have an interior it means that it is
  360. ## a disk. Then stop.
  361. while len(ring.interiors) > 0 and i < nrings:
  362. r -= thickness + gap
  363. if r <= 0:
  364. break
  365. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  366. result = cascaded_union([result, ring])
  367. i += 1
  368. ## Crosshair
  369. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  370. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  371. result = cascaded_union([result, hor, ver])
  372. return {"pol": 1, "geometry": result}
  373. @staticmethod
  374. def make_thermal(mods):
  375. """
  376. Note: Specs indicate that rotation is only allowed if the center
  377. (x, y) == (0, 0). I will tolerate breaking this rule.
  378. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  379. gap-thickness, rotation angle around origin]
  380. :return:
  381. """
  382. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  383. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  384. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  385. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  386. thermal = ring.difference(hline.union(vline))
  387. return {"pol": 1, "geometry": thermal}
  388. def make_geometry(self, modifiers):
  389. """
  390. Runs the macro for the given modifiers and generates
  391. the corresponding geometry.
  392. :param modifiers: Modifiers (parameters) for this macro
  393. :type modifiers: list
  394. """
  395. ## Primitive makers
  396. makers = {
  397. "1": ApertureMacro.make_circle,
  398. "2": ApertureMacro.make_vectorline,
  399. "20": ApertureMacro.make_vectorline,
  400. "21": ApertureMacro.make_centerline,
  401. "22": ApertureMacro.make_lowerleftline,
  402. "4": ApertureMacro.make_outline,
  403. "5": ApertureMacro.make_polygon,
  404. "6": ApertureMacro.make_moire,
  405. "7": ApertureMacro.make_thermal
  406. }
  407. ## Store modifiers as local variables
  408. modifiers = modifiers or []
  409. modifiers = [float(m) for m in modifiers]
  410. self.locvars = {}
  411. for i in range(0, len(modifiers)):
  412. self.locvars[str(i+1)] = modifiers[i]
  413. ## Parse
  414. self.primitives = [] # Cleanup
  415. self.geometry = None
  416. self.parse_content()
  417. ## Make the geometry
  418. for primitive in self.primitives:
  419. # Make the primitive
  420. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  421. # Add it (according to polarity)
  422. if self.geometry is None and prim_geo['pol'] == 1:
  423. self.geometry = prim_geo['geometry']
  424. continue
  425. if prim_geo['pol'] == 1:
  426. self.geometry = self.geometry.union(prim_geo['geometry'])
  427. continue
  428. if prim_geo['pol'] == 0:
  429. self.geometry = self.geometry.difference(prim_geo['geometry'])
  430. continue
  431. return self.geometry
  432. class Gerber (Geometry):
  433. """
  434. **ATTRIBUTES**
  435. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  436. The values are dictionaries key/value pairs which describe the aperture. The
  437. type key is always present and the rest depend on the key:
  438. +-----------+-----------------------------------+
  439. | Key | Value |
  440. +===========+===================================+
  441. | type | (str) "C", "R", "O", "P", or "AP" |
  442. +-----------+-----------------------------------+
  443. | others | Depend on ``type`` |
  444. +-----------+-----------------------------------+
  445. * ``paths`` (list): A path is described by a line an aperture that follows that
  446. line. Each paths[i] is a dictionary:
  447. +------------+------------------------------------------------+
  448. | Key | Value |
  449. +============+================================================+
  450. | linestring | (Shapely.LineString) The actual path. |
  451. +------------+------------------------------------------------+
  452. | aperture | (str) The key for an aperture in apertures. |
  453. +------------+------------------------------------------------+
  454. * ``flashes`` (list): Flashes are single-point strokes of an aperture. Each
  455. is a dictionary:
  456. +------------+------------------------------------------------+
  457. | Key | Value |
  458. +============+================================================+
  459. | loc | (Point) Shapely Point indicating location. |
  460. +------------+------------------------------------------------+
  461. | aperture | (str) The key for an aperture in apertures. |
  462. +------------+------------------------------------------------+
  463. * ``regions`` (list): Are surfaces defined by a polygon (Shapely.Polygon),
  464. which have an exterior and zero or more interiors. An aperture is also
  465. associated with a region. Each is a dictionary:
  466. +------------+-----------------------------------------------------+
  467. | Key | Value |
  468. +============+=====================================================+
  469. | polygon | (Shapely.Polygon) The polygon defining the region. |
  470. +------------+-----------------------------------------------------+
  471. | aperture | (str) The key for an aperture in apertures. |
  472. +------------+-----------------------------------------------------+
  473. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  474. that can be instanciated with different parameters in an aperture
  475. definition. See ``apertures`` above. The key is the name of the macro,
  476. and the macro itself, the value, is a ``Aperture_Macro`` object.
  477. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  478. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  479. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  480. *buffering* (or thickening) the ``paths`` with the aperture. These are
  481. generated from ``paths`` in ``buffer_paths()``.
  482. **USAGE**::
  483. g = Gerber()
  484. g.parse_file(filename)
  485. g.create_geometry()
  486. do_something(s.solid_geometry)
  487. """
  488. def __init__(self):
  489. """
  490. The constructor takes no parameters. Use ``gerber.parse_files()``
  491. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  492. :return: Gerber object
  493. :rtype: Gerber
  494. """
  495. # Initialize parent
  496. Geometry.__init__(self)
  497. self.solid_geometry = Polygon()
  498. # Number format
  499. self.int_digits = 3
  500. """Number of integer digits in Gerber numbers. Used during parsing."""
  501. self.frac_digits = 4
  502. """Number of fraction digits in Gerber numbers. Used during parsing."""
  503. ## Gerber elements ##
  504. # Apertures {'id':{'type':chr,
  505. # ['size':float], ['width':float],
  506. # ['height':float]}, ...}
  507. self.apertures = {}
  508. # Paths [{'linestring':LineString, 'aperture':str}]
  509. # self.paths = []
  510. # Buffered Paths [Polygon]
  511. # Paths transformed into Polygons by
  512. # offsetting the aperture size/2
  513. # self.buffered_paths = []
  514. # Polygon regions [{'polygon':Polygon, 'aperture':str}]
  515. # self.regions = []
  516. # Flashes [{'loc':[float,float], 'aperture':str}]
  517. # self.flashes = []
  518. # Geometry from flashes
  519. # self.flash_geometry = []
  520. # On-the-fly geometry. Initialized to an empty polygon
  521. self.otf_geometry = Polygon()
  522. # Aperture Macros
  523. self.aperture_macros = {}
  524. # Attributes to be included in serialization
  525. # Always append to it because it carries contents
  526. # from Geometry.
  527. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures', 'paths',
  528. 'buffered_paths', 'regions', 'flashes',
  529. 'flash_geometry', 'aperture_macros']
  530. #### Parser patterns ####
  531. # FS - Format Specification
  532. # The format of X and Y must be the same!
  533. # L-omit leading zeros, T-omit trailing zeros
  534. # A-absolute notation, I-incremental notation
  535. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  536. # Mode (IN/MM)
  537. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  538. # Comment G04|G4
  539. self.comm_re = re.compile(r'^G0?4(.*)$')
  540. # AD - Aperture definition
  541. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z0-9]*)(?:,(.*))?\*%$')
  542. # AM - Aperture Macro
  543. # Beginning of macro (Ends with *%):
  544. self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  545. # Tool change
  546. # May begin with G54 but that is deprecated
  547. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  548. # G01... - Linear interpolation plus flashes with coordinates
  549. # Operation code (D0x) missing is deprecated... oh well I will support it.
  550. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  551. # Operation code alone, usually just D03 (Flash)
  552. self.opcode_re = re.compile(r'^D0?([123])\*$')
  553. # G02/3... - Circular interpolation with coordinates
  554. # 2-clockwise, 3-counterclockwise
  555. # Operation code (D0x) missing is deprecated... oh well I will support it.
  556. # Optional start with G02 or G03, optional end with D01 or D02 with
  557. # optional coordinates but at least one in any order.
  558. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X(-?\d+))?(?=.*Y(-?\d+))' +
  559. '?(?=.*I(-?\d+))?(?=.*J(-?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  560. # G01/2/3 Occurring without coordinates
  561. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  562. # Single D74 or multi D75 quadrant for circular interpolation
  563. self.quad_re = re.compile(r'^G7([45])\*$')
  564. # Region mode on
  565. # In region mode, D01 starts a region
  566. # and D02 ends it. A new region can be started again
  567. # with D01. All contours must be closed before
  568. # D02 or G37.
  569. self.regionon_re = re.compile(r'^G36\*$')
  570. # Region mode off
  571. # Will end a region and come off region mode.
  572. # All contours must be closed before D02 or G37.
  573. self.regionoff_re = re.compile(r'^G37\*$')
  574. # End of file
  575. self.eof_re = re.compile(r'^M02\*')
  576. # IP - Image polarity
  577. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  578. # LP - Level polarity
  579. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  580. # Units (OBSOLETE)
  581. self.units_re = re.compile(r'^G7([01])\*$')
  582. # Absolute/Relative G90/1 (OBSOLETE)
  583. self.absrel_re = re.compile(r'^G9([01])\*$')
  584. # Aperture macros
  585. self.am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  586. self.am2_re = re.compile(r'(.*)%$')
  587. # TODO: This is bad.
  588. self.steps_per_circ = 40
  589. def scale(self, factor):
  590. """
  591. Scales the objects' geometry on the XY plane by a given factor.
  592. These are:
  593. * ``buffered_paths``
  594. * ``flash_geometry``
  595. * ``solid_geometry``
  596. * ``regions``
  597. NOTE:
  598. Does not modify the data used to create these elements. If these
  599. are recreated, the scaling will be lost. This behavior was modified
  600. because of the complexity reached in this class.
  601. :param factor: Number by which to scale.
  602. :type factor: float
  603. :rtype : None
  604. """
  605. # ## Apertures
  606. # # List of the non-dimension aperture parameters
  607. # nonDimensions = ["type", "nVertices", "rotation"]
  608. # for apid in self.apertures:
  609. # for param in self.apertures[apid]:
  610. # if param not in nonDimensions: # All others are dimensions.
  611. # print "Tool:", apid, "Parameter:", param
  612. # self.apertures[apid][param] *= factor
  613. #
  614. # ## Paths
  615. # for path in self.paths:
  616. # path['linestring'] = affinity.scale(path['linestring'],
  617. # factor, factor, origin=(0, 0))
  618. #
  619. # ## Flashes
  620. # for fl in self.flashes:
  621. # fl['loc'] = affinity.scale(fl['loc'], factor, factor, origin=(0, 0))
  622. # ## Regions
  623. # for reg in self.regions:
  624. # reg['polygon'] = affinity.scale(reg['polygon'], factor, factor,
  625. # origin=(0, 0))
  626. #
  627. # ## Flashes
  628. # for flash in self.flash_geometry:
  629. # flash = affinity.scale(flash, factor, factor, origin=(0, 0))
  630. #
  631. # ## Buffered paths
  632. # for bp in self.buffered_paths:
  633. # bp = affinity.scale(bp, factor, factor, origin=(0, 0))
  634. ## solid_geometry ???
  635. # It's a cascaded union of objects.
  636. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  637. factor, origin=(0, 0))
  638. # # Now buffered_paths, flash_geometry and solid_geometry
  639. # self.create_geometry()
  640. def offset(self, vect):
  641. """
  642. Offsets the objects' geometry on the XY plane by a given vector.
  643. These are:
  644. * ``buffered_paths``
  645. * ``flash_geometry``
  646. * ``solid_geometry``
  647. * ``regions``
  648. NOTE:
  649. Does not modify the data used to create these elements. If these
  650. are recreated, the scaling will be lost. This behavior was modified
  651. because of the complexity reached in this class.
  652. :param vect: (x, y) offset vector.
  653. :type vect: tuple
  654. :return: None
  655. """
  656. dx, dy = vect
  657. # ## Paths
  658. # for path in self.paths:
  659. # path['linestring'] = affinity.translate(path['linestring'],
  660. # xoff=dx, yoff=dy)
  661. #
  662. # ## Flashes
  663. # for fl in self.flashes:
  664. # fl['loc'] = affinity.translate(fl['loc'], xoff=dx, yoff=dy)
  665. # ## Regions
  666. # for reg in self.regions:
  667. # reg['polygon'] = affinity.translate(reg['polygon'],
  668. # xoff=dx, yoff=dy)
  669. #
  670. # ## Buffered paths
  671. # for bp in self.buffered_paths:
  672. # bp = affinity.translate(bp, xoff=dx, yoff=dy)
  673. #
  674. # ## Flash geometry
  675. # for fl in self.flash_geometry:
  676. # fl = affinity.translate(fl, xoff=dx, yoff=dy)
  677. ## Solid geometry
  678. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  679. # # Now buffered_paths, flash_geometry and solid_geometry
  680. # self.create_geometry()
  681. def mirror(self, axis, point):
  682. """
  683. Mirrors the object around a specified axis passign through
  684. the given point. What is affected:
  685. * ``buffered_paths``
  686. * ``flash_geometry``
  687. * ``solid_geometry``
  688. * ``regions``
  689. NOTE:
  690. Does not modify the data used to create these elements. If these
  691. are recreated, the scaling will be lost. This behavior was modified
  692. because of the complexity reached in this class.
  693. :param axis: "X" or "Y" indicates around which axis to mirror.
  694. :type axis: str
  695. :param point: [x, y] point belonging to the mirror axis.
  696. :type point: list
  697. :return: None
  698. """
  699. px, py = point
  700. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  701. # ## Paths
  702. # for path in self.paths:
  703. # path['linestring'] = affinity.scale(path['linestring'], xscale, yscale,
  704. # origin=(px, py))
  705. #
  706. # ## Flashes
  707. # for fl in self.flashes:
  708. # fl['loc'] = affinity.scale(fl['loc'], xscale, yscale, origin=(px, py))
  709. # ## Regions
  710. # for reg in self.regions:
  711. # reg['polygon'] = affinity.scale(reg['polygon'], xscale, yscale,
  712. # origin=(px, py))
  713. #
  714. # ## Flashes
  715. # for flash in self.flash_geometry:
  716. # flash = affinity.scale(flash, xscale, yscale, origin=(px, py))
  717. #
  718. # ## Buffered paths
  719. # for bp in self.buffered_paths:
  720. # bp = affinity.scale(bp, xscale, yscale, origin=(px, py))
  721. ## solid_geometry ???
  722. # It's a cascaded union of objects.
  723. self.solid_geometry = affinity.scale(self.solid_geometry,
  724. xscale, yscale, origin=(px, py))
  725. # # Now buffered_paths, flash_geometry and solid_geometry
  726. # self.create_geometry()
  727. # def fix_regions(self):
  728. # """
  729. # Overwrites the region polygons with fixed
  730. # versions if found to be invalid (according to Shapely).
  731. #
  732. # :return: None
  733. # """
  734. #
  735. # for region in self.regions:
  736. # if not region['polygon'].is_valid:
  737. # region['polygon'] = region['polygon'].buffer(0)
  738. # def buffer_paths(self):
  739. # """
  740. # This is part of the parsing process. "Thickens" the paths
  741. # by their appertures. This will only work for circular appertures.
  742. #
  743. # :return: None
  744. # """
  745. #
  746. # self.buffered_paths = []
  747. # for path in self.paths:
  748. # try:
  749. # width = self.apertures[path["aperture"]]["size"]
  750. # self.buffered_paths.append(path["linestring"].buffer(width/2))
  751. # except KeyError:
  752. # print "ERROR: Failed to buffer path: ", path
  753. # print "Apertures: ", self.apertures
  754. def aperture_parse(self, apertureId, apertureType, apParameters):
  755. """
  756. Parse gerber aperture definition into dictionary of apertures.
  757. The following kinds and their attributes are supported:
  758. * *Circular (C)*: size (float)
  759. * *Rectangle (R)*: width (float), height (float)
  760. * *Obround (O)*: width (float), height (float).
  761. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  762. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  763. :param apertureId: Id of the aperture being defined.
  764. :param apertureType: Type of the aperture.
  765. :param apParameters: Parameters of the aperture.
  766. :type apertureId: str
  767. :type apertureType: str
  768. :type apParameters: str
  769. :return: Identifier of the aperture.
  770. :rtype: str
  771. """
  772. # Found some Gerber with a leading zero in the aperture id and the
  773. # referenced it without the zero, so this is a hack to handle that.
  774. apid = str(int(apertureId))
  775. try: # Could be empty for aperture macros
  776. paramList = apParameters.split('X')
  777. except:
  778. paramList = None
  779. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  780. self.apertures[apid] = {"type": "C",
  781. "size": float(paramList[0])}
  782. return apid
  783. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  784. self.apertures[apid] = {"type": "R",
  785. "width": float(paramList[0]),
  786. "height": float(paramList[1])}
  787. return apid
  788. if apertureType == "O": # Obround
  789. self.apertures[apid] = {"type": "O",
  790. "width": float(paramList[0]),
  791. "height": float(paramList[1])}
  792. return apid
  793. if apertureType == "P": # Polygon (regular)
  794. self.apertures[apid] = {"type": "P",
  795. "diam": float(paramList[0]),
  796. "nVertices": int(paramList[1])}
  797. if len(paramList) >= 3:
  798. self.apertures[apid]["rotation"] = float(paramList[2])
  799. return apid
  800. if apertureType in self.aperture_macros:
  801. self.apertures[apid] = {"type": "AM",
  802. "macro": self.aperture_macros[apertureType],
  803. "modifiers": paramList}
  804. return apid
  805. print "WARNING: Aperture not implemented:", apertureType
  806. return None
  807. def parse_file(self, filename):
  808. """
  809. Calls Gerber.parse_lines() with array of lines
  810. read from the given file.
  811. :param filename: Gerber file to parse.
  812. :type filename: str
  813. :return: None
  814. """
  815. gfile = open(filename, 'r')
  816. gstr = gfile.readlines()
  817. gfile.close()
  818. self.parse_lines(gstr)
  819. def parse_lines(self, glines):
  820. """
  821. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  822. ``self.flashes``, ``self.regions`` and ``self.units``.
  823. :param glines: Gerber code as list of strings, each element being
  824. one line of the source file.
  825. :type glines: list
  826. :return: None
  827. :rtype: None
  828. """
  829. # Coordinates of the current path, each is [x, y]
  830. path = []
  831. # Polygons are stored here until there is a change in polarity.
  832. # Only then they are combined via cascaded_union and added or
  833. # subtracted from solid_geometry. This is ~100 times faster than
  834. # applyng a union for every new polygon.
  835. poly_buffer = []
  836. last_path_aperture = None
  837. current_aperture = None
  838. # 1,2 or 3 from "G01", "G02" or "G03"
  839. current_interpolation_mode = None
  840. # 1 or 2 from "D01" or "D02"
  841. # Note this is to support deprecated Gerber not putting
  842. # an operation code at the end of every coordinate line.
  843. current_operation_code = None
  844. # Current coordinates
  845. current_x = None
  846. current_y = None
  847. # Absolute or Relative/Incremental coordinates
  848. # Not implemented
  849. absolute = True
  850. # How to interpret circular interpolation: SINGLE or MULTI
  851. quadrant_mode = None
  852. # Indicates we are parsing an aperture macro
  853. current_macro = None
  854. # Indicates the current polarity: D-Dark, C-Clear
  855. current_polarity = 'D'
  856. # If a region is being defined
  857. making_region = False
  858. #### Parsing starts here ####
  859. line_num = 0
  860. for gline in glines:
  861. line_num += 1
  862. ### Cleanup
  863. gline = gline.strip(' \r\n')
  864. ### Aperture Macros
  865. # Having this at the beggining will slow things down
  866. # but macros can have complicated statements than could
  867. # be caught by other ptterns.
  868. if current_macro is None: # No macro started yet
  869. match = self.am1_re.search(gline)
  870. # Start macro if match, else not an AM, carry on.
  871. if match:
  872. current_macro = match.group(1)
  873. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  874. if match.group(2): # Append
  875. self.aperture_macros[current_macro].append(match.group(2))
  876. if match.group(3): # Finish macro
  877. #self.aperture_macros[current_macro].parse_content()
  878. current_macro = None
  879. continue
  880. else: # Continue macro
  881. match = self.am2_re.search(gline)
  882. if match: # Finish macro
  883. self.aperture_macros[current_macro].append(match.group(1))
  884. #self.aperture_macros[current_macro].parse_content()
  885. current_macro = None
  886. else: # Append
  887. self.aperture_macros[current_macro].append(gline)
  888. continue
  889. ### G01 - Linear interpolation plus flashes
  890. # Operation code (D0x) missing is deprecated... oh well I will support it.
  891. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  892. match = self.lin_re.search(gline)
  893. if match:
  894. # Dxx alone?
  895. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  896. # try:
  897. # current_operation_code = int(match.group(4))
  898. # except:
  899. # pass # A line with just * will match too.
  900. # continue
  901. # NOTE: Letting it continue allows it to react to the
  902. # operation code.
  903. # Parse coordinates
  904. if match.group(2) is not None:
  905. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  906. if match.group(3) is not None:
  907. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  908. # Parse operation code
  909. if match.group(4) is not None:
  910. current_operation_code = int(match.group(4))
  911. # Pen down: add segment
  912. if current_operation_code == 1:
  913. path.append([current_x, current_y])
  914. last_path_aperture = current_aperture
  915. elif current_operation_code == 2:
  916. if len(path) > 1:
  917. # self.paths.append({"linestring": LineString(path),
  918. # "aperture": last_path_aperture})
  919. # --- OTF ---
  920. # if making_region:
  921. # geo = Polygon(path)
  922. # else:
  923. # if last_path_aperture is None:
  924. # print "Warning: No aperture defined for curent path. (%d)" % line_num
  925. # width = self.apertures[last_path_aperture]["size"]
  926. # geo = LineString(path).buffer(width/2)
  927. # if current_polarity == 'D':
  928. # self.otf_geometry = self.otf_geometry.union(geo)
  929. # else:
  930. # self.otf_geometry = self.otf_geometry.difference(geo)
  931. ## --- BUFFERED ---
  932. if making_region:
  933. geo = Polygon(path)
  934. else:
  935. if last_path_aperture is None:
  936. print "Warning: No aperture defined for curent path. (%d)" % line_num
  937. width = self.apertures[last_path_aperture]["size"]
  938. geo = LineString(path).buffer(width/2)
  939. poly_buffer.append(geo)
  940. path = [[current_x, current_y]] # Start new path
  941. # Flash
  942. elif current_operation_code == 3:
  943. # self.flashes.append({"loc": Point([current_x, current_y]),
  944. # "aperture": current_aperture})
  945. # --- OTF ---
  946. # flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  947. # self.apertures[current_aperture])
  948. # if current_polarity == 'D':
  949. # self.otf_geometry = self.otf_geometry.union(flash)
  950. # else:
  951. # self.otf_geometry = self.otf_geometry.difference(flash)
  952. # --- BUFFERED ---
  953. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  954. self.apertures[current_aperture])
  955. poly_buffer.append(flash)
  956. continue
  957. ### G02/3 - Circular interpolation
  958. # 2-clockwise, 3-counterclockwise
  959. match = self.circ_re.search(gline)
  960. if match:
  961. mode, x, y, i, j, d = match.groups()
  962. try:
  963. x = parse_gerber_number(x, self.frac_digits)
  964. except:
  965. x = current_x
  966. try:
  967. y = parse_gerber_number(y, self.frac_digits)
  968. except:
  969. y = current_y
  970. try:
  971. i = parse_gerber_number(i, self.frac_digits)
  972. except:
  973. i = 0
  974. try:
  975. j = parse_gerber_number(j, self.frac_digits)
  976. except:
  977. j = 0
  978. if quadrant_mode is None:
  979. print "ERROR: Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num
  980. print gline
  981. continue
  982. if mode is None and current_interpolation_mode not in [2, 3]:
  983. print "ERROR: Found arc without circular interpolation mode defined. (%d)" % line_num
  984. print gline
  985. continue
  986. elif mode is not None:
  987. current_interpolation_mode = int(mode)
  988. # Set operation code if provided
  989. if d is not None:
  990. current_operation_code = int(d)
  991. # Nothing created! Pen Up.
  992. if current_operation_code == 2:
  993. print "Warning: Arc with D2. (%d)" % line_num
  994. if len(path) > 1:
  995. if last_path_aperture is None:
  996. print "Warning: No aperture defined for curent path. (%d)" % line_num
  997. # self.paths.append({"linestring": LineString(path),
  998. # "aperture": last_path_aperture})
  999. # --- OTF ---
  1000. # width = self.apertures[last_path_aperture]["size"]
  1001. # buffered = LineString(path).buffer(width/2)
  1002. # if current_polarity == 'D':
  1003. # self.otf_geometry = self.otf_geometry.union(buffered)
  1004. # else:
  1005. # self.otf_geometry = self.otf_geometry.difference(buffered)
  1006. # --- BUFFERED ---
  1007. width = self.apertures[last_path_aperture]["size"]
  1008. buffered = LineString(path).buffer(width/2)
  1009. poly_buffer.append(buffered)
  1010. current_x = x
  1011. current_y = y
  1012. path = [[current_x, current_y]] # Start new path
  1013. continue
  1014. # Flash should not happen here
  1015. if current_operation_code == 3:
  1016. print "ERROR: Trying to flash within arc. (%d)" % line_num
  1017. continue
  1018. if quadrant_mode == 'MULTI':
  1019. center = [i + current_x, j + current_y]
  1020. radius = sqrt(i**2 + j**2)
  1021. start = arctan2(-j, -i)
  1022. stop = arctan2(-center[1] + y, -center[0] + x)
  1023. arcdir = [None, None, "cw", "ccw"]
  1024. this_arc = arc(center, radius, start, stop,
  1025. arcdir[current_interpolation_mode],
  1026. self.steps_per_circ)
  1027. # Last point in path is current point
  1028. current_x = this_arc[-1][0]
  1029. current_y = this_arc[-1][1]
  1030. # Append
  1031. path += this_arc
  1032. last_path_aperture = current_aperture
  1033. continue
  1034. if quadrant_mode == 'SINGLE':
  1035. print "Warning: Single quadrant arc are not implemented yet. (%d)" % line_num
  1036. ### Operation code alone
  1037. match = self.opcode_re.search(gline)
  1038. if match:
  1039. current_operation_code = int(match.group(1))
  1040. if current_operation_code == 3:
  1041. ## --- OTF ---
  1042. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1043. # self.apertures[current_aperture])
  1044. # if current_polarity == 'D':
  1045. # self.otf_geometry = self.otf_geometry.union(flash)
  1046. # else:
  1047. # self.otf_geometry = self.otf_geometry.difference(flash)
  1048. ## --- Buffered ---
  1049. flash = Gerber.create_flash_geometry(Point(path[-1]),
  1050. self.apertures[current_aperture])
  1051. poly_buffer.append(flash)
  1052. continue
  1053. ### G74/75* - Single or multiple quadrant arcs
  1054. match = self.quad_re.search(gline)
  1055. if match:
  1056. if match.group(1) == '4':
  1057. quadrant_mode = 'SINGLE'
  1058. else:
  1059. quadrant_mode = 'MULTI'
  1060. continue
  1061. ### G36* - Begin region
  1062. if self.regionon_re.search(gline):
  1063. if len(path) > 1:
  1064. # Take care of what is left in the path
  1065. ## --- OTF ---
  1066. # width = self.apertures[last_path_aperture]["size"]
  1067. # geo = LineString(path).buffer(width/2)
  1068. # if current_polarity == 'D':
  1069. # self.otf_geometry = self.otf_geometry.union(geo)
  1070. # else:
  1071. # self.otf_geometry = self.otf_geometry.difference(geo)
  1072. ## --- Buffered ---
  1073. width = self.apertures[last_path_aperture]["size"]
  1074. geo = LineString(path).buffer(width/2)
  1075. poly_buffer.append(geo)
  1076. path = [path[-1]]
  1077. making_region = True
  1078. continue
  1079. ### G37* - End region
  1080. if self.regionoff_re.search(gline):
  1081. making_region = False
  1082. # Only one path defines region?
  1083. # This can happen if D02 happened before G37 and
  1084. # is not and error.
  1085. if len(path) < 3:
  1086. # print "ERROR: Path contains less than 3 points:"
  1087. # print path
  1088. # print "Line (%d): " % line_num, gline
  1089. # path = []
  1090. #path = [[current_x, current_y]]
  1091. continue
  1092. # For regions we may ignore an aperture that is None
  1093. # self.regions.append({"polygon": Polygon(path),
  1094. # "aperture": last_path_aperture})
  1095. # --- OTF ---
  1096. # region = Polygon(path)
  1097. # if not region.is_valid:
  1098. # region = region.buffer(0)
  1099. # if current_polarity == 'D':
  1100. # self.otf_geometry = self.otf_geometry.union(region)
  1101. # else:
  1102. # self.otf_geometry = self.otf_geometry.difference(region)
  1103. # --- Buffered ---
  1104. region = Polygon(path)
  1105. if not region.is_valid:
  1106. region = region.buffer(0)
  1107. poly_buffer.append(region)
  1108. path = [[current_x, current_y]] # Start new path
  1109. continue
  1110. ### Aperture definitions %ADD...
  1111. match = self.ad_re.search(gline)
  1112. if match:
  1113. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1114. continue
  1115. ### G01/2/3* - Interpolation mode change
  1116. # Can occur along with coordinates and operation code but
  1117. # sometimes by itself (handled here).
  1118. # Example: G01*
  1119. match = self.interp_re.search(gline)
  1120. if match:
  1121. current_interpolation_mode = int(match.group(1))
  1122. continue
  1123. ### Tool/aperture change
  1124. # Example: D12*
  1125. match = self.tool_re.search(gline)
  1126. if match:
  1127. current_aperture = match.group(1)
  1128. continue
  1129. ### Polarity change
  1130. # Example: %LPD*% or %LPC*%
  1131. match = self.lpol_re.search(gline)
  1132. if match:
  1133. if len(path) > 1 and current_polarity != match.group(1):
  1134. # --- OTF ---
  1135. # width = self.apertures[last_path_aperture]["size"]
  1136. # geo = LineString(path).buffer(width/2)
  1137. # if current_polarity == 'D':
  1138. # self.otf_geometry = self.otf_geometry.union(geo)
  1139. # else:
  1140. # self.otf_geometry = self.otf_geometry.difference(geo)
  1141. # --- Buffered ----
  1142. width = self.apertures[last_path_aperture]["size"]
  1143. geo = LineString(path).buffer(width/2)
  1144. poly_buffer.append(geo)
  1145. path = [path[-1]]
  1146. # --- Apply buffer ---
  1147. if current_polarity == 'D':
  1148. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1149. else:
  1150. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1151. poly_buffer = []
  1152. current_polarity = match.group(1)
  1153. continue
  1154. ### Number format
  1155. # Example: %FSLAX24Y24*%
  1156. # TODO: This is ignoring most of the format. Implement the rest.
  1157. match = self.fmt_re.search(gline)
  1158. if match:
  1159. absolute = {'A': True, 'I': False}
  1160. self.int_digits = int(match.group(3))
  1161. self.frac_digits = int(match.group(4))
  1162. continue
  1163. ### Mode (IN/MM)
  1164. # Example: %MOIN*%
  1165. match = self.mode_re.search(gline)
  1166. if match:
  1167. self.units = match.group(1)
  1168. continue
  1169. ### Units (G70/1) OBSOLETE
  1170. match = self.units_re.search(gline)
  1171. if match:
  1172. self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1173. continue
  1174. ### Absolute/relative coordinates G90/1 OBSOLETE
  1175. match = self.absrel_re.search(gline)
  1176. if match:
  1177. absolute = {'0': True, '1': False}[match.group(1)]
  1178. continue
  1179. #### Ignored lines
  1180. ## Comments
  1181. match = self.comm_re.search(gline)
  1182. if match:
  1183. continue
  1184. ## EOF
  1185. match = self.eof_re.search(gline)
  1186. if match:
  1187. continue
  1188. ### Line did not match any pattern. Warn user.
  1189. print "WARNING: Line ignored (%d):" % line_num, gline
  1190. if len(path) > 1:
  1191. # EOF, create shapely LineString if something still in path
  1192. # self.paths.append({"linestring": LineString(path),
  1193. # "aperture": last_path_aperture})
  1194. ## --- OTF ---
  1195. # width = self.apertures[last_path_aperture]["size"]
  1196. # geo = LineString(path).buffer(width/2)
  1197. # if current_polarity == 'D':
  1198. # self.otf_geometry = self.otf_geometry.union(geo)
  1199. # else:
  1200. # self.otf_geometry = self.otf_geometry.difference(geo)
  1201. ## --- Buffered ---
  1202. width = self.apertures[last_path_aperture]["size"]
  1203. geo = LineString(path).buffer(width/2)
  1204. poly_buffer.append(geo)
  1205. # --- Apply buffer ---
  1206. if current_polarity == 'D':
  1207. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1208. else:
  1209. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1210. @staticmethod
  1211. def create_flash_geometry(location, aperture):
  1212. if type(location) == list:
  1213. location = Point(location)
  1214. if aperture['type'] == 'C': # Circles
  1215. return location.buffer(aperture['size']/2)
  1216. if aperture['type'] == 'R': # Rectangles
  1217. loc = location.coords[0]
  1218. width = aperture['width']
  1219. height = aperture['height']
  1220. minx = loc[0] - width/2
  1221. maxx = loc[0] + width/2
  1222. miny = loc[1] - height/2
  1223. maxy = loc[1] + height/2
  1224. return shply_box(minx, miny, maxx, maxy)
  1225. if aperture['type'] == 'O': # Obround
  1226. loc = location.coords[0]
  1227. width = aperture['width']
  1228. height = aperture['height']
  1229. if width > height:
  1230. p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1231. p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1232. c1 = p1.buffer(height*0.5)
  1233. c2 = p2.buffer(height*0.5)
  1234. else:
  1235. p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1236. p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1237. c1 = p1.buffer(width*0.5)
  1238. c2 = p2.buffer(width*0.5)
  1239. return cascaded_union([c1, c2]).convex_hull
  1240. if aperture['type'] == 'P': # Regular polygon
  1241. loc = location.coords[0]
  1242. diam = aperture['diam']
  1243. n_vertices = aperture['nVertices']
  1244. points = []
  1245. for i in range(0, n_vertices):
  1246. x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1247. y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1248. points.append((x, y))
  1249. ply = Polygon(points)
  1250. if 'rotation' in aperture:
  1251. ply = affinity.rotate(ply, aperture['rotation'])
  1252. return ply
  1253. if aperture['type'] == 'AM': # Aperture Macro
  1254. loc = location.coords[0]
  1255. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1256. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1257. return None
  1258. # def do_flashes(self):
  1259. # """
  1260. # Creates geometry for Gerber flashes (aperture on a single point).
  1261. # """
  1262. #
  1263. # self.flash_geometry = []
  1264. # for flash in self.flashes:
  1265. #
  1266. # try:
  1267. # aperture = self.apertures[flash['aperture']]
  1268. # except KeyError:
  1269. # print "ERROR: Trying to flash with unknown aperture: ", flash['aperture']
  1270. # continue
  1271. #
  1272. # if aperture['type'] == 'C': # Circles
  1273. # #circle = Point(flash['loc']).buffer(aperture['size']/2)
  1274. # circle = flash['loc'].buffer(aperture['size']/2)
  1275. # self.flash_geometry.append(circle)
  1276. # continue
  1277. #
  1278. # if aperture['type'] == 'R': # Rectangles
  1279. # loc = flash['loc'].coords[0]
  1280. # width = aperture['width']
  1281. # height = aperture['height']
  1282. # minx = loc[0] - width/2
  1283. # maxx = loc[0] + width/2
  1284. # miny = loc[1] - height/2
  1285. # maxy = loc[1] + height/2
  1286. # rectangle = shply_box(minx, miny, maxx, maxy)
  1287. # self.flash_geometry.append(rectangle)
  1288. # continue
  1289. #
  1290. # if aperture['type'] == 'O': # Obround
  1291. # loc = flash['loc'].coords[0]
  1292. # width = aperture['width']
  1293. # height = aperture['height']
  1294. # if width > height:
  1295. # p1 = Point(loc[0] + 0.5*(width-height), loc[1])
  1296. # p2 = Point(loc[0] - 0.5*(width-height), loc[1])
  1297. # c1 = p1.buffer(height*0.5)
  1298. # c2 = p2.buffer(height*0.5)
  1299. # else:
  1300. # p1 = Point(loc[0], loc[1] + 0.5*(height-width))
  1301. # p2 = Point(loc[0], loc[1] - 0.5*(height-width))
  1302. # c1 = p1.buffer(width*0.5)
  1303. # c2 = p2.buffer(width*0.5)
  1304. # obround = cascaded_union([c1, c2]).convex_hull
  1305. # self.flash_geometry.append(obround)
  1306. # continue
  1307. #
  1308. # if aperture['type'] == 'P': # Regular polygon
  1309. # loc = flash['loc'].coords[0]
  1310. # diam = aperture['diam']
  1311. # n_vertices = aperture['nVertices']
  1312. # points = []
  1313. # for i in range(0, n_vertices):
  1314. # x = loc[0] + diam * (cos(2 * pi * i / n_vertices))
  1315. # y = loc[1] + diam * (sin(2 * pi * i / n_vertices))
  1316. # points.append((x, y))
  1317. # ply = Polygon(points)
  1318. # if 'rotation' in aperture:
  1319. # ply = affinity.rotate(ply, aperture['rotation'])
  1320. # self.flash_geometry.append(ply)
  1321. # continue
  1322. #
  1323. # if aperture['type'] == 'AM': # Aperture Macro
  1324. # loc = flash['loc'].coords[0]
  1325. # flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1326. # flash_geo_final = affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1327. # self.flash_geometry.append(flash_geo_final)
  1328. # continue
  1329. #
  1330. # print "WARNING: Aperture type %s not implemented" % (aperture['type'])
  1331. def create_geometry(self):
  1332. """
  1333. Geometry from a Gerber file is made up entirely of polygons.
  1334. Every stroke (linear or circular) has an aperture which gives
  1335. it thickness. Additionally, aperture strokes have non-zero area,
  1336. and regions naturally do as well.
  1337. :rtype : None
  1338. :return: None
  1339. """
  1340. # self.buffer_paths()
  1341. #
  1342. # self.fix_regions()
  1343. #
  1344. # self.do_flashes()
  1345. #
  1346. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1347. # [poly['polygon'] for poly in self.regions] +
  1348. # self.flash_geometry)
  1349. def get_bounding_box(self, margin=0.0, rounded=False):
  1350. """
  1351. Creates and returns a rectangular polygon bounding at a distance of
  1352. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1353. can optionally have rounded corners of radius equal to margin.
  1354. :param margin: Distance to enlarge the rectangular bounding
  1355. box in both positive and negative, x and y axes.
  1356. :type margin: float
  1357. :param rounded: Wether or not to have rounded corners.
  1358. :type rounded: bool
  1359. :return: The bounding box.
  1360. :rtype: Shapely.Polygon
  1361. """
  1362. bbox = self.solid_geometry.envelope.buffer(margin)
  1363. if not rounded:
  1364. bbox = bbox.envelope
  1365. return bbox
  1366. class Excellon(Geometry):
  1367. """
  1368. *ATTRIBUTES*
  1369. * ``tools`` (dict): The key is the tool name and the value is
  1370. a dictionary specifying the tool:
  1371. ================ ====================================
  1372. Key Value
  1373. ================ ====================================
  1374. C Diameter of the tool
  1375. Others Not supported (Ignored).
  1376. ================ ====================================
  1377. * ``drills`` (list): Each is a dictionary:
  1378. ================ ====================================
  1379. Key Value
  1380. ================ ====================================
  1381. point (Shapely.Point) Where to drill
  1382. tool (str) A key in ``tools``
  1383. ================ ====================================
  1384. """
  1385. def __init__(self):
  1386. """
  1387. The constructor takes no parameters.
  1388. :return: Excellon object.
  1389. :rtype: Excellon
  1390. """
  1391. Geometry.__init__(self)
  1392. self.tools = {}
  1393. self.drills = []
  1394. # Trailing "T" or leading "L"
  1395. self.zeros = ""
  1396. # Attributes to be included in serialization
  1397. # Always append to it because it carries contents
  1398. # from Geometry.
  1399. self.ser_attrs += ['tools', 'drills', 'zeros']
  1400. #### Patterns ####
  1401. # Regex basics:
  1402. # ^ - beginning
  1403. # $ - end
  1404. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1405. # M48 - Beggining of Part Program Header
  1406. self.hbegin_re = re.compile(r'^M48$')
  1407. # M95 or % - End of Part Program Header
  1408. # NOTE: % has different meaning in the body
  1409. self.hend_re = re.compile(r'^(?:M95|%)$')
  1410. # FMAT Excellon format
  1411. self.fmat_re = re.compile(r'^FMAT,([12])$')
  1412. # Number format and units
  1413. # INCH uses 6 digits
  1414. # METRIC uses 5/6
  1415. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1416. # Tool definition/parameters (?= is look-ahead
  1417. # NOTE: This might be an overkill!
  1418. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1419. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1420. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1421. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1422. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  1423. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1424. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1425. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1426. # Tool select
  1427. # Can have additional data after tool number but
  1428. # is ignored if present in the header.
  1429. # Warning: This will match toolset_re too.
  1430. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  1431. self.toolsel_re = re.compile(r'^T(\d+)')
  1432. # Comment
  1433. self.comm_re = re.compile(r'^;(.*)$')
  1434. # Absolute/Incremental G90/G91
  1435. self.absinc_re = re.compile(r'^G9([01])$')
  1436. # Modes of operation
  1437. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  1438. self.modes_re = re.compile(r'^G0([012345])')
  1439. # Measuring mode
  1440. # 1-metric, 2-inch
  1441. self.meas_re = re.compile(r'^M7([12])$')
  1442. # Coordinates
  1443. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  1444. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  1445. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  1446. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  1447. # R - Repeat hole (# times, X offset, Y offset)
  1448. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  1449. # Various stop/pause commands
  1450. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  1451. def parse_file(self, filename):
  1452. """
  1453. Reads the specified file as array of lines as
  1454. passes it to ``parse_lines()``.
  1455. :param filename: The file to be read and parsed.
  1456. :type filename: str
  1457. :return: None
  1458. """
  1459. efile = open(filename, 'r')
  1460. estr = efile.readlines()
  1461. efile.close()
  1462. self.parse_lines(estr)
  1463. def parse_lines(self, elines):
  1464. """
  1465. Main Excellon parser.
  1466. :param elines: List of strings, each being a line of Excellon code.
  1467. :type elines: list
  1468. :return: None
  1469. """
  1470. # State variables
  1471. current_tool = ""
  1472. in_header = False
  1473. current_x = None
  1474. current_y = None
  1475. line_num = 0 # Line number
  1476. for eline in elines:
  1477. line_num += 1
  1478. ### Cleanup
  1479. eline = eline.strip(' \r\n')
  1480. ## Header Begin/End ##
  1481. if self.hbegin_re.search(eline):
  1482. in_header = True
  1483. continue
  1484. if self.hend_re.search(eline):
  1485. in_header = False
  1486. continue
  1487. #### Body ####
  1488. if not in_header:
  1489. ## Tool change ##
  1490. match = self.toolsel_re.search(eline)
  1491. if match:
  1492. current_tool = str(int(match.group(1)))
  1493. continue
  1494. ## Coordinates without period ##
  1495. match = self.coordsnoperiod_re.search(eline)
  1496. if match:
  1497. try:
  1498. x = float(match.group(1))/10000
  1499. current_x = x
  1500. except TypeError:
  1501. x = current_x
  1502. try:
  1503. y = float(match.group(2))/10000
  1504. current_y = y
  1505. except TypeError:
  1506. y = current_y
  1507. if x is None or y is None:
  1508. print "ERROR: Missing coordinates"
  1509. continue
  1510. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1511. continue
  1512. ## Coordinates with period ##
  1513. match = self.coordsperiod_re.search(eline)
  1514. if match:
  1515. try:
  1516. x = float(match.group(1))
  1517. current_x = x
  1518. except TypeError:
  1519. x = current_x
  1520. try:
  1521. y = float(match.group(2))
  1522. current_y = y
  1523. except TypeError:
  1524. y = current_y
  1525. if x is None or y is None:
  1526. print "ERROR: Missing coordinates"
  1527. continue
  1528. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  1529. continue
  1530. #### Header ####
  1531. if in_header:
  1532. ## Tool definitions ##
  1533. match = self.toolset_re.search(eline)
  1534. if match:
  1535. name = str(int(match.group(1)))
  1536. spec = {
  1537. "C": float(match.group(2)),
  1538. # "F": float(match.group(3)),
  1539. # "S": float(match.group(4)),
  1540. # "B": float(match.group(5)),
  1541. # "H": float(match.group(6)),
  1542. # "Z": float(match.group(7))
  1543. }
  1544. self.tools[name] = spec
  1545. continue
  1546. ## Units and number format ##
  1547. match = self.units_re.match(eline)
  1548. if match:
  1549. self.zeros = match.group(2) # "T" or "L"
  1550. self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  1551. continue
  1552. print "WARNING: Line ignored:", eline
  1553. def create_geometry(self):
  1554. """
  1555. Creates circles of the tool diameter at every point
  1556. specified in ``self.drills``.
  1557. :return: None
  1558. """
  1559. self.solid_geometry = []
  1560. for drill in self.drills:
  1561. #poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  1562. tooldia = self.tools[drill['tool']]['C']
  1563. poly = drill['point'].buffer(tooldia/2.0)
  1564. self.solid_geometry.append(poly)
  1565. def scale(self, factor):
  1566. """
  1567. Scales geometry on the XY plane in the object by a given factor.
  1568. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1569. :param factor: Number by which to scale the object.
  1570. :type factor: float
  1571. :return: None
  1572. :rtype: NOne
  1573. """
  1574. # Drills
  1575. for drill in self.drills:
  1576. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  1577. self.create_geometry()
  1578. def offset(self, vect):
  1579. """
  1580. Offsets geometry on the XY plane in the object by a given vector.
  1581. :param vect: (x, y) offset vector.
  1582. :type vect: tuple
  1583. :return: None
  1584. """
  1585. dx, dy = vect
  1586. # Drills
  1587. for drill in self.drills:
  1588. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1589. # Recreate geometry
  1590. self.create_geometry()
  1591. def mirror(self, axis, point):
  1592. """
  1593. :param axis: "X" or "Y" indicates around which axis to mirror.
  1594. :type axis: str
  1595. :param point: [x, y] point belonging to the mirror axis.
  1596. :type point: list
  1597. :return: None
  1598. """
  1599. px, py = point
  1600. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1601. # Modify data
  1602. for drill in self.drills:
  1603. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1604. # Recreate geometry
  1605. self.create_geometry()
  1606. def convert_units(self, units):
  1607. factor = Geometry.convert_units(self, units)
  1608. # Tools
  1609. for tname in self.tools:
  1610. self.tools[tname]["C"] *= factor
  1611. self.create_geometry()
  1612. return factor
  1613. class CNCjob(Geometry):
  1614. """
  1615. Represents work to be done by a CNC machine.
  1616. *ATTRIBUTES*
  1617. * ``gcode_parsed`` (list): Each is a dictionary:
  1618. ===================== =========================================
  1619. Key Value
  1620. ===================== =========================================
  1621. geom (Shapely.LineString) Tool path (XY plane)
  1622. kind (string) "AB", A is "T" (travel) or
  1623. "C" (cut). B is "F" (fast) or "S" (slow).
  1624. ===================== =========================================
  1625. """
  1626. def __init__(self, units="in", kind="generic", z_move=0.1,
  1627. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  1628. Geometry.__init__(self)
  1629. self.kind = kind
  1630. self.units = units
  1631. self.z_cut = z_cut
  1632. self.z_move = z_move
  1633. self.feedrate = feedrate
  1634. self.tooldia = tooldia
  1635. self.unitcode = {"IN": "G20", "MM": "G21"}
  1636. self.pausecode = "G04 P1"
  1637. self.feedminutecode = "G94"
  1638. self.absolutecode = "G90"
  1639. self.gcode = ""
  1640. self.input_geometry_bounds = None
  1641. self.gcode_parsed = None
  1642. self.steps_per_circ = 20 # Used when parsing G-code arcs
  1643. # Attributes to be included in serialization
  1644. # Always append to it because it carries contents
  1645. # from Geometry.
  1646. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  1647. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  1648. 'steps_per_circ']
  1649. def convert_units(self, units):
  1650. factor = Geometry.convert_units(self, units)
  1651. print "CNCjob.convert_units()"
  1652. self.z_cut *= factor
  1653. self.z_move *= factor
  1654. self.feedrate *= factor
  1655. self.tooldia *= factor
  1656. return factor
  1657. def generate_from_excellon(self, exobj):
  1658. """
  1659. Generates G-code for drilling from Excellon object.
  1660. self.gcode becomes a list, each element is a
  1661. different job for each tool in the excellon code.
  1662. """
  1663. self.kind = "drill"
  1664. self.gcode = []
  1665. t = "G00 X%.4fY%.4f\n"
  1666. down = "G01 Z%.4f\n" % self.z_cut
  1667. up = "G01 Z%.4f\n" % self.z_move
  1668. for tool in exobj.tools:
  1669. points = []
  1670. for drill in exobj.drill:
  1671. if drill['tool'] == tool:
  1672. points.append(drill['point'])
  1673. gcode = self.unitcode[self.units.upper()] + "\n"
  1674. gcode += self.absolutecode + "\n"
  1675. gcode += self.feedminutecode + "\n"
  1676. gcode += "F%.2f\n" % self.feedrate
  1677. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1678. gcode += "M03\n" # Spindle start
  1679. gcode += self.pausecode + "\n"
  1680. for point in points:
  1681. gcode += t % point
  1682. gcode += down + up
  1683. gcode += t % (0, 0)
  1684. gcode += "M05\n" # Spindle stop
  1685. self.gcode.append(gcode)
  1686. def generate_from_excellon_by_tool(self, exobj, tools="all"):
  1687. """
  1688. Creates gcode for this object from an Excellon object
  1689. for the specified tools.
  1690. :param exobj: Excellon object to process
  1691. :type exobj: Excellon
  1692. :param tools: Comma separated tool names
  1693. :type: tools: str
  1694. :return: None
  1695. :rtype: None
  1696. """
  1697. print "Creating CNC Job from Excellon..."
  1698. if tools == "all":
  1699. tools = [tool for tool in exobj.tools]
  1700. else:
  1701. tools = [x.strip() for x in tools.split(",")]
  1702. tools = filter(lambda i: i in exobj.tools, tools)
  1703. print "Tools are:", tools
  1704. points = []
  1705. for drill in exobj.drills:
  1706. if drill['tool'] in tools:
  1707. points.append(drill['point'])
  1708. print "Found %d drills." % len(points)
  1709. #self.kind = "drill"
  1710. self.gcode = []
  1711. t = "G00 X%.4fY%.4f\n"
  1712. down = "G01 Z%.4f\n" % self.z_cut
  1713. up = "G01 Z%.4f\n" % self.z_move
  1714. gcode = self.unitcode[self.units.upper()] + "\n"
  1715. gcode += self.absolutecode + "\n"
  1716. gcode += self.feedminutecode + "\n"
  1717. gcode += "F%.2f\n" % self.feedrate
  1718. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1719. gcode += "M03\n" # Spindle start
  1720. gcode += self.pausecode + "\n"
  1721. for point in points:
  1722. x, y = point.coords.xy
  1723. gcode += t % (x[0], y[0])
  1724. gcode += down + up
  1725. gcode += t % (0, 0)
  1726. gcode += "M05\n" # Spindle stop
  1727. self.gcode = gcode
  1728. def generate_from_geometry(self, geometry, append=True, tooldia=None, tolerance=0):
  1729. """
  1730. Generates G-Code from a Geometry object. Stores in ``self.gcode``.
  1731. :param geometry: Geometry defining the toolpath
  1732. :type geometry: Geometry
  1733. :param append: Wether to append to self.gcode or re-write it.
  1734. :type append: bool
  1735. :param tooldia: If given, sets the tooldia property but does
  1736. not affect the process in any other way.
  1737. :type tooldia: bool
  1738. :param tolerance: All points in the simplified object will be within the
  1739. tolerance distance of the original geometry.
  1740. :return: None
  1741. :rtype: None
  1742. """
  1743. if tooldia is not None:
  1744. self.tooldia = tooldia
  1745. self.input_geometry_bounds = geometry.bounds()
  1746. if not append:
  1747. self.gcode = ""
  1748. self.gcode = self.unitcode[self.units.upper()] + "\n"
  1749. self.gcode += self.absolutecode + "\n"
  1750. self.gcode += self.feedminutecode + "\n"
  1751. self.gcode += "F%.2f\n" % self.feedrate
  1752. self.gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  1753. self.gcode += "M03\n" # Spindle start
  1754. self.gcode += self.pausecode + "\n"
  1755. for geo in geometry.solid_geometry:
  1756. if type(geo) == Polygon:
  1757. self.gcode += self.polygon2gcode(geo, tolerance=tolerance)
  1758. continue
  1759. if type(geo) == LineString or type(geo) == LinearRing:
  1760. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  1761. continue
  1762. if type(geo) == Point:
  1763. self.gcode += self.point2gcode(geo)
  1764. continue
  1765. if type(geo) == MultiPolygon:
  1766. for poly in geo:
  1767. self.gcode += self.polygon2gcode(poly, tolerance=tolerance)
  1768. continue
  1769. print "WARNING: G-code generation not implemented for %s" % (str(type(geo)))
  1770. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1771. self.gcode += "G00 X0Y0\n"
  1772. self.gcode += "M05\n" # Spindle stop
  1773. def pre_parse(self, gtext):
  1774. """
  1775. Separates parts of the G-Code text into a list of dictionaries.
  1776. Used by ``self.gcode_parse()``.
  1777. :param gtext: A single string with g-code
  1778. """
  1779. # Units: G20-inches, G21-mm
  1780. units_re = re.compile(r'^G2([01])')
  1781. # TODO: This has to be re-done
  1782. gcmds = []
  1783. lines = gtext.split("\n") # TODO: This is probably a lot of work!
  1784. for line in lines:
  1785. # Clean up
  1786. line = line.strip()
  1787. # Remove comments
  1788. # NOTE: Limited to 1 bracket pair
  1789. op = line.find("(")
  1790. cl = line.find(")")
  1791. #if op > -1 and cl > op:
  1792. if cl > op > -1:
  1793. #comment = line[op+1:cl]
  1794. line = line[:op] + line[(cl+1):]
  1795. # Units
  1796. match = units_re.match(line)
  1797. if match:
  1798. self.units = {'0': "IN", '1': "MM"}[match.group(1)]
  1799. # Parse GCode
  1800. # 0 4 12
  1801. # G01 X-0.007 Y-0.057
  1802. # --> codes_idx = [0, 4, 12]
  1803. codes = "NMGXYZIJFP"
  1804. codes_idx = []
  1805. i = 0
  1806. for ch in line:
  1807. if ch in codes:
  1808. codes_idx.append(i)
  1809. i += 1
  1810. n_codes = len(codes_idx)
  1811. if n_codes == 0:
  1812. continue
  1813. # Separate codes in line
  1814. parts = []
  1815. for p in range(n_codes-1):
  1816. parts.append(line[codes_idx[p]:codes_idx[p+1]].strip())
  1817. parts.append(line[codes_idx[-1]:].strip())
  1818. # Separate codes from values
  1819. cmds = {}
  1820. for part in parts:
  1821. cmds[part[0]] = float(part[1:])
  1822. gcmds.append(cmds)
  1823. return gcmds
  1824. def gcode_parse(self):
  1825. """
  1826. G-Code parser (from self.gcode). Generates dictionary with
  1827. single-segment LineString's and "kind" indicating cut or travel,
  1828. fast or feedrate speed.
  1829. """
  1830. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1831. # Results go here
  1832. geometry = []
  1833. # TODO: Merge into single parser?
  1834. gobjs = self.pre_parse(self.gcode)
  1835. # Last known instruction
  1836. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  1837. # Current path: temporary storage until tool is
  1838. # lifted or lowered.
  1839. path = [(0, 0)]
  1840. # Process every instruction
  1841. for gobj in gobjs:
  1842. ## Changing height
  1843. if 'Z' in gobj:
  1844. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  1845. print "WARNING: Non-orthogonal motion: From", current
  1846. print " To:", gobj
  1847. current['Z'] = gobj['Z']
  1848. # Store the path into geometry and reset path
  1849. if len(path) > 1:
  1850. geometry.append({"geom": LineString(path),
  1851. "kind": kind})
  1852. path = [path[-1]] # Start with the last point of last path.
  1853. if 'G' in gobj:
  1854. current['G'] = int(gobj['G'])
  1855. if 'X' in gobj or 'Y' in gobj:
  1856. if 'X' in gobj:
  1857. x = gobj['X']
  1858. else:
  1859. x = current['X']
  1860. if 'Y' in gobj:
  1861. y = gobj['Y']
  1862. else:
  1863. y = current['Y']
  1864. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  1865. if current['Z'] > 0:
  1866. kind[0] = 'T'
  1867. if current['G'] > 0:
  1868. kind[1] = 'S'
  1869. arcdir = [None, None, "cw", "ccw"]
  1870. if current['G'] in [0, 1]: # line
  1871. path.append((x, y))
  1872. if current['G'] in [2, 3]: # arc
  1873. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  1874. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  1875. start = arctan2(-gobj['J'], -gobj['I'])
  1876. stop = arctan2(-center[1]+y, -center[0]+x)
  1877. path += arc(center, radius, start, stop,
  1878. arcdir[current['G']],
  1879. self.steps_per_circ)
  1880. # Update current instruction
  1881. for code in gobj:
  1882. current[code] = gobj[code]
  1883. # There might not be a change in height at the
  1884. # end, therefore, see here too if there is
  1885. # a final path.
  1886. if len(path) > 1:
  1887. geometry.append({"geom": LineString(path),
  1888. "kind": kind})
  1889. self.gcode_parsed = geometry
  1890. return geometry
  1891. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  1892. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1893. # alpha={"T": 0.3, "C": 1.0}):
  1894. # """
  1895. # Creates a Matplotlib figure with a plot of the
  1896. # G-code job.
  1897. # """
  1898. # if tooldia is None:
  1899. # tooldia = self.tooldia
  1900. #
  1901. # fig = Figure(dpi=dpi)
  1902. # ax = fig.add_subplot(111)
  1903. # ax.set_aspect(1)
  1904. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  1905. # ax.set_xlim(xmin-margin, xmax+margin)
  1906. # ax.set_ylim(ymin-margin, ymax+margin)
  1907. #
  1908. # if tooldia == 0:
  1909. # for geo in self.gcode_parsed:
  1910. # linespec = '--'
  1911. # linecolor = color[geo['kind'][0]][1]
  1912. # if geo['kind'][0] == 'C':
  1913. # linespec = 'k-'
  1914. # x, y = geo['geom'].coords.xy
  1915. # ax.plot(x, y, linespec, color=linecolor)
  1916. # else:
  1917. # for geo in self.gcode_parsed:
  1918. # poly = geo['geom'].buffer(tooldia/2.0)
  1919. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1920. # edgecolor=color[geo['kind'][0]][1],
  1921. # alpha=alpha[geo['kind'][0]], zorder=2)
  1922. # ax.add_patch(patch)
  1923. #
  1924. # return fig
  1925. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  1926. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  1927. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  1928. """
  1929. Plots the G-code job onto the given axes.
  1930. :param axes: Matplotlib axes on which to plot.
  1931. :param tooldia: Tool diameter.
  1932. :param dpi: Not used!
  1933. :param margin: Not used!
  1934. :param color: Color specification.
  1935. :param alpha: Transparency specification.
  1936. :param tool_tolerance: Tolerance when drawing the toolshape.
  1937. :return: None
  1938. """
  1939. if tooldia is None:
  1940. tooldia = self.tooldia
  1941. if tooldia == 0:
  1942. for geo in self.gcode_parsed:
  1943. linespec = '--'
  1944. linecolor = color[geo['kind'][0]][1]
  1945. if geo['kind'][0] == 'C':
  1946. linespec = 'k-'
  1947. x, y = geo['geom'].coords.xy
  1948. axes.plot(x, y, linespec, color=linecolor)
  1949. else:
  1950. for geo in self.gcode_parsed:
  1951. poly = geo['geom'].buffer(tooldia/2.0).simplify(tool_tolerance)
  1952. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  1953. edgecolor=color[geo['kind'][0]][1],
  1954. alpha=alpha[geo['kind'][0]], zorder=2)
  1955. axes.add_patch(patch)
  1956. def create_geometry(self):
  1957. # TODO: This takes forever. Too much data?
  1958. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  1959. def polygon2gcode(self, polygon, tolerance=0):
  1960. """
  1961. Creates G-Code for the exterior and all interior paths
  1962. of a polygon.
  1963. :param polygon: A Shapely.Polygon
  1964. :type polygon: Shapely.Polygon
  1965. :param tolerance: All points in the simplified object will be within the
  1966. tolerance distance of the original geometry.
  1967. :type tolerance: float
  1968. :return: G-code to cut along polygon.
  1969. :rtype: str
  1970. """
  1971. if tolerance > 0:
  1972. target_polygon = polygon.simplify(tolerance)
  1973. else:
  1974. target_polygon = polygon
  1975. gcode = ""
  1976. t = "G0%d X%.4fY%.4f\n"
  1977. path = list(target_polygon.exterior.coords) # Polygon exterior
  1978. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1979. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1980. for pt in path[1:]:
  1981. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1982. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1983. for ints in target_polygon.interiors: # Polygon interiors
  1984. path = list(ints.coords)
  1985. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  1986. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  1987. for pt in path[1:]:
  1988. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  1989. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  1990. return gcode
  1991. def linear2gcode(self, linear, tolerance=0):
  1992. """
  1993. Generates G-code to cut along the linear feature.
  1994. :param linear: The path to cut along.
  1995. :type: Shapely.LinearRing or Shapely.Linear String
  1996. :param tolerance: All points in the simplified object will be within the
  1997. tolerance distance of the original geometry.
  1998. :type tolerance: float
  1999. :return: G-code to cut alon the linear feature.
  2000. :rtype: str
  2001. """
  2002. if tolerance > 0:
  2003. target_linear = linear.simplify(tolerance)
  2004. else:
  2005. target_linear = linear
  2006. gcode = ""
  2007. t = "G0%d X%.4fY%.4f\n"
  2008. path = list(target_linear.coords)
  2009. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2010. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2011. for pt in path[1:]:
  2012. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2013. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2014. return gcode
  2015. def point2gcode(self, point):
  2016. # TODO: This is not doing anything.
  2017. gcode = ""
  2018. t = "G0%d X%.4fY%.4f\n"
  2019. path = list(point.coords)
  2020. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2021. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2022. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2023. def scale(self, factor):
  2024. """
  2025. Scales all the geometry on the XY plane in the object by the
  2026. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2027. not altered.
  2028. :param factor: Number by which to scale the object.
  2029. :type factor: float
  2030. :return: None
  2031. :rtype: None
  2032. """
  2033. for g in self.gcode_parsed:
  2034. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2035. self.create_geometry()
  2036. def offset(self, vect):
  2037. """
  2038. Offsets all the geometry on the XY plane in the object by the
  2039. given vector.
  2040. :param vect: (x, y) offset vector.
  2041. :type vect: tuple
  2042. :return: None
  2043. """
  2044. dx, dy = vect
  2045. for g in self.gcode_parsed:
  2046. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2047. self.create_geometry()
  2048. # def get_bounds(geometry_set):
  2049. # xmin = Inf
  2050. # ymin = Inf
  2051. # xmax = -Inf
  2052. # ymax = -Inf
  2053. #
  2054. # #print "Getting bounds of:", str(geometry_set)
  2055. # for gs in geometry_set:
  2056. # try:
  2057. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2058. # xmin = min([xmin, gxmin])
  2059. # ymin = min([ymin, gymin])
  2060. # xmax = max([xmax, gxmax])
  2061. # ymax = max([ymax, gymax])
  2062. # except:
  2063. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2064. #
  2065. # return [xmin, ymin, xmax, ymax]
  2066. def get_bounds(geometry_list):
  2067. xmin = Inf
  2068. ymin = Inf
  2069. xmax = -Inf
  2070. ymax = -Inf
  2071. #print "Getting bounds of:", str(geometry_set)
  2072. for gs in geometry_list:
  2073. try:
  2074. gxmin, gymin, gxmax, gymax = gs.bounds()
  2075. xmin = min([xmin, gxmin])
  2076. ymin = min([ymin, gymin])
  2077. xmax = max([xmax, gxmax])
  2078. ymax = max([ymax, gymax])
  2079. except:
  2080. print "DEV WARNING: Tried to get bounds of empty geometry."
  2081. return [xmin, ymin, xmax, ymax]
  2082. def arc(center, radius, start, stop, direction, steps_per_circ):
  2083. """
  2084. Creates a list of point along the specified arc.
  2085. :param center: Coordinates of the center [x, y]
  2086. :type center: list
  2087. :param radius: Radius of the arc.
  2088. :type radius: float
  2089. :param start: Starting angle in radians
  2090. :type start: float
  2091. :param stop: End angle in radians
  2092. :type stop: float
  2093. :param direction: Orientation of the arc, "CW" or "CCW"
  2094. :type direction: string
  2095. :param steps_per_circ: Number of straight line segments to
  2096. represent a circle.
  2097. :type steps_per_circ: int
  2098. :return: The desired arc, as list of tuples
  2099. :rtype: list
  2100. """
  2101. # TODO: Resolution should be established by fraction of total length, not angle.
  2102. da_sign = {"cw": -1.0, "ccw": 1.0}
  2103. points = []
  2104. if direction == "ccw" and stop <= start:
  2105. stop += 2*pi
  2106. if direction == "cw" and stop >= start:
  2107. stop -= 2*pi
  2108. angle = abs(stop - start)
  2109. #angle = stop-start
  2110. steps = max([int(ceil(angle/(2*pi)*steps_per_circ)), 2])
  2111. delta_angle = da_sign[direction]*angle*1.0/steps
  2112. for i in range(steps+1):
  2113. theta = start + delta_angle*i
  2114. points.append((center[0]+radius*cos(theta), center[1]+radius*sin(theta)))
  2115. return points
  2116. def clear_poly(poly, tooldia, overlap=0.1):
  2117. """
  2118. Creates a list of Shapely geometry objects covering the inside
  2119. of a Shapely.Polygon. Use for removing all the copper in a region
  2120. or bed flattening.
  2121. :param poly: Target polygon
  2122. :type poly: Shapely.Polygon
  2123. :param tooldia: Diameter of the tool
  2124. :type tooldia: float
  2125. :param overlap: Fraction of the tool diameter to overlap
  2126. in each pass.
  2127. :type overlap: float
  2128. :return: list of Shapely.Polygon
  2129. :rtype: list
  2130. """
  2131. poly_cuts = [poly.buffer(-tooldia/2.0)]
  2132. while True:
  2133. poly = poly_cuts[-1].buffer(-tooldia*(1-overlap))
  2134. if poly.area > 0:
  2135. poly_cuts.append(poly)
  2136. else:
  2137. break
  2138. return poly_cuts
  2139. def find_polygon(poly_set, point):
  2140. """
  2141. Return the first polygon in the list of polygons poly_set
  2142. that contains the given point.
  2143. """
  2144. p = Point(point)
  2145. for poly in poly_set:
  2146. if poly.contains(p):
  2147. return poly
  2148. return None
  2149. def to_dict(obj):
  2150. """
  2151. Makes a Shapely geometry object into serializeable form.
  2152. :param obj: Shapely geometry.
  2153. :type obj: BaseGeometry
  2154. :return: Dictionary with serializable form if ``obj`` was
  2155. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  2156. """
  2157. if isinstance(obj, ApertureMacro):
  2158. return {
  2159. "__class__": "ApertureMacro",
  2160. "__inst__": obj.to_dict()
  2161. }
  2162. if isinstance(obj, BaseGeometry):
  2163. return {
  2164. "__class__": "Shply",
  2165. "__inst__": sdumps(obj)
  2166. }
  2167. return obj
  2168. def dict2obj(d):
  2169. """
  2170. Default deserializer.
  2171. :param d: Serializable dictionary representation of an object
  2172. to be reconstructed.
  2173. :return: Reconstructed object.
  2174. """
  2175. if '__class__' in d and '__inst__' in d:
  2176. if d['__class__'] == "Shply":
  2177. return sloads(d['__inst__'])
  2178. if d['__class__'] == "ApertureMacro":
  2179. am = ApertureMacro()
  2180. am.from_dict(d['__inst__'])
  2181. return am
  2182. return d
  2183. else:
  2184. return d
  2185. def plotg(geo):
  2186. try:
  2187. _ = iter(geo)
  2188. except:
  2189. geo = [geo]
  2190. for g in geo:
  2191. if type(g) == Polygon:
  2192. x, y = g.exterior.coords.xy
  2193. plot(x, y)
  2194. for ints in g.interiors:
  2195. x, y = ints.coords.xy
  2196. plot(x, y)
  2197. continue
  2198. if type(g) == LineString or type(g) == LinearRing:
  2199. x, y = g.coords.xy
  2200. plot(x, y)
  2201. continue
  2202. if type(g) == Point:
  2203. x, y = g.coords.xy
  2204. plot(x, y, 'o')
  2205. continue
  2206. try:
  2207. _ = iter(g)
  2208. plotg(g)
  2209. except:
  2210. print "Cannot plot:", str(type(g))
  2211. continue
  2212. def parse_gerber_number(strnumber, frac_digits):
  2213. """
  2214. Parse a single number of Gerber coordinates.
  2215. :param strnumber: String containing a number in decimal digits
  2216. from a coordinate data block, possibly with a leading sign.
  2217. :type strnumber: str
  2218. :param frac_digits: Number of digits used for the fractional
  2219. part of the number
  2220. :type frac_digits: int
  2221. :return: The number in floating point.
  2222. :rtype: float
  2223. """
  2224. return int(strnumber)*(10**(-frac_digits))
  2225. def parse_gerber_coords(gstr, int_digits, frac_digits):
  2226. """
  2227. Parse Gerber coordinates
  2228. :param gstr: Line of G-Code containing coordinates.
  2229. :type gstr: str
  2230. :param int_digits: Number of digits in integer part of a number.
  2231. :type int_digits: int
  2232. :param frac_digits: Number of digits in frac_digits part of a number.
  2233. :type frac_digits: int
  2234. :return: [x, y] coordinates.
  2235. :rtype: list
  2236. """
  2237. global gerbx, gerby
  2238. xindex = gstr.find("X")
  2239. yindex = gstr.find("Y")
  2240. index = gstr.find("D")
  2241. if xindex == -1:
  2242. x = gerbx
  2243. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  2244. elif yindex == -1:
  2245. y = gerby
  2246. x = int(gstr[(xindex+1):index])*(10**(-frac_digits))
  2247. else:
  2248. x = int(gstr[(xindex+1):yindex])*(10**(-frac_digits))
  2249. y = int(gstr[(yindex+1):index])*(10**(-frac_digits))
  2250. gerbx = x
  2251. gerby = y
  2252. return [x, y]