shapes.py 75 KB

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