shapes.py 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004
  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. from .MatplotlibDraw import MatplotlibDraw
  22. drawing_tool = MatplotlibDraw()
  23. class Sketch():
  24. """
  25. Yaml to Pysketcher native features implementation
  26. """
  27. def __init__(self, container, name="unknown"):
  28. """
  29. create a Sketch class instance providing the holding container
  30. """
  31. self.sketch = OrderedDict([('name',name),('parts',[])]) # repository used to collect all sketch parts
  32. self.container = container # save the container reference as an class instance variable
  33. @staticmethod
  34. def matplotlib2SVG():
  35. """
  36. Save sketch as a svg string
  37. """
  38. f = BytesIO()
  39. drawing_tool.mpl.savefig(f, format="svg")
  40. return f.getvalue()
  41. @staticmethod
  42. def matplotlib2PNG():
  43. """
  44. Save sketch as a python .png image
  45. """
  46. f = BytesIO()
  47. drawing_tool.mpl.gcf().canvas.print_png(f)
  48. img = Image.open(f)
  49. return img
  50. def sVe(self, key, expression, sketchpart):
  51. """
  52. sVe: Validate sketch part expression
  53. given an expression from a sketch part, check if valid or not
  54. provides a string feedback if error else return 1
  55. """
  56. try:
  57. root = ast.parse(expression)
  58. except Exception as e:
  59. return f"{sketch}/{key}: '''{expression}''' parse error {str(e)}"
  60. names = {node.id for node in ast.walk(root) if isinstance(node, ast.Name)}
  61. for name in names:
  62. if name not in self.container:
  63. return f"{sketch}/{key}: {name} in {expression} is not defined"
  64. return 1
  65. def getSketch(self):
  66. """
  67. dump sketch as a string
  68. """
  69. yaml = YAML()
  70. f = BytesIO()
  71. yaml.dump(self.sketch,f)
  72. return f.getvalue()
  73. def loadSketch(self,sketchstring):
  74. """
  75. load a sketch from string
  76. """
  77. yaml = YAML()
  78. sketch = yaml.load(sketchstring)
  79. self.sketch = OrderedDict([('name',sketch['name']),('parts',[])])
  80. for part in sketch['parts']:
  81. self.sketch['parts'].append(part)
  82. if not self.add(part['name'],part['shapes']):
  83. return False
  84. return True
  85. def append(self, sketchpart):
  86. """
  87. Append and Parse a string sketch part into a sketch and its associated container.
  88. A sketch is just the concatenation of all the sketch parts
  89. name specifices the 'name' of the sketch part
  90. A container is a name space which holds
  91. - all the libraries references needed to create pysketcher shapes
  92. - all the variable providing shapes dimensions or position
  93. - all the shapes needed to create the shapes it defines
  94. """
  95. yaml = YAML()
  96. psketch = yaml.load(sketchpart)
  97. self.sketch['parts'].append(psketch)
  98. sketch_name = psketch["name"]
  99. gwd = psketch['shapes']
  100. return self.add(sketch_name, gwd)
  101. def add(self, sketch_name, gwd):
  102. """
  103. actual append work common to various different calls
  104. """
  105. for _k in list(gwd.keys()):
  106. if _k == "stop":
  107. return True
  108. _c = gwd[_k]
  109. _t = str(type(_c))
  110. if _k == "libraries":
  111. for l in _c:
  112. _r = self.sVe(_k, l, sketch_name)
  113. if type(_r) == str:
  114. print(_r)
  115. return False
  116. exec(l,self.container)
  117. #print(_k, _c, _t)
  118. if _t == "<class 'ruamel.yaml.scalarfloat.ScalarFloat'>" or \
  119. _t == "<class 'str'>" or _t == "<class 'int'>":
  120. _expression = f"{_c}".replace("<bslash>","\\")
  121. _formula = f"{_k} = {_expression}"
  122. #print(_formula)
  123. _r = self.sVe(_k, _expression, sketch_name)
  124. if type(_r) == str:
  125. print(_r)
  126. return False
  127. exec(_formula,self.container)
  128. elif _t == "<class 'ruamel.yaml.comments.CommentedMap'>":
  129. #print(_c)
  130. _keys = list(_c.keys())
  131. #print(_keys)
  132. if 'formula' in _keys:
  133. _expression = f"{_c['formula']}".replace("<bslash>","\\")
  134. _formula = f"{_k} = {_expression}"
  135. #print(_formula)
  136. _r = self.sVe(_k, _expression, sketch_name)
  137. if type(_r) == str:
  138. print(_r)
  139. return False
  140. exec(_formula,self.container)
  141. # if the new object is a shape and has the sketch name, set this shape name as the sketch name
  142. if issubclass(type(self.container[_k]), Shape):
  143. if _k == sketch_name:
  144. self.container[_k].set_name(sketch_name)
  145. if 'style' in _keys:
  146. for _style in _c["style"]:
  147. # x_const.set_linestyle('dotted')
  148. _param = _c["style"][_style]
  149. __t = str(type(_param))
  150. #print(__t)
  151. if __t == "<class 'int'>":
  152. _style = f"{_k}.set_{_style}({_param})"
  153. else:
  154. _style = f"{_k}.set_{_style}('{_param}')"
  155. #print(_style)
  156. exec(_style,self.container)
  157. if 'transform' in _keys:
  158. #print(_c['transform'])
  159. if str(type(_c['transform'])) == "<class 'str'>":
  160. _t = f"{_k}.{_c['transform']}"
  161. #print(_t)
  162. _r = self.sVe(_k, _formula, sketch_name)
  163. if type(_r) == str:
  164. print(_r)
  165. return False
  166. exec(_t,self.container)
  167. else:
  168. for _transform in _c["transform"]:
  169. # x_const.rotate(-theta, contact)
  170. _t = f"{_k}.{_transform}"
  171. #print(_t)
  172. _r = self.sVe(_k, _t, sketch_name)
  173. if type(_r) == str:
  174. print(_r)
  175. return False
  176. exec(_t,self.container)
  177. if "action" in _keys:
  178. _action = _c["action"]
  179. #print(_action)
  180. _r = self.sVe(_k, _action, sketch_name)
  181. if type(_r) == str:
  182. print(_r)
  183. return False
  184. exec(_action,self.container)
  185. return True
  186. def point(x, y, check_inside=False):
  187. for obj, name in zip([x, y], ['x', 'y']):
  188. if isinstance(obj, (float,int)):
  189. pass
  190. elif isinstance(obj, ndarray):
  191. if obj.size == 1:
  192. pass
  193. else:
  194. raise TypeError('%s=%s of type %d has length=%d > 1' %
  195. (name, obj, type(obj), obj.size))
  196. else:
  197. raise TypeError('%s=%s is of wrong type %d' %
  198. (name, obj, type(obj)))
  199. if check_inside:
  200. ok, msg = drawing_tool.inside((x,y), exception=True)
  201. if not ok:
  202. print(msg)
  203. return array((x, y), dtype=float)
  204. def distance(p1, p2):
  205. p1 = arr2D(p1); p2 = arr2D(p2)
  206. d = p2 - p1
  207. return sqrt(d[0]**2 + d[1]**2)
  208. def unit_vec(x, y=None):
  209. """Return unit vector of the vector (x,y), or just x if x is a 2D point."""
  210. if isinstance(x, (float,int)) and isinstance(y, (float,int)):
  211. x = point(x, y)
  212. elif isinstance(x, (list,tuple,ndarray)) and y is None:
  213. return arr2D(x)/sqrt(x[0]**2 + x[1]**2)
  214. else:
  215. raise TypeError('x=%s is %s, must be float or ndarray 2D point' %
  216. (x, type(x)))
  217. def arr2D(x, check_inside=False):
  218. if isinstance(x, (tuple,list,ndarray)):
  219. if len(x) == 2:
  220. pass
  221. else:
  222. raise ValueError('x=%s has length %d, not 2' % (x, len(x)))
  223. else:
  224. raise TypeError('x=%s must be list/tuple/ndarray, not %s' %
  225. (x, type(x)))
  226. if check_inside:
  227. ok, msg = drawing_tool.inside(x, exception=True)
  228. if not ok:
  229. print(msg)
  230. return asarray(x, dtype=float)
  231. def _is_sequence(seq, length=None,
  232. can_be_None=False, error_message=True):
  233. if can_be_None:
  234. legal_types = (list,tuple,ndarray,None)
  235. else:
  236. legal_types = (list,tuple,ndarray)
  237. if isinstance(seq, legal_types):
  238. if length is not None:
  239. if length == len(seq):
  240. return True
  241. elif error_message:
  242. raise TypeError('sequence %s is not a sequence but %s; must be %s of length %d' %
  243. (str(seq), type(seq),
  244. ', '.join([str(t) for t in legal_types]),
  245. len(seq)))
  246. else:
  247. return False
  248. else:
  249. return True
  250. elif error_message:
  251. raise TypeError('sequence %s is not a sequence but %s, %s; must be %s' %
  252. (str(seq), seq.__class__.__name__, type(seq),
  253. ','.join([str(t)[5:-1] for t in legal_types])))
  254. else:
  255. return False
  256. def is_sequence(*sequences, **kwargs):
  257. length = kwargs.get('length', 2)
  258. can_be_None = kwargs.get('can_be_None', False)
  259. error_message = kwargs.get('error_message', True)
  260. check_inside = kwargs.get('check_inside', False)
  261. for x in sequences:
  262. _is_sequence(x, length=length, can_be_None=can_be_None,
  263. error_message=error_message)
  264. if check_inside:
  265. ok, msg = drawing_tool.inside(x, exception=True)
  266. if not ok:
  267. print(msg)
  268. def animate(fig, time_points, action, moviefiles=False,
  269. pause_per_frame=0.5, show_screen_graphics=True,
  270. title=None,
  271. **action_kwargs):
  272. if moviefiles:
  273. # Clean up old frame files
  274. framefilestem = 'tmp_frame_'
  275. framefiles = glob.glob('%s*.png' % framefilestem)
  276. for framefile in framefiles:
  277. os.remove(framefile)
  278. for n, t in enumerate(time_points):
  279. drawing_tool.erase()
  280. action(t, fig, **action_kwargs)
  281. #could demand returning fig, but in-place modifications
  282. #are done anyway
  283. #fig = action(t, fig)
  284. #if fig is None:
  285. # raise TypeError(
  286. # 'animate: action returns None, not fig\n'
  287. # '(a Shape object with the whole figure)')
  288. fig.draw()
  289. drawing_tool.display(title=title, show=show_screen_graphics)
  290. if moviefiles:
  291. drawing_tool.savefig('%s%04d.png' % (framefilestem, n),
  292. crop=False)
  293. if moviefiles:
  294. return '%s%%04d.png' % framefilestem
  295. """
  296. def save():
  297. os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")
  298. """
  299. class Shape(object):
  300. """
  301. Superclass for drawing different geometric shapes.
  302. Subclasses define shapes, but drawing, rotation, translation,
  303. etc. are done in generic functions in this superclass.
  304. """
  305. def __init__(self):
  306. """
  307. Never to be called from subclasses.
  308. """
  309. raise NotImplementedError(
  310. 'class %s must implement __init__,\nwhich defines '
  311. 'self.shapes as a dict (or list) of Shape objects\n'
  312. 'Do not call Shape.__init__!' % \
  313. self.__class__.__name__)
  314. def set_name(self, name):
  315. self.name = name
  316. return self
  317. def get_name(self):
  318. return self.name if hasattr(self, 'name') else 'no_name'
  319. def __iter__(self):
  320. # We iterate over self.shapes many places, and will
  321. # get here if self.shapes is just a Shape object and
  322. # not the assumed dict/list.
  323. print('Warning: class %s does not define self.shapes\n'\
  324. 'as a dict of Shape objects')
  325. return [self] # Make the iteration work
  326. def copy(self):
  327. return copy.deepcopy(self)
  328. def __getitem__(self, name):
  329. """
  330. Allow indexing like::
  331. obj1['name1']['name2']
  332. all the way down to ``Curve`` or ``Point`` (``Text``)
  333. objects.
  334. """
  335. if hasattr(self, 'shapes'):
  336. if name in self.shapes:
  337. return self.shapes[name]
  338. else:
  339. for shape in self.shapes:
  340. if isinstance(self.shapes[shape], (Curve,Point)):
  341. # Indexing of Curve/Point/Text is not possible
  342. raise TypeError(
  343. 'Index "%s" (%s) is illegal' %
  344. (name, self.__class__.__name__))
  345. return self.shapes[shape][name]
  346. else:
  347. raise Exception('This is a bug in __getitem__')
  348. def __setitem__(self, name, value):
  349. """
  350. Allow assignment like::
  351. obj1['name1']['name2'] = value
  352. all the way down to ``Curve`` or ``Point`` (``Text``)
  353. objects.
  354. """
  355. if hasattr(self, 'shapes'):
  356. self.shapes[name] = value
  357. else:
  358. raise Exception('Cannot assign')
  359. def _for_all_shapes(self, func, *args, **kwargs):
  360. verbose = kwargs.get('verbose', 0)
  361. if not hasattr(self, 'shapes'):
  362. # When self.shapes is lacking, we either come to
  363. # a special implementation of func or we come here
  364. # because Shape.func is just inherited. This is
  365. # an error if the class is not Curve or Point
  366. if isinstance(self, (Curve, Point)):
  367. return # ok: no shapes, but object is a curve or point end leaf
  368. else:
  369. raise AttributeError('class %s has no shapes attribute!' %
  370. self.__class__.__name__)
  371. is_dict = True if isinstance(self.shapes, dict) else False
  372. for k, shape in enumerate(self.shapes):
  373. if is_dict:
  374. shape_name = shape
  375. shape = self.shapes[shape]
  376. else:
  377. shape_name = k # use index as name if list (not dict)
  378. if not isinstance(shape, Shape):
  379. if isinstance(shape, dict):
  380. raise TypeError(
  381. 'class %s has a self.shapes member "%s" that is just\n'
  382. 'a plain dictionary,\n%s\n'
  383. 'Did you mean to embed this dict in a Composition\n'
  384. 'object?' % (self.__class__.__name__, shape_name,
  385. str(shape)))
  386. elif isinstance(shape, (list,tuple)):
  387. raise TypeError(
  388. 'class %s has self.shapes member "%s" containing\n'
  389. 'a %s object %s,\n'
  390. 'Did you mean to embed this list in a Composition\n'
  391. 'object?' % (self.__class__.__name__, shape_name,
  392. type(shape), str(shape)))
  393. elif shape is None:
  394. raise TypeError(
  395. 'class %s has a self.shapes member "%s" that is None.\n'
  396. 'Some variable name is wrong, or some function\n'
  397. 'did not return the right object...' \
  398. % (self.__class__.__name__, shape_name))
  399. else:
  400. raise TypeError(
  401. 'class %s has a self.shapes member "%s" of %s which '
  402. 'is not a Shape object\n%s' %
  403. (self.__class__.__name__, shape_name, type(shape),
  404. pprint.pformat(self.shapes)))
  405. if isinstance(shape, Curve):
  406. shape.name = shape_name
  407. if verbose > 0:
  408. print('calling %s.%s' % (shape_name, func))
  409. getattr(shape, func)(*args, **kwargs)
  410. def draw(self, verbose=0):
  411. self._for_all_shapes('draw', verbose=verbose)
  412. return self
  413. def draw_dimensions(self):
  414. if hasattr(self, 'dimensions'):
  415. for shape in self.dimensions:
  416. self.dimensions[shape].draw()
  417. return self
  418. else:
  419. #raise AttributeError('no self.dimensions dict for defining dimensions of class %s' % self.__classname__.__name__)
  420. return self
  421. def rotate(self, angle, center):
  422. is_sequence(center, length=2)
  423. self._for_all_shapes('rotate', angle, center)
  424. return self
  425. def translate(self, vec):
  426. is_sequence(vec, length=2)
  427. self._for_all_shapes('translate', vec)
  428. return self
  429. def scale(self, factor):
  430. self._for_all_shapes('scale', factor)
  431. return self
  432. def deform(self, displacement_function):
  433. self._for_all_shapes('deform', displacement_function)
  434. return self
  435. def minmax_coordinates(self, minmax=None):
  436. if minmax is None:
  437. minmax = {'xmin': 1E+20, 'xmax': -1E+20,
  438. 'ymin': 1E+20, 'ymax': -1E+20}
  439. self._for_all_shapes('minmax_coordinates', minmax)
  440. return minmax
  441. def recurse(self, name, indent=0):
  442. if not isinstance(self.shapes, dict):
  443. raise TypeError('recurse works only with dict self.shape, not %s' %
  444. type(self.shapes))
  445. space = ' '*indent
  446. print(space, '%s: %s.shapes has entries' % \
  447. (self.__class__.__name__, name), \
  448. str(list(self.shapes.keys()))[1:-1])
  449. for shape in self.shapes:
  450. print(space, end=' ')
  451. print('call %s.shapes["%s"].recurse("%s", %d)' % \
  452. (name, shape, shape, indent+2))
  453. self.shapes[shape].recurse(shape, indent+2)
  454. def graphviz_dot(self, name, classname=True):
  455. if not isinstance(self.shapes, dict):
  456. raise TypeError('recurse works only with dict self.shape, not %s' %
  457. type(self.shapes))
  458. dotfile = name + '.dot'
  459. pngfile = name + '.png'
  460. if classname:
  461. name = r"%s:\n%s" % (self.__class__.__name__, name)
  462. couplings = self._object_couplings(name, classname=classname)
  463. # Insert counter for similar names
  464. from collections import defaultdict
  465. count = defaultdict(lambda: 0)
  466. couplings2 = []
  467. for i in range(len(couplings)):
  468. parent, child = couplings[i]
  469. count[child] += 1
  470. parent += ' (%d)' % count[parent]
  471. child += ' (%d)' % count[child]
  472. couplings2.append((parent, child))
  473. print('graphviz', couplings, count)
  474. # Remove counter for names there are only one of
  475. for i in range(len(couplings)):
  476. parent2, child2 = couplings2[i]
  477. parent, child = couplings[i]
  478. if count[parent] > 1:
  479. parent = parent2
  480. if count[child] > 1:
  481. child = child2
  482. couplings[i] = (parent, child)
  483. print(couplings)
  484. f = open(dotfile, 'w')
  485. f.write('digraph G {\n')
  486. for parent, child in couplings:
  487. f.write('"%s" -> "%s";\n' % (parent, child))
  488. f.write('}\n')
  489. f.close()
  490. print('Run dot -Tpng -o %s %s' % (pngfile, dotfile))
  491. def _object_couplings(self, parent, couplings=[], classname=True):
  492. """Find all couplings of parent and child objects in a figure."""
  493. for shape in self.shapes:
  494. if classname:
  495. childname = r"%s:\n%s" % \
  496. (self.shapes[shape].__class__.__name__, shape)
  497. else:
  498. childname = shape
  499. couplings.append((parent, childname))
  500. self.shapes[shape]._object_couplings(childname, couplings,
  501. classname)
  502. return couplings
  503. def set_linestyle(self, style):
  504. styles = ('solid', 'dashed', 'dashdot', 'dotted')
  505. if style not in styles:
  506. raise ValueError('%s: style=%s must be in %s' %
  507. (self.__class__.__name__ + '.set_linestyle:',
  508. style, str(styles)))
  509. self._for_all_shapes('set_linestyle', style)
  510. return self
  511. def set_linewidth(self, width):
  512. if not isinstance(width, int) and width >= 0:
  513. raise ValueError('%s: width=%s must be positive integer' %
  514. (self.__class__.__name__ + '.set_linewidth:',
  515. width))
  516. self._for_all_shapes('set_linewidth', width)
  517. return self
  518. def set_linecolor(self, color):
  519. if color in drawing_tool.line_colors:
  520. color = drawing_tool.line_colors[color]
  521. elif color in list(drawing_tool.line_colors.values()):
  522. pass # color is ok
  523. else:
  524. raise ValueError('%s: invalid color "%s", must be in %s' %
  525. (self.__class__.__name__ + '.set_linecolor:',
  526. color, list(drawing_tool.line_colors.keys())))
  527. self._for_all_shapes('set_linecolor', color)
  528. return self
  529. def set_arrow(self, style):
  530. styles = ('->', '<-', '<->')
  531. if not style in styles:
  532. raise ValueError('%s: style=%s must be in %s' %
  533. (self.__class__.__name__ + '.set_arrow:',
  534. style, styles))
  535. self._for_all_shapes('set_arrow', style)
  536. return self
  537. def set_filled_curves(self, color='', pattern=''):
  538. if color in drawing_tool.line_colors:
  539. color = drawing_tool.line_colors[color]
  540. elif color in list(drawing_tool.line_colors.values()):
  541. pass # color is ok
  542. else:
  543. raise ValueError('%s: invalid color "%s", must be in %s' %
  544. (self.__class__.__name__ + '.set_filled_curves:',
  545. color, list(drawing_tool.line_colors.keys())))
  546. self._for_all_shapes('set_filled_curves', color, pattern)
  547. return self
  548. def set_shadow(self, pixel_displacement=3):
  549. self._for_all_shapes('set_shadow', pixel_displacement)
  550. return self
  551. def show_hierarchy(self, indent=0, format='std'):
  552. """Recursive pretty print of hierarchy of objects."""
  553. if not isinstance(self.shapes, dict):
  554. print('cannot print hierarchy when %s.shapes is not a dict' % \
  555. self.__class__.__name__)
  556. s = ''
  557. if format == 'dict':
  558. s += '{'
  559. for shape in self.shapes:
  560. if format == 'dict':
  561. shape_str = repr(shape) + ':'
  562. elif format == 'plain':
  563. shape_str = shape
  564. else:
  565. shape_str = shape + ':'
  566. if format == 'dict' or format == 'plain':
  567. class_str = ''
  568. else:
  569. class_str = ' (%s)' % \
  570. self.shapes[shape].__class__.__name__
  571. s += '\n%s%s%s %s,' % (
  572. ' '*indent,
  573. shape_str,
  574. class_str,
  575. self.shapes[shape].show_hierarchy(indent+4, format))
  576. if format == 'dict':
  577. s += '}'
  578. return s
  579. def __str__(self):
  580. """Display hierarchy with minimum information (just object names)."""
  581. return self.show_hierarchy(format='plain')
  582. def __repr__(self):
  583. """Display hierarchy as a dictionary."""
  584. return self.show_hierarchy(format='dict')
  585. #return pprint.pformat(self.shapes)
  586. class Curve(Shape):
  587. """General curve as a sequence of (x,y) coordinates."""
  588. def __init__(self, x, y):
  589. """
  590. `x`, `y`: arrays holding the coordinates of the curve.
  591. """
  592. self.x = asarray(x, dtype=float)
  593. self.y = asarray(y, dtype=float)
  594. #self.shapes must not be defined in this class
  595. #as self.shapes holds children objects:
  596. #Curve has no children (end leaf of self.shapes tree)
  597. self.linestyle = None
  598. self.linewidth = None
  599. self.linecolor = None
  600. self.fillcolor = None
  601. self.fillpattern = None
  602. self.arrow = None
  603. self.shadow = False
  604. self.name = None # name of object that this Curve represents
  605. def inside_plot_area(self, verbose=True):
  606. """Check that all coordinates are within drawing_tool's area."""
  607. xmin, xmax = self.x.min(), self.x.max()
  608. ymin, ymax = self.y.min(), self.y.max()
  609. t = drawing_tool
  610. inside = True
  611. if not hasattr(t, 'xmin'):
  612. return None # drawing area is not defined
  613. if xmin < t.xmin:
  614. inside = False
  615. if verbose:
  616. print('x_min=%g < plot area x_min=%g' % (xmin, t.xmin))
  617. if xmax > t.xmax:
  618. inside = False
  619. if verbose:
  620. print('x_max=%g > plot area x_max=%g' % (xmax, t.xmax))
  621. if ymin < t.ymin:
  622. inside = False
  623. if verbose:
  624. print('y_min=%g < plot area y_min=%g' % (ymin, t.ymin))
  625. if ymax > t.ymax:
  626. inside = False
  627. if verbose:
  628. print('y_max=%g > plot area y_max=%g' % (ymax, t.ymax))
  629. return inside
  630. def draw(self, verbose=0):
  631. """
  632. Send the curve to the plotting engine. That is, convert
  633. coordinate information in self.x and self.y, together
  634. with optional settings of linestyles, etc., to
  635. plotting commands for the chosen engine.
  636. """
  637. self.inside_plot_area()
  638. drawing_tool.plot_curve(
  639. self.x, self.y,
  640. self.linestyle, self.linewidth, self.linecolor,
  641. self.arrow, self.fillcolor, self.fillpattern,
  642. self.shadow, self.name)
  643. if verbose:
  644. print('drawing Curve object with %d points' % len(self.x))
  645. def rotate(self, angle, center):
  646. """
  647. Rotate all coordinates: `angle` is measured in degrees and
  648. (`x`,`y`) is the "origin" of the rotation.
  649. """
  650. angle = radians(angle)
  651. x, y = center
  652. c = cos(angle); s = sin(angle)
  653. xnew = x + (self.x - x)*c - (self.y - y)*s
  654. ynew = y + (self.x - x)*s + (self.y - y)*c
  655. self.x = xnew
  656. self.y = ynew
  657. return self
  658. def scale(self, factor):
  659. """Scale all coordinates by `factor`: ``x = factor*x``, etc."""
  660. self.x = factor*self.x
  661. self.y = factor*self.y
  662. return self
  663. def translate(self, vec):
  664. """Translate all coordinates by a vector `vec`."""
  665. self.x += vec[0]
  666. self.y += vec[1]
  667. return self
  668. def deform(self, displacement_function):
  669. """Displace all coordinates according to displacement_function(x,y)."""
  670. for i in range(len(self.x)):
  671. self.x[i], self.y[i] = displacement_function(self.x[i], self.y[i])
  672. return self
  673. def minmax_coordinates(self, minmax=None):
  674. if minmax is None:
  675. minmax = {'xmin': [], 'xmax': [], 'ymin': [], 'ymax': []}
  676. minmax['xmin'] = min(self.x.min(), minmax['xmin'])
  677. minmax['xmax'] = max(self.x.max(), minmax['xmax'])
  678. minmax['ymin'] = min(self.y.min(), minmax['ymin'])
  679. minmax['ymax'] = max(self.y.max(), minmax['ymax'])
  680. return minmax
  681. def recurse(self, name, indent=0):
  682. space = ' '*indent
  683. print(space, 'reached "bottom" object %s' % \
  684. self.__class__.__name__)
  685. def _object_couplings(self, parent, couplings=[], classname=True):
  686. return
  687. def set_linecolor(self, color):
  688. self.linecolor = color
  689. return self
  690. def set_linewidth(self, width):
  691. self.linewidth = width
  692. return self
  693. def set_linestyle(self, style):
  694. self.linestyle = style
  695. return self
  696. def set_arrow(self, style=None):
  697. self.arrow = style
  698. return self
  699. def set_filled_curves(self, color='', pattern=''):
  700. self.fillcolor = color
  701. self.fillpattern = pattern
  702. return self
  703. def set_shadow(self, pixel_displacement=3):
  704. self.shadow = pixel_displacement
  705. return self
  706. def show_hierarchy(self, indent=0, format='std'):
  707. if format == 'dict':
  708. return '"%s"' % str(self)
  709. elif format == 'plain':
  710. return ''
  711. else:
  712. return str(self)
  713. def __str__(self):
  714. """Compact pretty print of a Curve object."""
  715. s = '%d (x,y) coords' % self.x.size
  716. inside = self.inside_plot_area(verbose=False)
  717. if inside is None:
  718. pass # no info about the plotting area
  719. elif not inside:
  720. s += ', some coordinates are outside plotting area!\n'
  721. props = ('linecolor', 'linewidth', 'linestyle', 'arrow',
  722. 'fillcolor', 'fillpattern')
  723. for prop in props:
  724. value = getattr(self, prop)
  725. if value is not None:
  726. s += ' %s=%s' % (prop, repr(value))
  727. return s
  728. def __repr__(self):
  729. return str(self)
  730. class Spline(Shape):
  731. # Note: UnivariateSpline interpolation may not work if
  732. # the x[i] points are far from uniformly spaced
  733. def __init__(self, x, y, degree=3, resolution=501):
  734. from scipy.interpolate import UnivariateSpline
  735. self.smooth = UnivariateSpline(x, y, s=0, k=degree)
  736. self.xcoor = linspace(x[0], x[-1], resolution)
  737. ycoor = self.smooth(self.xcoor)
  738. self.shapes = {'smooth': Curve(self.xcoor, ycoor)}
  739. def geometric_features(self):
  740. s = self.shapes['smooth']
  741. return {'start': point(s.x[0], s.y[0]),
  742. 'end': point(s.x[-1], s.y[-1]),
  743. 'interval': [s.x[0], s.x[-1]]}
  744. def __call__(self, x):
  745. return self.smooth(x)
  746. # Can easily find the derivative and the integral as
  747. # self.smooth.derivative(n=1) and self.smooth.antiderivative()
  748. class SketchyFunc1(Spline):
  749. """
  750. A typical function curve used to illustrate an "arbitrary" function.
  751. """
  752. domain = [1, 6]
  753. def __init__(self, name=None, name_pos='start',
  754. xmin=0, xmax=6, ymin=0, ymax=2):
  755. x = array([0, 2, 3, 4, 5, 6])
  756. y = array([1, 1.8, 1.2, 0.7, 0.8, 0.85])
  757. #y = array([5, 3.5, 3.8, 3, 2.5, 2.4])
  758. # Scale x and y
  759. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  760. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  761. Spline.__init__(self, x, y)
  762. self.shapes['smooth'].set_linecolor('black')
  763. if name is not None:
  764. self.shapes['name'] = Text(name, self.geometric_features()[name_pos] + point(0,0.1))
  765. class SketchyFunc3(Spline):
  766. """
  767. A typical function curve used to illustrate an "arbitrary" function.
  768. """
  769. domain = [0, 6]
  770. def __init__(self, name=None, name_pos='start',
  771. xmin=0, xmax=6, ymin=0.5, ymax=3.8):
  772. x = array([0, 2, 3, 4, 5, 6])
  773. y = array([0.5, 3.5, 3.8, 2, 2.5, 3.5])
  774. # Scale x and y
  775. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  776. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  777. Spline.__init__(self, x, y)
  778. self.shapes['smooth'].set_linecolor('black')
  779. if name is not None:
  780. self.shapes['name'] = Text(name, self.geometric_features()[name_pos] + point(0,0.1))
  781. class SketchyFunc4(Spline):
  782. """
  783. A typical function curve used to illustrate an "arbitrary" function.
  784. Can be a companion function to SketchyFunc3.
  785. """
  786. domain = [1, 6]
  787. def __init__(self, name=None, name_pos='start',
  788. xmin=0, xmax=6, ymin=0.5, ymax=1.8):
  789. x = array([0, 2, 3, 4, 5, 6])
  790. y = array([1.5, 1.3, 0.7, 0.5, 0.6, 0.8])
  791. # Scale x and y
  792. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  793. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  794. Spline.__init__(self, x, y)
  795. self.shapes['smooth'].set_linecolor('black')
  796. if name is not None:
  797. self.shapes['name'] = Text(name, self.geometric_features()[name_pos] + point(0,0.1))
  798. class SketchyFunc2(Shape):
  799. """
  800. A typical function curve used to illustrate an "arbitrary" function.
  801. """
  802. domain = [0, 2.25]
  803. def __init__(self, name=None, name_pos='end',
  804. xmin=0, xmax=2.25, ymin=0.046679703125, ymax=1.259375):
  805. a = 0; b = 2.25
  806. resolution = 100
  807. x = linspace(a, b, resolution+1)
  808. f = self # for calling __call__
  809. y = f(x)
  810. # Scale x and y
  811. x = xmin - x.min() + x*(xmax - xmin)/(x.max()-x.min())
  812. y = ymin - y.min() + y*(ymax - ymin)/(y.max()-y.min())
  813. self.shapes = {'smooth': Curve(x, y)}
  814. self.shapes['smooth'].set_linecolor('black')
  815. pos = point(a, f(a)) if name_pos == 'start' else point(b, f(b))
  816. if name is not None:
  817. self.shapes['name'] = Text(name, pos + point(0,0.1))
  818. def __call__(self, x):
  819. return 0.5+x*(2-x)*(0.9-x) # on [0, 2.25]
  820. class Point(Shape):
  821. """A point (x,y) which can be rotated, translated, and scaled."""
  822. def __init__(self, x, y):
  823. self.x, self.y = x, y
  824. #self.shapes is not needed in this class
  825. def __add__(self, other):
  826. if isinstance(other, (list,tuple)):
  827. other = Point(other)
  828. return Point(self.x+other.x, self.y+other.y)
  829. # class Point is an abstract class - only subclasses are useful
  830. # and must implement draw
  831. def draw(self, verbose=0):
  832. raise NotImplementedError(
  833. 'class %s must implement the draw method' %
  834. self.__class__.__name__)
  835. def rotate(self, angle, center):
  836. """Rotate point an `angle` (in degrees) around (`x`,`y`)."""
  837. angle = angle*pi/180
  838. x, y = center
  839. c = cos(angle); s = sin(angle)
  840. xnew = x + (self.x - x)*c - (self.y - y)*s
  841. ynew = y + (self.x - x)*s + (self.y - y)*c
  842. self.x = xnew
  843. self.y = ynew
  844. return self
  845. def scale(self, factor):
  846. """Scale point coordinates by `factor`: ``x = factor*x``, etc."""
  847. self.x = factor*self.x
  848. self.y = factor*self.y
  849. return self
  850. def translate(self, vec):
  851. """Translate point by a vector `vec`."""
  852. self.x += vec[0]
  853. self.y += vec[1]
  854. return self
  855. def deform(self, displacement_function):
  856. """Displace coordinates according to displacement_function(x,y)."""
  857. for i in range(len(self.x)):
  858. self.x, self.y = displacement_function(self.x, self.y)
  859. return self
  860. def minmax_coordinates(self, minmax=None):
  861. if minmax is None:
  862. minmax = {'xmin': [], 'xmax': [], 'ymin': [], 'ymax': []}
  863. minmax['xmin'] = min(self.x, minmax['xmin'])
  864. minmax['xmax'] = max(self.x, minmax['xmax'])
  865. minmax['ymin'] = min(self.y, minmax['ymin'])
  866. minmax['ymax'] = max(self.y, minmax['ymax'])
  867. return minmax
  868. def recurse(self, name, indent=0):
  869. space = ' '*indent
  870. print(space, 'reached "bottom" object %s' % \
  871. self.__class__.__name__)
  872. def _object_couplings(self, parent, couplings=[], classname=True):
  873. return
  874. # No need for set_linecolor etc since self._for_all_shapes, which
  875. # is always called for these functions, makes a test and stops
  876. # calls if self.shapes is missing and the object is Point or Curve
  877. def show_hierarchy(self, indent=0, format='std'):
  878. s = '%s at (%g,%g)' % (self.__class__.__name__, self.x, self.y)
  879. if format == 'dict':
  880. return '"%s"' % s
  881. elif format == 'plain':
  882. return ''
  883. else:
  884. return s
  885. # no need to store input data as they are invalid after rotations etc.
  886. class Rectangle(Shape):
  887. """
  888. Rectangle specified by the point `lower_left_corner`, `width`,
  889. and `height`.
  890. """
  891. def __init__(self, lower_left_corner, width, height):
  892. is_sequence(lower_left_corner)
  893. p = arr2D(lower_left_corner) # short form
  894. x = [p[0], p[0] + width,
  895. p[0] + width, p[0], p[0]]
  896. y = [p[1], p[1], p[1] + height,
  897. p[1] + height, p[1]]
  898. self.shapes = {'rectangle': Curve(x,y)}
  899. # Dimensions
  900. dims = {
  901. 'width': Distance_wText(p + point(0, -height/5.),
  902. p + point(width, -height/5.),
  903. 'width'),
  904. 'height': Distance_wText(p + point(width + width/5., 0),
  905. p + point(width + width/5., height),
  906. 'height'),
  907. 'lower_left_corner': Text_wArrow('lower_left_corner',
  908. p - point(width/5., height/5.), p)
  909. }
  910. self.dimensions = dims
  911. def geometric_features(self):
  912. """
  913. Return dictionary with
  914. ==================== =============================================
  915. Attribute Description
  916. ==================== =============================================
  917. lower_left Lower left corner point.
  918. upper_left Upper left corner point.
  919. lower_right Lower right corner point.
  920. upper_right Upper right corner point.
  921. lower_mid Middle point on lower side.
  922. upper_mid Middle point on upper side.
  923. center Center point
  924. ==================== =============================================
  925. """
  926. r = self.shapes['rectangle']
  927. d = {'lower_left': point(r.x[0], r.y[0]),
  928. 'lower_right': point(r.x[1], r.y[1]),
  929. 'upper_right': point(r.x[2], r.y[2]),
  930. 'upper_left': point(r.x[3], r.y[3])}
  931. d['lower_mid'] = 0.5*(d['lower_left'] + d['lower_right'])
  932. d['upper_mid'] = 0.5*(d['upper_left'] + d['upper_right'])
  933. d['left_mid'] = 0.5*(d['lower_left'] + d['upper_left'])
  934. d['right_mid'] = 0.5*(d['lower_right'] + d['upper_right'])
  935. d['center'] = point(d['lower_mid'][0], d['left_mid'][1])
  936. return d
  937. class Triangle(Shape):
  938. """
  939. Triangle defined by its three vertices p1, p2, and p3.
  940. Recorded geometric features:
  941. ==================== =============================================
  942. Attribute Description
  943. ==================== =============================================
  944. p1, p2, p3 Corners as given to the constructor.
  945. ==================== =============================================
  946. """
  947. def __init__(self, p1, p2, p3):
  948. is_sequence(p1, p2, p3)
  949. x = [p1[0], p2[0], p3[0], p1[0]]
  950. y = [p1[1], p2[1], p3[1], p1[1]]
  951. self.shapes = {'triangle': Curve(x,y)}
  952. # Dimensions
  953. self.dimensions = {'p1': Text('p1', p1),
  954. 'p2': Text('p2', p2),
  955. 'p3': Text('p3', p3)}
  956. def geometric_features(self):
  957. t = self.shapes['triangle']
  958. return {'p1': point(t.x[0], t.y[0]),
  959. 'p2': point(t.x[1], t.y[1]),
  960. 'p3': point(t.x[2], t.y[2])}
  961. class Line(Shape):
  962. def __init__(self, start, end):
  963. is_sequence(start, end, length=2)
  964. if isinstance(start, (list,tuple)):
  965. start = array(start)
  966. if isinstance(end, (list,tuple)):
  967. end = array(end)
  968. if (start == end).all():
  969. # Introduce a very small perturbation since identical points
  970. # give drawing error
  971. end[0] = start[0] + 1E-10
  972. x = [start[0], end[0]]
  973. y = [start[1], end[1]]
  974. self.shapes = {'line': Curve(x, y)}
  975. def geometric_features(self):
  976. line = self.shapes['line']
  977. return {'start': point(line.x[0], line.y[0]),
  978. 'end': point(line.x[1], line.y[1]),}
  979. def compute_formulas(self):
  980. x, y = self.shapes['line'].x, self.shapes['line'].y
  981. # Define equations for line:
  982. # y = a*x + b, x = c*y + d
  983. try:
  984. self.a = (y[1] - y[0])/(x[1] - x[0])
  985. self.b = y[0] - self.a*x[0]
  986. except ZeroDivisionError:
  987. # Vertical line, y is not a function of x
  988. self.a = None
  989. self.b = None
  990. try:
  991. if self.a is None:
  992. self.c = 0
  993. else:
  994. self.c = 1/float(self.a)
  995. if self.b is None:
  996. self.d = x[1]
  997. except ZeroDivisionError:
  998. # Horizontal line, x is not a function of y
  999. self.c = None
  1000. self.d = None
  1001. def compute_formulas(self):
  1002. x, y = self.shapes['line'].x, self.shapes['line'].y
  1003. tol = 1E-14
  1004. # Define equations for line:
  1005. # y = a*x + b, x = c*y + d
  1006. if abs(x[1] - x[0]) > tol:
  1007. self.a = (y[1] - y[0])/(x[1] - x[0])
  1008. self.b = y[0] - self.a*x[0]
  1009. else:
  1010. # Vertical line, y is not a function of x
  1011. self.a = None
  1012. self.b = None
  1013. if self.a is None:
  1014. self.c = 0
  1015. elif abs(self.a) > tol:
  1016. self.c = 1/float(self.a)
  1017. self.d = x[1]
  1018. else: # self.a is 0
  1019. # Horizontal line, x is not a function of y
  1020. self.c = None
  1021. self.d = None
  1022. def __call__(self, x=None, y=None):
  1023. """Given x, return y on the line, or given y, return x."""
  1024. self.compute_formulas()
  1025. if x is not None and self.a is not None:
  1026. return self.a*x + self.b
  1027. elif y is not None and self.c is not None:
  1028. return self.c*y + self.d
  1029. else:
  1030. raise ValueError(
  1031. 'Line.__call__(x=%s, y=%s) not meaningful' % \
  1032. (x, y))
  1033. def new_interval(self, x=None, y=None):
  1034. """Redefine current Line to cover interval in x or y."""
  1035. if x is not None:
  1036. is_sequence(x, length=2)
  1037. xL, xR = x
  1038. new_line = Line((xL, self(x=xL)), (xR, self(x=xR)))
  1039. elif y is not None:
  1040. is_sequence(y, length=2)
  1041. yL, yR = y
  1042. new_line = Line((xL, self(y=xL)), (xR, self(y=xR)))
  1043. self.shapes['line'] = new_line['line']
  1044. return self
  1045. # First implementation of class Circle
  1046. class Circle(Shape):
  1047. def __init__(self, center, radius, resolution=180):
  1048. self.center, self.radius = center, radius
  1049. self.resolution = resolution
  1050. t = linspace(0, 2*pi, resolution+1)
  1051. x0 = center[0]; y0 = center[1]
  1052. R = radius
  1053. x = x0 + R*cos(t)
  1054. y = y0 + R*sin(t)
  1055. self.shapes = {'circle': Curve(x, y)}
  1056. def __call__(self, theta):
  1057. """
  1058. Return (x, y) point corresponding to angle theta.
  1059. Not valid after a translation, rotation, or scaling.
  1060. """
  1061. return self.center[0] + self.radius*cos(theta), \
  1062. self.center[1] + self.radius*sin(theta)
  1063. class Arc(Shape):
  1064. def __init__(self, center, radius,
  1065. start_angle, arc_angle,
  1066. resolution=180):
  1067. is_sequence(center)
  1068. # Must record some parameters for __call__
  1069. self.center = arr2D(center)
  1070. self.radius = radius
  1071. self.start_angle = radians(start_angle)
  1072. self.arc_angle = radians(arc_angle)
  1073. self.resolution = resolution
  1074. self.setCurve()
  1075. def setCurve(self):
  1076. t = linspace(self.start_angle,
  1077. self.start_angle + self.arc_angle,
  1078. self.resolution+1)
  1079. x0 = self.center[0]; y0 = self.center[1]
  1080. R = self.radius
  1081. x = x0 + R*cos(t)
  1082. y = y0 + R*sin(t)
  1083. self.shapes = {'arc': Curve(x, y)}
  1084. # Cannot set dimensions (Arc_wText recurses into this
  1085. # constructor forever). Set in test_Arc instead.
  1086. def geometric_features(self):
  1087. a = self.shapes['arc']
  1088. m = len(a.x)//2 # mid point in array
  1089. d = {'start': point(a.x[0], a.y[0]),
  1090. 'end': point(a.x[-1], a.y[-1]),
  1091. 'mid': point(a.x[m], a.y[m])}
  1092. return d
  1093. def __call__(self, theta):
  1094. """
  1095. Return (x,y) point at start_angle + theta.
  1096. Not valid after translation, rotation, or scaling.
  1097. """
  1098. theta = radians(theta)
  1099. t = self.start_angle + theta
  1100. x0 = self.center[0]
  1101. y0 = self.center[1]
  1102. R = self.radius
  1103. x = x0 + R*cos(t)
  1104. y = y0 + R*sin(t)
  1105. return (x, y)
  1106. # Alternative for small arcs: Parabola
  1107. class Parabola(Shape):
  1108. def __init__(self, start, mid, stop, resolution=21):
  1109. self.p1, self.p2, self.p3 = start, mid, stop
  1110. # y as function of x? (no point on line x=const?)
  1111. tol = 1E-14
  1112. if abs(self.p1[0] - self.p2[0]) > 1E-14 and \
  1113. abs(self.p2[0] - self.p3[0]) > 1E-14 and \
  1114. abs(self.p3[0] - self.p1[0]) > 1E-14:
  1115. self.y_of_x = True
  1116. else:
  1117. self.y_of_x = False
  1118. # x as function of y? (no point on line y=const?)
  1119. tol = 1E-14
  1120. if abs(self.p1[1] - self.p2[1]) > 1E-14 and \
  1121. abs(self.p2[1] - self.p3[1]) > 1E-14 and \
  1122. abs(self.p3[1] - self.p1[1]) > 1E-14:
  1123. self.x_of_y = True
  1124. else:
  1125. self.x_of_y = False
  1126. if self.y_of_x:
  1127. x = linspace(start[0], end[0], resolution)
  1128. y = self(x=x)
  1129. elif self.x_of_y:
  1130. y = linspace(start[1], end[1], resolution)
  1131. x = self(y=y)
  1132. else:
  1133. raise ValueError(
  1134. 'Parabola: two or more points lie on x=const '
  1135. 'or y=const - not allowed')
  1136. self.shapes = {'parabola': Curve(x, y)}
  1137. def __call__(self, x=None, y=None):
  1138. if x is not None and self.y_of_x:
  1139. return self._L2x(self.p1, self.p2)*self.p3[1] + \
  1140. self._L2x(self.p2, self.p3)*self.p1[1] + \
  1141. self._L2x(self.p3, self.p1)*self.p2[1]
  1142. elif y is not None and self.x_of_y:
  1143. return self._L2y(self.p1, self.p2)*self.p3[0] + \
  1144. self._L2y(self.p2, self.p3)*self.p1[0] + \
  1145. self._L2y(self.p3, self.p1)*self.p2[0]
  1146. else:
  1147. raise ValueError(
  1148. 'Parabola.__call__(x=%s, y=%s) not meaningful' % \
  1149. (x, y))
  1150. def _L2x(self, x, pi, pj, pk):
  1151. return (x - pi[0])*(x - pj[0])/((pk[0] - pi[0])*(pk[0] - pj[0]))
  1152. def _L2y(self, y, pi, pj, pk):
  1153. return (y - pi[1])*(y - pj[1])/((pk[1] - pi[1])*(pk[1] - pj[1]))
  1154. class Circle(Arc):
  1155. def __init__(self, center, radius, resolution=180):
  1156. Arc.__init__(self, center, radius, 0, 360, resolution)
  1157. class Wall(Shape):
  1158. """
  1159. defines an hached box given starting, ending point and thickness, filled with a pattern
  1160. """
  1161. def __init__(self, x, y, thickness, pattern='/', transparent=False):
  1162. is_sequence(x, y, length=len(x))
  1163. if isinstance(x[0], (tuple,list,ndarray)):
  1164. # x is list of curves
  1165. x1 = concatenate(x)
  1166. else:
  1167. x1 = asarray(x, float)
  1168. if isinstance(y[0], (tuple,list,ndarray)):
  1169. # x is list of curves
  1170. y1 = concatenate(y)
  1171. else:
  1172. y1 = asarray(y, float)
  1173. self.x1 = x1; self.y1 = y1
  1174. # Displaced curve (according to thickness)
  1175. x2 = x1
  1176. y2 = y1 + thickness
  1177. # Combine x1,y1 with x2,y2 reversed
  1178. from numpy import concatenate
  1179. x = concatenate((x1, x2[-1::-1]))
  1180. y = concatenate((y1, y2[-1::-1]))
  1181. wall = Curve(x, y)
  1182. wall.set_filled_curves(color='white', pattern=pattern)
  1183. x = [x1[-1]] + x2[-1::-1].tolist() + [x1[0]]
  1184. y = [y1[-1]] + y2[-1::-1].tolist() + [y1[0]]
  1185. self.shapes = {'wall': wall}
  1186. from collections import OrderedDict
  1187. self.shapes = OrderedDict()
  1188. self.shapes['wall'] = wall
  1189. if transparent:
  1190. white_eraser = Curve(x, y)
  1191. white_eraser.set_linecolor('white')
  1192. self.shapes['eraser'] = white_eraser
  1193. def geometric_features(self):
  1194. d = {'start': point(self.x1[0], self.y1[0]),
  1195. 'end': point(self.x1[-1], self.y1[-1])}
  1196. return d
  1197. class Wall2(Shape):
  1198. def __init__(self, x, y, thickness, pattern='/'):
  1199. is_sequence(x, y, length=len(x))
  1200. if isinstance(x[0], (tuple,list,ndarray)):
  1201. # x is list of curves
  1202. x1 = concatenate(x)
  1203. else:
  1204. x1 = asarray(x, float)
  1205. if isinstance(y[0], (tuple,list,ndarray)):
  1206. # x is list of curves
  1207. y1 = concatenate(y)
  1208. else:
  1209. y1 = asarray(y, float)
  1210. self.x1 = x1; self.y1 = y1
  1211. # Displaced curve (according to thickness)
  1212. x2 = x1.copy()
  1213. y2 = y1.copy()
  1214. def displace(idx, idx_m, idx_p):
  1215. # Find tangent and normal
  1216. tangent = point(x1[idx_m], y1[idx_m]) - point(x1[idx_p], y1[idx_p])
  1217. tangent = unit_vec(tangent)
  1218. normal = point(tangent[1], -tangent[0])
  1219. # Displace length "thickness" in "positive" normal direction
  1220. displaced_pt = point(x1[idx], y1[idx]) + thickness*normal
  1221. x2[idx], y2[idx] = displaced_pt
  1222. for i in range(1, len(x1)-1):
  1223. displace(i-1, i+1, i) # centered difference for normal comp.
  1224. # One-sided differences at the end points
  1225. i = 0
  1226. displace(i, i+1, i)
  1227. i = len(x1)-1
  1228. displace(i-1, i, i)
  1229. # Combine x1,y1 with x2,y2 reversed
  1230. from numpy import concatenate
  1231. x = concatenate((x1, x2[-1::-1]))
  1232. y = concatenate((y1, y2[-1::-1]))
  1233. wall = Curve(x, y)
  1234. wall.set_filled_curves(color='white', pattern=pattern)
  1235. x = [x1[-1]] + x2[-1::-1].tolist() + [x1[0]]
  1236. y = [y1[-1]] + y2[-1::-1].tolist() + [y1[0]]
  1237. self.shapes['wall'] = wall
  1238. def geometric_features(self):
  1239. d = {'start': point(self.x1[0], self.y1[0]),
  1240. 'end': point(self.x1[-1], self.y1[-1])}
  1241. return d
  1242. class VelocityProfile(Shape):
  1243. def __init__(self, start, height, profile, num_arrows, scaling=1):
  1244. # vx, vy = profile(y)
  1245. shapes = {}
  1246. # Draw left line
  1247. shapes['start line'] = Line(start, (start[0], start[1]+height))
  1248. # Draw velocity arrows
  1249. dy = float(height)/(num_arrows-1)
  1250. x = start[0]
  1251. y = start[1]
  1252. r = profile(y) # Test on return type
  1253. if not isinstance(r, (list,tuple,ndarray)) and len(r) != 2:
  1254. raise TypeError('VelocityProfile constructor: profile(y) function must return velocity vector (vx,vy), not %s' % type(r))
  1255. for i in range(num_arrows):
  1256. y = start[1] + i*dy
  1257. vx, vy = profile(y)
  1258. if abs(vx) < 1E-8:
  1259. continue
  1260. vx *= scaling
  1261. vy *= scaling
  1262. arr = Arrow1((x,y), (x+vx, y+vy), '->')
  1263. shapes['arrow%d' % i] = arr
  1264. # Draw smooth profile
  1265. xs = []
  1266. ys = []
  1267. n = 100
  1268. dy = float(height)/n
  1269. for i in range(n+2):
  1270. y = start[1] + i*dy
  1271. vx, vy = profile(y)
  1272. vx *= scaling
  1273. vy *= scaling
  1274. xs.append(x+vx)
  1275. ys.append(y+vy)
  1276. shapes['smooth curve'] = Curve(xs, ys)
  1277. self.shapes = shapes
  1278. class Arrow1(Shape):
  1279. """Draw a Line with arrow(s)."""
  1280. def __init__(self, start, end, style='->'):
  1281. arrow = Line(start, end)
  1282. arrow.set_arrow(style)
  1283. # Note:
  1284. self.shapes = {'arrow': arrow}
  1285. def geometric_features(self):
  1286. return self.shapes['arrow'].geometric_features()
  1287. class Arrow3(Shape):
  1288. """
  1289. Build a vertical line and arrow head from Line objects.
  1290. Then rotate `rotation_angle`.
  1291. """
  1292. def __init__(self, start, length, rotation_angle=0):
  1293. self.bottom = start
  1294. self.length = length
  1295. self.angle = rotation_angle
  1296. top = (self.bottom[0], self.bottom[1] + self.length)
  1297. main = Line(self.bottom, top)
  1298. #head_length = self.length/8.0
  1299. head_length = drawing_tool.xrange/50.
  1300. head_degrees = radians(30)
  1301. head_left_pt = (top[0] - head_length*sin(head_degrees),
  1302. top[1] - head_length*cos(head_degrees))
  1303. head_right_pt = (top[0] + head_length*sin(head_degrees),
  1304. top[1] - head_length*cos(head_degrees))
  1305. head_left = Line(head_left_pt, top)
  1306. head_right = Line(head_right_pt, top)
  1307. head_left.set_linestyle('solid')
  1308. head_right.set_linestyle('solid')
  1309. self.shapes = {'line': main, 'head left': head_left,
  1310. 'head right': head_right}
  1311. # rotate goes through self.shapes so self.shapes
  1312. # must be initialized first
  1313. self.rotate(rotation_angle, start)
  1314. def geometric_features(self):
  1315. return self.shapes['line'].geometric_features()
  1316. class Cross(Shape):
  1317. """
  1318. Place a cross at the (x,y) point `position`.
  1319. The cross fits in a 0.2 square which center is (x,y).
  1320. the color is black
  1321. the linewidth is 1
  1322. """
  1323. def __init__(self,c):
  1324. l = 0.1
  1325. line1 = Line(c+point(-l,l),c+point(l,-l))
  1326. line2 = Line(c+point(l,l), c+point(-l,-l))
  1327. cross = Composition({'line1': line1, 'line2': line2})
  1328. cross.set_linecolor('black')
  1329. cross.set_linewidth(1)
  1330. self.shapes = {'cross': cross}
  1331. class Text(Point):
  1332. """
  1333. Place `text` at the (x,y) point `position`, with the given
  1334. fontsize (0 indicates that the default fontsize set in drawing_tool
  1335. is to be used). The text is centered around `position` if `alignment` is
  1336. 'center'; if 'left', the text starts at `position`, and if
  1337. 'right', the right and of the text is located at `position`.
  1338. """
  1339. def __init__(self, text, position, alignment='center', fontsize=0,
  1340. bgcolor=None, fgcolor=None, fontfamily=None):
  1341. """
  1342. fontfamily can be (e.g.) 'serif' or 'monospace' (for code!).
  1343. """
  1344. is_sequence(position)
  1345. is_sequence(position, length=2, can_be_None=True)
  1346. self.text = text
  1347. self.position = position
  1348. self.alignment = alignment
  1349. self.fontsize = fontsize
  1350. self.bgcolor = bgcolor
  1351. self.fgcolor = fgcolor
  1352. self.fontfamily = fontfamily
  1353. Point.__init__(self, position[0], position[1])
  1354. #no need for self.shapes here
  1355. def draw(self, verbose=0):
  1356. drawing_tool.text(
  1357. self.text, (self.x, self.y),
  1358. self.alignment, self.fontsize,
  1359. arrow_tip=None, bgcolor=self.bgcolor, fgcolor=self.fgcolor,
  1360. fontfamily=self.fontfamily)
  1361. if verbose > 0:
  1362. print('drawing Text "%s"' % self.text)
  1363. def __str__(self):
  1364. return 'text "%s" at (%g,%g)' % (self.text, self.x, self.y)
  1365. def __repr__(self):
  1366. return repr(str(self))
  1367. class Text_wArrow(Text):
  1368. """
  1369. As class Text, but an arrow is drawn from the mid part of the text
  1370. to some point `arrow_tip`.
  1371. """
  1372. def __init__(self, text, position, arrow_tip,
  1373. alignment='center', fontsize=0):
  1374. is_sequence(arrow_tip, length=2, can_be_None=True)
  1375. is_sequence(position)
  1376. self.arrow_tip = arrow_tip
  1377. Text.__init__(self, text, position, alignment, fontsize)
  1378. def draw(self, verbose=0):
  1379. drawing_tool.text(
  1380. self.text, self.position,
  1381. self.alignment, self.fontsize,
  1382. arrow_tip=self.arrow_tip,
  1383. bgcolor=self.bgcolor, fgcolor=self.fgcolor,
  1384. fontfamily=self.fontfamily)
  1385. if verbose > 0:
  1386. print('drawing Text_wArrow "%s"' % self.text)
  1387. def __str__(self):
  1388. return 'annotation "%s" at (%g,%g) with arrow to (%g,%g)' % \
  1389. (self.text, self.x, self.y,
  1390. self.arrow_tip[0], self.arrow_tip[1])
  1391. def __repr__(self):
  1392. return repr(str(self))
  1393. class Axis(Shape):
  1394. def __init__(self, start, length, label,
  1395. rotation_angle=0, fontsize=0,
  1396. label_spacing=1./45, label_alignment='left'):
  1397. """
  1398. Draw axis from start with `length` to the right
  1399. (x axis). Place label at the end of the arrow tip.
  1400. Then return `rotation_angle` (in degrees).
  1401. The `label_spacing` denotes the space between the label
  1402. and the arrow tip as a fraction of the length of the plot
  1403. in x direction. A tuple can be given to adjust the position
  1404. in both the x and y directions (with one parameter, the
  1405. x position is adjusted).
  1406. With `label_alignment` one can place
  1407. the axis label text such that the arrow tip is to the 'left',
  1408. 'right', or 'center' with respect to the text field.
  1409. The `label_spacing` and `label_alignment`parameters can
  1410. be used to fine-tune the location of the label.
  1411. """
  1412. # Arrow is vertical arrow, make it horizontal
  1413. arrow = Arrow3(start, length, rotation_angle=-90)
  1414. arrow.rotate(rotation_angle, start)
  1415. if isinstance(label_spacing, (list,tuple)) and len(label_spacing) == 2:
  1416. x_spacing = drawing_tool.xrange*label_spacing[0]
  1417. y_spacing = drawing_tool.yrange*label_spacing[1]
  1418. elif isinstance(label_spacing, (int,float)):
  1419. # just x spacing
  1420. x_spacing = drawing_tool.xrange*label_spacing
  1421. y_spacing = 0
  1422. # should increase spacing for downward pointing axis
  1423. label_pos = [start[0] + length + x_spacing, start[1] + y_spacing]
  1424. label = Text(label, position=label_pos, fontsize=fontsize)
  1425. label.rotate(rotation_angle, start)
  1426. self.shapes = {'arrow': arrow, 'label': label}
  1427. def geometric_features(self):
  1428. return self.shapes['arrow'].geometric_features()
  1429. # Maybe Axis3 with label below/above?
  1430. class Force(Arrow1):
  1431. """
  1432. Indication of a force by an arrow and a text (symbol). Draw an
  1433. arrow, starting at `start` and with the tip at `end`. The symbol
  1434. is placed at `text_pos`, which can be 'start', 'end' or the
  1435. coordinates of a point. If 'end' or 'start', the text is placed at
  1436. a distance `text_spacing` times the width of the total plotting
  1437. area away from the specified point.
  1438. """
  1439. def __init__(self, start, end, text, text_spacing=1./60,
  1440. fontsize=0, text_pos='start', text_alignment='center'):
  1441. Arrow1.__init__(self, start, end, style='->')
  1442. if isinstance(text_spacing, (tuple,list)):
  1443. if len(text_spacing) == 2:
  1444. spacing = point(drawing_tool.xrange*text_spacing[0],
  1445. drawing_tool.xrange*text_spacing[1])
  1446. else:
  1447. spacing = drawing_tool.xrange*text_spacing[0]
  1448. else:
  1449. # just a number, this is x spacing
  1450. spacing = drawing_tool.xrange*text_spacing
  1451. start, end = arr2D(start), arr2D(end)
  1452. # Two cases: label at bottom of line or top, need more
  1453. # spacing if bottom
  1454. downward = (end-start)[1] < 0
  1455. upward = not downward # for easy code reading
  1456. if isinstance(text_pos, (str,bytes)):
  1457. if text_pos == 'start':
  1458. spacing_dir = unit_vec(start - end)
  1459. if upward:
  1460. spacing *= 1.7
  1461. if isinstance(spacing, (int, float)):
  1462. text_pos = start + spacing*spacing_dir
  1463. else:
  1464. text_pos = start + spacing
  1465. elif text_pos == 'end':
  1466. spacing_dir = unit_vec(end - start)
  1467. if downward:
  1468. spacing *= 1.7
  1469. if isinstance(spacing, (int, float)):
  1470. text_pos = end + spacing*spacing_dir
  1471. else:
  1472. text_pos = end + spacing
  1473. self.shapes['text'] = Text(text, text_pos, fontsize=fontsize,
  1474. alignment=text_alignment)
  1475. def geometric_features(self):
  1476. d = Arrow1.geometric_features(self)
  1477. d['symbol_location'] = self.shapes['text'].position
  1478. return d
  1479. class Axis2(Force):
  1480. def __init__(self, start, length, label,
  1481. rotation_angle=0, fontsize=0,
  1482. label_spacing=1./45, label_alignment='left'):
  1483. direction = point(cos(radians(rotation_angle)),
  1484. sin(radians(rotation_angle)))
  1485. Force.__init__(start=start, end=length*direction, text=label,
  1486. text_spacing=label_spacing,
  1487. fontsize=fontsize, text_pos='end',
  1488. text_alignment=label_alignment)
  1489. # Substitute text by label for axis
  1490. self.shapes['label'] = self.shapes['text']
  1491. del self.shapes['text']
  1492. # geometric features from Force is ok
  1493. class Gravity(Axis):
  1494. """Downward-pointing gravity arrow with the symbol g."""
  1495. def __init__(self, start, length, fontsize=0):
  1496. Axis.__init__(self, start, length, '$g$', below=False,
  1497. rotation_angle=-90, label_spacing=1./30,
  1498. fontsize=fontsize)
  1499. self.shapes['arrow'].set_linecolor('black')
  1500. class Gravity(Force):
  1501. """Downward-pointing gravity arrow with the symbol g."""
  1502. def __init__(self, start, length, text='$g$', fontsize=0):
  1503. Force.__init__(self, start, (start[0], start[1]-length),
  1504. text, text_spacing=1./60,
  1505. fontsize=0, text_pos='end')
  1506. self.shapes['arrow'].set_linecolor('black')
  1507. class Distance_wText(Shape):
  1508. """
  1509. Arrow <-> with text (usually a symbol) at the midpoint, used for
  1510. identifying a some distance in a figure. The text is placed
  1511. slightly to the right of vertical-like arrows, with text displaced
  1512. `text_spacing` times to total distance in x direction of the plot
  1513. area. The text is by default aligned 'left' in this case. For
  1514. horizontal-like arrows, the text is placed the same distance
  1515. above, but aligned 'center' by default (when `alignment` is None).
  1516. """
  1517. def __init__(self, start, end, text, fontsize=0, text_spacing=1/60.,
  1518. alignment=None, text_pos='mid'):
  1519. start = arr2D(start)
  1520. end = arr2D(end)
  1521. # Decide first if we have a vertical or horizontal arrow
  1522. vertical = abs(end[0]-start[0]) < 2*abs(end[1]-start[1])
  1523. if vertical:
  1524. # Assume end above start
  1525. if end[1] < start[1]:
  1526. start, end = end, start
  1527. if alignment is None:
  1528. alignment = 'left'
  1529. else: # horizontal arrow
  1530. # Assume start to the right of end
  1531. if start[0] < end[0]:
  1532. start, end = end, start
  1533. if alignment is None:
  1534. alignment = 'center'
  1535. tangent = end - start
  1536. # Tangeng goes always to the left and upward
  1537. normal = unit_vec([tangent[1], -tangent[0]])
  1538. mid = 0.5*(start + end) # midpoint of start-end line
  1539. if text_pos == 'mid':
  1540. text_pos = mid + normal*drawing_tool.xrange*text_spacing
  1541. text = Text(text, text_pos, fontsize=fontsize,
  1542. alignment=alignment)
  1543. else:
  1544. is_sequence(text_pos, length=2)
  1545. text = Text_wArrow(text, text_pos, mid, alignment='left',
  1546. fontsize=fontsize)
  1547. arrow = Arrow1(start, end, style='<->')
  1548. arrow.set_linecolor('black')
  1549. arrow.set_linewidth(1)
  1550. self.shapes = {'arrow': arrow, 'text': text}
  1551. def geometric_features(self):
  1552. d = self.shapes['arrow'].geometric_features()
  1553. d['text_position'] = self.shapes['text'].position
  1554. return d
  1555. class Arc_wText(Shape):
  1556. """
  1557. Arc with text positionned at the left of arc half-way
  1558. """
  1559. def __init__(self, text, center, radius,
  1560. start_angle, arc_angle, fontsize=0,
  1561. resolution=180, text_spacing=1/60.):
  1562. self.text = text
  1563. self.center = center
  1564. self.radius = radius
  1565. self.fontsize=fontsize
  1566. self.resolution=resolution
  1567. self.text_spacing=text_spacing
  1568. self.start_angle = start_angle
  1569. self.arc_angle = arc_angle
  1570. self.setArc()
  1571. def setArc(self):
  1572. arc = Arc(self.center, self.radius, self.start_angle, self.arc_angle,
  1573. self.resolution)
  1574. mid = arr2D(arc(self.arc_angle/2.))
  1575. normal = unit_vec(mid - arr2D(self.center))
  1576. text_pos = mid + normal*drawing_tool.xrange*self.text_spacing
  1577. if hasattr(self, 'linewidth'):
  1578. arc.set_linewidth(self.linewidth)
  1579. self.shapes = {'arc': arc,
  1580. 'text': Text(self.text, text_pos, fontsize=self.fontsize)}
  1581. def changeAngle(self,start_angle,arc_angle):
  1582. self.arc_angle = arc_angle
  1583. self.start_angle = start_angle
  1584. self.setArc()
  1585. def set_linewidth(self, width):
  1586. self.linewidth = width
  1587. self.change_linewidth()
  1588. def change_linewidth(self):
  1589. super().set_linewidth(self.linewidth)
  1590. class Composition(Shape):
  1591. def __init__(self, shapes):
  1592. """shapes: list or dict of Shape objects."""
  1593. if isinstance(shapes, (tuple,list)):
  1594. # Convert to dict using the type of the list element as key
  1595. # (add a counter to make the keys unique)
  1596. shapes = {s.__class__.__name__ + '_' + str(i): s
  1597. for i, s in enumerate(shapes)}
  1598. self.shapes = shapes
  1599. # can make help methods: Line.midpoint, Line.normal(pt, dir='left') -> (x,y)
  1600. # list annotations in each class? contains extra annotations for explaining
  1601. # important parameters to the constructor, e.g., Line.annotations holds
  1602. # start and end as Text objects. Shape.demo calls shape.draw and
  1603. # for annotation in self.demo: annotation.draw() YES!
  1604. # Can make overall demo of classes by making objects and calling demo
  1605. # Could include demo fig in each constructor
  1606. class SimplySupportedBeam(Shape):
  1607. def __init__(self, pos, size):
  1608. pos = arr2D(pos)
  1609. P0 = (pos[0] - size/2., pos[1]-size)
  1610. P1 = (pos[0] + size/2., pos[1]-size)
  1611. triangle = Triangle(P0, P1, pos)
  1612. gap = size/5.
  1613. h = size/4. # height of rectangle
  1614. P2 = (P0[0], P0[1]-gap-h)
  1615. rectangle = Rectangle(P2, size, h).set_filled_curves(pattern='/')
  1616. self.shapes = {'triangle': triangle, 'rectangle': rectangle}
  1617. self.dimensions = {'pos': Text('pos', pos),
  1618. 'size': Distance_wText((P2[0], P2[1]-size),
  1619. (P2[0]+size, P2[1]-size),
  1620. 'size')}
  1621. def geometric_features(self):
  1622. t = self.shapes['triangle']
  1623. r = self.shapes['rectangle']
  1624. d = {'pos': t.geometric_features()['p2'],
  1625. 'mid_support': r.geometric_features()['lower_mid']}
  1626. return d
  1627. class ConstantBeamLoad(Shape):
  1628. """
  1629. Downward-pointing arrows indicating a vertical load.
  1630. The arrows are of equal length and filling a rectangle
  1631. specified as in the :class:`Rectangle` class.
  1632. Recorded geometric features:
  1633. ==================== =============================================
  1634. Attribute Description
  1635. ==================== =============================================
  1636. mid_top Middle point at the top of the row of
  1637. arrows (often used for positioning a text).
  1638. ==================== =============================================
  1639. """
  1640. def __init__(self, lower_left_corner, width, height, num_arrows=10):
  1641. box = Rectangle(lower_left_corner, width, height)
  1642. self.shapes = {'box': box}
  1643. dx = float(width)/(num_arrows-1)
  1644. y_top = lower_left_corner[1] + height
  1645. y_tip = lower_left_corner[1]
  1646. for i in range(num_arrows):
  1647. x = lower_left_corner[0] + i*dx
  1648. self.shapes['arrow%d' % i] = Arrow1((x, y_top), (x, y_tip))
  1649. def geometric_features(self):
  1650. return {'mid_top': self.shapes['box'].geometric_features()['upper_mid']}
  1651. class Moment(Arc_wText):
  1652. """
  1653. defines a Moment arrow with text given text, center and radius
  1654. default direction is counter_clockwise, fontsize and text spacing as optional parameters
  1655. """
  1656. def __init__(self, text, center, radius,
  1657. left=True, counter_clockwise=True,
  1658. fontsize=0, text_spacing=1/60.):
  1659. style = '->' if counter_clockwise else '<-'
  1660. start_angle = 90 if left else -90
  1661. Arc_wText.__init__(self, text, center, radius,
  1662. start_angle=start_angle,
  1663. arc_angle=180, fontsize=fontsize,
  1664. text_spacing=text_spacing,
  1665. resolution=180)
  1666. self.shapes['arc']['arc'].set_arrow(style) # Curve object
  1667. class Wheel(Shape):
  1668. """
  1669. Hub and spokes Wheel given center, radius, spokes (default 10), inner_radius(default 1/5 of radius)
  1670. """
  1671. def __init__(self, center, radius, inner_radius=None, nlines=10):
  1672. if inner_radius is None:
  1673. inner_radius = radius/5.0
  1674. outer = Circle(center, radius)
  1675. inner = Circle(center, inner_radius)
  1676. lines = []
  1677. self.nlines = nlines
  1678. # Draw nlines+1 since the first and last coincide
  1679. # (then nlines lines will be visible)
  1680. t = linspace(0, 2*pi, self.nlines+1)
  1681. Ri = inner_radius; Ro = radius
  1682. x0 = center[0]; y0 = center[1]
  1683. xinner = x0 + Ri*cos(t)
  1684. yinner = y0 + Ri*sin(t)
  1685. xouter = x0 + Ro*cos(t)
  1686. youter = y0 + Ro*sin(t)
  1687. lines = [Line((xi,yi),(xo,yo)) for xi, yi, xo, yo in \
  1688. zip(xinner, yinner, xouter, youter)]
  1689. self.shapes = {'inner': inner, 'outer': outer,
  1690. 'spokes': Composition(
  1691. {'spoke%d' % i: lines[i]
  1692. for i in range(len(lines))})}
  1693. class SineWave(Shape):
  1694. def __init__(self, xstart, xstop,
  1695. wavelength, amplitude, mean_level):
  1696. self.xstart = xstart
  1697. self.xstop = xstop
  1698. self.wavelength = wavelength
  1699. self.amplitude = amplitude
  1700. self.mean_level = mean_level
  1701. npoints = (self.xstop - self.xstart)/(self.wavelength/61.0)
  1702. x = linspace(self.xstart, self.xstop, npoints)
  1703. k = 2*pi/self.wavelength # frequency
  1704. y = self.mean_level + self.amplitude*sin(k*x)
  1705. self.shapes = {'waves': Curve(x,y)}
  1706. class Spring(Shape):
  1707. """
  1708. Specify a *vertical* spring, starting at `start` and with `length`
  1709. as total vertical length. In the middle of the spring there are
  1710. `num_windings` circular windings to illustrate the spring. If
  1711. `teeth` is true, the spring windings look like saw teeth,
  1712. otherwise the windings are smooth circles. The parameters `width`
  1713. (total width of spring) and `bar_length` (length of first and last
  1714. bar are given sensible default values if they are not specified
  1715. (these parameters can later be extracted as attributes, see table
  1716. below).
  1717. """
  1718. spring_fraction = 1./2 # fraction of total length occupied by spring
  1719. def __init__(self, start, length, width=None, bar_length=None,
  1720. num_windings=11, teeth=False):
  1721. B = start
  1722. n = num_windings - 1 # n counts teeth intervals
  1723. if n <= 6:
  1724. n = 7
  1725. # n must be odd:
  1726. if n % 2 == 0:
  1727. n = n+1
  1728. L = length
  1729. if width is None:
  1730. w = L/10.
  1731. else:
  1732. w = width/2.0
  1733. s = bar_length
  1734. # [0, x, L-x, L], f = (L-2*x)/L
  1735. # x = L*(1-f)/2.
  1736. # B: start point
  1737. # w: half-width
  1738. # L: total length
  1739. # s: length of first bar
  1740. # P0: start of dashpot (B[0]+s)
  1741. # P1: end of dashpot
  1742. # P2: end point
  1743. shapes = {}
  1744. if s is None:
  1745. f = Spring.spring_fraction
  1746. s = L*(1-f)/2. # start of spring
  1747. self.bar_length = s # record
  1748. self.width = 2*w
  1749. P0 = (B[0], B[1] + s)
  1750. P1 = (B[0], B[1] + L-s)
  1751. P2 = (B[0], B[1] + L)
  1752. if s >= L:
  1753. raise ValueError('length of first bar: %g is larger than total length: %g' % (s, L))
  1754. shapes['bar1'] = Line(B, P0)
  1755. spring_length = L - 2*s
  1756. t = spring_length/n # height increment per winding
  1757. if teeth:
  1758. resolution = 4
  1759. else:
  1760. resolution = 90
  1761. q = linspace(0, n, n*resolution + 1)
  1762. x = P0[0] + w*sin(2*pi*q)
  1763. y = P0[1] + q*t
  1764. shapes['spiral'] = Curve(x, y)
  1765. shapes['bar2'] = Line(P1,P2)
  1766. self.shapes = shapes
  1767. # Dimensions
  1768. start = Text_wArrow('start', (B[0]-1.5*w,B[1]-1.5*w), B)
  1769. width = Distance_wText((B[0]-w, B[1]-3.5*w), (B[0]+w, B[1]-3.5*w),
  1770. 'width')
  1771. length = Distance_wText((B[0]+3*w, B[1]), (B[0]+3*w, B[1]+L),
  1772. 'length')
  1773. num_windings = Text_wArrow('num_windings',
  1774. (B[0]+2*w,P2[1]+w),
  1775. (B[0]+1.2*w, B[1]+L/2.))
  1776. blength1 = Distance_wText((B[0]-2*w, B[1]), (B[0]-2*w, P0[1]),
  1777. 'bar_length',
  1778. text_pos=(P0[0]-7*w, P0[1]+w))
  1779. blength2 = Distance_wText((P1[0]-2*w, P1[1]), (P2[0]-2*w, P2[1]),
  1780. 'bar_length',
  1781. text_pos=(P2[0]-7*w, P2[1]+w))
  1782. dims = {'start': start, 'width': width, 'length': length,
  1783. 'num_windings': num_windings, 'bar_length1': blength1,
  1784. 'bar_length2': blength2}
  1785. self.dimensions = dims
  1786. def geometric_features(self):
  1787. """
  1788. Recorded geometric features:
  1789. ==================== =============================================
  1790. Attribute Description
  1791. ==================== =============================================
  1792. start Start point of spring.
  1793. end End point of spring.
  1794. width Total width of spring.
  1795. bar_length Length of first (and last) bar part.
  1796. ==================== =============================================
  1797. """
  1798. b1 = self.shapes['bar1']
  1799. d = {'start': b1.geometric_features()['start'],
  1800. 'end': self.shapes['bar2'].geometric_features()['end'],
  1801. 'bar_length': self.bar_length,
  1802. 'width': self.width}
  1803. return d
  1804. class Dashpot(Shape):
  1805. """
  1806. Specify a vertical dashpot of height `total_length` and `start` as
  1807. bottom/starting point. The first bar part has length `bar_length`.
  1808. Then comes the dashpot as a rectangular construction of total
  1809. width `width` and height `dashpot_length`. The position of the
  1810. piston inside the rectangular dashpot area is given by
  1811. `piston_pos`, which is the distance between the first bar (given
  1812. by `bar_length`) to the piston.
  1813. If some of `dashpot_length`, `bar_length`, `width` or `piston_pos`
  1814. are not given, suitable default values are calculated. Their
  1815. values can be extracted as keys in the dict returned from
  1816. ``geometric_features``.
  1817. """
  1818. dashpot_fraction = 1./2 # fraction of total_length
  1819. piston_gap_fraction = 1./6 # fraction of width
  1820. piston_thickness_fraction = 1./8 # fraction of dashplot_length
  1821. def __init__(self, start, total_length, bar_length=None,
  1822. width=None, dashpot_length=None, piston_pos=None):
  1823. B = start
  1824. L = total_length
  1825. if width is None:
  1826. w = L/10. # total width 1/5 of length
  1827. else:
  1828. w = width/2.0
  1829. s = bar_length
  1830. # [0, x, L-x, L], f = (L-2*x)/L
  1831. # x = L*(1-f)/2.
  1832. # B: start point
  1833. # w: half-width
  1834. # L: total length
  1835. # s: length of first bar
  1836. # P0: start of dashpot (B[0]+s)
  1837. # P1: end of dashpot
  1838. # P2: end point
  1839. shapes = {}
  1840. # dashpot is P0-P1 in y and width 2*w
  1841. if dashpot_length is None:
  1842. if s is None:
  1843. f = Dashpot.dashpot_fraction
  1844. s = L*(1-f)/2. # default
  1845. P1 = (B[0], B[1]+L-s)
  1846. dashpot_length = f*L
  1847. else:
  1848. if s is None:
  1849. f = 1./2 # the bar lengths are taken as f*dashpot_length
  1850. s = f*dashpot_length # default
  1851. P1 = (B[0], B[1]+s+dashpot_length)
  1852. P0 = (B[0], B[1]+s)
  1853. P2 = (B[0], B[1]+L)
  1854. if P2[1] > P1[1] > P0[1]:
  1855. pass # ok
  1856. else:
  1857. 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]))
  1858. shapes['line start'] = Line(B, P0)
  1859. shapes['pot'] = Curve([P1[0]-w, P0[0]-w, P0[0]+w, P1[0]+w],
  1860. [P1[1], P0[1], P0[1], P1[1]])
  1861. piston_thickness = dashpot_length*Dashpot.piston_thickness_fraction
  1862. if piston_pos is None:
  1863. piston_pos = 1/3.*dashpot_length
  1864. if piston_pos < 0:
  1865. piston_pos = 0
  1866. elif piston_pos > dashpot_length:
  1867. piston_pos = dashpot_length - piston_thickness
  1868. abs_piston_pos = P0[1] + piston_pos
  1869. gap = w*Dashpot.piston_gap_fraction
  1870. shapes['piston'] = Composition(
  1871. {'line': Line(P2, (B[0], abs_piston_pos + piston_thickness)),
  1872. 'rectangle': Rectangle((B[0] - w+gap, abs_piston_pos),
  1873. 2*w-2*gap, piston_thickness),
  1874. })
  1875. shapes['piston']['rectangle'].set_filled_curves(pattern='X')
  1876. self.shapes = shapes
  1877. self.bar_length = s
  1878. self.width = 2*w
  1879. self.piston_pos = piston_pos
  1880. self.dashpot_length = dashpot_length
  1881. # Dimensions
  1882. start = Text_wArrow('start', (B[0]-1.5*w,B[1]-1.5*w), B)
  1883. width = Distance_wText((B[0]-w, B[1]-3.5*w), (B[0]+w, B[1]-3.5*w),
  1884. 'width')
  1885. dplength = Distance_wText((B[0]+2*w, P0[1]), (B[0]+2*w, P1[1]),
  1886. 'dashpot_length', text_pos=(B[0]+w,B[1]-w))
  1887. blength = Distance_wText((B[0]-2*w, B[1]), (B[0]-2*w, P0[1]),
  1888. 'bar_length', text_pos=(B[0]-6*w,P0[1]-w))
  1889. ppos = Distance_wText((B[0]-2*w, P0[1]), (B[0]-2*w, P0[1]+piston_pos),
  1890. 'piston_pos', text_pos=(B[0]-6*w,P0[1]+piston_pos-w))
  1891. tlength = Distance_wText((B[0]+4*w, B[1]), (B[0]+4*w, B[1]+L),
  1892. 'total_length',
  1893. text_pos=(B[0]+4.5*w, B[1]+L-2*w))
  1894. line = Line((B[0]+w, abs_piston_pos), (B[0]+7*w, abs_piston_pos)).set_linestyle('dashed').set_linecolor('black').set_linewidth(1)
  1895. pp = Text('abs_piston_pos', (B[0]+7*w, abs_piston_pos), alignment='left')
  1896. dims = {'start': start, 'width': width, 'dashpot_length': dplength,
  1897. 'bar_length': blength, 'total_length': tlength,
  1898. 'piston_pos': ppos,}
  1899. #'abs_piston_pos': Composition({'line': line, 'text': pp})}
  1900. self.dimensions = dims
  1901. def geometric_features(self):
  1902. """
  1903. Recorded geometric features:
  1904. ==================== =============================================
  1905. Attribute Description
  1906. ==================== =============================================
  1907. start Start point of dashpot.
  1908. end End point of dashpot.
  1909. bar_length Length of first bar (from start to spring).
  1910. dashpot_length Length of dashpot middle part.
  1911. width Total width of dashpot.
  1912. piston_pos Position of piston in dashpot, relative to
  1913. start[1] + bar_length.
  1914. ==================== =============================================
  1915. """
  1916. d = {'start': self.shapes['line start'].geometric_features()['start'],
  1917. 'end': self.shapes['piston']['line'].geometric_features()['start'],
  1918. 'bar_length': self.bar_length,
  1919. 'piston_pos': self.piston_pos,
  1920. 'width': self.width,
  1921. 'dashpot_length': self.dashpot_length,
  1922. }
  1923. return d
  1924. class Wavy(Shape):
  1925. """
  1926. A wavy graph consisting of a user-given main curve y=f(x) with
  1927. additional sinusoidal waves of given (constant) amplitude,
  1928. but varying wavelength (a characteristic wavelength is specified).
  1929. """
  1930. def __init__(self, main_curve, interval, wavelength_of_perturbations,
  1931. amplitude_of_perturbations, smoothness):
  1932. """
  1933. ============================ ====================================
  1934. Name Description
  1935. ============================ ====================================
  1936. main_curve f(x) Python function
  1937. interval interval for main_curve
  1938. wavelength_of_perturbations dominant wavelength perturbed waves
  1939. amplitude_of_perturbations amplitude of perturbed waves
  1940. smoothness in [0, 1]: smooth=0, rough=1
  1941. ============================ ====================================
  1942. """
  1943. xmin, xmax = interval
  1944. L = wavelength_of_perturbations
  1945. k_0 = 2*pi/L # main frequency of waves
  1946. k_p = k_0*0.5
  1947. k_k = k_0/2*smoothness
  1948. A_0 = amplitude_of_perturbations
  1949. A_p = 0.3*A_0
  1950. A_k = k_0/2
  1951. x = linspace(xmin, xmax, 2001)
  1952. def w(x):
  1953. A = A_0 + A_p*sin(A_k*x)
  1954. k = k_0 + k_p*sin(k_k*x)
  1955. y = main_curve(x) + A*sin(k*x)
  1956. return y
  1957. self.shapes = {'wavy': Curve(x, w(x))}
  1958. # Use closure w to define __call__ - then we do not need
  1959. # to store all the parameters A_0, A_k, etc. as attributes
  1960. self.__call__ = w
  1961. class StochasticWavyCurve(object):
  1962. """
  1963. Precomputed stochastic wavy graphs.
  1964. There are three graphs with different look.
  1965. Curve 0:
  1966. ----------------------------------------------------------------------
  1967. |
  1968. |
  1969. *|
  1970. * |
  1971. * |
  1972. * |
  1973. * |
  1974. * |
  1975. * |
  1976. * |
  1977. * |
  1978. * |
  1979. * |
  1980. * |
  1981. |*
  1982. | *
  1983. | *
  1984. | *
  1985. | *
  1986. | *
  1987. | *
  1988. | *
  1989. | *
  1990. | *
  1991. | *
  1992. | *
  1993. | *
  1994. | *
  1995. | *
  1996. | *
  1997. | *
  1998. | *
  1999. | *
  2000. | *
  2001. | *
  2002. | *
  2003. | *
  2004. | *
  2005. | *
  2006. | *
  2007. | *
  2008. | *
  2009. | *
  2010. | *
  2011. | *
  2012. | *
  2013. | *
  2014. | *
  2015. | *
  2016. | *
  2017. | *
  2018. | *
  2019. | *
  2020. | *
  2021. | *
  2022. | *
  2023. | *
  2024. | *
  2025. | *
  2026. | *
  2027. | *
  2028. | *
  2029. | *
  2030. | *
  2031. | *
  2032. | *
  2033. | *
  2034. | *
  2035. | *
  2036. | *
  2037. | *
  2038. | *
  2039. |*
  2040. *|
  2041. * |
  2042. * |
  2043. * |
  2044. * |
  2045. * |
  2046. * |
  2047. * |
  2048. * |
  2049. * |
  2050. * |
  2051. * |
  2052. * |
  2053. * |
  2054. * |
  2055. * |
  2056. |*
  2057. | *
  2058. | *
  2059. | *
  2060. | *
  2061. | *
  2062. | *
  2063. | *
  2064. | *
  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. Curve 2:
  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. | *
  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. Curve 2:
  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. | *
  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. See also hplgit.github.io/pysketcher/doc/src/tut/fig-tut/StochasticWavyCurve.png (and .pdf)
  2467. """
  2468. # The curves were generated by the script generate_road_profiles.py and
  2469. # the code below were generated by plot_roads.py. Both scripts are
  2470. # found doc/src/src-bumpy in the repo git@github.com:hplgit/bumpy.git
  2471. def __init__(self, curve_no=0, percentage=100):
  2472. """
  2473. ============= ===================================================
  2474. Argument Explanation
  2475. ============= ===================================================
  2476. curve_no 0, 1, or 2: chooses one out of three shapes.
  2477. percentage The percentage of the defined curve to be used.
  2478. ============= ===================================================
  2479. """
  2480. self._define_curves()
  2481. self.curve_no = curve_no
  2482. m = int(len(self.x)/float(percentage)*100)
  2483. self.shapes = {'wavy': Curve(self.x[:m], self.y[curve_no][:m])}
  2484. def __call__(self, x):
  2485. raise NotImplementedError
  2486. def _define_curves(self):
  2487. 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, ])
  2488. self.y = [None]*3
  2489. 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, ])
  2490. 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, ])
  2491. 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, ])
  2492. # COMPOSITE types:
  2493. # MassSpringForce: Line(horizontal), Spring, Rectangle, Arrow/Line(w/arrow)
  2494. # must be easy to find the tip of the arrow
  2495. # Maybe extra dict: self.name['mass'] = Rectangle object - YES!
  2496. class ArbitraryVolume(Shape):
  2497. """
  2498. An arbitrary closed volume with an optional normal vector and a
  2499. vector field to be used in derivation of continuum mechanical
  2500. equations.
  2501. """
  2502. def __init__(self, position, width=1,
  2503. volume_symbol='V',
  2504. volume_symbol_fontsize='18',
  2505. normal_vector_symbol='n',
  2506. vector_field_symbol=None):
  2507. """
  2508. ============================ ====================================
  2509. Name Description
  2510. ============================ ====================================
  2511. position center point of volume
  2512. width width of volume (about 3 is best)
  2513. normal_vector_symbol symbol of None (no boundary normal)
  2514. volume_symbol None (no center symbol) or character
  2515. volume_symbol_fontsize fontsize of volume symbol
  2516. vector_field_symbol None (no vector) or symbol
  2517. ============================ ====================================
  2518. """
  2519. self.position, self.width = position, width
  2520. self.vector_symbol = vector_field_symbol
  2521. self.normal_symbol = normal_vector_symbol
  2522. ellipse, normal, vector = self._perturbed_unit_ellipse()
  2523. self.shapes = {'closed_curve': ellipse}
  2524. if normal_vector_symbol:
  2525. self.shapes['normal'] = normal
  2526. if vector_field_symbol is not None:
  2527. self.shapes['vector'] = vector
  2528. # Scale and translate
  2529. self.rotate(20, (0,0))
  2530. self.scale(width/2.0)
  2531. self.translate(position)
  2532. # Must be placed at position after translation:
  2533. if volume_symbol:
  2534. self.shapes['name'] = Text('$%s$' % volume_symbol, position,
  2535. fontsize=volume_symbol_fontsize)
  2536. def _perturbed_unit_ellipse(self):
  2537. """Draw the volume as a perturbed ellipse of about unit size."""
  2538. a0 = 1.0
  2539. b0 = 0.75
  2540. eps_a = 0.2
  2541. eps_b = 0.1
  2542. a = lambda t: a0 + eps_a*sin(1*t)
  2543. b = lambda t: b0 + eps_b*cos(1*t)
  2544. x = lambda t: a(t)*cos(t)
  2545. y = lambda t: b(t)*sin(t)
  2546. t = linspace(0, 2*pi, 101) # parameter
  2547. ellipse = Curve(x(t), y(t))
  2548. # Make normal vector
  2549. tx = lambda t: eps_a*cos(t)*cos(t) - a(t)*sin(t)
  2550. ty = lambda t: -eps_b*sin(t)*sin(t) + b(t)*cos(t)
  2551. t0 = pi/5
  2552. nx = ty(t0)
  2553. ny = -tx(t0)
  2554. nx = nx/sqrt(nx**2 + ny**2)
  2555. ny = ny/sqrt(nx**2 + ny**2)
  2556. Px = x(t0)
  2557. Py = y(t0)
  2558. start = point(x(t0), y(t0))
  2559. end = start + point(0.75*b0*nx, 0.75*b0*ny)
  2560. normal = Force(start, end, '$\\boldsymbol{%s}$' % self.normal_symbol,
  2561. text_spacing=1./60,
  2562. text_pos='end',
  2563. text_alignment='center')
  2564. end = start + point(0.75*b0/3*nx, 0.75*b0*4*ny)
  2565. vector = Force(start, end, '$\\boldsymbol{%s}$' % self.vector_symbol,
  2566. text_spacing=1./60,
  2567. text_pos='end',
  2568. text_alignment='center')
  2569. return ellipse, normal, vector
  2570. def geometric_features(self):
  2571. """
  2572. Recorded geometric features:
  2573. ==================== =============================================
  2574. Attribute Description
  2575. ==================== =============================================
  2576. position center point of volume
  2577. normal_vector_start start of normal vector
  2578. normal_vector_end end of normal vector
  2579. ==================== =============================================
  2580. """
  2581. d = {'position': self.position}
  2582. if 'normal' in self.shapes:
  2583. d['normal_vector_start'] = self.shapes['normal'].geometric_features()['start']
  2584. d['normal_vector_end'] = self.shapes['normal'].geometric_features()['end']
  2585. return d
  2586. def _test1():
  2587. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2588. l1 = Line((0,0), (1,1))
  2589. l1.draw()
  2590. eval(input(': '))
  2591. c1 = Circle((5,2), 1)
  2592. c2 = Circle((6,2), 1)
  2593. w1 = Wheel((7,2), 1)
  2594. c1.draw()
  2595. c2.draw()
  2596. w1.draw()
  2597. hardcopy()
  2598. display() # show the plot
  2599. def _test2():
  2600. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2601. l1 = Line((0,0), (1,1))
  2602. l1.draw()
  2603. eval(input(': '))
  2604. c1 = Circle((5,2), 1)
  2605. c2 = Circle((6,2), 1)
  2606. w1 = Wheel((7,2), 1)
  2607. filled_curves(True)
  2608. set_linecolor('blue')
  2609. c1.draw()
  2610. set_linecolor('aqua')
  2611. c2.draw()
  2612. filled_curves(False)
  2613. set_linecolor('red')
  2614. w1.draw()
  2615. hardcopy()
  2616. display() # show the plot
  2617. def _test3():
  2618. """Test example from the book."""
  2619. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2620. l1 = Line(start=(0,0), stop=(1,1)) # define line
  2621. l1.draw() # make plot data
  2622. r1 = Rectangle(lower_left_corner=(0,1), width=3, height=5)
  2623. r1.draw()
  2624. Circle(center=(5,7), radius=1).draw()
  2625. Wheel(center=(6,2), radius=2, inner_radius=0.5, nlines=7).draw()
  2626. hardcopy()
  2627. display()
  2628. def _test4():
  2629. """Second example from the book."""
  2630. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2631. r1 = Rectangle(lower_left_corner=(0,1), width=3, height=5)
  2632. c1 = Circle(center=(5,7), radius=1)
  2633. w1 = Wheel(center=(6,2), radius=2, inner_radius=0.5, nlines=7)
  2634. c2 = Circle(center=(7,7), radius=1)
  2635. filled_curves(True)
  2636. c1.draw()
  2637. set_linecolor('blue')
  2638. r1.draw()
  2639. set_linecolor('aqua')
  2640. c2.draw()
  2641. # Add thick aqua line around rectangle:
  2642. filled_curves(False)
  2643. set_linewidth(4)
  2644. r1.draw()
  2645. set_linecolor('red')
  2646. # Draw wheel with thick lines:
  2647. w1.draw()
  2648. hardcopy('tmp_colors')
  2649. display()
  2650. def _test5():
  2651. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2652. c = 6. # center point of box
  2653. w = 2. # size of box
  2654. L = 3
  2655. r1 = Rectangle((c-w/2, c-w/2), w, w)
  2656. l1 = Line((c,c-w/2), (c,c-w/2-L))
  2657. linecolor('blue')
  2658. filled_curves(True)
  2659. r1.draw()
  2660. linecolor('aqua')
  2661. filled_curves(False)
  2662. l1.draw()
  2663. hardcopy()
  2664. display() # show the plot
  2665. def rolling_wheel(total_rotation_angle):
  2666. """Animation of a rotating wheel."""
  2667. set_coordinate_system(xmin=0, xmax=10, ymin=0, ymax=10)
  2668. import time
  2669. center = (6,2)
  2670. radius = 2.0
  2671. angle = 2.0
  2672. pngfiles = []
  2673. w1 = Wheel(center=center, radius=radius, inner_radius=0.5, nlines=7)
  2674. for i in range(int(total_rotation_angle/angle)):
  2675. w1.draw()
  2676. print('BIG PROBLEM WITH ANIMATE!!!')
  2677. display()
  2678. filename = 'tmp_%03d' % i
  2679. pngfiles.append(filename + '.png')
  2680. hardcopy(filename)
  2681. time.sleep(0.3) # pause
  2682. L = radius*angle*pi/180 # translation = arc length
  2683. w1.rotate(angle, center)
  2684. w1.translate((-L, 0))
  2685. center = (center[0] - L, center[1])
  2686. erase()
  2687. cmd = 'convert -delay 50 -loop 1000 %s tmp_movie.gif' \
  2688. % (' '.join(pngfiles))
  2689. print('converting PNG files to animated GIF:\n', cmd)
  2690. import subprocess
  2691. failure, output = subprocess.getstatusoutput(cmd)
  2692. if failure: print('Could not run', cmd)
  2693. if __name__ == '__main__':
  2694. #rolling_wheel(40)
  2695. #_test1()
  2696. #_test3()
  2697. funcs = [
  2698. #test_Axis,
  2699. test_inclined_plane,
  2700. ]
  2701. for func in funcs:
  2702. func()
  2703. input('Type Return: ')