shapes.py 79 KB

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