shapes.py 73 KB

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