shapes.py 78 KB

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