main_sketcher.txt 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. .. Automatically generated Sphinx-extended reStructuredText file from DocOnce source
  2. (https://github.com/hplgit/doconce/)
  3. .. Sphinx can only have title with less than 63 chars...
  4. .. Document title:
  5. Pysketcher: Create Principal Sketches of Physics Problems
  6. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7. :Authors: Hans Petter Langtangen
  8. :Date: Dec 22, 2015
  9. .. The below box could be typeset as .. admonition: Attention
  10. but we have decided not to do so since the admon needs a title
  11. (the box formatting is therefore just ignored)
  12. This document is derived from Chapter 9 in the book
  13. `A Primer on Scientific Programming with Python <http://www.amazon.com/Scientific-Programming-Computational-Science-Engineering/dp/3642549586/ref=sr_1_2?s=books&ie=UTF8&qid=1407225588&sr=1-2&keywords=langtangen>`__, by H. P. Langtangen,
  14. 4th edition, Springer, 2014.
  15. *Abstract.* Pysketcher is a Python package which allows principal sketches of
  16. physics and mechanics problems to be realized through short programs
  17. instead of interactive (and potentially tedious and inaccurate)
  18. drawing. Elements of the sketch, such as lines, circles, angles,
  19. forces, coordinate systems, etc., are realized as objects and
  20. collected in hierarchical structures. Parts of the hierarchical
  21. structures can easily change line styles and colors, or be copied,
  22. scaled, translated, and rotated. These features make it
  23. straightforward to move parts of the sketch to create animation,
  24. usually in accordance with the physics of the underlying problem.
  25. Exact dimensioning of the elements in the sketch is trivial to obtain
  26. since distances are specified in computer code.
  27. Pysketcher is easy to learn from a number of examples. Beyond
  28. essential Python programming and a knowledge about mechanics problems,
  29. no further background is required.
  30. .. Task (can be questions): make sketches of physical problems, see fig
  31. .. through user-friendly composition of basic shapes
  32. .. Desired knowledge: plotting curves, basic OO (ch. X.Y, ...)
  33. .. Required knowledge?
  34. .. Learning Goals: these targets the inner workings of pysketcher,
  35. .. which is just a part of this document...
  36. .. !split
  37. A First Glimpse of Pysketcher
  38. =============================
  39. Formulation of physical problems makes heavy use of *principal sketches*
  40. such as the one in Figure :ref:`sketcher:fig:inclinedplane`.
  41. This particular sketch illustrates the classical mechanics problem
  42. of a rolling wheel on an inclined plane.
  43. The figure
  44. is made up many individual elements: a rectangle
  45. filled with a pattern (the inclined plane), a hollow circle with color
  46. (the wheel), arrows with labels (the :math:`N` and :math:`Mg` forces, and the :math:`x`
  47. axis), an angle with symbol :math:`\theta`, and a dashed line indicating the
  48. starting location of the wheel.
  49. Drawing software and plotting programs can produce such figures quite
  50. easily in principle, but the amount of details the user needs to
  51. control with the mouse can be substantial. Software more tailored to
  52. producing sketches of this type would work with more convenient
  53. abstractions, such as circle, wall, angle, force arrow, axis, and so
  54. forth. And as soon we start *programming* to construct the figure we
  55. get a range of other powerful tools at disposal. For example, we can
  56. easily translate and rotate parts of the figure and make an animation
  57. that illustrates the physics of the problem.
  58. Programming as a superior alternative to interactive drawing is
  59. the mantra of this section.
  60. .. _sketcher:fig:inclinedplane:
  61. .. figure:: wheel_on_inclined_plane.png
  62. :width: 400
  63. *Sketch of a physics problem*
  64. Basic Construction of Sketches
  65. ------------------------------
  66. Before attacking real-life sketches as in Figure :ref:`sketcher:fig:inclinedplane`
  67. we focus on the significantly simpler drawing shown
  68. in Figure :ref:`sketcher:fig:vehicle0`. This toy sketch consists of
  69. several elements: two circles, two rectangles, and a "ground" element.
  70. .. _sketcher:fig:vehicle0:
  71. .. figure:: vehicle0_dim.png
  72. :width: 600
  73. *Sketch of a simple figure*
  74. When the sketch is defined in terms of computer code, it is natural to
  75. parameterize geometric features, such as the radius of the wheel (:math:`R`),
  76. the center point of the left wheel (:math:`w_1`), as well as the height (:math:`H`) and
  77. length (:math:`L`) of the main part. The simple vehicle in
  78. Figure :ref:`sketcher:fig:vehicle0` is quickly drawn in almost any interactive
  79. tool. However, if we want to change the radius of the wheels, you need a
  80. sophisticated drawing tool to avoid redrawing the whole figure, while
  81. in computer code this is a matter of changing the :math:`R` parameter and
  82. rerunning the program.
  83. For example, Figure :ref:`sketcher:fig:vehicle0b` shows
  84. a variation of the drawing in
  85. Figure :ref:`sketcher:fig:vehicle0` obtained by just setting
  86. :math:`R=0.5`, :math:`L=5`, :math:`H=2`, and :math:`R=2`. Being able
  87. to quickly change geometric sizes is key to many problem settings in
  88. physics and engineering, but then a program must define the geometry.
  89. .. _sketcher:fig:vehicle0b:
  90. .. figure:: vehicle_v2.png
  91. :width: 500
  92. *Redrawing a figure with other geometric parameters*
  93. Basic Drawing
  94. ~~~~~~~~~~~~~
  95. A typical program creating these five elements is shown next.
  96. After importing the ``pysketcher`` package, the first task is always to
  97. define a coordinate system:
  98. .. code-block:: python
  99. from pysketcher import *
  100. drawing_tool.set_coordinate_system(
  101. xmin=0, xmax=10, ymin=-1, ymax=8)
  102. Instead of working with lengths expressed by specific numbers it is
  103. highly recommended to use variables to parameterize lengths as
  104. this makes it easier to change dimensions later.
  105. Here we introduce some key lengths for the radius of the wheels,
  106. distance between the wheels, etc.:
  107. .. code-block:: python
  108. R = 1 # radius of wheel
  109. L = 4 # distance between wheels
  110. H = 2 # height of vehicle body
  111. w_1 = 5 # position of front wheel
  112. drawing_tool.set_coordinate_system(xmin=0, xmax=w_1 + 2*L + 3*R,
  113. ymin=-1, ymax=2*R + 3*H)
  114. With the drawing area in place we can make the first ``Circle`` object
  115. in an intuitive fashion:
  116. .. code-block:: python
  117. wheel1 = Circle(center=(w_1, R), radius=R)
  118. to change dimensions later.
  119. To translate the geometric information about the ``wheel1`` object to
  120. instructions for the plotting engine (in this case Matplotlib), one calls the
  121. ``wheel1.draw()``. To display all drawn objects, one issues
  122. ``drawing_tool.display()``. The typical steps are hence:
  123. .. code-block:: python
  124. wheel1 = Circle(center=(w_1, R), radius=R)
  125. wheel1.draw()
  126. # Define other objects and call their draw() methods
  127. drawing_tool.display()
  128. drawing_tool.savefig('tmp.png') # store picture
  129. The next wheel can be made by taking a copy of ``wheel1`` and
  130. translating the object to the right according to a
  131. displacement vector :math:`(L,0)`:
  132. .. code-block:: python
  133. wheel2 = wheel1.copy()
  134. wheel2.translate((L,0))
  135. The two rectangles are also made in an intuitive way:
  136. .. code-block:: python
  137. under = Rectangle(lower_left_corner=(w_1-2*R, 2*R),
  138. width=2*R + L + 2*R, height=H)
  139. over = Rectangle(lower_left_corner=(w_1, 2*R + H),
  140. width=2.5*R, height=1.25*H)
  141. Groups of Objects
  142. ~~~~~~~~~~~~~~~~~
  143. Instead of calling the ``draw`` method of every object, we can
  144. group objects and call ``draw``, or perform other operations, for
  145. the whole group. For example, we may collect the two wheels
  146. in a ``wheels`` group and the ``over`` and ``under`` rectangles
  147. in a ``body`` group. The whole vehicle is a composition
  148. of its ``wheels`` and ``body`` groups. The code goes like
  149. .. code-block:: python
  150. wheels = Composition({'wheel1': wheel1, 'wheel2': wheel2})
  151. body = Composition({'under': under, 'over': over})
  152. vehicle = Composition({'wheels': wheels, 'body': body})
  153. The ground is illustrated by an object of type ``Wall``,
  154. mostly used to indicate walls in sketches of mechanical systems.
  155. A ``Wall`` takes the ``x`` and ``y`` coordinates of some curve,
  156. and a ``thickness`` parameter, and creates a thick curve filled
  157. with a simple pattern. In this case the curve is just a flat
  158. line so the construction is made of two points on the
  159. ground line (:math:`(w_1-L,0)` and :math:`(w_1+3L,0)`):
  160. .. code-block:: python
  161. ground = Wall(x=[w_1 - L, w_1 + 3*L], y=[0, 0], thickness=-0.3*R)
  162. The negative thickness makes the pattern-filled rectangle appear below
  163. the defined line, otherwise it appears above.
  164. We may now collect all the objects in a "top" object that contains
  165. the whole figure:
  166. .. code-block:: python
  167. fig = Composition({'vehicle': vehicle, 'ground': ground})
  168. fig.draw() # send all figures to plotting backend
  169. drawing_tool.display()
  170. drawing_tool.savefig('tmp.png')
  171. The ``fig.draw()`` call will visit
  172. all subgroups, their subgroups,
  173. and so forth in the hierarchical tree structure of
  174. figure elements,
  175. and call ``draw`` for every object.
  176. Changing Line Styles and Colors
  177. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  178. Controlling the line style, line color, and line width is
  179. fundamental when designing figures. The ``pysketcher``
  180. package allows the user to control such properties in
  181. single objects, but also set global properties that are
  182. used if the object has no particular specification of
  183. the properties. Setting the global properties are done like
  184. .. code-block:: python
  185. drawing_tool.set_linestyle('dashed')
  186. drawing_tool.set_linecolor('black')
  187. drawing_tool.set_linewidth(4)
  188. At the object level the properties are specified in a similar
  189. way:
  190. .. code-block:: python
  191. wheels.set_linestyle('solid')
  192. wheels.set_linecolor('red')
  193. and so on.
  194. Geometric figures can be specified as *filled*, either with a color or with a
  195. special visual pattern:
  196. .. code-block:: python
  197. # Set filling of all curves
  198. drawing_tool.set_filled_curves(color='blue', pattern='/')
  199. # Turn off filling of all curves
  200. drawing_tool.set_filled_curves(False)
  201. # Fill the wheel with red color
  202. wheel1.set_filled_curves('red')
  203. .. `<http://packages.python.org/ete2/>`_ for visualizing tree structures!
  204. The Figure Composition as an Object Hierarchy
  205. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  206. The composition of objects making up the figure
  207. is hierarchical, similar to a family, where
  208. each object has a parent and a number of children. Do a
  209. ``print fig`` to display the relations:
  210. .. code-block:: text
  211. ground
  212. wall
  213. vehicle
  214. body
  215. over
  216. rectangle
  217. under
  218. rectangle
  219. wheels
  220. wheel1
  221. arc
  222. wheel2
  223. arc
  224. The indentation reflects how deep down in the hierarchy (family)
  225. we are.
  226. This output is to be interpreted as follows:
  227. * ``fig`` contains two objects, ``ground`` and ``vehicle``
  228. * ``ground`` contains an object ``wall``
  229. * ``vehicle`` contains two objects, ``body`` and ``wheels``
  230. * ``body`` contains two objects, ``over`` and ``under``
  231. * ``wheels`` contains two objects, ``wheel1`` and ``wheel2``
  232. In this listing there are also objects not defined by the
  233. programmer: ``rectangle`` and ``arc``. These are of type ``Curve``
  234. and automatically generated by the classes ``Rectangle`` and ``Circle``.
  235. More detailed information can be printed by
  236. .. code-block:: python
  237. print fig.show_hierarchy('std')
  238. yielding the output
  239. .. code-block:: text
  240. ground (Wall):
  241. wall (Curve): 4 coords fillcolor='white' fillpattern='/'
  242. vehicle (Composition):
  243. body (Composition):
  244. over (Rectangle):
  245. rectangle (Curve): 5 coords
  246. under (Rectangle):
  247. rectangle (Curve): 5 coords
  248. wheels (Composition):
  249. wheel1 (Circle):
  250. arc (Curve): 181 coords
  251. wheel2 (Circle):
  252. arc (Curve): 181 coords
  253. Here we can see the class type for each figure object, how many
  254. coordinates that are involved in basic figures (``Curve`` objects), and
  255. special settings of the basic figure (fillcolor, line types, etc.).
  256. For example, ``wheel2`` is a ``Circle`` object consisting of an ``arc``,
  257. which is a ``Curve`` object consisting of 181 coordinates (the
  258. points needed to draw a smooth circle). The ``Curve`` objects are the
  259. only objects that really holds specific coordinates to be drawn.
  260. The other object types are just compositions used to group
  261. parts of the complete figure.
  262. One can also get a graphical overview of the hierarchy of figure objects
  263. that build up a particular figure ``fig``.
  264. Just call ``fig.graphviz_dot('fig')`` to produce a file ``fig.dot`` in
  265. the *dot format*. This file contains relations between parent and
  266. child objects in the figure and can be turned into an image,
  267. as in Figure :ref:`sketcher:fig:vehicle0:hier1`, by
  268. running the ``dot`` program:
  269. .. code-block:: text
  270. Terminal> dot -Tpng -o fig.png fig.dot
  271. .. _sketcher:fig:vehicle0:hier1:
  272. .. figure:: vehicle0_hier1.png
  273. :width: 500
  274. *Hierarchical relation between figure objects*
  275. The call ``fig.graphviz_dot('fig', classname=True)`` makes a ``fig.dot`` file
  276. where the class type of each object is also visible, see
  277. Figure :ref:`sketcher:fig:vehicle0:hier2`. The ability to write out the
  278. object hierarchy or view it graphically can be of great help when
  279. working with complex figures that involve layers of subfigures.
  280. .. _sketcher:fig:vehicle0:hier2:
  281. .. figure:: Vehicle0_hier2.png
  282. :width: 500
  283. *Hierarchical relation between figure objects, including their class names*
  284. Any of the objects can in the program be reached through their names, e.g.,
  285. .. code-block:: python
  286. fig['vehicle']
  287. fig['vehicle']['wheels']
  288. fig['vehicle']['wheels']['wheel2']
  289. fig['vehicle']['wheels']['wheel2']['arc']
  290. fig['vehicle']['wheels']['wheel2']['arc'].x # x coords
  291. fig['vehicle']['wheels']['wheel2']['arc'].y # y coords
  292. fig['vehicle']['wheels']['wheel2']['arc'].linestyle
  293. fig['vehicle']['wheels']['wheel2']['arc'].linetype
  294. Grabbing a part of the figure this way is handy for
  295. changing properties of that part, for example, colors, line styles
  296. (see Figure :ref:`sketcher:fig:vehicle0:v2`):
  297. .. code-block:: python
  298. fig['vehicle']['wheels'].set_filled_curves('blue')
  299. fig['vehicle']['wheels'].set_linewidth(6)
  300. fig['vehicle']['wheels'].set_linecolor('black')
  301. fig['vehicle']['body']['under'].set_filled_curves('red')
  302. fig['vehicle']['body']['over'].set_filled_curves(pattern='/')
  303. fig['vehicle']['body']['over'].set_linewidth(14)
  304. fig['vehicle']['body']['over']['rectangle'].linewidth = 4
  305. The last line accesses the ``Curve`` object directly, while the line above,
  306. accesses the ``Rectangle`` object, which will then set the linewidth of
  307. its ``Curve`` object, and other objects if it had any.
  308. The result of the actions above is shown in Figure :ref:`sketcher:fig:vehicle0:v2`.
  309. .. _sketcher:fig:vehicle0:v2:
  310. .. figure:: vehicle0.png
  311. :width: 700
  312. *Left: Basic line-based drawing. Right: Thicker lines and filled parts*
  313. We can also change position of parts of the figure and thereby make
  314. animations, as shown next.
  315. Animation: Translating the Vehicle
  316. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  317. Can we make our little vehicle roll? A first attempt will be to
  318. fake rolling by just displacing all parts of the vehicle.
  319. The relevant parts constitute the ``fig['vehicle']`` object.
  320. This part of the figure can be translated, rotated, and scaled.
  321. A translation along the ground means a translation in :math:`x` direction,
  322. say a length :math:`L` to the right:
  323. .. code-block:: python
  324. fig['vehicle'].translate((L,0))
  325. You need to erase, draw, and display to see the movement:
  326. .. code-block:: python
  327. drawing_tool.erase()
  328. fig.draw()
  329. drawing_tool.display()
  330. Without erasing, the old drawing of the vehicle will remain in
  331. the figure so you get two vehicles. Without ``fig.draw()`` the
  332. new coordinates of the vehicle will not be communicated to
  333. the drawing tool, and without calling display the updated
  334. drawing will not be visible.
  335. A figure that moves in time is conveniently realized by the
  336. function ``animate``:
  337. .. code-block:: python
  338. animate(fig, tp, action)
  339. Here, ``fig`` is the entire figure, ``tp`` is an array of
  340. time points, and ``action`` is a user-specified function that changes
  341. ``fig`` at a specific time point. Typically, ``action`` will move
  342. parts of ``fig``.
  343. In the present case we can define the movement through a velocity
  344. function ``v(t)`` and displace the figure ``v(t)*dt`` for small time
  345. intervals ``dt``. A possible velocity function is
  346. .. code-block:: python
  347. def v(t):
  348. return -8*R*t*(1 - t/(2*R))
  349. Our action function for horizontal displacements ``v(t)*dt`` becomes
  350. .. code-block:: python
  351. def move(t, fig):
  352. x_displacement = dt*v(t)
  353. fig['vehicle'].translate((x_displacement, 0))
  354. Since our velocity is negative for :math:`t\in [0,2R]` the displacement is
  355. to the left.
  356. The ``animate`` function will for each time point ``t`` in ``tp`` erase
  357. the drawing, call ``action(t, fig)``, and show the new figure by
  358. ``fig.draw()`` and ``drawing_tool.display()``.
  359. Here we choose a resolution of the animation corresponding to
  360. 25 time points in the time interval :math:`[0,2R]`:
  361. .. code-block:: python
  362. import numpy
  363. tp = numpy.linspace(0, 2*R, 25)
  364. dt = tp[1] - tp[0] # time step
  365. animate(fig, tp, move, pause_per_frame=0.2)
  366. The ``pause_per_frame`` adds a pause, here 0.2 seconds, between
  367. each frame in the animation.
  368. We can also ask ``animate`` to store each frame in a file:
  369. .. code-block:: python
  370. files = animate(fig, tp, move_vehicle, moviefiles=True,
  371. pause_per_frame=0.2)
  372. The ``files`` variable, here ``'tmp_frame_%04d.png'``,
  373. is the printf-specification used to generate the individual
  374. plot files. We can use this specification to make a video
  375. file via ``ffmpeg`` (or ``avconv`` on Debian-based Linux systems such
  376. as Ubuntu). Videos in the Flash and WebM formats can be created
  377. by
  378. .. code-block:: text
  379. Terminal> ffmpeg -r 12 -i tmp_frame_%04d.png -vcodec flv mov.flv
  380. Terminal> ffmpeg -r 12 -i tmp_frame_%04d.png -vcodec libvpx mov.webm
  381. An animated GIF movie can also be made using the ``convert`` program
  382. from the ImageMagick software suite:
  383. .. code-block:: text
  384. Terminal> convert -delay 20 tmp_frame*.png mov.gif
  385. Terminal> animate mov.gif # play movie
  386. The delay between frames, in units of 1/100 s,
  387. governs the speed of the movie.
  388. To play the animated GIF file in a web page, simply insert
  389. ``<img src="mov.gif">`` in the HTML code.
  390. The individual PNG frames can be directly played in a web
  391. browser by running
  392. .. code-block:: text
  393. Terminal> scitools movie output_file=mov.html fps=5 tmp_frame*
  394. or calling
  395. .. code-block:: python
  396. from scitools.std import movie
  397. movie(files, encoder='html', output_file='mov.html')
  398. in Python. Load the resulting file ``mov.html`` into a web browser
  399. to play the movie.
  400. Try to run `vehicle0.py <http://tinyurl.com/ot733jn/vehicle0.py>`__ and
  401. then load ``mov.html`` into a browser, or play one of the ``mov.*``
  402. video files. Alternatively, you can view a ready-made `movie <http://tinyurl.com/oou9lp7/mov-tut/vehicle0.html>`__.
  403. .. _sketcher:vehicle1:anim:
  404. Animation: Rolling the Wheels
  405. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  406. It is time to show rolling wheels. To this end, we add spokes to the
  407. wheels, formed by two crossing lines, see Figure :ref:`sketcher:fig:vehicle1`.
  408. The construction of the wheels will now involve a circle and two lines:
  409. .. code-block:: python
  410. wheel1 = Composition({
  411. 'wheel': Circle(center=(w_1, R), radius=R),
  412. 'cross': Composition({'cross1': Line((w_1,0), (w_1,2*R)),
  413. 'cross2': Line((w_1-R,R), (w_1+R,R))})})
  414. wheel2 = wheel1.copy()
  415. wheel2.translate((L,0))
  416. Observe that ``wheel1.copy()`` copies all the objects that make
  417. up the first wheel, and ``wheel2.translate`` translates all
  418. the copied objects.
  419. .. _sketcher:fig:vehicle1:
  420. .. figure:: vehicle1.png
  421. :width: 400
  422. *Wheels with spokes to illustrate rolling*
  423. The ``move`` function now needs to displace all the objects in the
  424. entire vehicle and also rotate the ``cross1`` and ``cross2``
  425. objects in both wheels.
  426. The rotation angle follows from the fact that the arc length
  427. of a rolling wheel equals the displacement of the center of
  428. the wheel, leading to a rotation angle
  429. .. code-block:: python
  430. angle = - x_displacement/R
  431. With ``w_1`` tracking the :math:`x` coordinate of the center
  432. of the front wheel, we can rotate that wheel by
  433. .. code-block:: python
  434. w1 = fig['vehicle']['wheels']['wheel1']
  435. from math import degrees
  436. w1.rotate(degrees(angle), center=(w_1, R))
  437. The ``rotate`` function takes two parameters: the rotation angle
  438. (in degrees) and the center point of the rotation, which is the
  439. center of the wheel in this case. The other wheel is rotated by
  440. .. code-block:: python
  441. w2 = fig['vehicle']['wheels']['wheel2']
  442. w2.rotate(degrees(angle), center=(w_1 + L, R))
  443. That is, the angle is the same, but the rotation point is different.
  444. The update of the center point is done by ``w_1 += x_displacement``.
  445. The complete ``move`` function with translation of the entire
  446. vehicle and rotation of the wheels then becomes
  447. .. code-block:: python
  448. w_1 = w_1 + L # start position
  449. def move(t, fig):
  450. x_displacement = dt*v(t)
  451. fig['vehicle'].translate((x_displacement, 0))
  452. # Rotate wheels
  453. global w_1
  454. w_1 += x_displacement
  455. # R*angle = -x_displacement
  456. angle = - x_displacement/R
  457. w1 = fig['vehicle']['wheels']['wheel1']
  458. w1.rotate(degrees(angle), center=(w_1, R))
  459. w2 = fig['vehicle']['wheels']['wheel2']
  460. w2.rotate(degrees(angle), center=(w_1 + L, R))
  461. The complete example is found in the file
  462. `vehicle1.py <http://tinyurl.com/ot733jn/vehicle1.py>`__. You may run this file or watch a `ready-made movie <http://tinyurl.com/oou9lp7/mov-tut/vehicle1.html>`__.
  463. The advantages with making figures this way, through programming
  464. rather than using interactive drawing programs, are numerous. For
  465. example, the objects are parameterized by variables so that various
  466. dimensions can easily be changed. Subparts of the figure, possible
  467. involving a lot of figure objects, can change color, linetype, filling
  468. or other properties through a *single* function call. Subparts of the
  469. figure can be rotated, translated, or scaled. Subparts of the figure
  470. can also be copied and moved to other parts of the drawing
  471. area. However, the single most important feature is probably the
  472. ability to make animations governed by mathematical formulas or data
  473. coming from physics simulations of the problem, as shown in the example above.
  474. .. !split
  475. Basic Shapes
  476. ============
  477. This section presents many of the basic shapes in Pysketcher:
  478. ``Axis``, ``Distance_wText``, ``Rectangle``, ``Triangle``, ``Arc``,
  479. ``Spring``, ``Dashpot``, and ``Wavy``.
  480. Each shape is demonstrated with a figure and a
  481. unit test that shows how the figure is constructed in Python code.
  482. These demos rely heavily on the method ``draw_dimensions`` in
  483. the shape classes, which annotates the basic drawing of the shape
  484. with the various geometric parameters that govern the shape.
  485. Axis
  486. ----
  487. The ``Axis`` object gives the possibility draw a single axis to
  488. notify a coordinate system. Here is an example where we
  489. draw :math:`x` and :math:`y` axis of three coordinate systems of different
  490. rotation:
  491. |
  492. |
  493. .. figure:: Axis.png
  494. :width: 500
  495. |
  496. |
  497. The corresponding code looks like this:
  498. .. code-block:: python
  499. def test_Axis():
  500. drawing_tool.set_coordinate_system(
  501. xmin=0, xmax=15, ymin=-7, ymax=8, axis=True,
  502. instruction_file='tmp_Axis.py')
  503. # Draw normal x and y axis with origin at (7.5, 2)
  504. # in the coordinate system of the sketch: [0,15]x[-7,8]
  505. x_axis = Axis((7.5,2), 5, 'x', rotation_angle=0)
  506. y_axis = Axis((7.5,2), 5, 'y', rotation_angle=90)
  507. system = Composition({'x axis': x_axis, 'y axis': y_axis})
  508. system.draw()
  509. drawing_tool.display()
  510. # Rotate this system 40 degrees counter clockwise
  511. # and draw it with dashed lines
  512. system.set_linestyle('dashed')
  513. system.rotate(40, (7.5,2))
  514. system.draw()
  515. drawing_tool.display()
  516. # Rotate this system another 220 degrees and show
  517. # with dotted lines
  518. system.set_linestyle('dotted')
  519. system.rotate(220, (7.5,2))
  520. system.draw()
  521. drawing_tool.display()
  522. drawing_tool.display('Axis')
  523. Distance with Text
  524. ------------------
  525. The object ``Distance_wText`` is used to display an arrow, to indicate
  526. a distance in a sketch, with an additional text in the middle of the arrow.
  527. The figure
  528. |
  529. |
  530. .. figure:: Distance_wText.png
  531. :width: 500
  532. |
  533. |
  534. was produced by this code:
  535. .. code-block:: python
  536. def test_Distance_wText():
  537. drawing_tool.set_coordinate_system(
  538. xmin=0, xmax=10, ymin=0, ymax=6,
  539. axis=True, instruction_file='tmp_Distance_wText.py')
  540. fontsize=14
  541. t = r'$ 2\pi R^2 $' # sample text
  542. examples = Composition({
  543. 'a0': Distance_wText((4,5), (8, 5), t, fontsize),
  544. 'a6': Distance_wText((4,5), (4, 4), t, fontsize),
  545. 'a1': Distance_wText((0,2), (2, 4.5), t, fontsize),
  546. 'a2': Distance_wText((0,2), (2, 0), t, fontsize),
  547. 'a3': Distance_wText((2,4.5), (0, 5.5), t, fontsize),
  548. 'a4': Distance_wText((8,4), (10, 3), t, fontsize,
  549. text_spacing=old_div(-1.,60)),
  550. 'a5': Distance_wText((8,2), (10, 1), t, fontsize,
  551. text_spacing=old_div(-1.,40), alignment='right'),
  552. 'c1': Text_wArrow('text_spacing=-1./60',
  553. (4, 3.5), (9, 3.2),
  554. fontsize=10, alignment='left'),
  555. 'c2': Text_wArrow('text_spacing=-1./40, alignment="right"',
  556. (4, 0.5), (9, 1.2),
  557. fontsize=10, alignment='left'),
  558. })
  559. examples.draw()
  560. drawing_tool.display('Distance_wText and text positioning')
  561. Note the use of ``Text_wArrow`` to write an explaining text with an
  562. associated arrow, here used to explain how
  563. the ``text_spacing`` and ``alignment`` arguments can be used to adjust
  564. the appearance of the text that goes with the distance arrow.
  565. Rectangle
  566. ---------
  567. .. figure:: Rectangle.png
  568. :width: 500
  569. |
  570. |
  571. The above figure can be produced by the following code.
  572. .. code-block:: python
  573. def test_Rectangle():
  574. L = 3.0
  575. W = 4.0
  576. drawing_tool.set_coordinate_system(
  577. xmin=0, xmax=2*W, ymin=old_div(-L,2), ymax=2*L,
  578. axis=True, instruction_file='tmp_Rectangle.py')
  579. drawing_tool.set_linecolor('blue')
  580. drawing_tool.set_grid(True)
  581. xpos = old_div(W,2)
  582. r = Rectangle(lower_left_corner=(xpos,0), width=W, height=L)
  583. r.draw()
  584. r.draw_dimensions()
  585. drawing_tool.display('Rectangle')
  586. Note that the ``draw_dimension`` method adds explanation of dimensions and various
  587. important argument in the construction of a shape. It adapts the annotations
  588. to the geometry of the current shape.
  589. Triangle
  590. --------
  591. .. figure:: Triangle.png
  592. :width: 500
  593. |
  594. |
  595. The code below produces the figure.
  596. .. code-block:: python
  597. def test_Triangle():
  598. L = 3.0
  599. W = 4.0
  600. drawing_tool.set_coordinate_system(
  601. xmin=0, xmax=2*W, ymin=old_div(-L,2), ymax=1.2*L,
  602. axis=True, instruction_file='tmp_Triangle.py')
  603. drawing_tool.set_linecolor('blue')
  604. drawing_tool.set_grid(True)
  605. xpos = 1
  606. t = Triangle(p1=(old_div(W,2),0), p2=(3*W/2,old_div(W,2)), p3=(4*W/5.,L))
  607. t.draw()
  608. t.draw_dimensions()
  609. drawing_tool.display('Triangle')
  610. Here, the ``draw_dimension`` method writes the name of the corners at the
  611. position of the corners, which does not always look nice (the present figure
  612. is an example). For a high-quality sketch one would add some spacing
  613. to the location of the p1, p2, and even p3 texts.
  614. Arc
  615. ---
  616. .. figure:: Arc.png
  617. :width: 400
  618. |
  619. |
  620. An arc like the one above is produced by
  621. .. code-block:: python
  622. def test_Arc():
  623. L = 4.0
  624. W = 4.0
  625. drawing_tool.set_coordinate_system(
  626. xmin=old_div(-W,2), xmax=W, ymin=old_div(-L,2), ymax=1.5*L,
  627. axis=True, instruction_file='tmp_Arc.py')
  628. drawing_tool.set_linecolor('blue')
  629. drawing_tool.set_grid(True)
  630. center = point(0,0)
  631. radius = old_div(L,2)
  632. start_angle = 60
  633. arc_angle = 45
  634. a = Arc(center, radius, start_angle, arc_angle)
  635. a.draw()
  636. R1 = 1.25*radius
  637. R2 = 1.5*radius
  638. R = 2*radius
  639. a.dimensions = {
  640. 'start_angle':
  641. Arc_wText(
  642. 'start_angle', center, R1, start_angle=0,
  643. arc_angle=start_angle, text_spacing=old_div(1,10.)),
  644. 'arc_angle':
  645. Arc_wText(
  646. 'arc_angle', center, R2, start_angle=start_angle,
  647. arc_angle=arc_angle, text_spacing=old_div(1,20.)),
  648. 'r=0':
  649. Line(center, center +
  650. point(R*cos(radians(start_angle)),
  651. R*sin(radians(start_angle)))),
  652. 'r=start_angle':
  653. Line(center, center +
  654. point(R*cos(radians(start_angle+arc_angle)),
  655. R*sin(radians(start_angle+arc_angle)))),
  656. 'r=start+arc_angle':
  657. Line(center, center +
  658. point(R, 0)).set_linestyle('dashed'),
  659. 'radius': Distance_wText(center, a(0), 'radius', text_spacing=old_div(1,40.)),
  660. 'center': Text('center', center-point(old_div(radius,10.), old_div(radius,10.))),
  661. }
  662. for dimension in a.dimensions:
  663. if dimension.startswith('r='):
  664. dim = a.dimensions[dimension]
  665. dim.set_linestyle('dashed')
  666. dim.set_linewidth(1)
  667. dim.set_linecolor('black')
  668. a.draw_dimensions()
  669. drawing_tool.display('Arc')
  670. Spring
  671. ------
  672. .. figure:: Spring.png
  673. :width: 800
  674. |
  675. |
  676. The code for making these two springs goes like this:
  677. .. code-block:: python
  678. def test_Spring():
  679. L = 5.0
  680. W = 2.0
  681. drawing_tool.set_coordinate_system(
  682. xmin=0, xmax=7*W, ymin=old_div(-L,2), ymax=1.5*L,
  683. axis=True, instruction_file='tmp_Spring.py')
  684. drawing_tool.set_linecolor('blue')
  685. drawing_tool.set_grid(True)
  686. xpos = W
  687. s1 = Spring((W,0), L, teeth=True)
  688. s1_title = Text('Default Spring',
  689. s1.geometric_features()['end'] + point(0,old_div(L,10)))
  690. s1.draw()
  691. s1_title.draw()
  692. #s1.draw_dimensions()
  693. xpos += 3*W
  694. s2 = Spring(start=(xpos,0), length=L, width=old_div(W,2.),
  695. bar_length=old_div(L,6.), teeth=False)
  696. s2.draw()
  697. s2.draw_dimensions()
  698. drawing_tool.display('Spring')
  699. Dashpot
  700. -------
  701. .. figure:: Dashpot.png
  702. :width: 600
  703. |
  704. |
  705. This dashpot is produced by
  706. .. code-block:: python
  707. def test_Dashpot():
  708. L = 5.0
  709. W = 2.0
  710. xpos = 0
  711. drawing_tool.set_coordinate_system(
  712. xmin=xpos, xmax=xpos+5.5*W, ymin=old_div(-L,2), ymax=1.5*L,
  713. axis=True, instruction_file='tmp_Dashpot.py')
  714. drawing_tool.set_linecolor('blue')
  715. drawing_tool.set_grid(True)
  716. # Default (simple) dashpot
  717. xpos = 1.5
  718. d1 = Dashpot(start=(xpos,0), total_length=L)
  719. d1_title = Text('Dashpot (default)',
  720. d1.geometric_features()['end'] + point(0,old_div(L,10)))
  721. d1.draw()
  722. d1_title.draw()
  723. # Dashpot for animation with fixed bar_length, dashpot_length and
  724. # prescribed piston_pos
  725. xpos += 2.5*W
  726. d2 = Dashpot(start=(xpos,0), total_length=1.2*L, width=old_div(W,2),
  727. bar_length=W, dashpot_length=old_div(L,2), piston_pos=2*W)
  728. d2.draw()
  729. d2.draw_dimensions()
  730. drawing_tool.display('Dashpot')
  731. Wavy
  732. ----
  733. Looks strange. Fix x axis.
  734. Stochastic curves
  735. -----------------
  736. The ``StochasticWavyCurve`` object offers three precomputed
  737. graphics that have a random variation:
  738. |
  739. |
  740. .. figure:: StochasticWavyCurve.png
  741. :width: 600
  742. |
  743. |
  744. The usage is simple. The construction
  745. .. code-block:: python
  746. curve = StochasticWavyCurve(curve_no=1, percentage=40)
  747. picks the second curve (the three are numbered 0, 1, and 2),
  748. and the first 40% of that curve. In case one desires another extent
  749. of the axis, one can just scale the coordinates directly as these
  750. are stored in the arrays ``curve.x[curve_no]`` and
  751. ``curve.y[curve_no]``.
  752. .. !split
  753. Inner Workings of the Pysketcher Tool
  754. =====================================
  755. We shall now explain how we can, quite easily, realize software with
  756. the capabilities demonstrated in the previous examples. Each object in
  757. the figure is represented as a class in a class hierarchy. Using
  758. inheritance, classes can inherit properties from parent classes and
  759. add new geometric features.
  760. .. index:: tree data structure
  761. Class programming is a key technology for realizing Pysketcher.
  762. As soon as some classes are established, more are easily
  763. added. Enhanced functionality for all the classes is also easy to
  764. implement in common, generic code that can immediately be shared by
  765. all present and future classes. The fundamental data structure
  766. involved in the ``pysketcher`` package is a hierarchical tree, and much
  767. of the material on implementation issues targets how to traverse tree
  768. structures with recursive function calls in object hierarchies. This
  769. topic is of key relevance in a wide range of other applications as
  770. well. In total, the inner workings of Pysketcher constitute an
  771. excellent example on the power of class programming.
  772. Example of Classes for Geometric Objects
  773. ----------------------------------------
  774. We introduce class ``Shape`` as superclass for all specialized objects
  775. in a figure. This class does not store any data, but provides a
  776. series of functions that add functionality to all the subclasses.
  777. This will be shown later.
  778. Simple Geometric Objects
  779. ~~~~~~~~~~~~~~~~~~~~~~~~
  780. One simple subclass is ``Rectangle``, specified by the coordinates of
  781. the lower left corner and its width and height:
  782. .. code-block:: python
  783. class Rectangle(Shape):
  784. def __init__(self, lower_left_corner, width, height):
  785. p = lower_left_corner # short form
  786. x = [p[0], p[0] + width,
  787. p[0] + width, p[0], p[0]]
  788. y = [p[1], p[1], p[1] + height,
  789. p[1] + height, p[1]]
  790. self.shapes = {'rectangle': Curve(x,y)}
  791. Any subclass of ``Shape`` will have a constructor that takes geometric
  792. information about the shape of the object and creates a dictionary
  793. ``self.shapes`` with the shape built of simpler shapes. The most
  794. fundamental shape is ``Curve``, which is just a collection of :math:`(x,y)`
  795. coordinates in two arrays ``x`` and ``y``. Drawing the ``Curve`` object is
  796. a matter of plotting ``y`` versus ``x``. For class ``Rectangle`` the ``x``
  797. and ``y`` arrays contain the corner points of the rectangle in
  798. counterclockwise direction, starting and ending with in the lower left
  799. corner.
  800. Class ``Line`` is also a simple class:
  801. .. code-block:: python
  802. class Line(Shape):
  803. def __init__(self, start, end):
  804. x = [start[0], end[0]]
  805. y = [start[1], end[1]]
  806. self.shapes = {'line': Curve(x, y)}
  807. Here we only need two points, the start and end point on the line.
  808. However, we may want to add some useful functionality, e.g., the ability
  809. to give an :math:`x` coordinate and have the class calculate the
  810. corresponding :math:`y` coordinate:
  811. .. code-block:: python
  812. def __call__(self, x):
  813. """Given x, return y on the line."""
  814. x, y = self.shapes['line'].x, self.shapes['line'].y
  815. self.a = (y[1] - y[0])/(x[1] - x[0])
  816. self.b = y[0] - self.a*x[0]
  817. return self.a*x + self.b
  818. Unfortunately, this is too simplistic because vertical lines cannot be
  819. handled (infinite ``self.a``). The true source code of ``Line`` therefore
  820. provides a more general solution at the cost of significantly longer
  821. code with more tests.
  822. A circle implies a somewhat increased complexity. Again we represent
  823. the geometric object by a ``Curve`` object, but this time the ``Curve``
  824. object needs to store a large number of points on the curve such that
  825. a plotting program produces a visually smooth curve. The points on
  826. the circle must be calculated manually in the constructor of class
  827. ``Circle``. The formulas for points :math:`(x,y)` on a curve with radius :math:`R`
  828. and center at :math:`(x_0, y_0)` are given by
  829. .. math::
  830. x &= x_0 + R\cos (t),\\
  831. y &= y_0 + R\sin (t),
  832. where :math:`t\in [0, 2\pi]`. A discrete set of :math:`t` values in this
  833. interval gives the corresponding set of :math:`(x,y)` coordinates on
  834. the circle. The user must specify the resolution as the number
  835. of :math:`t` values. The circle's radius and center must of course
  836. also be specified.
  837. We can write the ``Circle`` class as
  838. .. code-block:: python
  839. class Circle(Shape):
  840. def __init__(self, center, radius, resolution=180):
  841. self.center, self.radius = center, radius
  842. self.resolution = resolution
  843. t = linspace(0, 2*pi, 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 = {'circle': Curve(x, y)}
  849. As in class ``Line`` we can offer the possibility to give an angle
  850. :math:`\theta` (equivalent to :math:`t` in the formulas above)
  851. and then get the corresponding :math:`x` and :math:`y` coordinates:
  852. .. code-block:: python
  853. def __call__(self, theta):
  854. """Return (x, y) point corresponding to angle theta."""
  855. return self.center[0] + self.radius*cos(theta), \
  856. self.center[1] + self.radius*sin(theta)
  857. There is one flaw with this method: it yields illegal values after
  858. a translation, scaling, or rotation of the circle.
  859. A part of a circle, an arc, is a frequent geometric object when
  860. drawing mechanical systems. The arc is constructed much like
  861. a circle, but :math:`t` runs in :math:`[\theta_s, \theta_s + \theta_a]`. Giving
  862. :math:`\theta_s` and :math:`\theta_a` the slightly more descriptive names
  863. ``start_angle`` and ``arc_angle``, the code looks like this:
  864. .. code-block:: python
  865. class Arc(Shape):
  866. def __init__(self, center, radius,
  867. start_angle, arc_angle,
  868. resolution=180):
  869. self.start_angle = radians(start_angle)
  870. self.arc_angle = radians(arc_angle)
  871. t = linspace(self.start_angle,
  872. self.start_angle + self.arc_angle,
  873. resolution+1)
  874. x0 = center[0]; y0 = center[1]
  875. R = radius
  876. x = x0 + R*cos(t)
  877. y = y0 + R*sin(t)
  878. self.shapes = {'arc': Curve(x, y)}
  879. Having the ``Arc`` class, a ``Circle`` can alternatively be defined as
  880. a subclass specializing the arc to a circle:
  881. .. code-block:: python
  882. class Circle(Arc):
  883. def __init__(self, center, radius, resolution=180):
  884. Arc.__init__(self, center, radius, 0, 360, resolution)
  885. Class Curve
  886. ~~~~~~~~~~~
  887. Class ``Curve`` sits on the coordinates to be drawn, but how is that
  888. done? The constructor of class ``Curve`` just stores the coordinates,
  889. while a method ``draw`` sends the coordinates to the plotting program to
  890. make a graph. Or more precisely, to avoid a lot of (e.g.)
  891. Matplotlib-specific plotting commands in class ``Curve`` we have created
  892. a small layer with a simple programming interface to plotting
  893. programs. This makes it straightforward to change from Matplotlib to
  894. another plotting program. The programming interface is represented by
  895. the ``drawing_tool`` object and has a few functions:
  896. * ``plot_curve`` for sending a curve in terms of :math:`x` and :math:`y` coordinates
  897. to the plotting program,
  898. * ``set_coordinate_system`` for specifying the graphics area,
  899. * ``erase`` for deleting all elements of the graph,
  900. * ``set_grid`` for turning on a grid (convenient while constructing the figure),
  901. * ``set_instruction_file`` for creating a separate file with all
  902. plotting commands (Matplotlib commands in our case),
  903. * a series of ``set_X`` functions where ``X`` is some property like
  904. ``linecolor``, ``linestyle``, ``linewidth``, ``filled_curves``.
  905. This is basically all we need to communicate to a plotting program.
  906. Any class in the ``Shape`` hierarchy inherits ``set_X`` functions for
  907. setting properties of curves. This information is propagated to
  908. all other shape objects in the ``self.shapes`` dictionary. Class
  909. ``Curve`` stores the line properties together with the coordinates
  910. of its curve and propagates this information to the plotting program.
  911. When saying ``vehicle.set_linewidth(10)``, all objects that make
  912. up the ``vehicle`` object will get a ``set_linewidth(10)`` call,
  913. but only the ``Curve`` object at the end of the chain will actually
  914. store the information and send it to the plotting program.
  915. A rough sketch of class ``Curve`` reads
  916. .. code-block:: python
  917. class Curve(Shape):
  918. """General curve as a sequence of (x,y) coordintes."""
  919. def __init__(self, x, y):
  920. self.x = asarray(x, dtype=float)
  921. self.y = asarray(y, dtype=float)
  922. def draw(self):
  923. drawing_tool.plot_curve(
  924. self.x, self.y,
  925. self.linestyle, self.linewidth, self.linecolor, ...)
  926. def set_linewidth(self, width):
  927. self.linewidth = width
  928. det set_linestyle(self, style):
  929. self.linestyle = style
  930. ...
  931. Compound Geometric Objects
  932. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  933. The simple classes ``Line``, ``Arc``, and ``Circle`` could can the geometric
  934. shape through just one ``Curve`` object. More complicated shapes are
  935. built from instances of various subclasses of ``Shape``. Classes used
  936. for professional drawings soon get quite complex in composition and
  937. have a lot of geometric details, so here we prefer to make a very
  938. simple composition: the already drawn vehicle from Figure
  939. :ref:`sketcher:fig:vehicle0`. That is, instead of composing the drawing
  940. in a Python program as shown above, we make a subclass ``Vehicle0`` in
  941. the ``Shape`` hierarchy for doing the same thing.
  942. The ``Shape`` hierarchy is found in the ``pysketcher`` package, so to use these
  943. classes or derive a new one, we need to import ``pysketcher``. The constructor
  944. of class ``Vehicle0`` performs approximately the same statements as
  945. in the example program we developed for making the drawing in
  946. Figure :ref:`sketcher:fig:vehicle0`.
  947. .. code-block:: python
  948. from pysketcher import *
  949. class Vehicle0(Shape):
  950. def __init__(self, w_1, R, L, H):
  951. wheel1 = Circle(center=(w_1, R), radius=R)
  952. wheel2 = wheel1.copy()
  953. wheel2.translate((L,0))
  954. under = Rectangle(lower_left_corner=(w_1-2*R, 2*R),
  955. width=2*R + L + 2*R, height=H)
  956. over = Rectangle(lower_left_corner=(w_1, 2*R + H),
  957. width=2.5*R, height=1.25*H)
  958. wheels = Composition(
  959. {'wheel1': wheel1, 'wheel2': wheel2})
  960. body = Composition(
  961. {'under': under, 'over': over})
  962. vehicle = Composition({'wheels': wheels, 'body': body})
  963. xmax = w_1 + 2*L + 3*R
  964. ground = Wall(x=[R, xmax], y=[0, 0], thickness=-0.3*R)
  965. self.shapes = {'vehicle': vehicle, 'ground': ground}
  966. Any subclass of ``Shape`` *must* define the ``shapes`` attribute, otherwise
  967. the inherited ``draw`` method (and a lot of other methods too) will
  968. not work.
  969. The painting of the vehicle, as shown in the right part of
  970. Figure :ref:`sketcher:fig:vehicle0:v2`, could in class ``Vehicle0``
  971. be offered by a method:
  972. .. code-block:: python
  973. def colorful(self):
  974. wheels = self.shapes['vehicle']['wheels']
  975. wheels.set_filled_curves('blue')
  976. wheels.set_linewidth(6)
  977. wheels.set_linecolor('black')
  978. under = self.shapes['vehicle']['body']['under']
  979. under.set_filled_curves('red')
  980. over = self.shapes['vehicle']['body']['over']
  981. over.set_filled_curves(pattern='/')
  982. over.set_linewidth(14)
  983. The usage of the class is simple: after having set up an appropriate
  984. coordinate system as previously shown, we can do
  985. .. code-block:: python
  986. vehicle = Vehicle0(w_1, R, L, H)
  987. vehicle.draw()
  988. drawing_tool.display()
  989. and go on the make a painted version by
  990. .. code-block:: python
  991. drawing_tool.erase()
  992. vehicle.colorful()
  993. vehicle.draw()
  994. drawing_tool.display()
  995. A complete code defining and using class ``Vehicle0`` is found in the file
  996. `vehicle2.py <http://tinyurl.com/ot733jn/vehicle2.py>`__.
  997. The ``pysketcher`` package contains a wide range of classes for various
  998. geometrical objects, particularly those that are frequently used in
  999. drawings of mechanical systems.
  1000. Adding Functionality via Recursion
  1001. ----------------------------------
  1002. .. index:: recursive function calls
  1003. The really powerful feature of our class hierarchy is that we can add
  1004. much functionality to the superclass ``Shape`` and to the "bottom" class
  1005. ``Curve``, and then all other classes for various types of geometrical shapes
  1006. immediately get the new functionality. To explain the idea we may
  1007. look at the ``draw`` method, which all classes in the ``Shape``
  1008. hierarchy must have. The inner workings of the ``draw`` method explain
  1009. the secrets of how a series of other useful operations on figures
  1010. can be implemented.
  1011. Basic Principles of Recursion
  1012. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1013. Note that we work with two types of hierarchies in the
  1014. present documentation: one Python *class hierarchy*,
  1015. with ``Shape`` as superclass, and one *object hierarchy* of figure elements
  1016. in a specific figure. A subclass of ``Shape`` stores its figure in the
  1017. ``self.shapes`` dictionary. This dictionary represents the object hierarchy
  1018. of figure elements for that class. We want to make one ``draw`` call
  1019. for an instance, say our class ``Vehicle0``, and then we want this call
  1020. to be propagated to *all* objects that are contained in
  1021. ``self.shapes`` and all is nested subdictionaries. How is this done?
  1022. The natural starting point is to call ``draw`` for each ``Shape`` object
  1023. in the ``self.shapes`` dictionary:
  1024. .. code-block:: python
  1025. def draw(self):
  1026. for shape in self.shapes:
  1027. self.shapes[shape].draw()
  1028. This general method can be provided by class ``Shape`` and inherited in
  1029. subclasses like ``Vehicle0``. Let ``v`` be a ``Vehicle0`` instance.
  1030. Seemingly, a call ``v.draw()`` just calls
  1031. .. code-block:: python
  1032. v.shapes['vehicle'].draw()
  1033. v.shapes['ground'].draw()
  1034. However, in the former call we call the ``draw`` method of a ``Composition`` object
  1035. whose ``self.shapes`` attributed has two elements: ``wheels`` and ``body``.
  1036. Since class ``Composition`` inherits the same ``draw`` method, this method will
  1037. run through ``self.shapes`` and call ``wheels.draw()`` and ``body.draw()``.
  1038. Now, the ``wheels`` object is also a ``Composition`` with the same ``draw``
  1039. method, which will run through ``self.shapes``, now containing
  1040. the ``wheel1`` and ``wheel2`` objects. The ``wheel1`` object is a ``Circle``,
  1041. so calling ``wheel1.draw()`` calls the ``draw`` method in class ``Circle``,
  1042. but this is the same ``draw`` method as shown above. This method will
  1043. therefore traverse the circle's ``shapes`` dictionary, which we have seen
  1044. consists of one ``Curve`` element.
  1045. The ``Curve`` object holds the coordinates to be plotted so here ``draw``
  1046. really needs to do something "physical", namely send the coordinates to
  1047. the plotting program. The ``draw`` method is outlined in the short listing
  1048. of class ``Curve`` shown previously.
  1049. We can go to any of the other shape objects that appear in the figure
  1050. hierarchy and follow their ``draw`` calls in the similar way. Every time,
  1051. a ``draw`` call will invoke a new ``draw`` call, until we eventually hit
  1052. a ``Curve`` object at the "bottom" of the figure hierarchy, and then that part
  1053. of the figure is really plotted (or more precisely, the coordinates
  1054. are sent to a plotting program).
  1055. When a method calls itself, such as ``draw`` does, the calls are known as
  1056. *recursive* and the programming principle is referred to as
  1057. *recursion*. This technique is very often used to traverse hierarchical
  1058. structures like the figure structures we work with here. Even though the
  1059. hierarchy of objects building up a figure are of different types, they
  1060. all inherit the same ``draw`` method and therefore exhibit the same
  1061. behavior with respect to drawing. Only the ``Curve`` object has a different
  1062. ``draw`` method, which does not lead to more recursion.
  1063. Explaining Recursion
  1064. ~~~~~~~~~~~~~~~~~~~~
  1065. Understanding recursion is usually a challenge. To get a better idea of
  1066. how recursion works, we have equipped class ``Shape`` with a method ``recurse``
  1067. that just visits all the objects in the ``shapes`` dictionary and prints
  1068. out a message for each object.
  1069. This feature allows us to trace the execution and see exactly where
  1070. we are in the hierarchy and which objects that are visited.
  1071. The ``recurse`` method is very similar to ``draw``:
  1072. .. code-block:: python
  1073. def recurse(self, name, indent=0):
  1074. # print message where we are (name is where we come from)
  1075. for shape in self.shapes:
  1076. # print message about which object to visit
  1077. self.shapes[shape].recurse(indent+2, shape)
  1078. The ``indent`` parameter governs how much the message from this
  1079. ``recurse`` method is intended. We increase ``indent`` by 2 for every
  1080. level in the hierarchy, i.e., every row of objects in Figure
  1081. :ref:`sketcher:fig:Vehicle0:hier2`. This indentation makes it easy to
  1082. see on the printout how far down in the hierarchy we are.
  1083. A typical message written by ``recurse`` when ``name`` is ``'body'`` and
  1084. the ``shapes`` dictionary has the keys ``'over'`` and ``'under'``,
  1085. will be
  1086. .. code-block:: text
  1087. Composition: body.shapes has entries 'over', 'under'
  1088. call body.shapes["over"].recurse("over", 6)
  1089. The number of leading blanks on each line corresponds to the value of
  1090. ``indent``. The code printing out such messages looks like
  1091. .. code-block:: python
  1092. def recurse(self, name, indent=0):
  1093. space = ' '*indent
  1094. print space, '%s: %s.shapes has entries' % \
  1095. (self.__class__.__name__, name), \
  1096. str(list(self.shapes.keys()))[1:-1]
  1097. for shape in self.shapes:
  1098. print space,
  1099. print 'call %s.shapes["%s"].recurse("%s", %d)' % \
  1100. (name, shape, shape, indent+2)
  1101. self.shapes[shape].recurse(shape, indent+2)
  1102. Let us follow a ``v.recurse('vehicle')`` call in detail, ``v`` being
  1103. a ``Vehicle0`` instance. Before looking into the output from ``recurse``,
  1104. let us get an overview of the figure hierarchy in the ``v`` object
  1105. (as produced by ``print v``)
  1106. .. code-block:: text
  1107. ground
  1108. wall
  1109. vehicle
  1110. body
  1111. over
  1112. rectangle
  1113. under
  1114. rectangle
  1115. wheels
  1116. wheel1
  1117. arc
  1118. wheel2
  1119. arc
  1120. The ``recurse`` method performs the same kind of traversal of the
  1121. hierarchy, but writes out and explains a lot more.
  1122. The data structure represented by ``v.shapes`` is known as a *tree*.
  1123. As in physical trees, there is a *root*, here the ``v.shapes``
  1124. dictionary. A graphical illustration of the tree (upside down) is
  1125. shown in Figure :ref:`sketcher:fig:Vehicle0:hier2`.
  1126. From the root there are one or more branches, here two:
  1127. ``ground`` and ``vehicle``. Following the ``vehicle`` branch, it has two new
  1128. branches, ``body`` and ``wheels``. Relationships as in family trees
  1129. are often used to describe the relations in object trees too: we say
  1130. that ``vehicle`` is the parent of ``body`` and that ``body`` is a child of
  1131. ``vehicle``. The term *node* is also often used to describe an element
  1132. in a tree. A node may have several other nodes as *descendants*.
  1133. .. _sketcher:fig:Vehicle0:hier2:
  1134. .. figure:: Vehicle0_hier2.png
  1135. :width: 600
  1136. *Hierarchy of figure elements in an instance of class `Vehicle0`*
  1137. Recursion is the principal programming technique to traverse tree structures.
  1138. Any object in the tree can be viewed as a root of a subtree. For
  1139. example, ``wheels`` is the root of a subtree that branches into
  1140. ``wheel1`` and ``wheel2``. So when processing an object in the tree,
  1141. we imagine we process the root and then recurse into a subtree, but the
  1142. first object we recurse into can be viewed as the root of the subtree, so the
  1143. processing procedure of the parent object can be repeated.
  1144. A recommended next step is to simulate the ``recurse`` method by hand and
  1145. carefully check that what happens in the visits to ``recurse`` is
  1146. consistent with the output listed below. Although tedious, this is
  1147. a major exercise that guaranteed will help to demystify recursion.
  1148. A part of the printout of ``v.recurse('vehicle')`` looks like
  1149. .. code-block:: text
  1150. Vehicle0: vehicle.shapes has entries 'ground', 'vehicle'
  1151. call vehicle.shapes["ground"].recurse("ground", 2)
  1152. Wall: ground.shapes has entries 'wall'
  1153. call ground.shapes["wall"].recurse("wall", 4)
  1154. reached "bottom" object Curve
  1155. call vehicle.shapes["vehicle"].recurse("vehicle", 2)
  1156. Composition: vehicle.shapes has entries 'body', 'wheels'
  1157. call vehicle.shapes["body"].recurse("body", 4)
  1158. Composition: body.shapes has entries 'over', 'under'
  1159. call body.shapes["over"].recurse("over", 6)
  1160. Rectangle: over.shapes has entries 'rectangle'
  1161. call over.shapes["rectangle"].recurse("rectangle", 8)
  1162. reached "bottom" object Curve
  1163. call body.shapes["under"].recurse("under", 6)
  1164. Rectangle: under.shapes has entries 'rectangle'
  1165. call under.shapes["rectangle"].recurse("rectangle", 8)
  1166. reached "bottom" object Curve
  1167. ...
  1168. This example should clearly demonstrate the principle that we
  1169. can start at any object in the tree and do a recursive set
  1170. of calls with that object as root.
  1171. .. _sketcher:scaling:
  1172. Scaling, Translating, and Rotating a Figure
  1173. -------------------------------------------
  1174. With recursion, as explained in the previous section, we can within
  1175. minutes equip *all* classes in the ``Shape`` hierarchy, both present and
  1176. future ones, with the ability to scale the figure, translate it,
  1177. or rotate it. This added functionality requires only a few lines
  1178. of code.
  1179. Scaling
  1180. ~~~~~~~
  1181. We start with the simplest of the three geometric transformations,
  1182. namely scaling. For a ``Curve`` instance containing a set of :math:`n`
  1183. coordinates :math:`(x_i,y_i)` that make up a curve, scaling by a factor :math:`a`
  1184. means that we multiply all the :math:`x` and :math:`y` coordinates by :math:`a`:
  1185. .. math::
  1186. x_i \leftarrow ax_i,\quad y_i\leftarrow ay_i,
  1187. \quad i=0,\ldots,n-1\thinspace .
  1188. Here we apply the arrow as an assignment operator.
  1189. The corresponding Python implementation in
  1190. class ``Curve`` reads
  1191. .. code-block:: python
  1192. class Curve:
  1193. ...
  1194. def scale(self, factor):
  1195. self.x = factor*self.x
  1196. self.y = factor*self.y
  1197. Note here that ``self.x`` and ``self.y`` are Numerical Python arrays,
  1198. so that multiplication by a scalar number ``factor`` is
  1199. a vectorized operation.
  1200. An even more efficient implementation is to make use of in-place
  1201. multiplication in the arrays,
  1202. .. code-block:: python
  1203. class Curve:
  1204. ...
  1205. def scale(self, factor):
  1206. self.x *= factor
  1207. self.y *= factor
  1208. as this saves the creation of temporary arrays like ``factor*self.x``.
  1209. In an instance of a subclass of ``Shape``, the meaning of a method
  1210. ``scale`` is to run through all objects in the dictionary ``shapes`` and
  1211. ask each object to scale itself. This is the same delegation of
  1212. actions to subclass instances as we do in the ``draw`` (or ``recurse``)
  1213. method. All objects, except ``Curve`` instances, can share the same
  1214. implementation of the ``scale`` method. Therefore, we place the ``scale``
  1215. method in the superclass ``Shape`` such that all subclasses inherit the
  1216. method. Since ``scale`` and ``draw`` are so similar, we can easily
  1217. implement the ``scale`` method in class ``Shape`` by copying and editing
  1218. the ``draw`` method:
  1219. .. code-block:: python
  1220. class Shape:
  1221. ...
  1222. def scale(self, factor):
  1223. for shape in self.shapes:
  1224. self.shapes[shape].scale(factor)
  1225. This is all we have to do in order to equip all subclasses of
  1226. ``Shape`` with scaling functionality!
  1227. Any piece of the figure will scale itself, in the same manner
  1228. as it can draw itself.
  1229. Translation
  1230. ~~~~~~~~~~~
  1231. A set of coordinates :math:`(x_i, y_i)` can be translated :math:`v_0` units in
  1232. the :math:`x` direction and :math:`v_1` units in the :math:`y` direction using the formulas
  1233. .. math::
  1234. x_i\leftarrow x_i+v_0,\quad y_i\leftarrow y_i+v_1,
  1235. \quad i=0,\ldots,n-1\thinspace .
  1236. The natural specification of the translation is in terms of the
  1237. vector :math:`v=(v_0,v_1)`.
  1238. The corresponding Python implementation in class ``Curve`` becomes
  1239. .. code-block:: python
  1240. class Curve:
  1241. ...
  1242. def translate(self, v):
  1243. self.x += v[0]
  1244. self.y += v[1]
  1245. The translation operation for a shape object is very similar to the
  1246. scaling and drawing operations. This means that we can implement a
  1247. common method ``translate`` in the superclass ``Shape``. The code
  1248. is parallel to the ``scale`` method:
  1249. .. code-block:: python
  1250. class Shape:
  1251. ....
  1252. def translate(self, v):
  1253. for shape in self.shapes:
  1254. self.shapes[shape].translate(v)
  1255. Rotation
  1256. ~~~~~~~~
  1257. Rotating a figure is more complicated than scaling and translating.
  1258. A counter clockwise rotation of :math:`\theta` degrees for a set of
  1259. coordinates :math:`(x_i,y_i)` is given by
  1260. .. math::
  1261. \bar x_i &\leftarrow x_i\cos\theta - y_i\sin\theta,\\
  1262. \bar y_i &\leftarrow x_i\sin\theta + y_i\cos\theta\thinspace .
  1263. This rotation is performed around the origin. If we want the figure
  1264. to be rotated with respect to a general point :math:`(x,y)`, we need to
  1265. extend the formulas above:
  1266. .. math::
  1267. \bar x_i &\leftarrow x + (x_i -x)\cos\theta - (y_i -y)\sin\theta,\\
  1268. \bar y_i &\leftarrow y + (x_i -x)\sin\theta + (y_i -y)\cos\theta\thinspace .
  1269. The Python implementation in class ``Curve``, assuming that :math:`\theta`
  1270. is given in degrees and not in radians, becomes
  1271. .. code-block:: python
  1272. def rotate(self, angle, center):
  1273. angle = radians(angle)
  1274. x, y = center
  1275. c = cos(angle); s = sin(angle)
  1276. xnew = x + (self.x - x)*c - (self.y - y)*s
  1277. ynew = y + (self.x - x)*s + (self.y - y)*c
  1278. self.x = xnew
  1279. self.y = ynew
  1280. The ``rotate`` method in class ``Shape`` follows the principle of the
  1281. ``draw``, ``scale``, and ``translate`` methods.
  1282. We have already seen the ``rotate`` method in action when animating the
  1283. rolling wheel at the end of the section :ref:`sketcher:vehicle1:anim`.