shapes.py 78 KB

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