shapes.py 79 KB

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