shapes.py 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107
  1. from __future__ import division
  2. from __future__ import unicode_literals
  3. from __future__ import print_function
  4. from __future__ import absolute_import
  5. from future import standard_library
  6. standard_library.install_aliases()
  7. from builtins import input
  8. from builtins import zip
  9. from builtins import str
  10. from builtins import range
  11. from builtins import *
  12. from builtins import object
  13. from numpy import linspace, sin, cos, pi, array, asarray, ndarray, sqrt, abs
  14. import pprint, copy, glob, os
  15. from math import radians
  16. from io import BytesIO
  17. from ruamel.yaml import YAML
  18. from PIL import Image
  19. import ast
  20. from collections import *
  21. import requests
  22. from .MatplotlibDraw import MatplotlibDraw
  23. drawing_tool = MatplotlibDraw()
  24. class Sketch():
  25. """
  26. Yaml to Pysketcher native features implementation
  27. """
  28. def __init__(self, container, name="unknown"):
  29. """
  30. create a Sketch class instance providing the holding container
  31. """
  32. self.sketch = OrderedDict([('name',name),('parts',[])]) # repository used to collect all sketch parts
  33. self.container = container # save the container reference as an class instance variable
  34. @staticmethod
  35. def matplotlib2SVG():
  36. """
  37. Save sketch as a svg string
  38. """
  39. f = BytesIO()
  40. drawing_tool.mpl.savefig(f, format="svg")
  41. return f.getvalue()
  42. @staticmethod
  43. def matplotlib2PNG():
  44. """
  45. Save sketch as a python .png image
  46. """
  47. f = BytesIO()
  48. drawing_tool.mpl.gcf().canvas.print_png(f)
  49. img = Image.open(f)
  50. return img
  51. def sVe(self, key, expression, sketchpart):
  52. """
  53. sVe: Validate sketch part expression
  54. given an expression from a sketch part, check if valid or not
  55. provides a string feedback if error else return 1
  56. """
  57. try:
  58. root = ast.parse(expression)
  59. except Exception as e:
  60. return f"{sketchpart}/{key}: '''{expression}''' parse error {str(e)}"
  61. names = {node.id for node in ast.walk(root) if isinstance(node, ast.Name)}
  62. for name in names:
  63. if name not in self.container:
  64. return f"{sketchpart}/{key}: {name} in {expression} is not defined"
  65. return 1
  66. def url2Sketch(self, url):
  67. """
  68. get a sketch given an url
  69. """
  70. r = requests.get(url) #, auth=('user', 'pass'))
  71. if r.status_code == 200:
  72. sketchstring = r.text
  73. return self.string2Sketch(sketchstring)
  74. return False
  75. def sketch2File(self, filePath):
  76. """
  77. dump a sketch to file
  78. """
  79. yaml = YAML()
  80. file = open(filePath,"w")
  81. yaml.dump(self.sketch,file)
  82. file.close()
  83. def file2Sketch(self,filePath):
  84. """
  85. load a sketch from file
  86. """
  87. yaml = YAML()
  88. file = open(filePath, "r")
  89. sketchstring = file.read()
  90. file.close()
  91. return self.string2Sketch(sketchstring)
  92. def sketch2String(self):
  93. """
  94. dump sketch as a string
  95. """
  96. yaml = YAML()
  97. f = BytesIO()
  98. yaml.dump(self.sketch,f)
  99. return f.getvalue()
  100. def string2Sketch(self,sketchstring):
  101. """
  102. load a sketch from string
  103. """
  104. yaml = YAML()
  105. sketch = yaml.load(sketchstring)
  106. self.sketch = OrderedDict([('name',sketch['name']),('parts',[])])
  107. for part in sketch['parts']:
  108. self.sketch['parts'].append(part)
  109. if not self.add(part['name'],part['shapes']):
  110. return False
  111. return True
  112. def append(self, sketchpart):
  113. """
  114. Append and Parse a string sketch part into a sketch and its associated container.
  115. A sketch is just the concatenation of all the sketch parts
  116. name specifices the 'name' of the sketch part
  117. A container is a name space which holds
  118. - all the libraries references needed to create pysketcher shapes
  119. - all the variable providing shapes dimensions or position
  120. - all the shapes needed to create the shapes it defines
  121. """
  122. yaml = YAML()
  123. psketch = yaml.load(sketchpart)
  124. self.sketch['parts'].append(psketch)
  125. sketch_name = psketch["name"]
  126. gwd = psketch['shapes']
  127. return self.add(sketch_name, gwd)
  128. def normalize(self, input):
  129. # print(input," ",type(input))
  130. t = str(type(input))
  131. if t == "<class 'str'>" or t == "<class 'ruamel.yaml.scalarstring.LiteralScalarString'>":
  132. return "".join([s.strip() for s in input.split("\n")])
  133. else:
  134. return input
  135. def add(self, sketch_name, gwd):
  136. """
  137. actual append work common to various different calls
  138. """
  139. for _k in list(gwd.keys()):
  140. if _k == "stop":
  141. return True
  142. _c = gwd[_k]
  143. _t = str(type(_c))
  144. if _k == "libraries":
  145. for l in _c:
  146. _r = self.sVe(_k, l, sketch_name)
  147. if type(_r) == str:
  148. print(_r)
  149. return False
  150. try:
  151. exec(l,self.container)
  152. except Exception as e:
  153. print(f"{_k} / {l} error: {str(e)}")
  154. return False
  155. #print(_k, _c, _t)
  156. if _t == "<class 'ruamel.yaml.scalarfloat.ScalarFloat'>" or \
  157. _t == "<class 'str'>" or _t == "<class 'int'>" or _t == "<class 'ruamel.yaml.scalarstring.LiteralScalarString'>":
  158. _expression = f"{self.normalize(_c)}".replace("<bslash>","\\")
  159. _formula = f"{_k} = {_expression}"
  160. #print(_formula)
  161. _r = self.sVe(_k, _expression, sketch_name)
  162. if type(_r) == str:
  163. print(_r)
  164. return False
  165. try:
  166. exec(_formula,self.container)
  167. except Exception as e:
  168. print(f"{_formula} error: {str(e)}")
  169. return False
  170. elif _t == "<class 'ruamel.yaml.comments.CommentedMap'>":
  171. #print(_c)
  172. _keys = list(_c.keys())
  173. #print(_keys)
  174. if 'formula' in _keys:
  175. _expression = f"{self.normalize(_c['formula'])}".replace("<bslash>","\\")
  176. _formula = f"{_k} = {_expression}"
  177. #print(_formula)
  178. _r = self.sVe(_k, _expression, sketch_name)
  179. if type(_r) == str:
  180. print(_r)
  181. return False
  182. try:
  183. exec(_formula,self.container)
  184. except Exception as e:
  185. print(f"{_formula} error: {str(e)}")
  186. return False
  187. # if the new object is a shape and has the sketch name, set this shape name as the sketch name
  188. if issubclass(type(self.container[_k]), Shape):
  189. if _k == sketch_name:
  190. self.container[_k].set_name(sketch_name)
  191. if 'style' in _keys:
  192. for _style in _c["style"]:
  193. # x_const.set_linestyle('dotted')
  194. _param = _c["style"][_style]
  195. __t = str(type(_param))
  196. #print(__t)
  197. if __t == "<class 'int'>":
  198. if _style == 'shadow':
  199. _style = f"{_k}.set_{_style}(pixel_displacement={_param})"
  200. else:
  201. _style = f"{_k}.set_{_style}({_param})"
  202. try:
  203. exec(_style,self.container)
  204. except Exception as e:
  205. print(f"{_style} error: {str(e)}")
  206. return False
  207. else:
  208. if 'filled_curves' == _style:
  209. if 'color' in list(_param.keys()):
  210. _style = f"{_k}.set_{_style}(color='{_param['color']}')"
  211. try:
  212. exec(_style,self.container)
  213. except Exception as e:
  214. print(f"{_style} error: {str(e)}")
  215. return False
  216. if 'pattern' in list(_param.keys()):
  217. _style = f"{_k}.set_{_style}(pattern='{_param['pattern']}')"
  218. try:
  219. exec(_style,self.container)
  220. except Exception as e:
  221. print(f"{_style} error: {str(e)}")
  222. return False
  223. else:
  224. _style = f"{_k}.set_{_style}('{_param}')"
  225. try:
  226. exec(_style,self.container)
  227. except Exception as e:
  228. print(f"{_style} error: {str(e)}")
  229. return False
  230. #print(_style)
  231. if 'transform' in _keys:
  232. #print(_c['transform'])
  233. if str(type(_c['transform'])) == "<class 'str'>":
  234. _t = f"{_k}.{self.normalize(_c['transform'])}"
  235. #print(_t)
  236. _r = self.sVe(_k, _formula, sketch_name)
  237. if type(_r) == str:
  238. print(_r)
  239. return False
  240. try:
  241. exec(_t,self.container)
  242. except Exception as e:
  243. print(f"{_t} error: {str(e)}")
  244. return False
  245. else:
  246. for _transform in _c["transform"]:
  247. # x_const.rotate(-theta, contact)
  248. _t = f"{_k}.{self.normalize(_transform)}"
  249. #print(_t)
  250. _r = self.sVe(_k, _t, sketch_name)
  251. if type(_r) == str:
  252. print(_r)
  253. return False
  254. try:
  255. exec(_t,self.container)
  256. except Exception as e:
  257. print(f"{_t} error: {str(e)}")
  258. return False
  259. if "action" in _keys:
  260. _action = self.normalize(_c["action"])
  261. #print(_action)
  262. _r = self.sVe(_k, _action, sketch_name)
  263. if type(_r) == str:
  264. print(_r)
  265. return False
  266. try:
  267. exec(_action,self.container)
  268. except Exception as e:
  269. print(f"{_k}/{_action} error: {str(e)}")
  270. return False
  271. return True
  272. def point(x, y, check_inside=False):
  273. for obj, name in zip([x, y], ['x', 'y']):
  274. if isinstance(obj, (float,int)):
  275. pass
  276. elif isinstance(obj, ndarray):
  277. if obj.size == 1:
  278. pass
  279. else:
  280. raise TypeError('%s=%s of type %d has length=%d > 1' %
  281. (name, obj, type(obj), obj.size))
  282. else:
  283. raise TypeError('%s=%s is of wrong type %d' %
  284. (name, obj, type(obj)))
  285. if check_inside:
  286. ok, msg = drawing_tool.inside((x,y), exception=True)
  287. if not ok:
  288. print(msg)
  289. return array((x, y), dtype=float)
  290. def distance(p1, p2):
  291. p1 = arr2D(p1); p2 = arr2D(p2)
  292. d = p2 - p1
  293. return sqrt(d[0]**2 + d[1]**2)
  294. def unit_vec(x, y=None):
  295. """Return unit vector of the vector (x,y), or just x if x is a 2D point."""
  296. if isinstance(x, (float,int)) and isinstance(y, (float,int)):
  297. x = point(x, y)
  298. elif isinstance(x, (list,tuple,ndarray)) and y is None:
  299. return arr2D(x)/sqrt(x[0]**2 + x[1]**2)
  300. else:
  301. raise TypeError('x=%s is %s, must be float or ndarray 2D point' %
  302. (x, type(x)))
  303. def arr2D(x, check_inside=False):
  304. if isinstance(x, (tuple,list,ndarray)):
  305. if len(x) == 2:
  306. pass
  307. else:
  308. raise ValueError('x=%s has length %d, not 2' % (x, len(x)))
  309. else:
  310. if isinstance(x, (Point)):
  311. x = (x.x,x.y)
  312. else:
  313. raise TypeError('x=%s must be list/tuple/ndarray, not %s' %
  314. (x, type(x)))
  315. if check_inside:
  316. ok, msg = drawing_tool.inside(x, exception=True)
  317. if not ok:
  318. print(msg)
  319. return asarray(x, dtype=float)
  320. def _is_sequence(seq, length=None,
  321. can_be_None=False, error_message=True):
  322. if can_be_None:
  323. legal_types = (list,tuple,ndarray,None)
  324. else:
  325. legal_types = (list,tuple,ndarray)
  326. if isinstance(seq, legal_types):
  327. if length is not None:
  328. if length == len(seq):
  329. return True
  330. elif error_message:
  331. raise TypeError('sequence %s is not a sequence but %s; must be %s of length %d' %
  332. (str(seq), type(seq),
  333. ', '.join([str(t) for t in legal_types]),
  334. len(seq)))
  335. else:
  336. return False
  337. else:
  338. return True
  339. elif error_message:
  340. raise TypeError('sequence %s is not a sequence but %s, %s; must be %s' %
  341. (str(seq), seq.__class__.__name__, type(seq),
  342. ','.join([str(t)[5:-1] for t in legal_types])))
  343. else:
  344. return False
  345. def is_sequence(*sequences, **kwargs):
  346. length = kwargs.get('length', 2)
  347. can_be_None = kwargs.get('can_be_None', False)
  348. error_message = kwargs.get('error_message', True)
  349. check_inside = kwargs.get('check_inside', False)
  350. for x in sequences:
  351. _is_sequence(x, length=length, can_be_None=can_be_None,
  352. error_message=error_message)
  353. if check_inside:
  354. ok, msg = drawing_tool.inside(x, exception=True)
  355. if not ok:
  356. print(msg)
  357. def animate(fig, time_points, action, moviefiles=False,
  358. pause_per_frame=0.5, show_screen_graphics=True,
  359. title=None,
  360. **action_kwargs):
  361. if moviefiles:
  362. # Clean up old frame files
  363. framefilestem = 'tmp_frame_'
  364. framefiles = glob.glob('%s*.png' % framefilestem)
  365. for framefile in framefiles:
  366. os.remove(framefile)
  367. for n, t in enumerate(time_points):
  368. drawing_tool.erase()
  369. action(t, fig, **action_kwargs)
  370. #could demand returning fig, but in-place modifications
  371. #are done anyway
  372. #fig = action(t, fig)
  373. #if fig is None:
  374. # raise TypeError(
  375. # 'animate: action returns None, not fig\n'
  376. # '(a Shape object with the whole figure)')
  377. fig.draw()
  378. drawing_tool.display(title=title, show=show_screen_graphics)
  379. if moviefiles:
  380. drawing_tool.savefig('%s%04d.png' % (framefilestem, n),
  381. crop=False)
  382. if moviefiles:
  383. return '%s%%04d.png' % framefilestem
  384. """
  385. def save():
  386. os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")
  387. """
  388. class Shape(object):
  389. """
  390. Superclass for drawing different geometric shapes.
  391. Subclasses define shapes, but drawing, rotation, translation,
  392. etc. are done in generic functions in this superclass.
  393. """
  394. def __init__(self):
  395. """
  396. Never to be called from subclasses.
  397. """
  398. raise NotImplementedError(
  399. 'class %s must implement __init__,\nwhich defines '
  400. 'self.shapes as a dict (or list) of Shape objects\n'
  401. 'Do not call Shape.__init__!' % \
  402. self.__class__.__name__)
  403. def set_name(self, name):
  404. self.name = name
  405. return self
  406. def get_name(self):
  407. return self.name if hasattr(self, 'name') else 'no_name'
  408. def __iter__(self):
  409. # We iterate over self.shapes many places, and will
  410. # get here if self.shapes is just a Shape object and
  411. # not the assumed dict/list.
  412. print('Warning: class %s does not define self.shapes\n'\
  413. 'as a dict of Shape objects')
  414. return [self] # Make the iteration work
  415. def copy(self):
  416. return copy.deepcopy(self)
  417. def __getitem__(self, name):
  418. """
  419. Allow indexing like::
  420. obj1['name1']['name2']
  421. all the way down to ``Curve`` or ``Point`` (``Text``)
  422. objects.
  423. """
  424. if hasattr(self, 'shapes'):
  425. if name in self.shapes:
  426. return self.shapes[name]
  427. else:
  428. for shape in self.shapes:
  429. if isinstance(self.shapes[shape], (Curve,Point)):
  430. # Indexing of Curve/Point/Text is not possible
  431. raise TypeError(
  432. 'Index "%s" (%s) is illegal' %
  433. (name, self.__class__.__name__))
  434. return self.shapes[shape][name]
  435. else:
  436. raise Exception('This is a bug in __getitem__')
  437. def __setitem__(self, name, value):
  438. """
  439. Allow assignment like::
  440. obj1['name1']['name2'] = value
  441. all the way down to ``Curve`` or ``Point`` (``Text``)
  442. objects.
  443. """
  444. if hasattr(self, 'shapes'):
  445. self.shapes[name] = value
  446. else:
  447. raise Exception('Cannot assign')
  448. def _for_all_shapes(self, func, *args, **kwargs):
  449. verbose = kwargs.get('verbose', 0)
  450. if not hasattr(self, 'shapes'):
  451. # When self.shapes is lacking, we either come to
  452. # a special implementation of func or we come here
  453. # because Shape.func is just inherited. This is
  454. # an error if the class is not Curve or Point
  455. if isinstance(self, (Curve, Point)):
  456. return # ok: no shapes, but object is a curve or point end leaf
  457. else:
  458. raise AttributeError('class %s has no shapes attribute!' %
  459. self.__class__.__name__)
  460. is_dict = True if isinstance(self.shapes, dict) else False
  461. for k, shape in enumerate(self.shapes):
  462. if is_dict:
  463. shape_name = shape
  464. shape = self.shapes[shape]
  465. else:
  466. shape_name = k # use index as name if list (not dict)
  467. if not isinstance(shape, Shape):
  468. if isinstance(shape, dict):
  469. raise TypeError(
  470. 'class %s has a self.shapes member "%s" that is just\n'
  471. 'a plain dictionary,\n%s\n'
  472. 'Did you mean to embed this dict in a Composition\n'
  473. 'object?' % (self.__class__.__name__, shape_name,
  474. str(shape)))
  475. elif isinstance(shape, (list,tuple)):
  476. raise TypeError(
  477. 'class %s has self.shapes member "%s" containing\n'
  478. 'a %s object %s,\n'
  479. 'Did you mean to embed this list in a Composition\n'
  480. 'object?' % (self.__class__.__name__, shape_name,
  481. type(shape), str(shape)))
  482. elif shape is None:
  483. raise TypeError(
  484. 'class %s has a self.shapes member "%s" that is None.\n'
  485. 'Some variable name is wrong, or some function\n'
  486. 'did not return the right object...' \
  487. % (self.__class__.__name__, shape_name))
  488. else:
  489. raise TypeError(
  490. 'class %s has a self.shapes member "%s" of %s which '
  491. 'is not a Shape object\n%s' %
  492. (self.__class__.__name__, shape_name, type(shape),
  493. pprint.pformat(self.shapes)))
  494. if isinstance(shape, Curve):
  495. shape.name = shape_name
  496. if verbose > 0:
  497. print('calling %s.%s' % (shape_name, func))
  498. getattr(shape, func)(*args, **kwargs)
  499. def draw(self, verbose=0):
  500. self._for_all_shapes('draw', verbose=verbose)
  501. return self
  502. def draw_dimensions(self):
  503. if hasattr(self, 'dimensions'):
  504. for shape in self.dimensions:
  505. self.dimensions[shape].draw()
  506. return self
  507. else:
  508. #raise AttributeError('no self.dimensions dict for defining dimensions of class %s' % self.__classname__.__name__)
  509. return self
  510. def rotate(self, angle, center):
  511. is_sequence(center, length=2)
  512. self._for_all_shapes('rotate', angle, center)
  513. return self
  514. def translate(self, vec):
  515. is_sequence(vec, length=2)
  516. self._for_all_shapes('translate', vec)
  517. return self
  518. def scale(self, factor):
  519. self._for_all_shapes('scale', factor)
  520. return self
  521. def deform(self, displacement_function):
  522. self._for_all_shapes('deform', displacement_function)
  523. return self
  524. def minmax_coordinates(self, minmax=None):
  525. if minmax is None:
  526. minmax = {'xmin': 1E+20, 'xmax': -1E+20,
  527. 'ymin': 1E+20, 'ymax': -1E+20}
  528. self._for_all_shapes('minmax_coordinates', minmax)
  529. return minmax
  530. def recurse(self, name, indent=0):
  531. if not isinstance(self.shapes, dict):
  532. raise TypeError('recurse works only with dict self.shape, not %s' %
  533. type(self.shapes))
  534. space = ' '*indent
  535. print(space, '%s: %s.shapes has entries' % \
  536. (self.__class__.__name__, name), \
  537. str(list(self.shapes.keys()))[1:-1])
  538. for shape in self.shapes:
  539. print(space, end=' ')
  540. print('call %s.shapes["%s"].recurse("%s", %d)' % \
  541. (name, shape, shape, indent+2))
  542. self.shapes[shape].recurse(shape, indent+2)
  543. def graphviz_dot(self, name, classname=True):
  544. if not isinstance(self.shapes, dict):
  545. raise TypeError('recurse works only with dict self.shape, not %s' %
  546. type(self.shapes))
  547. dotfile = name + '.dot'
  548. pngfile = name + '.png'
  549. if classname:
  550. name = r"%s:\n%s" % (self.__class__.__name__, name)
  551. couplings = self._object_couplings(name, classname=classname)
  552. # Insert counter for similar names
  553. from collections import defaultdict
  554. count = defaultdict(lambda: 0)
  555. couplings2 = []
  556. for i in range(len(couplings)):
  557. parent, child = couplings[i]
  558. count[child] += 1
  559. parent += ' (%d)' % count[parent]
  560. child += ' (%d)' % count[child]
  561. couplings2.append((parent, child))
  562. print('graphviz', couplings, count)
  563. # Remove counter for names there are only one of
  564. for i in range(len(couplings)):
  565. parent2, child2 = couplings2[i]
  566. parent, child = couplings[i]
  567. if count[parent] > 1:
  568. parent = parent2
  569. if count[child] > 1:
  570. child = child2
  571. couplings[i] = (parent, child)
  572. print(couplings)
  573. f = open(dotfile, 'w')
  574. f.write('digraph G {\n')
  575. for parent, child in couplings:
  576. f.write('"%s" -> "%s";\n' % (parent, child))
  577. f.write('}\n')
  578. f.close()
  579. print('Run dot -Tpng -o %s %s' % (pngfile, dotfile))
  580. def _object_couplings(self, parent, couplings=[], classname=True):
  581. """Find all couplings of parent and child objects in a figure."""
  582. for shape in self.shapes:
  583. if classname:
  584. childname = r"%s:\n%s" % \
  585. (self.shapes[shape].__class__.__name__, shape)
  586. else:
  587. childname = shape
  588. couplings.append((parent, childname))
  589. self.shapes[shape]._object_couplings(childname, couplings,
  590. classname)
  591. return couplings
  592. def set_linestyle(self, style):
  593. styles = ('solid', 'dashed', 'dashdot', 'dotted')
  594. if style not in styles:
  595. raise ValueError('%s: style=%s must be in %s' %
  596. (self.__class__.__name__ + '.set_linestyle:',
  597. style, str(styles)))
  598. self._for_all_shapes('set_linestyle', style)
  599. return self
  600. def set_linewidth(self, width):
  601. if not isinstance(width, int) and width >= 0:
  602. raise ValueError('%s: width=%s must be positive integer' %
  603. (self.__class__.__name__ + '.set_linewidth:',
  604. width))
  605. self._for_all_shapes('set_linewidth', width)
  606. return self
  607. def set_linecolor(self, color):
  608. if color in drawing_tool.line_colors:
  609. color = drawing_tool.line_colors[color]
  610. elif color in list(drawing_tool.line_colors.values()):
  611. pass # color is ok
  612. else:
  613. raise ValueError('%s: invalid color "%s", must be in %s' %
  614. (self.__class__.__name__ + '.set_linecolor:',
  615. color, list(drawing_tool.line_colors.keys())))
  616. self._for_all_shapes('set_linecolor', color)
  617. return self
  618. def set_arrow(self, style):
  619. styles = ('->', '<-', '<->')
  620. if not style in styles:
  621. raise ValueError('%s: style=%s must be in %s' %
  622. (self.__class__.__name__ + '.set_arrow:',
  623. style, styles))
  624. self._for_all_shapes('set_arrow', style)
  625. return self
  626. def set_filled_curves(self, color='', pattern=''):
  627. if color in drawing_tool.line_colors:
  628. color = drawing_tool.line_colors[color]
  629. elif color in list(drawing_tool.line_colors.values()):
  630. pass # color is ok
  631. else:
  632. raise ValueError('%s: invalid color "%s", must be in %s' %
  633. (self.__class__.__name__ + '.set_filled_curves:',
  634. color, list(drawing_tool.line_colors.keys())))
  635. self._for_all_shapes('set_filled_curves', color, pattern)
  636. return self
  637. def set_shadow(self, pixel_displacement=3):
  638. self._for_all_shapes('set_shadow', pixel_displacement)
  639. return self
  640. def show_hierarchy(self, indent=0, format='std'):
  641. """Recursive pretty print of hierarchy of objects."""
  642. if not isinstance(self.shapes, dict):
  643. print('cannot print hierarchy when %s.shapes is not a dict' % \
  644. self.__class__.__name__)
  645. s = ''
  646. if format == 'dict':
  647. s += '{'
  648. for shape in self.shapes:
  649. if format == 'dict':
  650. shape_str = repr(shape) + ':'
  651. elif format == 'plain':
  652. shape_str = shape
  653. else:
  654. shape_str = shape + ':'
  655. if format == 'dict' or format == 'plain':
  656. class_str = ''
  657. else:
  658. class_str = ' (%s)' % \
  659. self.shapes[shape].__class__.__name__
  660. s += '\n%s%s%s %s,' % (
  661. ' '*indent,
  662. shape_str,
  663. class_str,
  664. self.shapes[shape].show_hierarchy(indent+4, format))
  665. if format == 'dict':
  666. s += '}'
  667. return s
  668. def __str__(self):
  669. """Display hierarchy with minimum information (just object names)."""
  670. return self.show_hierarchy(format='plain')
  671. def __repr__(self):
  672. """Display hierarchy as a dictionary."""
  673. return self.show_hierarchy(format='dict')
  674. #return pprint.pformat(self.shapes)
  675. class Curve(Shape):
  676. """General curve as a sequence of (x,y) coordinates."""
  677. def __init__(self, x, y):
  678. """
  679. `x`, `y`: arrays holding the coordinates of the curve.
  680. """
  681. self.x = asarray(x, dtype=float)
  682. self.y = asarray(y, dtype=float)
  683. #self.shapes must not be defined in this class
  684. #as self.shapes holds children objects:
  685. #Curve has no children (end leaf of self.shapes tree)
  686. self.linestyle = None
  687. self.linewidth = None
  688. self.linecolor = None
  689. self.fillcolor = None
  690. self.fillpattern = None
  691. self.arrow = None
  692. self.shadow = False
  693. self.name = None # name of object that this Curve represents
  694. def inside_plot_area(self, verbose=True):
  695. """Check that all coordinates are within drawing_tool's area."""
  696. xmin, xmax = self.x.min(), self.x.max()
  697. ymin, ymax = self.y.min(), self.y.max()
  698. t = drawing_tool
  699. inside = True
  700. if not hasattr(t, 'xmin'):
  701. return None # drawing area is not defined
  702. if xmin < t.xmin:
  703. inside = False
  704. if verbose:
  705. print('x_min=%g < plot area x_min=%g' % (xmin, t.xmin))
  706. if xmax > t.xmax:
  707. inside = False
  708. if verbose:
  709. print('x_max=%g > plot area x_max=%g' % (xmax, t.xmax))
  710. if ymin < t.ymin:
  711. inside = False
  712. if verbose:
  713. print('y_min=%g < plot area y_min=%g' % (ymin, t.ymin))
  714. if ymax > t.ymax:
  715. inside = False
  716. if verbose:
  717. print('y_max=%g > plot area y_max=%g' % (ymax, t.ymax))
  718. return inside
  719. def draw(self, verbose=0):
  720. """
  721. Send the curve to the plotting engine. That is, convert
  722. coordinate information in self.x and self.y, together
  723. with optional settings of linestyles, etc., to
  724. plotting commands for the chosen engine.
  725. """
  726. self.inside_plot_area()
  727. drawing_tool.plot_curve(
  728. self.x, self.y,
  729. self.linestyle, self.linewidth, self.linecolor,
  730. self.arrow, self.fillcolor, self.fillpattern,
  731. self.shadow, self.name)
  732. if verbose:
  733. print('drawing Curve object with %d points' % len(self.x))
  734. def rotate(self, angle, center):
  735. """
  736. Rotate all coordinates: `angle` is measured in degrees and
  737. (`x`,`y`) is the "origin" of the rotation.
  738. """
  739. angle = radians(angle)
  740. x, y = center
  741. c = cos(angle); s = sin(angle)
  742. xnew = x + (self.x - x)*c - (self.y - y)*s
  743. ynew = y + (self.x - x)*s + (self.y - y)*c
  744. self.x = xnew
  745. self.y = ynew
  746. return self
  747. def scale(self, factor):
  748. """Scale all coordinates by `factor`: ``x = factor*x``, etc."""
  749. self.x = factor*self.x
  750. self.y = factor*self.y
  751. return self
  752. def translate(self, vec):
  753. """Translate all coordinates by a vector `vec`."""
  754. self.x += vec[0]
  755. self.y += vec[1]
  756. return self
  757. def deform(self, displacement_function):
  758. """Displace all coordinates according to displacement_function(x,y)."""
  759. for i in range(len(self.x)):
  760. self.x[i], self.y[i] = displacement_function(self.x[i], self.y[i])
  761. return self
  762. def minmax_coordinates(self, minmax=None):
  763. if minmax is None:
  764. minmax = {'xmin': [], 'xmax': [], 'ymin': [], 'ymax': []}
  765. minmax['xmin'] = min(self.x.min(), minmax['xmin'])
  766. minmax['xmax'] = max(self.x.max(), minmax['xmax'])
  767. minmax['ymin'] = min(self.y.min(), minmax['ymin'])
  768. minmax['ymax'] = max(self.y.max(), minmax['ymax'])
  769. return minmax
  770. def recurse(self, name, indent=0):
  771. space = ' '*indent
  772. print(space, 'reached "bottom" object %s' % \
  773. self.__class__.__name__)
  774. def _object_couplings(self, parent, couplings=[], classname=True):
  775. return
  776. def set_linecolor(self, color):
  777. self.linecolor = color
  778. return self
  779. def set_linewidth(self, width):
  780. self.linewidth = width
  781. return self
  782. def set_linestyle(self, style):
  783. self.linestyle = style
  784. return self
  785. def set_arrow(self, style=None):
  786. self.arrow = style
  787. return self
  788. def set_filled_curves(self, color='', pattern=''):
  789. self.fillcolor = color
  790. self.fillpattern = pattern
  791. return self
  792. def set_shadow(self, pixel_displacement=3):
  793. self.shadow = pixel_displacement
  794. return self
  795. def show_hierarchy(self, indent=0, format='std'):
  796. if format == 'dict':
  797. return '"%s"' % str(self)
  798. elif format == 'plain':
  799. return ''
  800. else:
  801. return str(self)
  802. def __str__(self):
  803. """Compact pretty print of a Curve object."""
  804. s = '%d (x,y) coords' % self.x.size
  805. inside = self.inside_plot_area(verbose=False)
  806. if inside is None:
  807. pass # no info about the plotting area
  808. elif not inside:
  809. s += ', some coordinates are outside plotting area!\n'
  810. props = ('linecolor', 'linewidth', 'linestyle', 'arrow',
  811. 'fillcolor', 'fillpattern')
  812. for prop in props:
  813. value = getattr(self, prop)
  814. if value is not None:
  815. s += ' %s=%s' % (prop, repr(value))
  816. return s
  817. def __repr__(self):
  818. return str(self)
  819. class Trajectory(Curve):
  820. def __init__(self,points):
  821. self.x = asarray([p.x for p in points], dtype=float)
  822. self.y = asarray([p.y for p in points], dtype=float)
  823. self.linestyle = None
  824. self.linewidth = None
  825. self.linecolor = None
  826. self.fillcolor = None
  827. self.fillpattern = None
  828. self.arrow = None
  829. self.shadow = False
  830. self.name = None # name of object that this Curve represents
  831. class Spline(Shape):
  832. # Note: UnivariateSpline interpolation may not work if
  833. # the x[i] points are far from uniformly spaced
  834. def __init__(self, x, y, degree=3, resolution=501):
  835. from scipy.interpolate import UnivariateSpline
  836. self.smooth = UnivariateSpline(x, y, s=0, k=degree)
  837. self.xcoor = linspace(x[0], x[-1], resolution)
  838. ycoor = self.smooth(self.xcoor)
  839. self.shapes = {'smooth': Curve(self.xcoor, ycoor)}
  840. def geometric_features(self):
  841. s = self.shapes['smooth']
  842. return {'start': point(s.x[0], s.y[0]),
  843. 'end': point(s.x[-1], s.y[-1]),
  844. 'interval': [s.x[0], s.x[-1]]}
  845. def __call__(self, x):
  846. return self.smooth(x)
  847. # Can easily find the derivative and the integral as
  848. # self.smooth.derivative(n=1) and self.smooth.antiderivative()
  849. class SketchyFunc1(Spline):
  850. """
  851. A typical function curve used to illustrate an "arbitrary" function.
  852. """
  853. domain = [1, 6]
  854. def __init__(self, name=None, name_pos='start',
  855. xmin=0, xmax=6, ymin=0, ymax=2):
  856. x = array([0, 2, 3, 4, 5, 6])
  857. y = array([1, 1.8, 1.2, 0.7, 0.8, 0.85])
  858. #y = array([5, 3.5, 3.8, 3, 2.5, 2.4])
  859. # Scale x and y
  860. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  861. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  862. Spline.__init__(self, x, y)
  863. self.shapes['smooth'].set_linecolor('black')
  864. if name is not None:
  865. self.shapes['name'] = Text(name, self.geometric_features()[name_pos] + point(0,0.1))
  866. class SketchyFunc3(Spline):
  867. """
  868. A typical function curve used to illustrate an "arbitrary" function.
  869. """
  870. domain = [0, 6]
  871. def __init__(self, name=None, name_pos='start',
  872. xmin=0, xmax=6, ymin=0.5, ymax=3.8):
  873. x = array([0, 2, 3, 4, 5, 6])
  874. y = array([0.5, 3.5, 3.8, 2, 2.5, 3.5])
  875. # Scale x and y
  876. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  877. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  878. Spline.__init__(self, x, y)
  879. self.shapes['smooth'].set_linecolor('black')
  880. if name is not None:
  881. self.shapes['name'] = Text(name, self.geometric_features()[name_pos] + point(0,0.1))
  882. class SketchyFunc4(Spline):
  883. """
  884. A typical function curve used to illustrate an "arbitrary" function.
  885. Can be a companion function to SketchyFunc3.
  886. """
  887. domain = [1, 6]
  888. def __init__(self, name=None, name_pos='start',
  889. xmin=0, xmax=6, ymin=0.5, ymax=1.8):
  890. x = array([0, 2, 3, 4, 5, 6])
  891. y = array([1.5, 1.3, 0.7, 0.5, 0.6, 0.8])
  892. # Scale x and y
  893. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  894. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  895. Spline.__init__(self, x, y)
  896. self.shapes['smooth'].set_linecolor('black')
  897. if name is not None:
  898. self.shapes['name'] = Text(name, self.geometric_features()[name_pos] + point(0,0.1))
  899. class SketchyFunc2(Shape):
  900. """
  901. A typical function curve used to illustrate an "arbitrary" function.
  902. """
  903. domain = [0, 2.25]
  904. def __init__(self, name=None, name_pos='end',
  905. xmin=0, xmax=2.25, ymin=0.046679703125, ymax=1.259375):
  906. a = 0; b = 2.25
  907. resolution = 100
  908. x = linspace(a, b, resolution+1)
  909. f = self # for calling __call__
  910. y = f(x)
  911. # Scale x and y
  912. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  913. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  914. self.shapes = {'smooth': Curve(x, y)}
  915. self.shapes['smooth'].set_linecolor('black')
  916. pos = point(a, f(a)) if name_pos == 'start' else point(b, f(b))
  917. if name is not None:
  918. self.shapes['name'] = Text(name, pos + point(0,0.1))
  919. def __call__(self, x):
  920. return 0.5+x*(2-x)*(0.9-x) # on [0, 2.25]
  921. class Point(Shape):
  922. """A point (x,y) which can be rotated, translated, and scaled."""
  923. def __init__(self, x, y):
  924. self.x, self.y = x, y
  925. #self.shapes is not needed in this class
  926. def __add__(self, other):
  927. if isinstance(other, (list,tuple)):
  928. other = Point(other)
  929. return Point(self.x+other.x, self.y+other.y)
  930. def __sub__(self, other):
  931. if isinstance(other, (list,tuple)):
  932. other = Point(other)
  933. return Point(self.x-other.x, self.y-other.y)
  934. # class Point is an abstract class - only subclasses are useful
  935. # and must implement draw
  936. def draw(self, verbose=0):
  937. raise NotImplementedError(
  938. 'class %s must implement the draw method' %
  939. self.__class__.__name__)
  940. def rotate(self, angle, center):
  941. """Rotate point an `angle` (in degrees) around (`x`,`y`)."""
  942. angle = angle*pi/180
  943. x, y = center
  944. c = cos(angle); s = sin(angle)
  945. xnew = x + (self.x - x)*c - (self.y - y)*s
  946. ynew = y + (self.x - x)*s + (self.y - y)*c
  947. self.x = xnew
  948. self.y = ynew
  949. return self
  950. def scale(self, factor):
  951. """Scale point coordinates by `factor`: ``x = factor*x``, etc."""
  952. self.x = factor*self.x
  953. self.y = factor*self.y
  954. return self
  955. def translate(self, vec):
  956. """Translate point by a vector `vec`."""
  957. self.x += vec[0]
  958. self.y += vec[1]
  959. return self
  960. def deform(self, displacement_function):
  961. """Displace coordinates according to displacement_function(x,y)."""
  962. for i in range(len(self.x)):
  963. self.x, self.y = displacement_function(self.x, self.y)
  964. return self
  965. def minmax_coordinates(self, minmax=None):
  966. if minmax is None:
  967. minmax = {'xmin': [], 'xmax': [], 'ymin': [], 'ymax': []}
  968. minmax['xmin'] = min(self.x, minmax['xmin'])
  969. minmax['xmax'] = max(self.x, minmax['xmax'])
  970. minmax['ymin'] = min(self.y, minmax['ymin'])
  971. minmax['ymax'] = max(self.y, minmax['ymax'])
  972. return minmax
  973. def recurse(self, name, indent=0):
  974. space = ' '*indent
  975. print(space, 'reached "bottom" object %s' % \
  976. self.__class__.__name__)
  977. def _object_couplings(self, parent, couplings=[], classname=True):
  978. return
  979. # No need for set_linecolor etc since self._for_all_shapes, which
  980. # is always called for these functions, makes a test and stops
  981. # calls if self.shapes is missing and the object is Point or Curve
  982. def show_hierarchy(self, indent=0, format='std'):
  983. s = '%s at (%g,%g)' % (self.__class__.__name__, self.x, self.y)
  984. if format == 'dict':
  985. return '"%s"' % s
  986. elif format == 'plain':
  987. return ''
  988. else:
  989. return s
  990. # no need to store input data as they are invalid after rotations etc.
  991. class Rectangle(Shape):
  992. """
  993. Rectangle specified by the point `lower_left_corner`, `width`,
  994. and `height`.
  995. """
  996. def __init__(self, lower_left_corner, width, height):
  997. is_sequence(lower_left_corner)
  998. p = arr2D(lower_left_corner) # short form
  999. x = [p[0], p[0] + width,
  1000. p[0] + width, p[0], p[0]]
  1001. y = [p[1], p[1], p[1] + height,
  1002. p[1] + height, p[1]]
  1003. self.shapes = {'rectangle': Curve(x,y)}
  1004. # Dimensions
  1005. dims = {
  1006. 'width': Distance_wText(p + point(0, -height/5.),
  1007. p + point(width, -height/5.),
  1008. 'width'),
  1009. 'height': Distance_wText(p + point(width + width/5., 0),
  1010. p + point(width + width/5., height),
  1011. 'height'),
  1012. 'lower_left_corner': Text_wArrow('lower_left_corner',
  1013. p - point(width/5., height/5.), p)
  1014. }
  1015. self.dimensions = dims
  1016. def geometric_features(self):
  1017. """
  1018. Return dictionary with
  1019. ==================== =============================================
  1020. Attribute Description
  1021. ==================== =============================================
  1022. lower_left Lower left corner point.
  1023. upper_left Upper left corner point.
  1024. lower_right Lower right corner point.
  1025. upper_right Upper right corner point.
  1026. lower_mid Middle point on lower side.
  1027. upper_mid Middle point on upper side.
  1028. center Center point
  1029. ==================== =============================================
  1030. """
  1031. r = self.shapes['rectangle']
  1032. d = {'lower_left': point(r.x[0], r.y[0]),
  1033. 'lower_right': point(r.x[1], r.y[1]),
  1034. 'upper_right': point(r.x[2], r.y[2]),
  1035. 'upper_left': point(r.x[3], r.y[3])}
  1036. d['lower_mid'] = 0.5*(d['lower_left'] + d['lower_right'])
  1037. d['upper_mid'] = 0.5*(d['upper_left'] + d['upper_right'])
  1038. d['left_mid'] = 0.5*(d['lower_left'] + d['upper_left'])
  1039. d['right_mid'] = 0.5*(d['lower_right'] + d['upper_right'])
  1040. d['center'] = point(d['lower_mid'][0], d['left_mid'][1])
  1041. return d
  1042. class Triangle(Shape):
  1043. """
  1044. Triangle defined by its three vertices p1, p2, and p3.
  1045. Recorded geometric features:
  1046. ==================== =============================================
  1047. Attribute Description
  1048. ==================== =============================================
  1049. p1, p2, p3 Corners as given to the constructor.
  1050. ==================== =============================================
  1051. """
  1052. def __init__(self, p1, p2, p3):
  1053. is_sequence(p1, p2, p3)
  1054. x = [p1[0], p2[0], p3[0], p1[0]]
  1055. y = [p1[1], p2[1], p3[1], p1[1]]
  1056. self.shapes = {'triangle': Curve(x,y)}
  1057. # Dimensions
  1058. self.dimensions = {'p1': Text('p1', p1),
  1059. 'p2': Text('p2', p2),
  1060. 'p3': Text('p3', p3)}
  1061. def geometric_features(self):
  1062. t = self.shapes['triangle']
  1063. return {'p1': point(t.x[0], t.y[0]),
  1064. 'p2': point(t.x[1], t.y[1]),
  1065. 'p3': point(t.x[2], t.y[2])}
  1066. class Line(Shape):
  1067. def __init__(self, start, end):
  1068. is_sequence(start, end, length=2)
  1069. if isinstance(start, (list,tuple)):
  1070. start = array(start)
  1071. if isinstance(end, (list,tuple)):
  1072. end = array(end)
  1073. if (start == end).all():
  1074. # Introduce a very small perturbation since identical points
  1075. # give drawing error
  1076. end[0] = start[0] + 1E-10
  1077. x = [start[0], end[0]]
  1078. y = [start[1], end[1]]
  1079. self.shapes = {'line': Curve(x, y)}
  1080. def geometric_features(self):
  1081. line = self.shapes['line']
  1082. return {'start': point(line.x[0], line.y[0]),
  1083. 'end': point(line.x[1], line.y[1]),}
  1084. def compute_formulas(self):
  1085. x, y = self.shapes['line'].x, self.shapes['line'].y
  1086. # Define equations for line:
  1087. # y = a*x + b, x = c*y + d
  1088. try:
  1089. self.a = (y[1] - y[0])/(x[1] - x[0])
  1090. self.b = y[0] - self.a*x[0]
  1091. except ZeroDivisionError:
  1092. # Vertical line, y is not a function of x
  1093. self.a = None
  1094. self.b = None
  1095. try:
  1096. if self.a is None:
  1097. self.c = 0
  1098. else:
  1099. self.c = 1/float(self.a)
  1100. if self.b is None:
  1101. self.d = x[1]
  1102. except ZeroDivisionError:
  1103. # Horizontal line, x is not a function of y
  1104. self.c = None
  1105. self.d = None
  1106. def __call__(self, x=None, y=None):
  1107. """Given x, return y on the line, or given y, return x."""
  1108. self.compute_formulas()
  1109. if x is not None and self.a is not None:
  1110. return self.a*x + self.b
  1111. elif y is not None and self.c is not None:
  1112. return self.c*y + self.d
  1113. else:
  1114. raise ValueError(
  1115. 'Line.__call__(x=%s, y=%s) not meaningful' % \
  1116. (x, y))
  1117. def new_interval(self, x=None, y=None):
  1118. """Redefine current Line to cover interval in x or y."""
  1119. if x is not None:
  1120. is_sequence(x, length=2)
  1121. xL, xR = x
  1122. new_line = Line((xL, self(x=xL)), (xR, self(x=xR)))
  1123. elif y is not None:
  1124. is_sequence(y, length=2)
  1125. yL, yR = y
  1126. new_line = Line((xL, self(y=xL)), (xR, self(y=xR)))
  1127. self.shapes['line'] = new_line['line']
  1128. return self
  1129. # First implementation of class Circle
  1130. class Circle(Shape):
  1131. def __init__(self, center, radius, resolution=180):
  1132. self.center, self.radius = center, radius
  1133. self.resolution = resolution
  1134. t = linspace(0, 2*pi, resolution+1)
  1135. x0 = center[0]; y0 = center[1]
  1136. R = radius
  1137. x = x0 + R*cos(t)
  1138. y = y0 + R*sin(t)
  1139. self.shapes = {'circle': Curve(x, y)}
  1140. def __call__(self, theta):
  1141. """
  1142. Return (x, y) point corresponding to angle theta.
  1143. Not valid after a translation, rotation, or scaling.
  1144. """
  1145. return self.center[0] + self.radius*cos(theta), \
  1146. self.center[1] + self.radius*sin(theta)
  1147. class Arc(Shape):
  1148. def __init__(self, center, radius,
  1149. start_angle, arc_angle,
  1150. resolution=180):
  1151. is_sequence(center)
  1152. # Must record some parameters for __call__
  1153. self.center = arr2D(center)
  1154. self.radius = radius
  1155. self.start_angle = radians(start_angle)
  1156. self.arc_angle = radians(arc_angle)
  1157. self.resolution = resolution
  1158. self.setCurve()
  1159. def setCurve(self):
  1160. t = linspace(self.start_angle,
  1161. self.start_angle + self.arc_angle,
  1162. self.resolution+1)
  1163. x0 = self.center[0]; y0 = self.center[1]
  1164. R = self.radius
  1165. x = x0 + R*cos(t)
  1166. y = y0 + R*sin(t)
  1167. self.shapes = {'arc': Curve(x, y)}
  1168. # Cannot set dimensions (Arc_wText recurses into this
  1169. # constructor forever). Set in test_Arc instead.
  1170. def geometric_features(self):
  1171. a = self.shapes['arc']
  1172. m = len(a.x)//2 # mid point in array
  1173. d = {'start': point(a.x[0], a.y[0]),
  1174. 'end': point(a.x[-1], a.y[-1]),
  1175. 'mid': point(a.x[m], a.y[m])}
  1176. return d
  1177. def __call__(self, theta):
  1178. """
  1179. Return (x,y) point at start_angle + theta.
  1180. Not valid after translation, rotation, or scaling.
  1181. """
  1182. theta = radians(theta)
  1183. t = self.start_angle + theta
  1184. x0 = self.center[0]
  1185. y0 = self.center[1]
  1186. R = self.radius
  1187. x = x0 + R*cos(t)
  1188. y = y0 + R*sin(t)
  1189. return (x, y)
  1190. # Alternative for small arcs: Parabola
  1191. class Parabola(Shape):
  1192. def __init__(self, start, mid, stop, resolution=21):
  1193. self.p1, self.p2, self.p3 = start, mid, stop
  1194. # y as function of x? (no point on line x=const?)
  1195. tol = 1E-14
  1196. if abs(self.p1[0] - self.p2[0]) > 1E-14 and \
  1197. abs(self.p2[0] - self.p3[0]) > 1E-14 and \
  1198. abs(self.p3[0] - self.p1[0]) > 1E-14:
  1199. self.y_of_x = True
  1200. else:
  1201. self.y_of_x = False
  1202. # x as function of y? (no point on line y=const?)
  1203. tol = 1E-14
  1204. if abs(self.p1[1] - self.p2[1]) > 1E-14 and \
  1205. abs(self.p2[1] - self.p3[1]) > 1E-14 and \
  1206. abs(self.p3[1] - self.p1[1]) > 1E-14:
  1207. self.x_of_y = True
  1208. else:
  1209. self.x_of_y = False
  1210. if self.y_of_x:
  1211. x = linspace(start[0], end[0], resolution)
  1212. y = self(x=x)
  1213. elif self.x_of_y:
  1214. y = linspace(start[1], end[1], resolution)
  1215. x = self(y=y)
  1216. else:
  1217. raise ValueError(
  1218. 'Parabola: two or more points lie on x=const '
  1219. 'or y=const - not allowed')
  1220. self.shapes = {'parabola': Curve(x, y)}
  1221. def __call__(self, x=None, y=None):
  1222. if x is not None and self.y_of_x:
  1223. return self._L2x(self.p1, self.p2)*self.p3[1] + \
  1224. self._L2x(self.p2, self.p3)*self.p1[1] + \
  1225. self._L2x(self.p3, self.p1)*self.p2[1]
  1226. elif y is not None and self.x_of_y:
  1227. return self._L2y(self.p1, self.p2)*self.p3[0] + \
  1228. self._L2y(self.p2, self.p3)*self.p1[0] + \
  1229. self._L2y(self.p3, self.p1)*self.p2[0]
  1230. else:
  1231. raise ValueError(
  1232. 'Parabola.__call__(x=%s, y=%s) not meaningful' % \
  1233. (x, y))
  1234. def _L2x(self, x, pi, pj, pk):
  1235. return (x - pi[0])*(x - pj[0])/((pk[0] - pi[0])*(pk[0] - pj[0]))
  1236. def _L2y(self, y, pi, pj, pk):
  1237. return (y - pi[1])*(y - pj[1])/((pk[1] - pi[1])*(pk[1] - pj[1]))
  1238. class Ellipse(Shape):
  1239. def __init__(self, center, width, height, resolution=180):
  1240. self.center = center
  1241. self.width = width
  1242. self.height = height
  1243. self.resolution = resolution
  1244. t = linspace(0, 2*pi, resolution+1)
  1245. x0 = center[0]; y0 = center[1]
  1246. x = x0 + self.width*cos(t)
  1247. y = y0 + self.height*sin(t)
  1248. self.shapes = {'ellipse': Curve(x, y)}
  1249. def __call__(self, theta):
  1250. """
  1251. Return (x, y) point corresponding to angle theta.
  1252. Not valid after a translation, rotation, or scaling.
  1253. """
  1254. return self.center[0] + self.width*cos(theta), \
  1255. self.center[1] + self.height*sin(theta)
  1256. class Wall(Shape):
  1257. """
  1258. defines an hached box given starting, ending point and thickness, filled with a pattern
  1259. """
  1260. def __init__(self, x, y, thickness, pattern='/', transparent=False):
  1261. is_sequence(x, y, length=len(x))
  1262. if isinstance(x[0], (tuple,list,ndarray)):
  1263. # x is list of curves
  1264. x1 = concatenate(x)
  1265. else:
  1266. x1 = asarray(x, float)
  1267. if isinstance(y[0], (tuple,list,ndarray)):
  1268. # x is list of curves
  1269. y1 = concatenate(y)
  1270. else:
  1271. y1 = asarray(y, float)
  1272. self.x1 = x1; self.y1 = y1
  1273. # Displaced curve (according to thickness)
  1274. x2 = x1
  1275. y2 = y1 + thickness
  1276. # Combine x1,y1 with x2,y2 reversed
  1277. from numpy import concatenate
  1278. x = concatenate((x1, x2[-1::-1]))
  1279. y = concatenate((y1, y2[-1::-1]))
  1280. wall = Curve(x, y)
  1281. wall.set_filled_curves(color='white', pattern=pattern)
  1282. x = [x1[-1]] + x2[-1::-1].tolist() + [x1[0]]
  1283. y = [y1[-1]] + y2[-1::-1].tolist() + [y1[0]]
  1284. self.shapes = {'wall': wall}
  1285. from collections import OrderedDict
  1286. self.shapes = OrderedDict()
  1287. self.shapes['wall'] = wall
  1288. if transparent:
  1289. white_eraser = Curve(x, y)
  1290. white_eraser.set_linecolor('white')
  1291. self.shapes['eraser'] = white_eraser
  1292. def geometric_features(self):
  1293. d = {'start': point(self.x1[0], self.y1[0]),
  1294. 'end': point(self.x1[-1], self.y1[-1])}
  1295. return d
  1296. class Wall2(Shape):
  1297. def __init__(self, x, y, thickness, pattern='/'):
  1298. is_sequence(x, y, length=len(x))
  1299. if isinstance(x[0], (tuple,list,ndarray)):
  1300. # x is list of curves
  1301. x1 = concatenate(x)
  1302. else:
  1303. x1 = asarray(x, float)
  1304. if isinstance(y[0], (tuple,list,ndarray)):
  1305. # x is list of curves
  1306. y1 = concatenate(y)
  1307. else:
  1308. y1 = asarray(y, float)
  1309. self.x1 = x1; self.y1 = y1
  1310. # Displaced curve (according to thickness)
  1311. x2 = x1.copy()
  1312. y2 = y1.copy()
  1313. def displace(idx, idx_m, idx_p):
  1314. # Find tangent and normal
  1315. tangent = point(x1[idx_m], y1[idx_m]) - point(x1[idx_p], y1[idx_p])
  1316. tangent = unit_vec(tangent)
  1317. normal = point(tangent[1], -tangent[0])
  1318. # Displace length "thickness" in "positive" normal direction
  1319. displaced_pt = point(x1[idx], y1[idx]) + thickness*normal
  1320. x2[idx], y2[idx] = displaced_pt
  1321. for i in range(1, len(x1)-1):
  1322. displace(i-1, i+1, i) # centered difference for normal comp.
  1323. # One-sided differences at the end points
  1324. i = 0
  1325. displace(i, i+1, i)
  1326. i = len(x1)-1
  1327. displace(i-1, i, i)
  1328. # Combine x1,y1 with x2,y2 reversed
  1329. from numpy import concatenate
  1330. x = concatenate((x1, x2[-1::-1]))
  1331. y = concatenate((y1, y2[-1::-1]))
  1332. wall = Curve(x, y)
  1333. wall.set_filled_curves(color='white', pattern=pattern)
  1334. x = [x1[-1]] + x2[-1::-1].tolist() + [x1[0]]
  1335. y = [y1[-1]] + y2[-1::-1].tolist() + [y1[0]]
  1336. self.shapes['wall'] = wall
  1337. def geometric_features(self):
  1338. d = {'start': point(self.x1[0], self.y1[0]),
  1339. 'end': point(self.x1[-1], self.y1[-1])}
  1340. return d
  1341. class VelocityProfile(Shape):
  1342. def __init__(self, start, height, profile, num_arrows, scaling=1):
  1343. # vx, vy = profile(y)
  1344. shapes = {}
  1345. # Draw left line
  1346. shapes['start line'] = Line(start, (start[0], start[1]+height))
  1347. # Draw velocity arrows
  1348. dy = float(height)/(num_arrows-1)
  1349. x = start[0]
  1350. y = start[1]
  1351. r = profile(y) # Test on return type
  1352. if not isinstance(r, (list,tuple,ndarray)) and len(r) != 2:
  1353. raise TypeError('VelocityProfile constructor: profile(y) function must return velocity vector (vx,vy), not %s' % type(r))
  1354. for i in range(num_arrows):
  1355. y = start[1] + i*dy
  1356. vx, vy = profile(y)
  1357. if abs(vx) < 1E-8:
  1358. continue
  1359. vx *= scaling
  1360. vy *= scaling
  1361. arr = Arrow1((x,y), (x+vx, y+vy), '->')
  1362. shapes['arrow%d' % i] = arr
  1363. # Draw smooth profile
  1364. xs = []
  1365. ys = []
  1366. n = 100
  1367. dy = float(height)/n
  1368. for i in range(n+2):
  1369. y = start[1] + i*dy
  1370. vx, vy = profile(y)
  1371. vx *= scaling
  1372. vy *= scaling
  1373. xs.append(x+vx)
  1374. ys.append(y+vy)
  1375. shapes['smooth curve'] = Curve(xs, ys)
  1376. self.shapes = shapes
  1377. class Arrow1(Shape):
  1378. """Draw a Line with arrow(s)."""
  1379. def __init__(self, start, end, style='->'):
  1380. arrow = Line(start, end)
  1381. arrow.set_arrow(style)
  1382. # Note:
  1383. self.shapes = {'arrow': arrow}
  1384. def geometric_features(self):
  1385. return self.shapes['arrow'].geometric_features()
  1386. class Arrow3(Shape):
  1387. """
  1388. Build a vertical line and arrow head from Line objects.
  1389. Then rotate `rotation_angle`.
  1390. """
  1391. def __init__(self, start, length, rotation_angle=0):
  1392. self.bottom = start
  1393. self.length = length
  1394. self.angle = rotation_angle
  1395. top = (self.bottom[0], self.bottom[1] + self.length)
  1396. main = Line(self.bottom, top)
  1397. #head_length = self.length/8.0
  1398. head_length = drawing_tool.xrange/50.
  1399. head_degrees = radians(30)
  1400. head_left_pt = (top[0] - head_length*sin(head_degrees),
  1401. top[1] - head_length*cos(head_degrees))
  1402. head_right_pt = (top[0] + head_length*sin(head_degrees),
  1403. top[1] - head_length*cos(head_degrees))
  1404. head_left = Line(head_left_pt, top)
  1405. head_right = Line(head_right_pt, top)
  1406. head_left.set_linestyle('solid')
  1407. head_right.set_linestyle('solid')
  1408. self.shapes = {'line': main, 'head left': head_left,
  1409. 'head right': head_right}
  1410. # rotate goes through self.shapes so self.shapes
  1411. # must be initialized first
  1412. self.rotate(rotation_angle, start)
  1413. def geometric_features(self):
  1414. return self.shapes['line'].geometric_features()
  1415. class Cross(Shape):
  1416. """
  1417. Place a cross at the (x,y) point `position`.
  1418. The cross fits in a 0.2 square which center is (x,y).
  1419. the color is black
  1420. the linewidth is 1
  1421. """
  1422. def __init__(self,c):
  1423. l = 0.1
  1424. line1 = Line(c+point(-l,l),c+point(l,-l))
  1425. line2 = Line(c+point(l,l), c+point(-l,-l))
  1426. cross = Composition({'line1': line1, 'line2': line2})
  1427. cross.set_linecolor('black')
  1428. cross.set_linewidth(1)
  1429. self.shapes = {'cross': cross}
  1430. class Text(Point):
  1431. """
  1432. Place `text` at the (x,y) point `position`, with the given
  1433. fontsize (0 indicates that the default fontsize set in drawing_tool
  1434. is to be used). The text is centered around `position` if `alignment` is
  1435. 'center'; if 'left', the text starts at `position`, and if
  1436. 'right', the right and of the text is located at `position`.
  1437. """
  1438. def __init__(self, text, position, alignment='center', fontsize=0,
  1439. bgcolor=None, fgcolor=None, fontfamily=None):
  1440. """
  1441. fontfamily can be (e.g.) 'serif' or 'monospace' (for code!).
  1442. """
  1443. is_sequence(position)
  1444. is_sequence(position, length=2, can_be_None=True)
  1445. self.text = text
  1446. self.position = position
  1447. self.alignment = alignment
  1448. self.fontsize = fontsize
  1449. self.bgcolor = bgcolor
  1450. self.fgcolor = fgcolor
  1451. self.fontfamily = fontfamily
  1452. Point.__init__(self, position[0], position[1])
  1453. #no need for self.shapes here
  1454. def draw(self, verbose=0):
  1455. drawing_tool.text(
  1456. self.text, (self.x, self.y),
  1457. self.alignment, self.fontsize,
  1458. arrow_tip=None, bgcolor=self.bgcolor, fgcolor=self.fgcolor,
  1459. fontfamily=self.fontfamily)
  1460. if verbose > 0:
  1461. print('drawing Text "%s"' % self.text)
  1462. def __str__(self):
  1463. return 'text "%s" at (%g,%g)' % (self.text, self.x, self.y)
  1464. def __repr__(self):
  1465. return repr(str(self))
  1466. class Text_wArrow(Text):
  1467. """
  1468. As class Text, but an arrow is drawn from the mid part of the text
  1469. to some point `arrow_tip`.
  1470. """
  1471. def __init__(self, text, position, arrow_tip,
  1472. alignment='center', fontsize=0):
  1473. is_sequence(arrow_tip, length=2, can_be_None=True)
  1474. is_sequence(position)
  1475. self.arrow_tip = arrow_tip
  1476. Text.__init__(self, text, position, alignment, fontsize)
  1477. def draw(self, verbose=0):
  1478. drawing_tool.text(
  1479. self.text, self.position,
  1480. self.alignment, self.fontsize,
  1481. arrow_tip=self.arrow_tip,
  1482. bgcolor=self.bgcolor, fgcolor=self.fgcolor,
  1483. fontfamily=self.fontfamily)
  1484. if verbose > 0:
  1485. print('drawing Text_wArrow "%s"' % self.text)
  1486. def __str__(self):
  1487. return 'annotation "%s" at (%g,%g) with arrow to (%g,%g)' % \
  1488. (self.text, self.x, self.y,
  1489. self.arrow_tip[0], self.arrow_tip[1])
  1490. def __repr__(self):
  1491. return repr(str(self))
  1492. class Axis(Shape):
  1493. def __init__(self, start, length, label,
  1494. rotation_angle=0, fontsize=0,
  1495. label_spacing=1./45, label_alignment='left'):
  1496. """
  1497. Draw axis from start with `length` to the right
  1498. (x axis). Place label at the end of the arrow tip.
  1499. Then return `rotation_angle` (in degrees).
  1500. The `label_spacing` denotes the space between the label
  1501. and the arrow tip as a fraction of the length of the plot
  1502. in x direction. A tuple can be given to adjust the position
  1503. in both the x and y directions (with one parameter, the
  1504. x position is adjusted).
  1505. With `label_alignment` one can place
  1506. the axis label text such that the arrow tip is to the 'left',
  1507. 'right', or 'center' with respect to the text field.
  1508. The `label_spacing` and `label_alignment`parameters can
  1509. be used to fine-tune the location of the label.
  1510. """
  1511. # Arrow is vertical arrow, make it horizontal
  1512. arrow = Arrow3(start, length, rotation_angle=-90)
  1513. arrow.rotate(rotation_angle, start)
  1514. if isinstance(label_spacing, (list,tuple)) and len(label_spacing) == 2:
  1515. x_spacing = drawing_tool.xrange*label_spacing[0]
  1516. y_spacing = drawing_tool.yrange*label_spacing[1]
  1517. elif isinstance(label_spacing, (int,float)):
  1518. # just x spacing
  1519. x_spacing = drawing_tool.xrange*label_spacing
  1520. y_spacing = 0
  1521. # should increase spacing for downward pointing axis
  1522. label_pos = [start[0] + length + x_spacing, start[1] + y_spacing]
  1523. label = Text(label, position=label_pos, fontsize=fontsize)
  1524. label.rotate(rotation_angle, start)
  1525. self.shapes = {'arrow': arrow, 'label': label}
  1526. def geometric_features(self):
  1527. return self.shapes['arrow'].geometric_features()
  1528. # Maybe Axis3 with label below/above?
  1529. class Force(Arrow1):
  1530. """
  1531. Indication of a force by an arrow and a text (symbol). Draw an
  1532. arrow, starting at `start` and with the tip at `end`. The symbol
  1533. is placed at `text_pos`, which can be 'start', 'end' or the
  1534. coordinates of a point. If 'end' or 'start', the text is placed at
  1535. a distance `text_spacing` times the width of the total plotting
  1536. area away from the specified point.
  1537. """
  1538. def __init__(self, start, end, text, text_spacing=1./60,
  1539. fontsize=0, text_pos='start', text_alignment='center'):
  1540. Arrow1.__init__(self, start, end, style='->')
  1541. if isinstance(text_spacing, (tuple,list)):
  1542. if len(text_spacing) == 2:
  1543. spacing = point(drawing_tool.xrange*text_spacing[0],
  1544. drawing_tool.xrange*text_spacing[1])
  1545. else:
  1546. spacing = drawing_tool.xrange*text_spacing[0]
  1547. else:
  1548. # just a number, this is x spacing
  1549. spacing = drawing_tool.xrange*text_spacing
  1550. start, end = arr2D(start), arr2D(end)
  1551. # Two cases: label at bottom of line or top, need more
  1552. # spacing if bottom
  1553. downward = (end-start)[1] < 0
  1554. upward = not downward # for easy code reading
  1555. if isinstance(text_pos, (str,bytes)):
  1556. if text_pos == 'start':
  1557. spacing_dir = unit_vec(start - end)
  1558. if upward:
  1559. spacing *= 1.7
  1560. if isinstance(spacing, (int, float)):
  1561. text_pos = start + spacing*spacing_dir
  1562. else:
  1563. text_pos = start + spacing
  1564. elif text_pos == 'end':
  1565. spacing_dir = unit_vec(end - start)
  1566. if downward:
  1567. spacing *= 1.7
  1568. if isinstance(spacing, (int, float)):
  1569. text_pos = end + spacing*spacing_dir
  1570. else:
  1571. text_pos = end + spacing
  1572. self.shapes['text'] = Text(text, text_pos, fontsize=fontsize,
  1573. alignment=text_alignment)
  1574. def geometric_features(self):
  1575. d = Arrow1.geometric_features(self)
  1576. d['symbol_location'] = self.shapes['text'].position
  1577. return d
  1578. class Axis2(Force):
  1579. def __init__(self, start, length, label,
  1580. rotation_angle=0, fontsize=0,
  1581. label_spacing=1./45, label_alignment='left'):
  1582. direction = point(cos(radians(rotation_angle)),
  1583. sin(radians(rotation_angle)))
  1584. Force.__init__(start=start, end=length*direction, text=label,
  1585. text_spacing=label_spacing,
  1586. fontsize=fontsize, text_pos='end',
  1587. text_alignment=label_alignment)
  1588. # Substitute text by label for axis
  1589. self.shapes['label'] = self.shapes['text']
  1590. del self.shapes['text']
  1591. # geometric features from Force is ok
  1592. class Gravity(Axis):
  1593. """Downward-pointing gravity arrow with the symbol g."""
  1594. def __init__(self, start, length, fontsize=0):
  1595. Axis.__init__(self, start, length, '$g$', below=False,
  1596. rotation_angle=-90, label_spacing=1./30,
  1597. fontsize=fontsize)
  1598. self.shapes['arrow'].set_linecolor('black')
  1599. class Gravity(Force):
  1600. """Downward-pointing gravity arrow with the symbol g."""
  1601. def __init__(self, start, length, text='$g$', fontsize=0):
  1602. Force.__init__(self, start, (start[0], start[1]-length),
  1603. text, text_spacing=1./60,
  1604. fontsize=0, text_pos='end')
  1605. self.shapes['arrow'].set_linecolor('black')
  1606. class Distance_wText(Shape):
  1607. """
  1608. Arrow <-> with text (usually a symbol) at the midpoint, used for
  1609. identifying a some distance in a figure. The text is placed
  1610. slightly to the right of vertical-like arrows, with text displaced
  1611. `text_spacing` times to total distance in x direction of the plot
  1612. area. The text is by default aligned 'left' in this case. For
  1613. horizontal-like arrows, the text is placed the same distance
  1614. above, but aligned 'center' by default (when `alignment` is None).
  1615. """
  1616. def __init__(self, start, end, text, fontsize=0, text_spacing=1/60.,
  1617. alignment=None, text_pos='mid'):
  1618. start = arr2D(start)
  1619. end = arr2D(end)
  1620. # Decide first if we have a vertical or horizontal arrow
  1621. vertical = abs(end[0]-start[0]) < 2*abs(end[1]-start[1])
  1622. if vertical:
  1623. # Assume end above start
  1624. if end[1] < start[1]:
  1625. start, end = end, start
  1626. if alignment is None:
  1627. alignment = 'left'
  1628. else: # horizontal arrow
  1629. # Assume start to the right of end
  1630. if start[0] < end[0]:
  1631. start, end = end, start
  1632. if alignment is None:
  1633. alignment = 'center'
  1634. tangent = end - start
  1635. # Tangeng goes always to the left and upward
  1636. normal = unit_vec([tangent[1], -tangent[0]])
  1637. mid = 0.5*(start + end) # midpoint of start-end line
  1638. if text_pos == 'mid':
  1639. text_pos = mid + normal*drawing_tool.xrange*text_spacing
  1640. text = Text(text, text_pos, fontsize=fontsize,
  1641. alignment=alignment)
  1642. else:
  1643. is_sequence(text_pos, length=2)
  1644. text = Text_wArrow(text, text_pos, mid, alignment='left',
  1645. fontsize=fontsize)
  1646. arrow = Arrow1(start, end, style='<->')
  1647. arrow.set_linecolor('black')
  1648. arrow.set_linewidth(1)
  1649. self.shapes = {'arrow': arrow, 'text': text}
  1650. def geometric_features(self):
  1651. d = self.shapes['arrow'].geometric_features()
  1652. d['text_position'] = self.shapes['text'].position
  1653. return d
  1654. class Arc_wText(Shape):
  1655. """
  1656. Arc with text positionned at the left of arc half-way
  1657. """
  1658. def __init__(self, text, center, radius,
  1659. start_angle, arc_angle, fontsize=0,
  1660. resolution=180, text_spacing=1/60.):
  1661. self.text = text
  1662. self.center = center
  1663. self.radius = radius
  1664. self.fontsize=fontsize
  1665. self.resolution=resolution
  1666. self.text_spacing=text_spacing
  1667. self.start_angle = start_angle
  1668. self.arc_angle = arc_angle
  1669. self.setArc()
  1670. def setArc(self):
  1671. arc = Arc(self.center, self.radius, self.start_angle, self.arc_angle,
  1672. self.resolution)
  1673. mid = arr2D(arc(self.arc_angle/2.))
  1674. normal = unit_vec(mid - arr2D(self.center))
  1675. text_pos = mid + normal*drawing_tool.xrange*self.text_spacing
  1676. if hasattr(self, 'linewidth'):
  1677. arc.set_linewidth(self.linewidth)
  1678. self.shapes = {'arc': arc,
  1679. 'text': Text(self.text, text_pos, fontsize=self.fontsize)}
  1680. def changeAngle(self,start_angle,arc_angle):
  1681. self.arc_angle = arc_angle
  1682. self.start_angle = start_angle
  1683. self.setArc()
  1684. def set_linewidth(self, width):
  1685. self.linewidth = width
  1686. self.change_linewidth()
  1687. def change_linewidth(self):
  1688. super().set_linewidth(self.linewidth)
  1689. class Composition(Shape):
  1690. def __init__(self, shapes):
  1691. """shapes: list or dict of Shape objects."""
  1692. if isinstance(shapes, (tuple,list)):
  1693. # Convert to dict using the type of the list element as key
  1694. # (add a counter to make the keys unique)
  1695. shapes = {s.__class__.__name__ + '_' + str(i): s
  1696. for i, s in enumerate(shapes)}
  1697. self.shapes = shapes
  1698. # can make help methods: Line.midpoint, Line.normal(pt, dir='left') -> (x,y)
  1699. # list annotations in each class? contains extra annotations for explaining
  1700. # important parameters to the constructor, e.g., Line.annotations holds
  1701. # start and end as Text objects. Shape.demo calls shape.draw and
  1702. # for annotation in self.demo: annotation.draw() YES!
  1703. # Can make overall demo of classes by making objects and calling demo
  1704. # Could include demo fig in each constructor
  1705. class SimplySupportedBeam(Shape):
  1706. def __init__(self, pos, size):
  1707. pos = arr2D(pos)
  1708. P0 = (pos[0] - size/2., pos[1]-size)
  1709. P1 = (pos[0] + size/2., pos[1]-size)
  1710. triangle = Triangle(P0, P1, pos)
  1711. gap = size/5.
  1712. h = size/4. # height of rectangle
  1713. P2 = (P0[0], P0[1]-gap-h)
  1714. rectangle = Rectangle(P2, size, h).set_filled_curves(pattern='/')
  1715. self.shapes = {'triangle': triangle, 'rectangle': rectangle}
  1716. self.dimensions = {'pos': Text('pos', pos),
  1717. 'size': Distance_wText((P2[0], P2[1]-size),
  1718. (P2[0]+size, P2[1]-size),
  1719. 'size')}
  1720. def geometric_features(self):
  1721. t = self.shapes['triangle']
  1722. r = self.shapes['rectangle']
  1723. d = {'pos': t.geometric_features()['p2'],
  1724. 'mid_support': r.geometric_features()['lower_mid']}
  1725. return d
  1726. class ConstantBeamLoad(Shape):
  1727. """
  1728. Downward-pointing arrows indicating a vertical load.
  1729. The arrows are of equal length and filling a rectangle
  1730. specified as in the :class:`Rectangle` class.
  1731. Recorded geometric features:
  1732. ==================== =============================================
  1733. Attribute Description
  1734. ==================== =============================================
  1735. mid_top Middle point at the top of the row of
  1736. arrows (often used for positioning a text).
  1737. ==================== =============================================
  1738. """
  1739. def __init__(self, lower_left_corner, width, height, num_arrows=10):
  1740. box = Rectangle(lower_left_corner, width, height)
  1741. self.shapes = {'box': box}
  1742. dx = float(width)/(num_arrows-1)
  1743. y_top = lower_left_corner[1] + height
  1744. y_tip = lower_left_corner[1]
  1745. for i in range(num_arrows):
  1746. x = lower_left_corner[0] + i*dx
  1747. self.shapes['arrow%d' % i] = Arrow1((x, y_top), (x, y_tip))
  1748. def geometric_features(self):
  1749. return {'mid_top': self.shapes['box'].geometric_features()['upper_mid']}
  1750. class Moment(Arc_wText):
  1751. """
  1752. defines a Moment arrow with text given text, center and radius
  1753. default direction is counter_clockwise, fontsize and text spacing as optional parameters
  1754. """
  1755. def __init__(self, text, center, radius,
  1756. left=True, counter_clockwise=True,
  1757. fontsize=0, text_spacing=1/60.):
  1758. style = '->' if counter_clockwise else '<-'
  1759. start_angle = 90 if left else -90
  1760. Arc_wText.__init__(self, text, center, radius,
  1761. start_angle=start_angle,
  1762. arc_angle=180, fontsize=fontsize,
  1763. text_spacing=text_spacing,
  1764. resolution=180)
  1765. self.shapes['arc']['arc'].set_arrow(style) # Curve object
  1766. class Wheel(Shape):
  1767. """
  1768. Hub and spokes Wheel given center, radius, spokes (default 10), inner_radius(default 1/5 of radius)
  1769. """
  1770. def __init__(self, center, radius, inner_radius=None, nlines=10):
  1771. if inner_radius is None:
  1772. inner_radius = radius/5.0
  1773. outer = Circle(center, radius)
  1774. inner = Circle(center, inner_radius)
  1775. lines = []
  1776. self.nlines = nlines
  1777. # Draw nlines+1 since the first and last coincide
  1778. # (then nlines lines will be visible)
  1779. t = linspace(0, 2*pi, self.nlines+1)
  1780. Ri = inner_radius; Ro = radius
  1781. x0 = center[0]; y0 = center[1]
  1782. xinner = x0 + Ri*cos(t)
  1783. yinner = y0 + Ri*sin(t)
  1784. xouter = x0 + Ro*cos(t)
  1785. youter = y0 + Ro*sin(t)
  1786. lines = [Line((xi,yi),(xo,yo)) for xi, yi, xo, yo in \
  1787. zip(xinner, yinner, xouter, youter)]
  1788. self.shapes = {'inner': inner, 'outer': outer,
  1789. 'spokes': Composition(
  1790. {'spoke%d' % i: lines[i]
  1791. for i in range(len(lines))})}
  1792. class SineWave(Shape):
  1793. def __init__(self, xstart, xstop,
  1794. wavelength, amplitude, mean_level):
  1795. self.xstart = xstart
  1796. self.xstop = xstop
  1797. self.wavelength = wavelength
  1798. self.amplitude = amplitude
  1799. self.mean_level = mean_level
  1800. npoints = (self.xstop - self.xstart)/(self.wavelength/61.0)
  1801. x = linspace(self.xstart, self.xstop, npoints)
  1802. k = 2*pi/self.wavelength # frequency
  1803. y = self.mean_level + self.amplitude*sin(k*x)
  1804. self.shapes = {'waves': Curve(x,y)}
  1805. class Spring(Shape):
  1806. """
  1807. Specify a *vertical* spring, starting at `start` and with `length`
  1808. as total vertical length. In the middle of the spring there are
  1809. `num_windings` circular windings to illustrate the spring. If
  1810. `teeth` is true, the spring windings look like saw teeth,
  1811. otherwise the windings are smooth circles. The parameters `width`
  1812. (total width of spring) and `bar_length` (length of first and last
  1813. bar are given sensible default values if they are not specified
  1814. (these parameters can later be extracted as attributes, see table
  1815. below).
  1816. """
  1817. spring_fraction = 1./2 # fraction of total length occupied by spring
  1818. def __init__(self, start, length, width=None, bar_length=None,
  1819. num_windings=11, teeth=False):
  1820. B = start
  1821. n = num_windings - 1 # n counts teeth intervals
  1822. if n <= 6:
  1823. n = 7
  1824. # n must be odd:
  1825. if n % 2 == 0:
  1826. n = n+1
  1827. L = length
  1828. if width is None:
  1829. w = L/10.
  1830. else:
  1831. w = width/2.0
  1832. s = bar_length
  1833. # [0, x, L-x, L], f = (L-2*x)/L
  1834. # x = L*(1-f)/2.
  1835. # B: start point
  1836. # w: half-width
  1837. # L: total length
  1838. # s: length of first bar
  1839. # P0: start of dashpot (B[0]+s)
  1840. # P1: end of dashpot
  1841. # P2: end point
  1842. shapes = {}
  1843. if s is None:
  1844. f = Spring.spring_fraction
  1845. s = L*(1-f)/2. # start of spring
  1846. self.bar_length = s # record
  1847. self.width = 2*w
  1848. P0 = (B[0], B[1] + s)
  1849. P1 = (B[0], B[1] + L-s)
  1850. P2 = (B[0], B[1] + L)
  1851. if s >= L:
  1852. raise ValueError('length of first bar: %g is larger than total length: %g' % (s, L))
  1853. shapes['bar1'] = Line(B, P0)
  1854. spring_length = L - 2*s
  1855. t = spring_length/n # height increment per winding
  1856. if teeth:
  1857. resolution = 4
  1858. else:
  1859. resolution = 90
  1860. q = linspace(0, n, n*resolution + 1)
  1861. x = P0[0] + w*sin(2*pi*q)
  1862. y = P0[1] + q*t
  1863. shapes['spiral'] = Curve(x, y)
  1864. shapes['bar2'] = Line(P1,P2)
  1865. self.shapes = shapes
  1866. # Dimensions
  1867. start = Text_wArrow('start', (B[0]-1.5*w,B[1]-1.5*w), B)
  1868. width = Distance_wText((B[0]-w, B[1]-3.5*w), (B[0]+w, B[1]-3.5*w),
  1869. 'width')
  1870. length = Distance_wText((B[0]+3*w, B[1]), (B[0]+3*w, B[1]+L),
  1871. 'length')
  1872. num_windings = Text_wArrow('num_windings',
  1873. (B[0]+2*w,P2[1]+w),
  1874. (B[0]+1.2*w, B[1]+L/2.))
  1875. blength1 = Distance_wText((B[0]-2*w, B[1]), (B[0]-2*w, P0[1]),
  1876. 'bar_length',
  1877. text_pos=(P0[0]-7*w, P0[1]+w))
  1878. blength2 = Distance_wText((P1[0]-2*w, P1[1]), (P2[0]-2*w, P2[1]),
  1879. 'bar_length',
  1880. text_pos=(P2[0]-7*w, P2[1]+w))
  1881. dims = {'start': start, 'width': width, 'length': length,
  1882. 'num_windings': num_windings, 'bar_length1': blength1,
  1883. 'bar_length2': blength2}
  1884. self.dimensions = dims
  1885. def geometric_features(self):
  1886. """
  1887. Recorded geometric features:
  1888. ==================== =============================================
  1889. Attribute Description
  1890. ==================== =============================================
  1891. start Start point of spring.
  1892. end End point of spring.
  1893. width Total width of spring.
  1894. bar_length Length of first (and last) bar part.
  1895. ==================== =============================================
  1896. """
  1897. b1 = self.shapes['bar1']
  1898. d = {'start': b1.geometric_features()['start'],
  1899. 'end': self.shapes['bar2'].geometric_features()['end'],
  1900. 'bar_length': self.bar_length,
  1901. 'width': self.width}
  1902. return d
  1903. class Dashpot(Shape):
  1904. """
  1905. Specify a vertical dashpot of height `total_length` and `start` as
  1906. bottom/starting point. The first bar part has length `bar_length`.
  1907. Then comes the dashpot as a rectangular construction of total
  1908. width `width` and height `dashpot_length`. The position of the
  1909. piston inside the rectangular dashpot area is given by
  1910. `piston_pos`, which is the distance between the first bar (given
  1911. by `bar_length`) to the piston.
  1912. If some of `dashpot_length`, `bar_length`, `width` or `piston_pos`
  1913. are not given, suitable default values are calculated. Their
  1914. values can be extracted as keys in the dict returned from
  1915. ``geometric_features``.
  1916. """
  1917. dashpot_fraction = 1./2 # fraction of total_length
  1918. piston_gap_fraction = 1./6 # fraction of width
  1919. piston_thickness_fraction = 1./8 # fraction of dashplot_length
  1920. def __init__(self, start, total_length, bar_length=None,
  1921. width=None, dashpot_length=None, piston_pos=None):
  1922. B = start
  1923. L = total_length
  1924. if width is None:
  1925. w = L/10. # total width 1/5 of length
  1926. else:
  1927. w = width/2.0
  1928. s = bar_length
  1929. # [0, x, L-x, L], f = (L-2*x)/L
  1930. # x = L*(1-f)/2.
  1931. # B: start point
  1932. # w: half-width
  1933. # L: total length
  1934. # s: length of first bar
  1935. # P0: start of dashpot (B[0]+s)
  1936. # P1: end of dashpot
  1937. # P2: end point
  1938. shapes = {}
  1939. # dashpot is P0-P1 in y and width 2*w
  1940. if dashpot_length is None:
  1941. if s is None:
  1942. f = Dashpot.dashpot_fraction
  1943. s = L*(1-f)/2. # default
  1944. P1 = (B[0], B[1]+L-s)
  1945. dashpot_length = f*L
  1946. else:
  1947. if s is None:
  1948. f = 1./2 # the bar lengths are taken as f*dashpot_length
  1949. s = f*dashpot_length # default
  1950. P1 = (B[0], B[1]+s+dashpot_length)
  1951. P0 = (B[0], B[1]+s)
  1952. P2 = (B[0], B[1]+L)
  1953. if P2[1] > P1[1] > P0[1]:
  1954. pass # ok
  1955. else:
  1956. raise ValueError('Dashpot has inconsistent dimensions! start: %g, dashpot begin: %g, dashpot end: %g, very end: %g' % (B[1], P0[1], P1[1], P2[1]))
  1957. shapes['line start'] = Line(B, P0)
  1958. shapes['pot'] = Curve([P1[0]-w, P0[0]-w, P0[0]+w, P1[0]+w],
  1959. [P1[1], P0[1], P0[1], P1[1]])
  1960. piston_thickness = dashpot_length*Dashpot.piston_thickness_fraction
  1961. if piston_pos is None:
  1962. piston_pos = 1/3.*dashpot_length
  1963. if piston_pos < 0:
  1964. piston_pos = 0
  1965. elif piston_pos > dashpot_length:
  1966. piston_pos = dashpot_length - piston_thickness
  1967. abs_piston_pos = P0[1] + piston_pos
  1968. gap = w*Dashpot.piston_gap_fraction
  1969. shapes['piston'] = Composition(
  1970. {'line': Line(P2, (B[0], abs_piston_pos + piston_thickness)),
  1971. 'rectangle': Rectangle((B[0] - w+gap, abs_piston_pos),
  1972. 2*w-2*gap, piston_thickness),
  1973. })
  1974. shapes['piston']['rectangle'].set_filled_curves(pattern='X')
  1975. self.shapes = shapes
  1976. self.bar_length = s
  1977. self.width = 2*w
  1978. self.piston_pos = piston_pos
  1979. self.dashpot_length = dashpot_length
  1980. # Dimensions
  1981. start = Text_wArrow('start', (B[0]-1.5*w,B[1]-1.5*w), B)
  1982. width = Distance_wText((B[0]-w, B[1]-3.5*w), (B[0]+w, B[1]-3.5*w),
  1983. 'width')
  1984. dplength = Distance_wText((B[0]+2*w, P0[1]), (B[0]+2*w, P1[1]),
  1985. 'dashpot_length', text_pos=(B[0]+w,B[1]-w))
  1986. blength = Distance_wText((B[0]-2*w, B[1]), (B[0]-2*w, P0[1]),
  1987. 'bar_length', text_pos=(B[0]-6*w,P0[1]-w))
  1988. ppos = Distance_wText((B[0]-2*w, P0[1]), (B[0]-2*w, P0[1]+piston_pos),
  1989. 'piston_pos', text_pos=(B[0]-6*w,P0[1]+piston_pos-w))
  1990. tlength = Distance_wText((B[0]+4*w, B[1]), (B[0]+4*w, B[1]+L),
  1991. 'total_length',
  1992. text_pos=(B[0]+4.5*w, B[1]+L-2*w))
  1993. line = Line((B[0]+w, abs_piston_pos), (B[0]+7*w, abs_piston_pos)).set_linestyle('dashed').set_linecolor('black').set_linewidth(1)
  1994. pp = Text('abs_piston_pos', (B[0]+7*w, abs_piston_pos), alignment='left')
  1995. dims = {'start': start, 'width': width, 'dashpot_length': dplength,
  1996. 'bar_length': blength, 'total_length': tlength,
  1997. 'piston_pos': ppos,}
  1998. #'abs_piston_pos': Composition({'line': line, 'text': pp})}
  1999. self.dimensions = dims
  2000. def geometric_features(self):
  2001. """
  2002. Recorded geometric features:
  2003. ==================== =============================================
  2004. Attribute Description
  2005. ==================== =============================================
  2006. start Start point of dashpot.
  2007. end End point of dashpot.
  2008. bar_length Length of first bar (from start to spring).
  2009. dashpot_length Length of dashpot middle part.
  2010. width Total width of dashpot.
  2011. piston_pos Position of piston in dashpot, relative to
  2012. start[1] + bar_length.
  2013. ==================== =============================================
  2014. """
  2015. d = {'start': self.shapes['line start'].geometric_features()['start'],
  2016. 'end': self.shapes['piston']['line'].geometric_features()['start'],
  2017. 'bar_length': self.bar_length,
  2018. 'piston_pos': self.piston_pos,
  2019. 'width': self.width,
  2020. 'dashpot_length': self.dashpot_length,
  2021. }
  2022. return d
  2023. class Wavy(Shape):
  2024. """
  2025. A wavy graph consisting of a user-given main curve y=f(x) with
  2026. additional sinusoidal waves of given (constant) amplitude,
  2027. but varying wavelength (a characteristic wavelength is specified).
  2028. """
  2029. def __init__(self, main_curve, interval, wavelength_of_perturbations,
  2030. amplitude_of_perturbations, smoothness):
  2031. """
  2032. ============================ ====================================
  2033. Name Description
  2034. ============================ ====================================
  2035. main_curve f(x) Python function
  2036. interval interval for main_curve
  2037. wavelength_of_perturbations dominant wavelength perturbed waves
  2038. amplitude_of_perturbations amplitude of perturbed waves
  2039. smoothness in [0, 1]: smooth=0, rough=1
  2040. ============================ ====================================
  2041. """
  2042. xmin, xmax = interval
  2043. L = wavelength_of_perturbations
  2044. k_0 = 2*pi/L # main frequency of waves
  2045. k_p = k_0*0.5
  2046. k_k = k_0/2*smoothness
  2047. A_0 = amplitude_of_perturbations
  2048. A_p = 0.3*A_0
  2049. A_k = k_0/2
  2050. x = linspace(xmin, xmax, 2001)
  2051. def w(x):
  2052. A = A_0 + A_p*sin(A_k*x)
  2053. k = k_0 + k_p*sin(k_k*x)
  2054. y = main_curve(x) + A*sin(k*x)
  2055. return y
  2056. self.shapes = {'wavy': Curve(x, w(x))}
  2057. # Use closure w to define __call__ - then we do not need
  2058. # to store all the parameters A_0, A_k, etc. as attributes
  2059. self.__call__ = w
  2060. class StochasticWavyCurve(object):
  2061. """
  2062. Precomputed stochastic wavy graphs.
  2063. There are three graphs with different look.
  2064. Curve 0:
  2065. ----------------------------------------------------------------------
  2066. |
  2067. |
  2068. *|
  2069. * |
  2070. * |
  2071. * |
  2072. * |
  2073. * |
  2074. * |
  2075. * |
  2076. * |
  2077. * |
  2078. * |
  2079. * |
  2080. |*
  2081. | *
  2082. | *
  2083. | *
  2084. | *
  2085. | *
  2086. | *
  2087. | *
  2088. | *
  2089. | *
  2090. | *
  2091. | *
  2092. | *
  2093. | *
  2094. | *
  2095. | *
  2096. | *
  2097. | *
  2098. | *
  2099. | *
  2100. | *
  2101. | *
  2102. | *
  2103. | *
  2104. | *
  2105. | *
  2106. | *
  2107. | *
  2108. | *
  2109. | *
  2110. | *
  2111. | *
  2112. | *
  2113. | *
  2114. | *
  2115. | *
  2116. | *
  2117. | *
  2118. | *
  2119. | *
  2120. | *
  2121. | *
  2122. | *
  2123. | *
  2124. | *
  2125. | *
  2126. | *
  2127. | *
  2128. | *
  2129. | *
  2130. | *
  2131. | *
  2132. | *
  2133. | *
  2134. | *
  2135. | *
  2136. | *
  2137. | *
  2138. |*
  2139. *|
  2140. * |
  2141. * |
  2142. * |
  2143. * |
  2144. * |
  2145. * |
  2146. * |
  2147. * |
  2148. * |
  2149. * |
  2150. * |
  2151. * |
  2152. * |
  2153. * |
  2154. * |
  2155. |*
  2156. | *
  2157. | *
  2158. | *
  2159. | *
  2160. | *
  2161. | *
  2162. | *
  2163. | *
  2164. | *
  2165. | *
  2166. | *
  2167. | *
  2168. | *
  2169. | *
  2170. | *
  2171. | *
  2172. | *
  2173. | *
  2174. | *
  2175. | *
  2176. | *
  2177. | *
  2178. | *
  2179. | *
  2180. | *
  2181. | *
  2182. | *
  2183. | *
  2184. | *
  2185. | *
  2186. | *
  2187. | *
  2188. | *
  2189. | *
  2190. | *
  2191. | *
  2192. | *
  2193. | *
  2194. | *
  2195. | *
  2196. | *
  2197. | *
  2198. | *
  2199. | *
  2200. |
  2201. * |
  2202. * |
  2203. * |
  2204. * |
  2205. * |
  2206. * |
  2207. * |
  2208. * |
  2209. * |
  2210. * |
  2211. * |
  2212. * |
  2213. * |
  2214. * |
  2215. * |
  2216. * |
  2217. * |
  2218. * |
  2219. * |
  2220. * |
  2221. * |
  2222. * |
  2223. * |
  2224. * |
  2225. * |
  2226. * |
  2227. * |
  2228. * |
  2229. * |
  2230. * |
  2231. Curve 2:
  2232. ----------------------------------------------------------------------
  2233. |
  2234. |
  2235. |
  2236. |*
  2237. |*
  2238. |*
  2239. |
  2240. |
  2241. *|
  2242. |*
  2243. | *
  2244. | *
  2245. | *
  2246. | *
  2247. | *
  2248. | *
  2249. | *
  2250. | *
  2251. | *
  2252. | *
  2253. | *
  2254. | *
  2255. | *
  2256. | *
  2257. | *
  2258. | *
  2259. | *
  2260. | *
  2261. | *
  2262. | *
  2263. | *
  2264. | *
  2265. | *
  2266. | *
  2267. | *
  2268. | *
  2269. | *
  2270. | *
  2271. | *
  2272. | *
  2273. | *
  2274. | *
  2275. | *
  2276. | *
  2277. | *
  2278. | *
  2279. | *
  2280. | *
  2281. | *
  2282. | *
  2283. | *
  2284. | *
  2285. | *
  2286. | *
  2287. | *
  2288. | *
  2289. | *
  2290. | *
  2291. | *
  2292. | *
  2293. | *
  2294. |
  2295. * |
  2296. * |
  2297. * |
  2298. * |
  2299. * |
  2300. * |
  2301. * |
  2302. * |
  2303. * |
  2304. * |
  2305. * |
  2306. * |
  2307. * |
  2308. * |
  2309. * |
  2310. * |
  2311. * |
  2312. * |
  2313. * |
  2314. * |
  2315. * |
  2316. * |
  2317. * |
  2318. * |
  2319. * |
  2320. * |
  2321. * |
  2322. * |
  2323. * |
  2324. |
  2325. | *
  2326. | *
  2327. | *
  2328. | *
  2329. | *
  2330. | *
  2331. | *
  2332. | *
  2333. | *
  2334. | *
  2335. | *
  2336. | *
  2337. | *
  2338. | *
  2339. | *
  2340. | *
  2341. | *
  2342. | *
  2343. | *
  2344. | *
  2345. | *
  2346. | *
  2347. |*
  2348. |*
  2349. |
  2350. |
  2351. |
  2352. |*
  2353. | *
  2354. | *
  2355. |*
  2356. |
  2357. *|
  2358. |*
  2359. | *
  2360. | *
  2361. | *
  2362. | *
  2363. | *
  2364. | *
  2365. | *
  2366. | *
  2367. | *
  2368. | *
  2369. | *
  2370. | *
  2371. | *
  2372. | *
  2373. | *
  2374. | *
  2375. | *
  2376. | *
  2377. | *
  2378. | *
  2379. | *
  2380. | *
  2381. | *
  2382. | *
  2383. | *
  2384. | *
  2385. | *
  2386. | *
  2387. | *
  2388. | *
  2389. | *
  2390. | *
  2391. | *
  2392. | *
  2393. | *
  2394. | *
  2395. | *
  2396. | *
  2397. | *
  2398. Curve 2:
  2399. ----------------------------------------------------------------------
  2400. |
  2401. |
  2402. |
  2403. |
  2404. |*
  2405. | *
  2406. | *
  2407. | *
  2408. | *
  2409. | *
  2410. | *
  2411. | *
  2412. | *
  2413. | *
  2414. | *
  2415. | *
  2416. | *
  2417. | *
  2418. | *
  2419. | *
  2420. | *
  2421. | *
  2422. | *
  2423. | *
  2424. | *
  2425. | *
  2426. | *
  2427. | *
  2428. |*
  2429. |
  2430. * |
  2431. * |
  2432. * |
  2433. * |
  2434. * |
  2435. * |
  2436. * |
  2437. * |
  2438. * |
  2439. * |
  2440. |*
  2441. | *
  2442. | *
  2443. | *
  2444. | *
  2445. | *
  2446. | *
  2447. | *
  2448. | *
  2449. | *
  2450. | *
  2451. | *
  2452. | *
  2453. | *
  2454. | *
  2455. | *
  2456. | *
  2457. | *
  2458. | *
  2459. | *
  2460. *|
  2461. * |
  2462. * |
  2463. * |
  2464. * |
  2465. * |
  2466. * |
  2467. * |
  2468. * |
  2469. * |
  2470. * |
  2471. * |
  2472. * |
  2473. * |
  2474. * |
  2475. * |
  2476. * |
  2477. |
  2478. | *
  2479. | *
  2480. | *
  2481. | *
  2482. | *
  2483. | *
  2484. | *
  2485. | *
  2486. | *
  2487. | *
  2488. | *
  2489. | *
  2490. | *
  2491. | *
  2492. | *
  2493. | *
  2494. | *
  2495. | *
  2496. | *
  2497. | *
  2498. | *
  2499. | *
  2500. |*
  2501. *|
  2502. * |
  2503. * |
  2504. * |
  2505. * |
  2506. * |
  2507. * |
  2508. * |
  2509. * |
  2510. * |
  2511. * |
  2512. * |
  2513. * |
  2514. * |
  2515. * |
  2516. * |
  2517. * |
  2518. * |
  2519. * |
  2520. * |
  2521. * |
  2522. * |
  2523. * |
  2524. * |
  2525. * |
  2526. * |
  2527. * |
  2528. * |
  2529. * |
  2530. * |
  2531. * |
  2532. * |
  2533. * |
  2534. * |
  2535. * |
  2536. * |
  2537. * |
  2538. * |
  2539. * |
  2540. * |
  2541. * |
  2542. * |
  2543. * |
  2544. * |
  2545. * |
  2546. * |
  2547. * |
  2548. * |
  2549. * |
  2550. * |
  2551. * |
  2552. * |
  2553. * |
  2554. * |
  2555. * |
  2556. * |
  2557. *|
  2558. |*
  2559. | *
  2560. | *
  2561. | *
  2562. | *
  2563. | *
  2564. | *
  2565. See also hplgit.github.io/pysketcher/doc/src/tut/fig-tut/StochasticWavyCurve.png (and .pdf)
  2566. """
  2567. # The curves were generated by the script generate_road_profiles.py and
  2568. # the code below were generated by plot_roads.py. Both scripts are
  2569. # found doc/src/src-bumpy in the repo git@github.com:hplgit/bumpy.git
  2570. def __init__(self, curve_no=0, percentage=100):
  2571. """
  2572. ============= ===================================================
  2573. Argument Explanation
  2574. ============= ===================================================
  2575. curve_no 0, 1, or 2: chooses one out of three shapes.
  2576. percentage The percentage of the defined curve to be used.
  2577. ============= ===================================================
  2578. """
  2579. self._define_curves()
  2580. self.curve_no = curve_no
  2581. m = int(len(self.x)/float(percentage)*100)
  2582. self.shapes = {'wavy': Curve(self.x[:m], self.y[curve_no][:m])}
  2583. def __call__(self, x):
  2584. raise NotImplementedError
  2585. def _define_curves(self):
  2586. self.x = array([0.0000, 0.0606, 0.1212, 0.1818, 0.2424, 0.3030, 0.3636, 0.4242, 0.4848, 0.5455, 0.6061, 0.6667, 0.7273, 0.7879, 0.8485, 0.9091, 0.9697, 1.0303, 1.0909, 1.1515, 1.2121, 1.2727, 1.3333, 1.3939, 1.4545, 1.5152, 1.5758, 1.6364, 1.6970, 1.7576, 1.8182, 1.8788, 1.9394, 2.0000, 2.0606, 2.1212, 2.1818, 2.2424, 2.3030, 2.3636, 2.4242, 2.4848, 2.5455, 2.6061, 2.6667, 2.7273, 2.7879, 2.8485, 2.9091, 2.9697, 3.0303, 3.0909, 3.1515, 3.2121, 3.2727, 3.3333, 3.3939, 3.4545, 3.5152, 3.5758, 3.6364, 3.6970, 3.7576, 3.8182, 3.8788, 3.9394, 4.0000, 4.0606, 4.1212, 4.1818, 4.2424, 4.3030, 4.3636, 4.4242, 4.4848, 4.5455, 4.6061, 4.6667, 4.7273, 4.7879, 4.8485, 4.9091, 4.9697, 5.0303, 5.0909, 5.1515, 5.2121, 5.2727, 5.3333, 5.3939, 5.4545, 5.5152, 5.5758, 5.6364, 5.6970, 5.7576, 5.8182, 5.8788, 5.9394, 6.0000, 6.0606, 6.1212, 6.1818, 6.2424, 6.3030, 6.3636, 6.4242, 6.4848, 6.5455, 6.6061, 6.6667, 6.7273, 6.7879, 6.8485, 6.9091, 6.9697, 7.0303, 7.0909, 7.1515, 7.2121, 7.2727, 7.3333, 7.3939, 7.4545, 7.5152, 7.5758, 7.6364, 7.6970, 7.7576, 7.8182, 7.8788, 7.9394, 8.0000, 8.0606, 8.1212, 8.1818, 8.2424, 8.3030, 8.3636, 8.4242, 8.4848, 8.5455, 8.6061, 8.6667, 8.7273, 8.7879, 8.8485, 8.9091, 8.9697, 9.0303, 9.0909, 9.1515, 9.2121, 9.2727, 9.3333, 9.3939, 9.4545, 9.5152, 9.5758, 9.6364, 9.6970, 9.7576, 9.8182, 9.8788, 9.9394, 10.0000, 10.0606, 10.1212, 10.1818, 10.2424, 10.3030, 10.3636, 10.4242, 10.4848, 10.5455, 10.6061, 10.6667, 10.7273, 10.7879, 10.8485, 10.9091, 10.9697, 11.0303, 11.0909, 11.1515, 11.2121, 11.2727, 11.3333, 11.3939, 11.4545, 11.5152, 11.5758, 11.6364, 11.6970, 11.7576, 11.8182, 11.8788, 11.9394, 12.0000, 12.0606, 12.1212, 12.1818, 12.2424, 12.3030, 12.3636, 12.4242, 12.4848, 12.5455, 12.6061, 12.6667, 12.7273, 12.7879, 12.8485, 12.9091, 12.9697, 13.0303, 13.0909, 13.1515, 13.2121, 13.2727, 13.3333, 13.3939, 13.4545, 13.5152, 13.5758, 13.6364, 13.6970, 13.7576, 13.8182, 13.8788, 13.9394, 14.0000, 14.0606, 14.1212, 14.1818, 14.2424, 14.3030, 14.3636, 14.4242, 14.4848, 14.5455, 14.6061, 14.6667, 14.7273, 14.7879, 14.8485, 14.9091, 14.9697, 15.0303, 15.0909, 15.1515, 15.2121, 15.2727, 15.3333, 15.3939, 15.4545, 15.5152, 15.5758, 15.6364, 15.6970, 15.7576, 15.8182, 15.8788, 15.9394, 16.0000, 16.0606, 16.1212, 16.1818, 16.2424, 16.3030, 16.3636, 16.4242, 16.4848, 16.5455, 16.6061, 16.6667, 16.7273, 16.7879, 16.8485, 16.9091, 16.9697, 17.0303, 17.0909, 17.1515, 17.2121, 17.2727, 17.3333, 17.3939, 17.4545, 17.5152, 17.5758, 17.6364, 17.6970, 17.7576, 17.8182, 17.8788, 17.9394, 18.0000, 18.0606, 18.1212, 18.1818, 18.2424, 18.3030, 18.3636, 18.4242, 18.4848, 18.5455, 18.6061, 18.6667, 18.7273, 18.7879, 18.8485, 18.9091, 18.9697, 19.0303, 19.0909, 19.1515, 19.2121, 19.2727, 19.3333, 19.3939, 19.4545, 19.5152, 19.5758, 19.6364, 19.6970, 19.7576, 19.8182, 19.8788, 19.9394, 20.0000, 20.0606, 20.1212, 20.1818, 20.2424, 20.3030, 20.3636, 20.4242, 20.4848, 20.5455, 20.6061, 20.6667, 20.7273, 20.7879, 20.8485, 20.9091, 20.9697, 21.0303, 21.0909, 21.1515, 21.2121, 21.2727, 21.3333, 21.3939, 21.4545, 21.5152, 21.5758, 21.6364, 21.6970, 21.7576, 21.8182, 21.8788, 21.9394, 22.0000, 22.0606, 22.1212, 22.1818, 22.2424, 22.3030, 22.3636, 22.4242, 22.4848, 22.5455, 22.6061, 22.6667, 22.7273, 22.7879, 22.8485, 22.9091, 22.9697, 23.0303, 23.0909, 23.1515, 23.2121, 23.2727, 23.3333, 23.3939, 23.4545, 23.5152, 23.5758, 23.6364, 23.6970, 23.7576, 23.8182, 23.8788, 23.9394, 24.0000, 24.0606, 24.1212, 24.1818, 24.2424, 24.3030, 24.3636, 24.4242, 24.4848, 24.5455, 24.6061, 24.6667, 24.7273, 24.7879, 24.8485, 24.9091, 24.9697, 25.0303, 25.0909, 25.1515, 25.2121, 25.2727, 25.3333, 25.3939, 25.4545, 25.5152, 25.5758, 25.6364, 25.6970, 25.7576, 25.8182, 25.8788, 25.9394, 26.0000, 26.0606, 26.1212, 26.1818, 26.2424, 26.3030, 26.3636, 26.4242, 26.4848, 26.5455, 26.6061, 26.6667, 26.7273, 26.7879, 26.8485, 26.9091, 26.9697, 27.0303, 27.0909, 27.1515, 27.2121, 27.2727, 27.3333, 27.3939, 27.4545, 27.5152, 27.5758, 27.6364, 27.6970, 27.7576, 27.8182, 27.8788, 27.9394, 28.0000, 28.0606, 28.1212, 28.1818, 28.2424, 28.3030, 28.3636, 28.4242, 28.4848, 28.5455, 28.6061, 28.6667, 28.7273, 28.7879, 28.8485, 28.9091, 28.9697, 29.0303, 29.0909, 29.1515, 29.2121, 29.2727, 29.3333, 29.3939, 29.4545, 29.5152, 29.5758, 29.6364, 29.6970, 29.7576, 29.8182, 29.8788, 29.9394, 30.0000, 30.0606, 30.1212, 30.1818, 30.2424, 30.3030, 30.3636, 30.4242, 30.4848, 30.5455, 30.6061, 30.6667, 30.7273, 30.7879, 30.8485, 30.9091, 30.9697, 31.0303, 31.0909, 31.1515, 31.2121, 31.2727, 31.3333, 31.3939, 31.4545, 31.5152, 31.5758, 31.6364, 31.6970, 31.7576, 31.8182, 31.8788, 31.9394, 32.0000, 32.0606, 32.1212, 32.1818, 32.2424, 32.3030, 32.3636, 32.4242, 32.4848, 32.5455, 32.6061, 32.6667, 32.7273, 32.7879, 32.8485, 32.9091, 32.9697, 33.0303, 33.0909, 33.1515, 33.2121, 33.2727, 33.3333, 33.3939, 33.4545, 33.5152, 33.5758, 33.6364, 33.6970, 33.7576, 33.8182, 33.8788, 33.9394, 34.0000, 34.0606, 34.1212, 34.1818, 34.2424, 34.3030, 34.3636, 34.4242, 34.4848, 34.5455, 34.6061, 34.6667, 34.7273, 34.7879, 34.8485, 34.9091, 34.9697, 35.0303, 35.0909, 35.1515, 35.2121, 35.2727, 35.3333, 35.3939, 35.4545, 35.5152, 35.5758, 35.6364, 35.6970, 35.7576, 35.8182, 35.8788, 35.9394, 36.0000, 36.0606, 36.1212, 36.1818, 36.2424, 36.3030, 36.3636, 36.4242, 36.4848, 36.5455, 36.6061, 36.6667, 36.7273, 36.7879, 36.8485, 36.9091, 36.9697, 37.0303, 37.0909, 37.1515, 37.2121, 37.2727, 37.3333, 37.3939, 37.4545, 37.5152, 37.5758, 37.6364, 37.6970, 37.7576, 37.8182, 37.8788, 37.9394, 38.0000, 38.0606, 38.1212, 38.1818, 38.2424, 38.3030, 38.3636, 38.4242, 38.4848, 38.5455, 38.6061, 38.6667, 38.7273, 38.7879, 38.8485, 38.9091, 38.9697, 39.0303, 39.0909, 39.1515, 39.2121, 39.2727, 39.3333, 39.3939, 39.4545, 39.5152, 39.5758, 39.6364, 39.6970, 39.7576, 39.8182, 39.8788, 39.9394, 40.0000, 40.0606, 40.1212, 40.1818, 40.2424, 40.3030, 40.3636, 40.4242, 40.4848, 40.5455, 40.6061, 40.6667, 40.7273, 40.7879, 40.8485, 40.9091, 40.9697, 41.0303, 41.0909, 41.1515, 41.2121, 41.2727, 41.3333, 41.3939, 41.4545, 41.5152, 41.5758, 41.6364, 41.6970, 41.7576, 41.8182, 41.8788, 41.9394, 42.0000, 42.0606, 42.1212, 42.1818, 42.2424, 42.3030, 42.3636, 42.4242, 42.4848, 42.5455, 42.6061, 42.6667, 42.7273, 42.7879, 42.8485, 42.9091, 42.9697, 43.0303, 43.0909, 43.1515, 43.2121, 43.2727, 43.3333, 43.3939, 43.4545, 43.5152, 43.5758, 43.6364, 43.6970, 43.7576, 43.8182, 43.8788, 43.9394, 44.0000, 44.0606, 44.1212, 44.1818, 44.2424, 44.3030, 44.3636, 44.4242, 44.4848, 44.5455, 44.6061, 44.6667, 44.7273, 44.7879, 44.8485, 44.9091, 44.9697, 45.0303, 45.0909, 45.1515, 45.2121, 45.2727, 45.3333, 45.3939, 45.4545, 45.5152, 45.5758, 45.6364, 45.6970, 45.7576, 45.8182, 45.8788, 45.9394, 46.0000, 46.0606, 46.1212, 46.1818, 46.2424, 46.3030, 46.3636, 46.4242, 46.4848, 46.5455, 46.6061, 46.6667, 46.7273, 46.7879, 46.8485, 46.9091, 46.9697, 47.0303, 47.0909, 47.1515, 47.2121, 47.2727, 47.3333, 47.3939, 47.4545, 47.5152, 47.5758, 47.6364, 47.6970, 47.7576, 47.8182, 47.8788, 47.9394, 48.0000, 48.0606, 48.1212, 48.1818, 48.2424, 48.3030, 48.3636, 48.4242, 48.4848, 48.5455, 48.6061, 48.6667, 48.7273, 48.7879, 48.8485, 48.9091, 48.9697, 49.0303, 49.0909, 49.1515, 49.2121, 49.2727, 49.3333, 49.3939, 49.4545, 49.5152, 49.5758, 49.6364, 49.6970, 49.7576, 49.8182, 49.8788, 49.9394, ])
  2587. self.y = [None]*3
  2588. self.y[0] = array([0.0000, 0.0005, 0.0006, 0.0004, -0.0004, -0.0007, -0.0022, -0.0027, -0.0036, -0.0042, -0.0050, -0.0049, -0.0060, -0.0072, -0.0085, -0.0092, -0.0104, -0.0116, -0.0133, -0.0148, -0.0160, -0.0177, -0.0186, -0.0191, -0.0192, -0.0187, -0.0187, -0.0187, -0.0192, -0.0198, -0.0201, -0.0208, -0.0216, -0.0227, -0.0242, -0.0260, -0.0277, -0.0299, -0.0319, -0.0328, -0.0333, -0.0338, -0.0347, -0.0360, -0.0363, -0.0365, -0.0370, -0.0373, -0.0364, -0.0355, -0.0343, -0.0329, -0.0317, -0.0312, -0.0309, -0.0306, -0.0301, -0.0290, -0.0275, -0.0259, -0.0238, -0.0222, -0.0200, -0.0176, -0.0154, -0.0130, -0.0108, -0.0081, -0.0046, -0.0001, 0.0035, 0.0061, 0.0083, 0.0105, 0.0130, 0.0156, 0.0170, 0.0181, 0.0196, 0.0212, 0.0231, 0.0247, 0.0262, 0.0277, 0.0293, 0.0309, 0.0325, 0.0336, 0.0348, 0.0360, 0.0378, 0.0401, 0.0423, 0.0443, 0.0457, 0.0473, 0.0488, 0.0500, 0.0511, 0.0518, 0.0528, 0.0534, 0.0547, 0.0561, 0.0577, 0.0585, 0.0594, 0.0606, 0.0611, 0.0614, 0.0617, 0.0612, 0.0607, 0.0608, 0.0603, 0.0599, 0.0588, 0.0577, 0.0557, 0.0543, 0.0532, 0.0520, 0.0505, 0.0496, 0.0499, 0.0490, 0.0489, 0.0496, 0.0504, 0.0504, 0.0509, 0.0512, 0.0512, 0.0504, 0.0499, 0.0498, 0.0493, 0.0491, 0.0483, 0.0478, 0.0474, 0.0468, 0.0462, 0.0460, 0.0462, 0.0467, 0.0472, 0.0476, 0.0483, 0.0491, 0.0502, 0.0510, 0.0504, 0.0503, 0.0514, 0.0527, 0.0538, 0.0547, 0.0554, 0.0561, 0.0561, 0.0558, 0.0548, 0.0540, 0.0531, 0.0524, 0.0516, 0.0513, 0.0511, 0.0520, 0.0519, 0.0513, 0.0512, 0.0525, 0.0535, 0.0545, 0.0552, 0.0566, 0.0577, 0.0591, 0.0602, 0.0605, 0.0609, 0.0615, 0.0627, 0.0638, 0.0644, 0.0652, 0.0661, 0.0670, 0.0678, 0.0692, 0.0706, 0.0729, 0.0757, 0.0786, 0.0805, 0.0825, 0.0846, 0.0870, 0.0897, 0.0921, 0.0947, 0.0968, 0.0997, 0.1018, 0.1027, 0.1025, 0.1018, 0.1004, 0.1000, 0.0994, 0.0980, 0.0972, 0.0960, 0.0941, 0.0927, 0.0916, 0.0902, 0.0896, 0.0890, 0.0892, 0.0896, 0.0908, 0.0919, 0.0922, 0.0937, 0.0948, 0.0957, 0.0960, 0.0961, 0.0963, 0.0965, 0.0970, 0.0983, 0.0994, 0.0997, 0.0993, 0.0984, 0.0965, 0.0951, 0.0934, 0.0916, 0.0897, 0.0870, 0.0840, 0.0813, 0.0791, 0.0766, 0.0751, 0.0730, 0.0707, 0.0683, 0.0644, 0.0616, 0.0592, 0.0562, 0.0545, 0.0531, 0.0519, 0.0504, 0.0490, 0.0468, 0.0451, 0.0432, 0.0414, 0.0403, 0.0394, 0.0386, 0.0380, 0.0370, 0.0364, 0.0367, 0.0374, 0.0385, 0.0390, 0.0390, 0.0381, 0.0380, 0.0377, 0.0381, 0.0380, 0.0377, 0.0374, 0.0376, 0.0378, 0.0380, 0.0382, 0.0385, 0.0381, 0.0377, 0.0373, 0.0367, 0.0365, 0.0358, 0.0351, 0.0342, 0.0336, 0.0334, 0.0326, 0.0322, 0.0329, 0.0327, 0.0321, 0.0310, 0.0297, 0.0293, 0.0290, 0.0283, 0.0279, 0.0272, 0.0271, 0.0271, 0.0279, 0.0282, 0.0302, 0.0325, 0.0351, 0.0375, 0.0393, 0.0406, 0.0416, 0.0422, 0.0428, 0.0430, 0.0434, 0.0443, 0.0447, 0.0457, 0.0465, 0.0479, 0.0494, 0.0514, 0.0527, 0.0539, 0.0557, 0.0571, 0.0572, 0.0563, 0.0539, 0.0504, 0.0469, 0.0441, 0.0412, 0.0385, 0.0359, 0.0334, 0.0308, 0.0282, 0.0260, 0.0232, 0.0211, 0.0196, 0.0180, 0.0169, 0.0154, 0.0137, 0.0121, 0.0105, 0.0088, 0.0067, 0.0044, 0.0027, -0.0000, -0.0024, -0.0048, -0.0066, -0.0082, -0.0111, -0.0136, -0.0158, -0.0179, -0.0201, -0.0218, -0.0235, -0.0242, -0.0245, -0.0236, -0.0231, -0.0237, -0.0237, -0.0233, -0.0229, -0.0233, -0.0239, -0.0241, -0.0244, -0.0247, -0.0251, -0.0259, -0.0270, -0.0288, -0.0295, -0.0305, -0.0311, -0.0322, -0.0327, -0.0343, -0.0352, -0.0361, -0.0358, -0.0362, -0.0365, -0.0365, -0.0358, -0.0353, -0.0348, -0.0355, -0.0365, -0.0373, -0.0373, -0.0375, -0.0365, -0.0345, -0.0327, -0.0322, -0.0327, -0.0335, -0.0337, -0.0337, -0.0348, -0.0359, -0.0361, -0.0364, -0.0371, -0.0366, -0.0361, -0.0358, -0.0353, -0.0348, -0.0345, -0.0335, -0.0320, -0.0300, -0.0281, -0.0257, -0.0233, -0.0208, -0.0179, -0.0146, -0.0104, -0.0062, -0.0031, -0.0007, 0.0023, 0.0049, 0.0077, 0.0099, 0.0125, 0.0147, 0.0177, 0.0202, 0.0232, 0.0264, 0.0291, 0.0322, 0.0346, 0.0365, 0.0386, 0.0403, 0.0415, 0.0425, 0.0428, 0.0436, 0.0447, 0.0457, 0.0465, 0.0475, 0.0494, 0.0516, 0.0534, 0.0555, 0.0574, 0.0591, 0.0616, 0.0638, 0.0655, 0.0660, 0.0657, 0.0656, 0.0650, 0.0647, 0.0637, 0.0623, 0.0613, 0.0611, 0.0611, 0.0618, 0.0633, 0.0652, 0.0665, 0.0677, 0.0690, 0.0700, 0.0712, 0.0713, 0.0710, 0.0709, 0.0695, 0.0675, 0.0655, 0.0626, 0.0598, 0.0566, 0.0533, 0.0501, 0.0470, 0.0437, 0.0405, 0.0372, 0.0342, 0.0323, 0.0305, 0.0289, 0.0267, 0.0250, 0.0229, 0.0204, 0.0183, 0.0164, 0.0152, 0.0148, 0.0141, 0.0135, 0.0139, 0.0148, 0.0160, 0.0179, 0.0193, 0.0210, 0.0234, 0.0266, 0.0291, 0.0314, 0.0337, 0.0358, 0.0375, 0.0395, 0.0412, 0.0417, 0.0424, 0.0428, 0.0428, 0.0418, 0.0415, 0.0398, 0.0373, 0.0347, 0.0328, 0.0318, 0.0301, 0.0284, 0.0258, 0.0240, 0.0214, 0.0188, 0.0168, 0.0148, 0.0137, 0.0122, 0.0109, 0.0101, 0.0093, 0.0093, 0.0096, 0.0089, 0.0104, 0.0123, 0.0141, 0.0150, 0.0159, 0.0165, 0.0174, 0.0185, 0.0205, 0.0225, 0.0247, 0.0269, 0.0290, 0.0308, 0.0331, 0.0357, 0.0379, 0.0392, 0.0405, 0.0423, 0.0440, 0.0465, 0.0484, 0.0503, 0.0506, 0.0506, 0.0504, 0.0504, 0.0513, 0.0521, 0.0537, 0.0555, 0.0577, 0.0595, 0.0619, 0.0636, 0.0654, 0.0666, 0.0674, 0.0672, 0.0667, 0.0664, 0.0660, 0.0648, 0.0645, 0.0642, 0.0645, 0.0651, 0.0653, 0.0643, 0.0629, 0.0621, 0.0607, 0.0597, 0.0585, 0.0574, 0.0553, 0.0539, 0.0525, 0.0516, 0.0508, 0.0505, 0.0500, 0.0500, 0.0490, 0.0475, 0.0464, 0.0452, 0.0440, 0.0427, 0.0416, 0.0403, 0.0393, 0.0377, 0.0360, 0.0349, 0.0343, 0.0332, 0.0325, 0.0313, 0.0305, 0.0287, 0.0263, 0.0237, 0.0211, 0.0194, 0.0182, 0.0180, 0.0184, 0.0186, 0.0186, 0.0192, 0.0198, 0.0203, 0.0200, 0.0196, 0.0177, 0.0156, 0.0130, 0.0110, 0.0087, 0.0064, 0.0049, 0.0029, 0.0011, -0.0016, -0.0042, -0.0064, -0.0080, -0.0100, -0.0118, -0.0133, -0.0147, -0.0160, -0.0170, -0.0176, -0.0188, -0.0206, -0.0209, -0.0201, -0.0200, -0.0198, -0.0191, -0.0181, -0.0170, -0.0165, -0.0161, -0.0159, -0.0157, -0.0156, -0.0156, -0.0150, -0.0137, -0.0131, -0.0128, -0.0129, -0.0124, -0.0119, -0.0106, -0.0096, -0.0086, -0.0084, -0.0075, -0.0069, -0.0070, -0.0075, -0.0092, -0.0109, -0.0124, -0.0137, -0.0140, -0.0146, -0.0146, -0.0144, -0.0144, -0.0155, -0.0160, -0.0167, -0.0174, -0.0187, -0.0198, -0.0208, -0.0217, -0.0226, -0.0229, -0.0226, -0.0219, -0.0194, -0.0173, -0.0155, -0.0143, -0.0129, -0.0120, -0.0126, -0.0137, -0.0148, -0.0153, -0.0166, -0.0182, -0.0197, -0.0216, -0.0230, -0.0244, -0.0255, -0.0270, -0.0275, -0.0280, -0.0277, -0.0276, -0.0272, -0.0272, -0.0276, -0.0284, -0.0292, -0.0300, -0.0299, -0.0305, -0.0315, -0.0316, -0.0313, -0.0320, -0.0324, -0.0326, -0.0339, -0.0354, -0.0368, -0.0376, -0.0379, -0.0381, -0.0377, -0.0373, -0.0374, -0.0380, -0.0382, -0.0394, -0.0402, -0.0415, -0.0429, -0.0439, -0.0442, -0.0455, -0.0472, -0.0487, -0.0504, -0.0515, -0.0537, -0.0555, -0.0570, -0.0583, -0.0589, -0.0601, -0.0606, -0.0614, -0.0617, -0.0621, -0.0620, -0.0614, -0.0616, -0.0618, -0.0620, -0.0622, -0.0628, -0.0623, -0.0617, -0.0602, -0.0590, -0.0584, -0.0577, -0.0572, -0.0555, -0.0536, -0.0511, -0.0488, -0.0468, -0.0448, -0.0427, -0.0401, -0.0378, -0.0358, ])
  2589. self.y[1] = array([0.0000, 0.0002, 0.0002, 0.0001, 0.0001, 0.0003, 0.0008, 0.0009, 0.0009, 0.0015, 0.0019, 0.0027, 0.0033, 0.0037, 0.0041, 0.0052, 0.0055, 0.0050, 0.0048, 0.0054, 0.0054, 0.0059, 0.0061, 0.0060, 0.0054, 0.0050, 0.0047, 0.0042, 0.0033, 0.0031, 0.0027, 0.0021, 0.0015, 0.0008, -0.0002, -0.0011, -0.0015, -0.0015, -0.0021, -0.0025, -0.0027, -0.0013, 0.0005, 0.0030, 0.0049, 0.0074, 0.0099, 0.0119, 0.0142, 0.0166, 0.0186, 0.0205, 0.0229, 0.0247, 0.0266, 0.0286, 0.0307, 0.0327, 0.0346, 0.0368, 0.0379, 0.0393, 0.0409, 0.0434, 0.0457, 0.0478, 0.0499, 0.0520, 0.0534, 0.0544, 0.0561, 0.0576, 0.0587, 0.0593, 0.0597, 0.0599, 0.0594, 0.0588, 0.0588, 0.0595, 0.0609, 0.0628, 0.0651, 0.0673, 0.0693, 0.0721, 0.0760, 0.0798, 0.0837, 0.0881, 0.0931, 0.0977, 0.1023, 0.1076, 0.1127, 0.1175, 0.1223, 0.1264, 0.1302, 0.1333, 0.1373, 0.1408, 0.1441, 0.1472, 0.1497, 0.1516, 0.1523, 0.1527, 0.1532, 0.1537, 0.1542, 0.1549, 0.1551, 0.1543, 0.1536, 0.1532, 0.1524, 0.1512, 0.1497, 0.1484, 0.1473, 0.1460, 0.1445, 0.1429, 0.1411, 0.1398, 0.1395, 0.1395, 0.1388, 0.1386, 0.1380, 0.1369, 0.1355, 0.1341, 0.1319, 0.1293, 0.1266, 0.1240, 0.1215, 0.1189, 0.1160, 0.1135, 0.1111, 0.1079, 0.1049, 0.1016, 0.0995, 0.0972, 0.0948, 0.0927, 0.0914, 0.0904, 0.0892, 0.0878, 0.0862, 0.0848, 0.0829, 0.0809, 0.0792, 0.0776, 0.0760, 0.0754, 0.0740, 0.0724, 0.0700, 0.0680, 0.0668, 0.0658, 0.0655, 0.0653, 0.0648, 0.0636, 0.0613, 0.0589, 0.0573, 0.0559, 0.0552, 0.0558, 0.0571, 0.0587, 0.0602, 0.0608, 0.0613, 0.0607, 0.0601, 0.0595, 0.0595, 0.0590, 0.0591, 0.0598, 0.0603, 0.0603, 0.0610, 0.0610, 0.0607, 0.0603, 0.0601, 0.0607, 0.0608, 0.0616, 0.0627, 0.0640, 0.0653, 0.0662, 0.0669, 0.0673, 0.0667, 0.0654, 0.0646, 0.0635, 0.0624, 0.0604, 0.0583, 0.0562, 0.0547, 0.0537, 0.0524, 0.0522, 0.0516, 0.0515, 0.0518, 0.0515, 0.0504, 0.0501, 0.0501, 0.0501, 0.0498, 0.0494, 0.0489, 0.0485, 0.0483, 0.0484, 0.0477, 0.0472, 0.0468, 0.0471, 0.0463, 0.0461, 0.0460, 0.0466, 0.0461, 0.0454, 0.0448, 0.0445, 0.0439, 0.0437, 0.0439, 0.0438, 0.0430, 0.0423, 0.0418, 0.0415, 0.0409, 0.0400, 0.0386, 0.0376, 0.0370, 0.0357, 0.0351, 0.0354, 0.0356, 0.0356, 0.0362, 0.0366, 0.0380, 0.0385, 0.0378, 0.0381, 0.0390, 0.0390, 0.0388, 0.0386, 0.0379, 0.0366, 0.0362, 0.0364, 0.0365, 0.0363, 0.0363, 0.0359, 0.0354, 0.0348, 0.0354, 0.0350, 0.0337, 0.0314, 0.0282, 0.0258, 0.0240, 0.0230, 0.0227, 0.0227, 0.0221, 0.0214, 0.0201, 0.0188, 0.0179, 0.0173, 0.0165, 0.0155, 0.0133, 0.0109, 0.0082, 0.0052, 0.0028, 0.0003, -0.0026, -0.0062, -0.0095, -0.0120, -0.0151, -0.0180, -0.0209, -0.0233, -0.0262, -0.0293, -0.0316, -0.0337, -0.0361, -0.0385, -0.0419, -0.0445, -0.0470, -0.0494, -0.0515, -0.0534, -0.0561, -0.0590, -0.0619, -0.0643, -0.0666, -0.0688, -0.0710, -0.0733, -0.0753, -0.0774, -0.0795, -0.0822, -0.0837, -0.0851, -0.0865, -0.0876, -0.0892, -0.0892, -0.0893, -0.0896, -0.0901, -0.0905, -0.0909, -0.0909, -0.0901, -0.0890, -0.0884, -0.0880, -0.0873, -0.0871, -0.0872, -0.0860, -0.0858, -0.0863, -0.0865, -0.0864, -0.0865, -0.0871, -0.0887, -0.0904, -0.0924, -0.0941, -0.0962, -0.0980, -0.0999, -0.1014, -0.1021, -0.1029, -0.1037, -0.1041, -0.1052, -0.1056, -0.1065, -0.1070, -0.1075, -0.1073, -0.1079, -0.1080, -0.1078, -0.1075, -0.1074, -0.1078, -0.1082, -0.1087, -0.1083, -0.1079, -0.1087, -0.1096, -0.1101, -0.1105, -0.1114, -0.1121, -0.1127, -0.1135, -0.1137, -0.1133, -0.1131, -0.1126, -0.1115, -0.1109, -0.1099, -0.1097, -0.1092, -0.1081, -0.1066, -0.1057, -0.1050, -0.1047, -0.1040, -0.1030, -0.1018, -0.1004, -0.0988, -0.0972, -0.0955, -0.0946, -0.0938, -0.0925, -0.0905, -0.0886, -0.0864, -0.0838, -0.0805, -0.0776, -0.0748, -0.0720, -0.0686, -0.0655, -0.0621, -0.0588, -0.0555, -0.0520, -0.0477, -0.0434, -0.0389, -0.0353, -0.0323, -0.0287, -0.0247, -0.0211, -0.0179, -0.0149, -0.0123, -0.0094, -0.0065, -0.0042, -0.0020, -0.0001, 0.0016, 0.0028, 0.0044, 0.0072, 0.0097, 0.0109, 0.0120, 0.0127, 0.0135, 0.0140, 0.0151, 0.0147, 0.0158, 0.0161, 0.0162, 0.0154, 0.0154, 0.0162, 0.0172, 0.0186, 0.0204, 0.0214, 0.0213, 0.0210, 0.0211, 0.0208, 0.0204, 0.0202, 0.0201, 0.0187, 0.0179, 0.0167, 0.0164, 0.0167, 0.0170, 0.0180, 0.0188, 0.0199, 0.0204, 0.0213, 0.0209, 0.0203, 0.0198, 0.0186, 0.0183, 0.0181, 0.0168, 0.0163, 0.0161, 0.0160, 0.0154, 0.0157, 0.0162, 0.0166, 0.0171, 0.0171, 0.0179, 0.0186, 0.0196, 0.0205, 0.0229, 0.0254, 0.0280, 0.0305, 0.0327, 0.0343, 0.0354, 0.0361, 0.0367, 0.0363, 0.0361, 0.0355, 0.0353, 0.0351, 0.0342, 0.0335, 0.0328, 0.0326, 0.0324, 0.0325, 0.0330, 0.0333, 0.0333, 0.0327, 0.0326, 0.0328, 0.0326, 0.0327, 0.0329, 0.0328, 0.0332, 0.0331, 0.0325, 0.0315, 0.0311, 0.0305, 0.0302, 0.0300, 0.0289, 0.0275, 0.0260, 0.0246, 0.0234, 0.0230, 0.0216, 0.0211, 0.0205, 0.0191, 0.0172, 0.0147, 0.0131, 0.0112, 0.0094, 0.0082, 0.0062, 0.0045, 0.0041, 0.0035, 0.0037, 0.0035, 0.0033, 0.0033, 0.0037, 0.0034, 0.0036, 0.0033, 0.0028, 0.0021, 0.0015, 0.0008, 0.0004, 0.0002, -0.0002, -0.0008, -0.0001, 0.0007, 0.0015, 0.0020, 0.0020, 0.0028, 0.0037, 0.0045, 0.0052, 0.0060, 0.0063, 0.0074, 0.0083, 0.0092, 0.0095, 0.0095, 0.0096, 0.0093, 0.0100, 0.0097, 0.0093, 0.0084, 0.0071, 0.0050, 0.0044, 0.0031, 0.0017, 0.0005, -0.0004, -0.0018, -0.0026, -0.0026, -0.0020, -0.0018, -0.0010, 0.0003, 0.0024, 0.0046, 0.0066, 0.0090, 0.0110, 0.0126, 0.0143, 0.0157, 0.0167, 0.0171, 0.0179, 0.0195, 0.0223, 0.0254, 0.0287, 0.0320, 0.0359, 0.0400, 0.0439, 0.0470, 0.0491, 0.0515, 0.0535, 0.0563, 0.0585, 0.0605, 0.0620, 0.0635, 0.0654, 0.0670, 0.0687, 0.0701, 0.0728, 0.0746, 0.0766, 0.0785, 0.0800, 0.0812, 0.0817, 0.0822, 0.0820, 0.0814, 0.0814, 0.0817, 0.0820, 0.0823, 0.0826, 0.0826, 0.0831, 0.0833, 0.0846, 0.0851, 0.0853, 0.0855, 0.0858, 0.0859, 0.0864, 0.0868, 0.0876, 0.0884, 0.0890, 0.0894, 0.0895, 0.0888, 0.0882, 0.0883, 0.0884, 0.0892, 0.0903, 0.0915, 0.0917, 0.0916, 0.0908, 0.0900, 0.0891, 0.0881, 0.0869, 0.0849, 0.0825, 0.0805, 0.0789, 0.0773, 0.0761, 0.0750, 0.0738, 0.0729, 0.0717, 0.0712, 0.0714, 0.0718, 0.0727, 0.0737, 0.0735, 0.0733, 0.0723, 0.0706, 0.0683, 0.0666, 0.0651, 0.0636, 0.0620, 0.0599, 0.0580, 0.0563, 0.0551, 0.0540, 0.0526, 0.0516, 0.0503, 0.0492, 0.0482, 0.0469, 0.0468, 0.0471, 0.0471, 0.0471, 0.0483, 0.0490, 0.0486, 0.0489, 0.0495, 0.0510, 0.0523, 0.0538, 0.0547, 0.0552, 0.0556, 0.0569, 0.0573, 0.0578, 0.0583, 0.0579, 0.0579, 0.0580, 0.0583, 0.0585, 0.0594, 0.0601, 0.0598, 0.0594, 0.0597, 0.0602, 0.0611, 0.0612, 0.0618, 0.0620, 0.0626, 0.0635, 0.0637, 0.0645, 0.0649, 0.0657, 0.0667, 0.0680, 0.0688, 0.0693, 0.0698, 0.0702, 0.0699, 0.0703, 0.0702, 0.0705, 0.0716, 0.0725, 0.0730, 0.0736, 0.0736, 0.0734, 0.0735, 0.0739, 0.0736, 0.0728, 0.0720, 0.0717, 0.0715, 0.0709, 0.0704, 0.0707, 0.0704, 0.0695, 0.0690, 0.0687, 0.0667, 0.0648, 0.0629, 0.0620, 0.0620, 0.0618, 0.0621, 0.0623, 0.0633, 0.0637, 0.0637, 0.0638, 0.0639, 0.0639, 0.0642, 0.0650, 0.0653, 0.0657, 0.0661, ])
  2590. self.y[2] = array([0.0000, 0.0001, -0.0002, -0.0003, 0.0004, 0.0014, 0.0021, 0.0025, 0.0025, 0.0021, 0.0018, 0.0022, 0.0016, 0.0018, 0.0018, 0.0021, 0.0027, 0.0034, 0.0046, 0.0060, 0.0076, 0.0080, 0.0084, 0.0090, 0.0100, 0.0104, 0.0098, 0.0097, 0.0100, 0.0100, 0.0105, 0.0117, 0.0124, 0.0128, 0.0133, 0.0133, 0.0133, 0.0132, 0.0132, 0.0136, 0.0144, 0.0161, 0.0179, 0.0196, 0.0222, 0.0251, 0.0265, 0.0279, 0.0287, 0.0291, 0.0297, 0.0305, 0.0316, 0.0328, 0.0340, 0.0361, 0.0382, 0.0408, 0.0425, 0.0442, 0.0460, 0.0474, 0.0489, 0.0502, 0.0512, 0.0517, 0.0526, 0.0525, 0.0525, 0.0521, 0.0508, 0.0498, 0.0487, 0.0478, 0.0472, 0.0461, 0.0446, 0.0434, 0.0415, 0.0399, 0.0388, 0.0374, 0.0360, 0.0351, 0.0339, 0.0320, 0.0308, 0.0294, 0.0286, 0.0278, 0.0255, 0.0224, 0.0194, 0.0170, 0.0147, 0.0131, 0.0123, 0.0121, 0.0110, 0.0106, 0.0100, 0.0090, 0.0089, 0.0093, 0.0100, 0.0111, 0.0132, 0.0159, 0.0179, 0.0195, 0.0207, 0.0220, 0.0229, 0.0242, 0.0261, 0.0279, 0.0290, 0.0300, 0.0303, 0.0309, 0.0316, 0.0328, 0.0335, 0.0332, 0.0323, 0.0314, 0.0300, 0.0283, 0.0268, 0.0248, 0.0225, 0.0201, 0.0172, 0.0143, 0.0119, 0.0104, 0.0088, 0.0071, 0.0059, 0.0051, 0.0038, 0.0027, 0.0017, 0.0009, 0.0007, -0.0002, -0.0008, -0.0020, -0.0034, -0.0055, -0.0069, -0.0082, -0.0086, -0.0085, -0.0089, -0.0088, -0.0092, -0.0099, -0.0110, -0.0121, -0.0137, -0.0150, -0.0157, -0.0160, -0.0155, -0.0149, -0.0140, -0.0139, -0.0134, -0.0135, -0.0136, -0.0138, -0.0145, -0.0158, -0.0155, -0.0155, -0.0153, -0.0154, -0.0159, -0.0157, -0.0152, -0.0143, -0.0140, -0.0138, -0.0142, -0.0148, -0.0154, -0.0154, -0.0147, -0.0136, -0.0122, -0.0107, -0.0102, -0.0091, -0.0082, -0.0063, -0.0042, -0.0028, -0.0007, 0.0015, 0.0038, 0.0054, 0.0075, 0.0093, 0.0110, 0.0137, 0.0156, 0.0170, 0.0184, 0.0195, 0.0199, 0.0206, 0.0209, 0.0207, 0.0201, 0.0198, 0.0196, 0.0191, 0.0192, 0.0193, 0.0196, 0.0201, 0.0206, 0.0216, 0.0229, 0.0253, 0.0278, 0.0304, 0.0321, 0.0341, 0.0356, 0.0367, 0.0372, 0.0379, 0.0383, 0.0394, 0.0396, 0.0397, 0.0391, 0.0382, 0.0362, 0.0346, 0.0334, 0.0325, 0.0325, 0.0325, 0.0323, 0.0316, 0.0321, 0.0328, 0.0338, 0.0352, 0.0366, 0.0378, 0.0389, 0.0401, 0.0403, 0.0406, 0.0419, 0.0425, 0.0424, 0.0421, 0.0415, 0.0407, 0.0406, 0.0411, 0.0413, 0.0419, 0.0420, 0.0416, 0.0415, 0.0402, 0.0388, 0.0377, 0.0368, 0.0357, 0.0353, 0.0351, 0.0348, 0.0347, 0.0340, 0.0326, 0.0314, 0.0306, 0.0295, 0.0288, 0.0275, 0.0257, 0.0234, 0.0209, 0.0188, 0.0169, 0.0151, 0.0132, 0.0114, 0.0093, 0.0076, 0.0055, 0.0026, -0.0008, -0.0038, -0.0069, -0.0097, -0.0118, -0.0132, -0.0148, -0.0164, -0.0183, -0.0202, -0.0213, -0.0228, -0.0253, -0.0280, -0.0299, -0.0315, -0.0329, -0.0343, -0.0349, -0.0364, -0.0373, -0.0383, -0.0391, -0.0400, -0.0401, -0.0404, -0.0414, -0.0422, -0.0425, -0.0425, -0.0420, -0.0419, -0.0412, -0.0412, -0.0408, -0.0400, -0.0396, -0.0397, -0.0400, -0.0401, -0.0405, -0.0412, -0.0410, -0.0401, -0.0389, -0.0377, -0.0372, -0.0369, -0.0364, -0.0356, -0.0347, -0.0345, -0.0346, -0.0353, -0.0359, -0.0367, -0.0376, -0.0385, -0.0387, -0.0391, -0.0401, -0.0400, -0.0398, -0.0395, -0.0391, -0.0385, -0.0383, -0.0377, -0.0374, -0.0371, -0.0361, -0.0357, -0.0355, -0.0342, -0.0324, -0.0303, -0.0280, -0.0257, -0.0232, -0.0205, -0.0179, -0.0147, -0.0113, -0.0091, -0.0059, -0.0019, 0.0024, 0.0071, 0.0120, 0.0177, 0.0219, 0.0248, 0.0273, 0.0290, 0.0302, 0.0318, 0.0325, 0.0331, 0.0334, 0.0344, 0.0360, 0.0387, 0.0414, 0.0437, 0.0456, 0.0471, 0.0491, 0.0511, 0.0526, 0.0536, 0.0550, 0.0570, 0.0597, 0.0622, 0.0647, 0.0672, 0.0696, 0.0710, 0.0725, 0.0748, 0.0777, 0.0806, 0.0832, 0.0854, 0.0874, 0.0893, 0.0906, 0.0914, 0.0927, 0.0937, 0.0944, 0.0959, 0.0970, 0.0970, 0.0967, 0.0955, 0.0945, 0.0934, 0.0927, 0.0921, 0.0916, 0.0909, 0.0901, 0.0893, 0.0884, 0.0881, 0.0877, 0.0870, 0.0870, 0.0871, 0.0872, 0.0867, 0.0860, 0.0845, 0.0821, 0.0800, 0.0775, 0.0752, 0.0728, 0.0703, 0.0676, 0.0655, 0.0637, 0.0618, 0.0593, 0.0558, 0.0518, 0.0483, 0.0445, 0.0414, 0.0384, 0.0365, 0.0349, 0.0338, 0.0330, 0.0323, 0.0320, 0.0319, 0.0320, 0.0323, 0.0324, 0.0324, 0.0322, 0.0327, 0.0328, 0.0320, 0.0314, 0.0295, 0.0279, 0.0258, 0.0243, 0.0229, 0.0211, 0.0195, 0.0176, 0.0163, 0.0151, 0.0136, 0.0123, 0.0108, 0.0088, 0.0064, 0.0041, 0.0021, 0.0002, -0.0020, -0.0051, -0.0078, -0.0106, -0.0137, -0.0169, -0.0195, -0.0218, -0.0235, -0.0253, -0.0269, -0.0281, -0.0290, -0.0299, -0.0315, -0.0328, -0.0336, -0.0344, -0.0352, -0.0354, -0.0353, -0.0358, -0.0355, -0.0347, -0.0344, -0.0338, -0.0335, -0.0324, -0.0319, -0.0319, -0.0322, -0.0334, -0.0351, -0.0365, -0.0381, -0.0401, -0.0424, -0.0449, -0.0472, -0.0491, -0.0506, -0.0522, -0.0533, -0.0544, -0.0553, -0.0553, -0.0557, -0.0558, -0.0563, -0.0573, -0.0587, -0.0602, -0.0617, -0.0636, -0.0666, -0.0699, -0.0734, -0.0760, -0.0791, -0.0817, -0.0840, -0.0857, -0.0869, -0.0881, -0.0882, -0.0884, -0.0888, -0.0893, -0.0889, -0.0876, -0.0869, -0.0858, -0.0851, -0.0836, -0.0825, -0.0813, -0.0807, -0.0800, -0.0802, -0.0805, -0.0807, -0.0813, -0.0818, -0.0819, -0.0822, -0.0829, -0.0825, -0.0829, -0.0838, -0.0840, -0.0836, -0.0824, -0.0810, -0.0799, -0.0789, -0.0785, -0.0785, -0.0774, -0.0770, -0.0761, -0.0755, -0.0752, -0.0746, -0.0744, -0.0741, -0.0729, -0.0718, -0.0710, -0.0694, -0.0673, -0.0649, -0.0627, -0.0606, -0.0592, -0.0582, -0.0571, -0.0555, -0.0539, -0.0527, -0.0516, -0.0508, -0.0503, -0.0508, -0.0518, -0.0527, -0.0536, -0.0544, -0.0545, -0.0541, -0.0547, -0.0553, -0.0561, -0.0573, -0.0587, -0.0600, -0.0608, -0.0616, -0.0624, -0.0626, -0.0631, -0.0638, -0.0630, -0.0621, -0.0612, -0.0603, -0.0594, -0.0577, -0.0564, -0.0551, -0.0535, -0.0511, -0.0485, -0.0455, -0.0424, -0.0396, -0.0374, -0.0360, -0.0351, -0.0343, -0.0336, -0.0324, -0.0311, -0.0296, -0.0276, -0.0259, -0.0240, -0.0223, -0.0212, -0.0205, -0.0201, -0.0203, -0.0214, -0.0232, -0.0261, -0.0285, -0.0304, -0.0320, -0.0342, -0.0365, -0.0381, -0.0394, -0.0416, -0.0434, -0.0443, -0.0450, -0.0465, -0.0482, -0.0490, -0.0497, -0.0508, -0.0506, -0.0509, -0.0514, -0.0522, -0.0525, -0.0532, -0.0547, -0.0553, -0.0575, -0.0597, -0.0629, -0.0666, -0.0702, -0.0737, -0.0773, -0.0805, -0.0835, -0.0847, -0.0875, -0.0893, -0.0913, -0.0929, -0.0935, -0.0943, -0.0949, -0.0957, -0.0962, -0.0977, -0.0994, -0.1011, -0.1031, -0.1057, -0.1086, -0.1114, -0.1141, -0.1158, -0.1174, -0.1197, -0.1219, -0.1234, -0.1250, -0.1267, -0.1273, -0.1270, -0.1268, -0.1263, -0.1257, -0.1240, -0.1220, -0.1210, -0.1197, -0.1197, -0.1188, -0.1171, -0.1147, -0.1122, -0.1101, -0.1077, -0.1052, -0.1031, -0.1020, -0.1008, -0.0983, -0.0960, -0.0934, -0.0908, -0.0889, -0.0865, -0.0836, -0.0799, -0.0767, -0.0740, -0.0716, -0.0692, -0.0663, -0.0628, -0.0596, -0.0567, -0.0535, -0.0508, -0.0472, -0.0435, -0.0394, -0.0347, -0.0301, -0.0253, -0.0210, -0.0165, -0.0126, -0.0095, -0.0072, -0.0046, -0.0020, -0.0001, 0.0023, 0.0050, 0.0077, 0.0102, 0.0135, 0.0175, 0.0212, 0.0245, 0.0280, 0.0309, 0.0336, 0.0365, 0.0397, 0.0433, 0.0474, 0.0511, 0.0546, 0.0574, 0.0602, 0.0634, 0.0663, 0.0695, 0.0729, 0.0752, 0.0762, 0.0773, 0.0781, 0.0790, 0.0806, 0.0836, 0.0857, 0.0879, 0.0896, 0.0920, 0.0949, 0.0975, 0.1002, ])
  2591. # COMPOSITE types:
  2592. # MassSpringForce: Line(horizontal), Spring, Rectangle, Arrow/Line(w/arrow)
  2593. # must be easy to find the tip of the arrow
  2594. # Maybe extra dict: self.name['mass'] = Rectangle object - YES!
  2595. class ArbitraryVolume(Shape):
  2596. """
  2597. An arbitrary closed volume with an optional normal vector and a
  2598. vector field to be used in derivation of continuum mechanical
  2599. equations.
  2600. """
  2601. def __init__(self, position, width=1,
  2602. volume_symbol='V',
  2603. volume_symbol_fontsize='18',
  2604. normal_vector_symbol='n',
  2605. vector_field_symbol=None):
  2606. """
  2607. ============================ ====================================
  2608. Name Description
  2609. ============================ ====================================
  2610. position center point of volume
  2611. width width of volume (about 3 is best)
  2612. normal_vector_symbol symbol of None (no boundary normal)
  2613. volume_symbol None (no center symbol) or character
  2614. volume_symbol_fontsize fontsize of volume symbol
  2615. vector_field_symbol None (no vector) or symbol
  2616. ============================ ====================================
  2617. """
  2618. self.position, self.width = position, width
  2619. self.vector_symbol = vector_field_symbol
  2620. self.normal_symbol = normal_vector_symbol
  2621. ellipse, normal, vector = self._perturbed_unit_ellipse()
  2622. self.shapes = {'closed_curve': ellipse}
  2623. if normal_vector_symbol:
  2624. self.shapes['normal'] = normal
  2625. if vector_field_symbol is not None:
  2626. self.shapes['vector'] = vector
  2627. # Scale and translate
  2628. self.rotate(20, (0,0))
  2629. self.scale(width/2.0)
  2630. self.translate(position)
  2631. # Must be placed at position after translation:
  2632. if volume_symbol:
  2633. self.shapes['name'] = Text('$%s$' % volume_symbol, position,
  2634. fontsize=volume_symbol_fontsize)
  2635. def _perturbed_unit_ellipse(self):
  2636. """Draw the volume as a perturbed ellipse of about unit size."""
  2637. a0 = 1.0
  2638. b0 = 0.75
  2639. eps_a = 0.2
  2640. eps_b = 0.1
  2641. a = lambda t: a0 + eps_a*sin(1*t)
  2642. b = lambda t: b0 + eps_b*cos(1*t)
  2643. x = lambda t: a(t)*cos(t)
  2644. y = lambda t: b(t)*sin(t)
  2645. t = linspace(0, 2*pi, 101) # parameter
  2646. ellipse = Curve(x(t), y(t))
  2647. # Make normal vector
  2648. tx = lambda t: eps_a*cos(t)*cos(t) - a(t)*sin(t)
  2649. ty = lambda t: -eps_b*sin(t)*sin(t) + b(t)*cos(t)
  2650. t0 = pi/5
  2651. nx = ty(t0)
  2652. ny = -tx(t0)
  2653. nx = nx/sqrt(nx**2 + ny**2)
  2654. ny = ny/sqrt(nx**2 + ny**2)
  2655. Px = x(t0)
  2656. Py = y(t0)
  2657. start = point(x(t0), y(t0))
  2658. end = start + point(0.75*b0*nx, 0.75*b0*ny)
  2659. normal = Force(start, end, '$\\boldsymbol{%s}$' % self.normal_symbol,
  2660. text_spacing=1./60,
  2661. text_pos='end',
  2662. text_alignment='center')
  2663. end = start + point(0.75*b0/3*nx, 0.75*b0*4*ny)
  2664. vector = Force(start, end, '$\\boldsymbol{%s}$' % self.vector_symbol,
  2665. text_spacing=1./60,
  2666. text_pos='end',
  2667. text_alignment='center')
  2668. return ellipse, normal, vector
  2669. def geometric_features(self):
  2670. """
  2671. Recorded geometric features:
  2672. ==================== =============================================
  2673. Attribute Description
  2674. ==================== =============================================
  2675. position center point of volume
  2676. normal_vector_start start of normal vector
  2677. normal_vector_end end of normal vector
  2678. ==================== =============================================
  2679. """
  2680. d = {'position': self.position}
  2681. if 'normal' in self.shapes:
  2682. d['normal_vector_start'] = self.shapes['normal'].geometric_features()['start']
  2683. d['normal_vector_end'] = self.shapes['normal'].geometric_features()['end']
  2684. return d
  2685. def _test1():
  2686. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2687. l1 = Line((0,0), (1,1))
  2688. l1.draw()
  2689. eval(input(': '))
  2690. c1 = Circle((5,2), 1)
  2691. c2 = Circle((6,2), 1)
  2692. w1 = Wheel((7,2), 1)
  2693. c1.draw()
  2694. c2.draw()
  2695. w1.draw()
  2696. hardcopy()
  2697. display() # show the plot
  2698. def _test2():
  2699. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2700. l1 = Line((0,0), (1,1))
  2701. l1.draw()
  2702. eval(input(': '))
  2703. c1 = Circle((5,2), 1)
  2704. c2 = Circle((6,2), 1)
  2705. w1 = Wheel((7,2), 1)
  2706. filled_curves(True)
  2707. set_linecolor('blue')
  2708. c1.draw()
  2709. set_linecolor('aqua')
  2710. c2.draw()
  2711. filled_curves(False)
  2712. set_linecolor('red')
  2713. w1.draw()
  2714. hardcopy()
  2715. display() # show the plot
  2716. def _test3():
  2717. """Test example from the book."""
  2718. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2719. l1 = Line(start=(0,0), stop=(1,1)) # define line
  2720. l1.draw() # make plot data
  2721. r1 = Rectangle(lower_left_corner=(0,1), width=3, height=5)
  2722. r1.draw()
  2723. Circle(center=(5,7), radius=1).draw()
  2724. Wheel(center=(6,2), radius=2, inner_radius=0.5, nlines=7).draw()
  2725. hardcopy()
  2726. display()
  2727. def _test4():
  2728. """Second example from the book."""
  2729. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2730. r1 = Rectangle(lower_left_corner=(0,1), width=3, height=5)
  2731. c1 = Circle(center=(5,7), radius=1)
  2732. w1 = Wheel(center=(6,2), radius=2, inner_radius=0.5, nlines=7)
  2733. c2 = Circle(center=(7,7), radius=1)
  2734. filled_curves(True)
  2735. c1.draw()
  2736. set_linecolor('blue')
  2737. r1.draw()
  2738. set_linecolor('aqua')
  2739. c2.draw()
  2740. # Add thick aqua line around rectangle:
  2741. filled_curves(False)
  2742. set_linewidth(4)
  2743. r1.draw()
  2744. set_linecolor('red')
  2745. # Draw wheel with thick lines:
  2746. w1.draw()
  2747. hardcopy('tmp_colors')
  2748. display()
  2749. def _test5():
  2750. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2751. c = 6. # center point of box
  2752. w = 2. # size of box
  2753. L = 3
  2754. r1 = Rectangle((c-w/2, c-w/2), w, w)
  2755. l1 = Line((c,c-w/2), (c,c-w/2-L))
  2756. linecolor('blue')
  2757. filled_curves(True)
  2758. r1.draw()
  2759. linecolor('aqua')
  2760. filled_curves(False)
  2761. l1.draw()
  2762. hardcopy()
  2763. display() # show the plot
  2764. def rolling_wheel(total_rotation_angle):
  2765. """Animation of a rotating wheel."""
  2766. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2767. import time
  2768. center = (6,2)
  2769. radius = 2.0
  2770. angle = 2.0
  2771. pngfiles = []
  2772. w1 = Wheel(center=center, radius=radius, inner_radius=0.5, nlines=7)
  2773. for i in range(int(total_rotation_angle/angle)):
  2774. w1.draw()
  2775. print('BIG PROBLEM WITH ANIMATE!!!')
  2776. display()
  2777. filename = 'tmp_%03d' % i
  2778. pngfiles.append(filename + '.png')
  2779. hardcopy(filename)
  2780. time.sleep(0.3) # pause
  2781. L = radius*angle*pi/180 # translation = arc length
  2782. w1.rotate(angle, center)
  2783. w1.translate((-L, 0))
  2784. center = (center[0] - L, center[1])
  2785. erase()
  2786. cmd = 'convert -delay 50 -loop 1000 %s tmp_movie.gif' \
  2787. % (' '.join(pngfiles))
  2788. print('converting PNG files to animated GIF:\n', cmd)
  2789. import subprocess
  2790. failure, output = subprocess.getstatusoutput(cmd)
  2791. if failure: print('Could not run', cmd)
  2792. if __name__ == '__main__':
  2793. #rolling_wheel(40)
  2794. #_test1()
  2795. #_test3()
  2796. funcs = [
  2797. #test_Axis,
  2798. test_inclined_plane,
  2799. ]
  2800. for func in funcs:
  2801. func()
  2802. input('Type Return: ')