shapes.py 81 KB

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