main_sketcher.txt 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041
  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: Jan 22, 2016
  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. .. _sketcher:ex:pendulum:
  476. A simple pendulum
  477. =================
  478. .. _sketcher:ex:pendulum:basic:
  479. The basic physics sketch
  480. ------------------------
  481. We now want to make a sketch of simple pendulum from physics, as shown
  482. in Figure :ref:`sketcher:ex:pendulum:fig1`. A suggested work flow is to
  483. first sketch the figure on a piece of paper and introduce a coordinate
  484. system. A simple coordinate system is indicated in Figure
  485. :ref:`sketcher:ex:pendulum:fig1wgrid`. In a code we introduce variables
  486. ``W`` and ``H`` for the width and height of the figure (i.e., extent of
  487. the coordinate system) and open the program like this:
  488. .. code-block:: python
  489. from pysketcher import *
  490. H = 7.
  491. W = 6.
  492. drawing_tool.set_coordinate_system(xmin=0, xmax=W,
  493. ymin=0, ymax=H,
  494. axis=True)
  495. drawing_tool.set_grid(True)
  496. drawing_tool.set_linecolor('blue')
  497. Note that when the sketch is ready for "production", we will (normally)
  498. set ``axis=False`` to remove the coordinate system and also remove the
  499. grid, i.e., delete or
  500. comment out the line ``drawing_tool.set_grid(True)``.
  501. Also note that we in this example let all lines be blue by default.
  502. .. _sketcher:ex:pendulum:fig1:
  503. .. figure:: pendulum1.png
  504. :width: 400
  505. *Sketch of a simple pendulum*
  506. .. _sketcher:ex:pendulum:fig1wgrid:
  507. .. figure:: pendulum1_wgrid.png
  508. :width: 400
  509. *Sketch of a simple pendulum*
  510. The next step is to introduce variables for key quantities in the sketch.
  511. Let ``L`` be the length of the pendulum, ``P`` the rotation point, and let
  512. ``a`` be the angle the pendulum makes with the vertical (measured in degrees).
  513. We may set
  514. .. code-block:: python
  515. L = 5*H/7 # length
  516. P = (W/6, 0.85*H) # rotation point
  517. a = 40 # angle
  518. Be careful with integer division if you use Python 2! Fortunately, we
  519. started out with ``float`` objects for ``W`` and ``H`` so the expressions above
  520. are safe.
  521. What kind of objects do we need in this sketch? Looking at
  522. Figure :ref:`sketcher:ex:pendulum:fig1` we see that we need
  523. 1. a vertical, dashed line
  524. 2. an arc with no text but dashed line to indicate the *path* of the
  525. mass
  526. 3. an arc with name :math:`\theta` to indicate the *angle*
  527. 4. a line, here called *rod*, from the rotation point to the mass
  528. 5. a blue, filled circle representing the *mass*
  529. 6. a text :math:`m` associated with the mass
  530. 7. an indicator of the pendulum's *length* :math:`L`, visualized as
  531. a line with two arrows tips and the text :math:`L`
  532. 8. a gravity vector with the text :math:`g`
  533. Pysketcher has objects for each of these elements in our sketch.
  534. We start with the simplest element: the vertical line, going from
  535. ``P`` to ``P`` minus the length in :math:`y` direction:
  536. .. code-block:: python
  537. vertical = Line(P, P-point(0,L))
  538. The path of the mass is an arc that can be made by
  539. Pysketcher's ``Arc`` object:
  540. .. code-block:: python
  541. path = Arc(P, L, -90, a)
  542. The first argument ``P`` is the center point, the second is the
  543. radius (``L`` here), the next arguments is the start angle, here
  544. it starts at -90 degrees, while the next argument is the angle of
  545. the arc, here ``a``.
  546. For the path of the mass, we also need an arc object, but this
  547. time with an associated text. Pysketcher has a specialized object
  548. for this purpose, ``Arc_wText``, since placing the text manually can
  549. be somewhat cumbersome.
  550. .. code-block:: python
  551. angle = Arc_wText(r'$\theta$', P, L/4, -90, a, text_spacing=1/30.)
  552. The arguments are as for ``Arc`` above, but the first one is the desired
  553. text. Remember to use a raw string since we want a LaTeX greek letter
  554. that contains a backslash.
  555. The ``text_spacing`` argument must often be tweaked. It is recommended
  556. to create only a few objects before rendering the sketch and then
  557. adjust spacings as one goes along.
  558. The rod is simply a line from ``P`` to the mass. We can easily
  559. compute the position of the mass from basic geometry considerations,
  560. but it is easier and safer to look up this point in other objects
  561. if it is already computed. The ``path`` object stores its start and
  562. end points, so ``path.geometric_features()['end']`` is the end point
  563. of the path, which is the position of the mass. We can therefore
  564. create the rod simply as a line from ``P`` to this end point:
  565. .. code-block:: python
  566. mass_pt = path.geometric_features()['end']
  567. rod = Line(P, mass_pt)
  568. The mass is a circle filled with color:
  569. .. code-block:: python
  570. mass = Circle(center=mass_pt, radius=L/20.)
  571. mass.set_filled_curves(color='blue')
  572. To place the :math:`m` correctly, we go a small distance in the direction of
  573. the rod, from the center of the circle. To this end, we need to
  574. compute the direction. This is easiest done by computing a vector
  575. from ``P`` to the center of the circle and calling ``unit_vec`` to make
  576. a unit vector in this direction:
  577. .. code-block:: python
  578. rod_vec = rod.geometric_features()['end'] - \
  579. rod.geometric_features()['start']
  580. unit_rod_vec = unit_vec(rod_vec)
  581. mass_symbol = Text('$m$', mass_pt + L/10*unit_rod_vec)
  582. Again, the distance ``L/10`` is something one has to experiment with.
  583. The next object is the length measure with the text :math:`L`. Such length
  584. measures are represented by Pysketcher's ``Distance_wText`` object.
  585. An easy construction is to first place this length measure along the
  586. rod and then translate it a little distance (``L/15``) in the
  587. normal direction of the rod:
  588. .. code-block:: python
  589. length = Distance_wText(P, mass_pt, '$L$')
  590. length.translate(L/15*point(cos(radians(a)), sin(radians(a))))
  591. For this translation we need a unit vector in the normal direction
  592. of the rod, which is from geometric considerations given by
  593. :math:`(\cos a, \sin a)`, when :math:`a` is the angle of the pendulum.
  594. The final object is the gravity force vector, which is so common
  595. in physics sketches that Pysketcher has a ready-made object: ``Gravity``,
  596. .. code-block:: python
  597. gravity = Gravity(start=P+point(0.8*L,0), length=L/3)
  598. Since blue is the default color for
  599. lines, we want the dashed lines (``vertical`` and ``path``) to be black
  600. and dashed with linewidth 1. These properties can be set one by one,
  601. but we can also make a little helper function:
  602. .. code-block:: python
  603. def set_dashed_thin_blackline(*objects):
  604. """Set linestyle of an object to dashed, black, width=1."""
  605. for obj in objects:
  606. obj.set_linestyle('dashed')
  607. obj.set_linecolor('black')
  608. obj.set_linewidth(1)
  609. set_dashed_thin_blackline(vertical, path)
  610. Now, all objects are in place, so it remains to compose the final
  611. figure and draw the composition:
  612. .. code-block:: python
  613. fig = Composition(
  614. {'body': mass, 'rod': rod,
  615. 'vertical': vertical, 'theta': angle, 'path': path,
  616. 'g': gravity, 'L': length, 'm': mass_symbol})
  617. fig.draw()
  618. drawing_tool.display()
  619. drawing_tool.savefig('pendulum1')
  620. The body diagram
  621. ----------------
  622. Now we want to isolate the mass and draw all the forces that act on it.
  623. Figure :ref:`sketcher:ex:pendulum:fig2wgrid` shows the desired result, but
  624. embedded in the coordinate system.
  625. We consider three types of forces: the gravity force, the force from the
  626. rod, and air resistance. The body diagram is key for deriving the
  627. equation of motion, so it is illustrative to add useful mathematical
  628. quantities needed in the derivation, such as the unit vectors in polar
  629. coordinates.
  630. .. _sketcher:ex:pendulum:fig2wgrid:
  631. .. figure:: pendulum5_wgrid.png
  632. :width: 400
  633. *Body diagram of a simple pendulum*
  634. We start by listing the objects in the sketch:
  635. 1. a text :math:`(x_0,y_0)` representing the rotation point ``P``
  636. 2. unit vector :math:`\boldsymbol{i}_r` with text
  637. 3. unit vector :math:`\boldsymbol{i}_\theta` with text
  638. 4. a dashed vertical line
  639. 5. a dashed line along the rod
  640. 6. an arc with text :math:`\theta`
  641. 7. the gravity force with text :math:`mg`
  642. 8. the force in the rod with text :math:`S`
  643. 9. the air resistance force with text :math:`\sim |v|v`
  644. The first object, :math:`(x_0,y_0)`, is simply a plain text where we have
  645. to experiment with the position. The unit vectors in polar coordinates
  646. may be drawn using the Pysketcher's ``Force`` object since it has an
  647. arrow with a text. The first three object can then be made as follows:
  648. .. code-block:: python
  649. x0y0 = Text('$(x_0,y_0)$', P + point(-0.4,-0.1))
  650. ir = Force(P, P + L/10*unit_vec(rod_vec),
  651. r'$\boldsymbol{i}_r$', text_pos='end',
  652. text_spacing=(0.015,0))
  653. ith = Force(P, P + L/10*unit_vec((-rod_vec[1], rod_vec[0])),
  654. r'$\boldsymbol{i}_{\theta}$', text_pos='end',
  655. text_spacing=(0.02,0.005))
  656. Note that tweaking of the position of ``x0y0`` use absolute coordinates, so
  657. if ``W`` or ``H`` is changed in the beginning of the figure, the tweaked position
  658. will most likely not look good. A better solution would be to express
  659. the tweaked displacement ``point(-0.4,-0.1)`` in terms of ``W`` and ``H``.
  660. The ``text_spacing`` values in the ``Force`` objects also use absolute
  661. coordinates. Very often, this is much more convenient when adjusting
  662. the objects, and global size parameters like ``W`` and ``H`` are in practice
  663. seldom changed.
  664. The vertical, dashed line, the dashed rod, and the arc for :math:`\theta`
  665. are made by
  666. .. code-block:: python
  667. rod_start = rod.geometric_features()['start'] # Point P
  668. vertical2 = Line(rod_start, rod_start + point(0,-L/3))
  669. set_dashed_thin_blackline(vertical2)
  670. set_dashed_thin_blackline(rod)
  671. angle2 = Arc_wText(r'$\theta$', rod_start, L/6, -90, a,
  672. text_spacing=1/30.)
  673. Note how we reuse the earlier defined object ``rod``.
  674. The forces are constructed as shown below.
  675. .. code-block:: python
  676. mg_force = Force(mass_pt, mass_pt + L/5*point(0,-1),
  677. '$mg$', text_pos='end')
  678. rod_force = Force(mass_pt, mass_pt - L/3*unit_vec(rod_vec),
  679. '$S$', text_pos='end',
  680. text_spacing=(0.03, 0.01))
  681. air_force = Force(mass_pt, mass_pt -
  682. L/6*unit_vec((rod_vec[1], -rod_vec[0])),
  683. '$\sim|v|v$', text_pos='end',
  684. text_spacing=(0.04,0.005))
  685. All objects are in place, and we can compose a figure to be drawn:
  686. .. code-block:: python
  687. body_diagram = Composition(
  688. {'mg': mg_force, 'S': rod_force, 'rod': rod,
  689. 'vertical': vertical2, 'theta': angle2,
  690. 'body': mass, 'm': mass_symbol})
  691. body_diagram['air'] = air_force
  692. body_diagram['ir'] = ir
  693. body_diagram['ith'] = ith
  694. body_diagram['origin'] = x0y0
  695. Here, we exemplify that we can start out with a composition as a
  696. dictionary, but (as in ordinary Python dictionaries) add new
  697. elements later when desired.
  698. .. FIGURE: [fig-tut/pendulum1.png, width=400 frac=0.5] Sketch of a simple pendulum.
  699. .. !split
  700. Basic shapes
  701. ============
  702. This section presents many of the basic shapes in Pysketcher:
  703. ``Axis``, ``Distance_wText``, ``Rectangle``, ``Triangle``, ``Arc``,
  704. ``Spring``, ``Dashpot``, and ``Wavy``.
  705. Each shape is demonstrated with a figure and a
  706. unit test that shows how the figure is constructed in Python code.
  707. These demos rely heavily on the method ``draw_dimensions`` in
  708. the shape classes, which annotates the basic drawing of the shape
  709. with the various geometric parameters that govern the shape.
  710. Axis
  711. ----
  712. The ``Axis`` object gives the possibility draw a single axis to
  713. notify a coordinate system. Here is an example where we
  714. draw :math:`x` and :math:`y` axis of three coordinate systems of different
  715. rotation:
  716. |
  717. |
  718. .. figure:: Axis.png
  719. :width: 500
  720. |
  721. |
  722. The corresponding code looks like this:
  723. .. code-block:: python
  724. def test_Axis():
  725. drawing_tool.set_coordinate_system(
  726. xmin=0, xmax=15, ymin=-7, ymax=8, axis=True,
  727. instruction_file='tmp_Axis.py')
  728. # Draw normal x and y axis with origin at (7.5, 2)
  729. # in the coordinate system of the sketch: [0,15]x[-7,8]
  730. x_axis = Axis((7.5,2), 5, 'x', rotation_angle=0)
  731. y_axis = Axis((7.5,2), 5, 'y', rotation_angle=90)
  732. system = Composition({'x axis': x_axis, 'y axis': y_axis})
  733. system.draw()
  734. drawing_tool.display()
  735. # Rotate this system 40 degrees counter clockwise
  736. # and draw it with dashed lines
  737. system.set_linestyle('dashed')
  738. system.rotate(40, (7.5,2))
  739. system.draw()
  740. drawing_tool.display()
  741. # Rotate this system another 220 degrees and show
  742. # with dotted lines
  743. system.set_linestyle('dotted')
  744. system.rotate(220, (7.5,2))
  745. system.draw()
  746. drawing_tool.display()
  747. drawing_tool.display('Axis')
  748. Distance with text
  749. ------------------
  750. The object ``Distance_wText`` is used to display an arrow, to indicate
  751. a distance in a sketch, with an additional text in the middle of the arrow.
  752. The figure
  753. |
  754. |
  755. .. figure:: Distance_wText.png
  756. :width: 500
  757. |
  758. |
  759. was produced by this code:
  760. .. code-block:: python
  761. def test_Distance_wText():
  762. drawing_tool.set_coordinate_system(
  763. xmin=0, xmax=10, ymin=0, ymax=6,
  764. axis=True, instruction_file='tmp_Distance_wText.py')
  765. fontsize=14
  766. t = r'$ 2\pi R^2 $' # sample text
  767. examples = Composition({
  768. 'a0': Distance_wText((4,5), (8, 5), t, fontsize),
  769. 'a6': Distance_wText((4,5), (4, 4), t, fontsize),
  770. 'a1': Distance_wText((0,2), (2, 4.5), t, fontsize),
  771. 'a2': Distance_wText((0,2), (2, 0), t, fontsize),
  772. 'a3': Distance_wText((2,4.5), (0, 5.5), t, fontsize),
  773. 'a4': Distance_wText((8,4), (10, 3), t, fontsize,
  774. text_spacing=-1./60),
  775. 'a5': Distance_wText((8,2), (10, 1), t, fontsize,
  776. text_spacing=-1./40, alignment='right'),
  777. 'c1': Text_wArrow('text_spacing=-1./60',
  778. (4, 3.5), (9, 3.2),
  779. fontsize=10, alignment='left'),
  780. 'c2': Text_wArrow('text_spacing=-1./40, alignment="right"',
  781. (4, 0.5), (9, 1.2),
  782. fontsize=10, alignment='left'),
  783. })
  784. examples.draw()
  785. drawing_tool.display('Distance_wText and text positioning')
  786. Note the use of ``Text_wArrow`` to write an explaining text with an
  787. associated arrow, here used to explain how
  788. the ``text_spacing`` and ``alignment`` arguments can be used to adjust
  789. the appearance of the text that goes with the distance arrow.
  790. Rectangle
  791. ---------
  792. .. figure:: Rectangle.png
  793. :width: 500
  794. |
  795. |
  796. The above figure can be produced by the following code.
  797. .. code-block:: python
  798. def test_Rectangle():
  799. L = 3.0
  800. W = 4.0
  801. drawing_tool.set_coordinate_system(
  802. xmin=0, xmax=2*W, ymin=-L/2, ymax=2*L,
  803. axis=True, instruction_file='tmp_Rectangle.py')
  804. drawing_tool.set_linecolor('blue')
  805. drawing_tool.set_grid(True)
  806. xpos = W/2
  807. r = Rectangle(lower_left_corner=(xpos,0), width=W, height=L)
  808. r.draw()
  809. r.draw_dimensions()
  810. drawing_tool.display('Rectangle')
  811. Note that the ``draw_dimension`` method adds explanation of dimensions and various
  812. important argument in the construction of a shape. It adapts the annotations
  813. to the geometry of the current shape.
  814. Triangle
  815. --------
  816. .. figure:: Triangle.png
  817. :width: 500
  818. |
  819. |
  820. The code below produces the figure.
  821. .. code-block:: python
  822. def test_Triangle():
  823. L = 3.0
  824. W = 4.0
  825. drawing_tool.set_coordinate_system(
  826. xmin=0, xmax=2*W, ymin=-L/2, ymax=1.2*L,
  827. axis=True, instruction_file='tmp_Triangle.py')
  828. drawing_tool.set_linecolor('blue')
  829. drawing_tool.set_grid(True)
  830. xpos = 1
  831. t = Triangle(p1=(W/2,0), p2=(3*W/2,W/2), p3=(4*W/5.,L))
  832. t.draw()
  833. t.draw_dimensions()
  834. drawing_tool.display('Triangle')
  835. Here, the ``draw_dimension`` method writes the name of the corners at the
  836. position of the corners, which does not always look nice (the present figure
  837. is an example). For a high-quality sketch one would add some spacing
  838. to the location of the p1, p2, and even p3 texts.
  839. Arc
  840. ---
  841. .. figure:: Arc.png
  842. :width: 400
  843. |
  844. |
  845. An arc like the one above is produced by
  846. .. code-block:: python
  847. def test_Arc():
  848. L = 4.0
  849. W = 4.0
  850. drawing_tool.set_coordinate_system(
  851. xmin=-W/2, xmax=W, ymin=-L/2, ymax=1.5*L,
  852. axis=True, instruction_file='tmp_Arc.py')
  853. drawing_tool.set_linecolor('blue')
  854. drawing_tool.set_grid(True)
  855. center = point(0,0)
  856. radius = L/2
  857. start_angle = 60
  858. arc_angle = 45
  859. a = Arc(center, radius, start_angle, arc_angle)
  860. a.draw()
  861. R1 = 1.25*radius
  862. R2 = 1.5*radius
  863. R = 2*radius
  864. a.dimensions = {
  865. 'start_angle':
  866. Arc_wText(
  867. 'start_angle', center, R1, start_angle=0,
  868. arc_angle=start_angle, text_spacing=1/10.),
  869. 'arc_angle':
  870. Arc_wText(
  871. 'arc_angle', center, R2, start_angle=start_angle,
  872. arc_angle=arc_angle, text_spacing=1/20.),
  873. 'r=0':
  874. Line(center, center +
  875. point(R*cos(radians(start_angle)),
  876. R*sin(radians(start_angle)))),
  877. 'r=start_angle':
  878. Line(center, center +
  879. point(R*cos(radians(start_angle+arc_angle)),
  880. R*sin(radians(start_angle+arc_angle)))),
  881. 'r=start+arc_angle':
  882. Line(center, center +
  883. point(R, 0)).set_linestyle('dashed'),
  884. 'radius': Distance_wText(center, a(0), 'radius', text_spacing=1/40.),
  885. 'center': Text('center', center-point(radius/10., radius/10.)),
  886. }
  887. for dimension in a.dimensions:
  888. if dimension.startswith('r='):
  889. dim = a.dimensions[dimension]
  890. dim.set_linestyle('dashed')
  891. dim.set_linewidth(1)
  892. dim.set_linecolor('black')
  893. a.draw_dimensions()
  894. drawing_tool.display('Arc')
  895. Spring
  896. ------
  897. .. figure:: Spring.png
  898. :width: 800
  899. |
  900. |
  901. The code for making these two springs goes like this:
  902. .. code-block:: python
  903. def test_Spring():
  904. L = 5.0
  905. W = 2.0
  906. drawing_tool.set_coordinate_system(
  907. xmin=0, xmax=7*W, ymin=-L/2, ymax=1.5*L,
  908. axis=True, instruction_file='tmp_Spring.py')
  909. drawing_tool.set_linecolor('blue')
  910. drawing_tool.set_grid(True)
  911. xpos = W
  912. s1 = Spring((W,0), L, teeth=True)
  913. s1_title = Text('Default Spring',
  914. s1.geometric_features()['end'] + point(0,L/10))
  915. s1.draw()
  916. s1_title.draw()
  917. #s1.draw_dimensions()
  918. xpos += 3*W
  919. s2 = Spring(start=(xpos,0), length=L, width=W/2.,
  920. bar_length=L/6., teeth=False)
  921. s2.draw()
  922. s2.draw_dimensions()
  923. drawing_tool.display('Spring')
  924. Dashpot
  925. -------
  926. .. figure:: Dashpot.png
  927. :width: 600
  928. |
  929. |
  930. This dashpot is produced by
  931. .. code-block:: python
  932. def test_Dashpot():
  933. L = 5.0
  934. W = 2.0
  935. xpos = 0
  936. drawing_tool.set_coordinate_system(
  937. xmin=xpos, xmax=xpos+5.5*W, ymin=-L/2, ymax=1.5*L,
  938. axis=True, instruction_file='tmp_Dashpot.py')
  939. drawing_tool.set_linecolor('blue')
  940. drawing_tool.set_grid(True)
  941. # Default (simple) dashpot
  942. xpos = 1.5
  943. d1 = Dashpot(start=(xpos,0), total_length=L)
  944. d1_title = Text('Dashpot (default)',
  945. d1.geometric_features()['end'] + point(0,L/10))
  946. d1.draw()
  947. d1_title.draw()
  948. # Dashpot for animation with fixed bar_length, dashpot_length and
  949. # prescribed piston_pos
  950. xpos += 2.5*W
  951. d2 = Dashpot(start=(xpos,0), total_length=1.2*L, width=W/2,
  952. bar_length=W, dashpot_length=L/2, piston_pos=2*W)
  953. d2.draw()
  954. d2.draw_dimensions()
  955. drawing_tool.display('Dashpot')
  956. Wavy
  957. ----
  958. Looks strange. Fix x axis.
  959. Stochastic curves
  960. -----------------
  961. The ``StochasticWavyCurve`` object offers three precomputed
  962. graphics that have a random variation:
  963. |
  964. |
  965. .. figure:: StochasticWavyCurve.png
  966. :width: 600
  967. |
  968. |
  969. The usage is simple. The construction
  970. .. code-block:: python
  971. curve = StochasticWavyCurve(curve_no=1, percentage=40)
  972. picks the second curve (the three are numbered 0, 1, and 2),
  973. and the first 40% of that curve. In case one desires another extent
  974. of the axis, one can just scale the coordinates directly as these
  975. are stored in the arrays ``curve.x[curve_no]`` and
  976. ``curve.y[curve_no]``.
  977. .. !split
  978. Inner workings of the Pysketcher tool
  979. =====================================
  980. We shall now explain how we can, quite easily, realize software with
  981. the capabilities demonstrated in the previous examples. Each object in
  982. the figure is represented as a class in a class hierarchy. Using
  983. inheritance, classes can inherit properties from parent classes and
  984. add new geometric features.
  985. .. index:: tree data structure
  986. Class programming is a key technology for realizing Pysketcher.
  987. As soon as some classes are established, more are easily
  988. added. Enhanced functionality for all the classes is also easy to
  989. implement in common, generic code that can immediately be shared by
  990. all present and future classes. The fundamental data structure
  991. involved in the ``pysketcher`` package is a hierarchical tree, and much
  992. of the material on implementation issues targets how to traverse tree
  993. structures with recursive function calls in object hierarchies. This
  994. topic is of key relevance in a wide range of other applications as
  995. well. In total, the inner workings of Pysketcher constitute an
  996. excellent example on the power of class programming.
  997. Example of classes for geometric objects
  998. ----------------------------------------
  999. We introduce class ``Shape`` as superclass for all specialized objects
  1000. in a figure. This class does not store any data, but provides a
  1001. series of functions that add functionality to all the subclasses.
  1002. This will be shown later.
  1003. Simple geometric objects
  1004. ~~~~~~~~~~~~~~~~~~~~~~~~
  1005. One simple subclass is ``Rectangle``, specified by the coordinates of
  1006. the lower left corner and its width and height:
  1007. .. code-block:: python
  1008. class Rectangle(Shape):
  1009. def __init__(self, lower_left_corner, width, height):
  1010. p = lower_left_corner # short form
  1011. x = [p[0], p[0] + width,
  1012. p[0] + width, p[0], p[0]]
  1013. y = [p[1], p[1], p[1] + height,
  1014. p[1] + height, p[1]]
  1015. self.shapes = {'rectangle': Curve(x,y)}
  1016. Any subclass of ``Shape`` will have a constructor that takes geometric
  1017. information about the shape of the object and creates a dictionary
  1018. ``self.shapes`` with the shape built of simpler shapes. The most
  1019. fundamental shape is ``Curve``, which is just a collection of :math:`(x,y)`
  1020. coordinates in two arrays ``x`` and ``y``. Drawing the ``Curve`` object is
  1021. a matter of plotting ``y`` versus ``x``. For class ``Rectangle`` the ``x``
  1022. and ``y`` arrays contain the corner points of the rectangle in
  1023. counterclockwise direction, starting and ending with in the lower left
  1024. corner.
  1025. Class ``Line`` is also a simple class:
  1026. .. code-block:: python
  1027. class Line(Shape):
  1028. def __init__(self, start, end):
  1029. x = [start[0], end[0]]
  1030. y = [start[1], end[1]]
  1031. self.shapes = {'line': Curve(x, y)}
  1032. Here we only need two points, the start and end point on the line.
  1033. However, we may want to add some useful functionality, e.g., the ability
  1034. to give an :math:`x` coordinate and have the class calculate the
  1035. corresponding :math:`y` coordinate:
  1036. .. code-block:: python
  1037. def __call__(self, x):
  1038. """Given x, return y on the line."""
  1039. x, y = self.shapes['line'].x, self.shapes['line'].y
  1040. self.a = (y[1] - y[0])/(x[1] - x[0])
  1041. self.b = y[0] - self.a*x[0]
  1042. return self.a*x + self.b
  1043. Unfortunately, this is too simplistic because vertical lines cannot be
  1044. handled (infinite ``self.a``). The true source code of ``Line`` therefore
  1045. provides a more general solution at the cost of significantly longer
  1046. code with more tests.
  1047. A circle implies a somewhat increased complexity. Again we represent
  1048. the geometric object by a ``Curve`` object, but this time the ``Curve``
  1049. object needs to store a large number of points on the curve such that
  1050. a plotting program produces a visually smooth curve. The points on
  1051. the circle must be calculated manually in the constructor of class
  1052. ``Circle``. The formulas for points :math:`(x,y)` on a curve with radius :math:`R`
  1053. and center at :math:`(x_0, y_0)` are given by
  1054. .. math::
  1055. x &= x_0 + R\cos (t),\\
  1056. y &= y_0 + R\sin (t),
  1057. where :math:`t\in [0, 2\pi]`. A discrete set of :math:`t` values in this
  1058. interval gives the corresponding set of :math:`(x,y)` coordinates on
  1059. the circle. The user must specify the resolution as the number
  1060. of :math:`t` values. The circle's radius and center must of course
  1061. also be specified.
  1062. We can write the ``Circle`` class as
  1063. .. code-block:: python
  1064. class Circle(Shape):
  1065. def __init__(self, center, radius, resolution=180):
  1066. self.center, self.radius = center, radius
  1067. self.resolution = resolution
  1068. t = linspace(0, 2*pi, resolution+1)
  1069. x0 = center[0]; y0 = center[1]
  1070. R = radius
  1071. x = x0 + R*cos(t)
  1072. y = y0 + R*sin(t)
  1073. self.shapes = {'circle': Curve(x, y)}
  1074. As in class ``Line`` we can offer the possibility to give an angle
  1075. :math:`\theta` (equivalent to :math:`t` in the formulas above)
  1076. and then get the corresponding :math:`x` and :math:`y` coordinates:
  1077. .. code-block:: python
  1078. def __call__(self, theta):
  1079. """Return (x, y) point corresponding to angle theta."""
  1080. return self.center[0] + self.radius*cos(theta), \
  1081. self.center[1] + self.radius*sin(theta)
  1082. There is one flaw with this method: it yields illegal values after
  1083. a translation, scaling, or rotation of the circle.
  1084. A part of a circle, an arc, is a frequent geometric object when
  1085. drawing mechanical systems. The arc is constructed much like
  1086. a circle, but :math:`t` runs in :math:`[\theta_s, \theta_s + \theta_a]`. Giving
  1087. :math:`\theta_s` and :math:`\theta_a` the slightly more descriptive names
  1088. ``start_angle`` and ``arc_angle``, the code looks like this:
  1089. .. code-block:: python
  1090. class Arc(Shape):
  1091. def __init__(self, center, radius,
  1092. start_angle, arc_angle,
  1093. resolution=180):
  1094. self.start_angle = radians(start_angle)
  1095. self.arc_angle = radians(arc_angle)
  1096. t = linspace(self.start_angle,
  1097. self.start_angle + self.arc_angle,
  1098. resolution+1)
  1099. x0 = center[0]; y0 = center[1]
  1100. R = radius
  1101. x = x0 + R*cos(t)
  1102. y = y0 + R*sin(t)
  1103. self.shapes = {'arc': Curve(x, y)}
  1104. Having the ``Arc`` class, a ``Circle`` can alternatively be defined as
  1105. a subclass specializing the arc to a circle:
  1106. .. code-block:: python
  1107. class Circle(Arc):
  1108. def __init__(self, center, radius, resolution=180):
  1109. Arc.__init__(self, center, radius, 0, 360, resolution)
  1110. Class curve
  1111. ~~~~~~~~~~~
  1112. Class ``Curve`` sits on the coordinates to be drawn, but how is that
  1113. done? The constructor of class ``Curve`` just stores the coordinates,
  1114. while a method ``draw`` sends the coordinates to the plotting program to
  1115. make a graph. Or more precisely, to avoid a lot of (e.g.)
  1116. Matplotlib-specific plotting commands in class ``Curve`` we have created
  1117. a small layer with a simple programming interface to plotting
  1118. programs. This makes it straightforward to change from Matplotlib to
  1119. another plotting program. The programming interface is represented by
  1120. the ``drawing_tool`` object and has a few functions:
  1121. * ``plot_curve`` for sending a curve in terms of :math:`x` and :math:`y` coordinates
  1122. to the plotting program,
  1123. * ``set_coordinate_system`` for specifying the graphics area,
  1124. * ``erase`` for deleting all elements of the graph,
  1125. * ``set_grid`` for turning on a grid (convenient while constructing the figure),
  1126. * ``set_instruction_file`` for creating a separate file with all
  1127. plotting commands (Matplotlib commands in our case),
  1128. * a series of ``set_X`` functions where ``X`` is some property like
  1129. ``linecolor``, ``linestyle``, ``linewidth``, ``filled_curves``.
  1130. This is basically all we need to communicate to a plotting program.
  1131. Any class in the ``Shape`` hierarchy inherits ``set_X`` functions for
  1132. setting properties of curves. This information is propagated to
  1133. all other shape objects in the ``self.shapes`` dictionary. Class
  1134. ``Curve`` stores the line properties together with the coordinates
  1135. of its curve and propagates this information to the plotting program.
  1136. When saying ``vehicle.set_linewidth(10)``, all objects that make
  1137. up the ``vehicle`` object will get a ``set_linewidth(10)`` call,
  1138. but only the ``Curve`` object at the end of the chain will actually
  1139. store the information and send it to the plotting program.
  1140. A rough sketch of class ``Curve`` reads
  1141. .. code-block:: python
  1142. class Curve(Shape):
  1143. """General curve as a sequence of (x,y) coordintes."""
  1144. def __init__(self, x, y):
  1145. self.x = asarray(x, dtype=float)
  1146. self.y = asarray(y, dtype=float)
  1147. def draw(self):
  1148. drawing_tool.plot_curve(
  1149. self.x, self.y,
  1150. self.linestyle, self.linewidth, self.linecolor, ...)
  1151. def set_linewidth(self, width):
  1152. self.linewidth = width
  1153. det set_linestyle(self, style):
  1154. self.linestyle = style
  1155. ...
  1156. Compound geometric objects
  1157. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1158. The simple classes ``Line``, ``Arc``, and ``Circle`` could can the geometric
  1159. shape through just one ``Curve`` object. More complicated shapes are
  1160. built from instances of various subclasses of ``Shape``. Classes used
  1161. for professional drawings soon get quite complex in composition and
  1162. have a lot of geometric details, so here we prefer to make a very
  1163. simple composition: the already drawn vehicle from Figure
  1164. :ref:`sketcher:fig:vehicle0`. That is, instead of composing the drawing
  1165. in a Python program as shown above, we make a subclass ``Vehicle0`` in
  1166. the ``Shape`` hierarchy for doing the same thing.
  1167. The ``Shape`` hierarchy is found in the ``pysketcher`` package, so to use these
  1168. classes or derive a new one, we need to import ``pysketcher``. The constructor
  1169. of class ``Vehicle0`` performs approximately the same statements as
  1170. in the example program we developed for making the drawing in
  1171. Figure :ref:`sketcher:fig:vehicle0`.
  1172. .. code-block:: python
  1173. from pysketcher import *
  1174. class Vehicle0(Shape):
  1175. def __init__(self, w_1, R, L, H):
  1176. wheel1 = Circle(center=(w_1, R), radius=R)
  1177. wheel2 = wheel1.copy()
  1178. wheel2.translate((L,0))
  1179. under = Rectangle(lower_left_corner=(w_1-2*R, 2*R),
  1180. width=2*R + L + 2*R, height=H)
  1181. over = Rectangle(lower_left_corner=(w_1, 2*R + H),
  1182. width=2.5*R, height=1.25*H)
  1183. wheels = Composition(
  1184. {'wheel1': wheel1, 'wheel2': wheel2})
  1185. body = Composition(
  1186. {'under': under, 'over': over})
  1187. vehicle = Composition({'wheels': wheels, 'body': body})
  1188. xmax = w_1 + 2*L + 3*R
  1189. ground = Wall(x=[R, xmax], y=[0, 0], thickness=-0.3*R)
  1190. self.shapes = {'vehicle': vehicle, 'ground': ground}
  1191. Any subclass of ``Shape`` *must* define the ``shapes`` attribute, otherwise
  1192. the inherited ``draw`` method (and a lot of other methods too) will
  1193. not work.
  1194. The painting of the vehicle, as shown in the right part of
  1195. Figure :ref:`sketcher:fig:vehicle0:v2`, could in class ``Vehicle0``
  1196. be offered by a method:
  1197. .. code-block:: python
  1198. def colorful(self):
  1199. wheels = self.shapes['vehicle']['wheels']
  1200. wheels.set_filled_curves('blue')
  1201. wheels.set_linewidth(6)
  1202. wheels.set_linecolor('black')
  1203. under = self.shapes['vehicle']['body']['under']
  1204. under.set_filled_curves('red')
  1205. over = self.shapes['vehicle']['body']['over']
  1206. over.set_filled_curves(pattern='/')
  1207. over.set_linewidth(14)
  1208. The usage of the class is simple: after having set up an appropriate
  1209. coordinate system as previously shown, we can do
  1210. .. code-block:: python
  1211. vehicle = Vehicle0(w_1, R, L, H)
  1212. vehicle.draw()
  1213. drawing_tool.display()
  1214. and go on the make a painted version by
  1215. .. code-block:: python
  1216. drawing_tool.erase()
  1217. vehicle.colorful()
  1218. vehicle.draw()
  1219. drawing_tool.display()
  1220. A complete code defining and using class ``Vehicle0`` is found in the file
  1221. `vehicle2.py <http://tinyurl.com/ot733jn/vehicle2.py>`__.
  1222. The ``pysketcher`` package contains a wide range of classes for various
  1223. geometrical objects, particularly those that are frequently used in
  1224. drawings of mechanical systems.
  1225. Adding functionality via recursion
  1226. ----------------------------------
  1227. .. index:: recursive function calls
  1228. The really powerful feature of our class hierarchy is that we can add
  1229. much functionality to the superclass ``Shape`` and to the "bottom" class
  1230. ``Curve``, and then all other classes for various types of geometrical shapes
  1231. immediately get the new functionality. To explain the idea we may
  1232. look at the ``draw`` method, which all classes in the ``Shape``
  1233. hierarchy must have. The inner workings of the ``draw`` method explain
  1234. the secrets of how a series of other useful operations on figures
  1235. can be implemented.
  1236. Basic principles of recursion
  1237. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1238. Note that we work with two types of hierarchies in the
  1239. present documentation: one Python *class hierarchy*,
  1240. with ``Shape`` as superclass, and one *object hierarchy* of figure elements
  1241. in a specific figure. A subclass of ``Shape`` stores its figure in the
  1242. ``self.shapes`` dictionary. This dictionary represents the object hierarchy
  1243. of figure elements for that class. We want to make one ``draw`` call
  1244. for an instance, say our class ``Vehicle0``, and then we want this call
  1245. to be propagated to *all* objects that are contained in
  1246. ``self.shapes`` and all is nested subdictionaries. How is this done?
  1247. The natural starting point is to call ``draw`` for each ``Shape`` object
  1248. in the ``self.shapes`` dictionary:
  1249. .. code-block:: python
  1250. def draw(self):
  1251. for shape in self.shapes:
  1252. self.shapes[shape].draw()
  1253. This general method can be provided by class ``Shape`` and inherited in
  1254. subclasses like ``Vehicle0``. Let ``v`` be a ``Vehicle0`` instance.
  1255. Seemingly, a call ``v.draw()`` just calls
  1256. .. code-block:: python
  1257. v.shapes['vehicle'].draw()
  1258. v.shapes['ground'].draw()
  1259. However, in the former call we call the ``draw`` method of a ``Composition`` object
  1260. whose ``self.shapes`` attributed has two elements: ``wheels`` and ``body``.
  1261. Since class ``Composition`` inherits the same ``draw`` method, this method will
  1262. run through ``self.shapes`` and call ``wheels.draw()`` and ``body.draw()``.
  1263. Now, the ``wheels`` object is also a ``Composition`` with the same ``draw``
  1264. method, which will run through ``self.shapes``, now containing
  1265. the ``wheel1`` and ``wheel2`` objects. The ``wheel1`` object is a ``Circle``,
  1266. so calling ``wheel1.draw()`` calls the ``draw`` method in class ``Circle``,
  1267. but this is the same ``draw`` method as shown above. This method will
  1268. therefore traverse the circle's ``shapes`` dictionary, which we have seen
  1269. consists of one ``Curve`` element.
  1270. The ``Curve`` object holds the coordinates to be plotted so here ``draw``
  1271. really needs to do something "physical", namely send the coordinates to
  1272. the plotting program. The ``draw`` method is outlined in the short listing
  1273. of class ``Curve`` shown previously.
  1274. We can go to any of the other shape objects that appear in the figure
  1275. hierarchy and follow their ``draw`` calls in the similar way. Every time,
  1276. a ``draw`` call will invoke a new ``draw`` call, until we eventually hit
  1277. a ``Curve`` object at the "bottom" of the figure hierarchy, and then that part
  1278. of the figure is really plotted (or more precisely, the coordinates
  1279. are sent to a plotting program).
  1280. When a method calls itself, such as ``draw`` does, the calls are known as
  1281. *recursive* and the programming principle is referred to as
  1282. *recursion*. This technique is very often used to traverse hierarchical
  1283. structures like the figure structures we work with here. Even though the
  1284. hierarchy of objects building up a figure are of different types, they
  1285. all inherit the same ``draw`` method and therefore exhibit the same
  1286. behavior with respect to drawing. Only the ``Curve`` object has a different
  1287. ``draw`` method, which does not lead to more recursion.
  1288. Explaining recursion
  1289. ~~~~~~~~~~~~~~~~~~~~
  1290. Understanding recursion is usually a challenge. To get a better idea of
  1291. how recursion works, we have equipped class ``Shape`` with a method ``recurse``
  1292. that just visits all the objects in the ``shapes`` dictionary and prints
  1293. out a message for each object.
  1294. This feature allows us to trace the execution and see exactly where
  1295. we are in the hierarchy and which objects that are visited.
  1296. The ``recurse`` method is very similar to ``draw``:
  1297. .. code-block:: python
  1298. def recurse(self, name, indent=0):
  1299. # print message where we are (name is where we come from)
  1300. for shape in self.shapes:
  1301. # print message about which object to visit
  1302. self.shapes[shape].recurse(indent+2, shape)
  1303. The ``indent`` parameter governs how much the message from this
  1304. ``recurse`` method is intended. We increase ``indent`` by 2 for every
  1305. level in the hierarchy, i.e., every row of objects in Figure
  1306. :ref:`sketcher:fig:Vehicle0:hier2`. This indentation makes it easy to
  1307. see on the printout how far down in the hierarchy we are.
  1308. A typical message written by ``recurse`` when ``name`` is ``'body'`` and
  1309. the ``shapes`` dictionary has the keys ``'over'`` and ``'under'``,
  1310. will be
  1311. .. code-block:: text
  1312. Composition: body.shapes has entries 'over', 'under'
  1313. call body.shapes["over"].recurse("over", 6)
  1314. The number of leading blanks on each line corresponds to the value of
  1315. ``indent``. The code printing out such messages looks like
  1316. .. code-block:: python
  1317. def recurse(self, name, indent=0):
  1318. space = ' '*indent
  1319. print space, '%s: %s.shapes has entries' % \
  1320. (self.__class__.__name__, name), \
  1321. str(list(self.shapes.keys()))[1:-1]
  1322. for shape in self.shapes:
  1323. print space,
  1324. print 'call %s.shapes["%s"].recurse("%s", %d)' % \
  1325. (name, shape, shape, indent+2)
  1326. self.shapes[shape].recurse(shape, indent+2)
  1327. Let us follow a ``v.recurse('vehicle')`` call in detail, ``v`` being
  1328. a ``Vehicle0`` instance. Before looking into the output from ``recurse``,
  1329. let us get an overview of the figure hierarchy in the ``v`` object
  1330. (as produced by ``print v``)
  1331. .. code-block:: text
  1332. ground
  1333. wall
  1334. vehicle
  1335. body
  1336. over
  1337. rectangle
  1338. under
  1339. rectangle
  1340. wheels
  1341. wheel1
  1342. arc
  1343. wheel2
  1344. arc
  1345. The ``recurse`` method performs the same kind of traversal of the
  1346. hierarchy, but writes out and explains a lot more.
  1347. The data structure represented by ``v.shapes`` is known as a *tree*.
  1348. As in physical trees, there is a *root*, here the ``v.shapes``
  1349. dictionary. A graphical illustration of the tree (upside down) is
  1350. shown in Figure :ref:`sketcher:fig:Vehicle0:hier2`.
  1351. From the root there are one or more branches, here two:
  1352. ``ground`` and ``vehicle``. Following the ``vehicle`` branch, it has two new
  1353. branches, ``body`` and ``wheels``. Relationships as in family trees
  1354. are often used to describe the relations in object trees too: we say
  1355. that ``vehicle`` is the parent of ``body`` and that ``body`` is a child of
  1356. ``vehicle``. The term *node* is also often used to describe an element
  1357. in a tree. A node may have several other nodes as *descendants*.
  1358. .. _sketcher:fig:Vehicle0:hier2:
  1359. .. figure:: Vehicle0_hier2.png
  1360. :width: 600
  1361. *Hierarchy of figure elements in an instance of class `Vehicle0`*
  1362. Recursion is the principal programming technique to traverse tree structures.
  1363. Any object in the tree can be viewed as a root of a subtree. For
  1364. example, ``wheels`` is the root of a subtree that branches into
  1365. ``wheel1`` and ``wheel2``. So when processing an object in the tree,
  1366. we imagine we process the root and then recurse into a subtree, but the
  1367. first object we recurse into can be viewed as the root of the subtree, so the
  1368. processing procedure of the parent object can be repeated.
  1369. A recommended next step is to simulate the ``recurse`` method by hand and
  1370. carefully check that what happens in the visits to ``recurse`` is
  1371. consistent with the output listed below. Although tedious, this is
  1372. a major exercise that guaranteed will help to demystify recursion.
  1373. A part of the printout of ``v.recurse('vehicle')`` looks like
  1374. .. code-block:: text
  1375. Vehicle0: vehicle.shapes has entries 'ground', 'vehicle'
  1376. call vehicle.shapes["ground"].recurse("ground", 2)
  1377. Wall: ground.shapes has entries 'wall'
  1378. call ground.shapes["wall"].recurse("wall", 4)
  1379. reached "bottom" object Curve
  1380. call vehicle.shapes["vehicle"].recurse("vehicle", 2)
  1381. Composition: vehicle.shapes has entries 'body', 'wheels'
  1382. call vehicle.shapes["body"].recurse("body", 4)
  1383. Composition: body.shapes has entries 'over', 'under'
  1384. call body.shapes["over"].recurse("over", 6)
  1385. Rectangle: over.shapes has entries 'rectangle'
  1386. call over.shapes["rectangle"].recurse("rectangle", 8)
  1387. reached "bottom" object Curve
  1388. call body.shapes["under"].recurse("under", 6)
  1389. Rectangle: under.shapes has entries 'rectangle'
  1390. call under.shapes["rectangle"].recurse("rectangle", 8)
  1391. reached "bottom" object Curve
  1392. ...
  1393. This example should clearly demonstrate the principle that we
  1394. can start at any object in the tree and do a recursive set
  1395. of calls with that object as root.
  1396. .. _sketcher:scaling:
  1397. Scaling, translating, and rotating a figure
  1398. -------------------------------------------
  1399. With recursion, as explained in the previous section, we can within
  1400. minutes equip *all* classes in the ``Shape`` hierarchy, both present and
  1401. future ones, with the ability to scale the figure, translate it,
  1402. or rotate it. This added functionality requires only a few lines
  1403. of code.
  1404. Scaling
  1405. ~~~~~~~
  1406. We start with the simplest of the three geometric transformations,
  1407. namely scaling. For a ``Curve`` instance containing a set of :math:`n`
  1408. coordinates :math:`(x_i,y_i)` that make up a curve, scaling by a factor :math:`a`
  1409. means that we multiply all the :math:`x` and :math:`y` coordinates by :math:`a`:
  1410. .. math::
  1411. x_i \leftarrow ax_i,\quad y_i\leftarrow ay_i,
  1412. \quad i=0,\ldots,n-1\thinspace .
  1413. Here we apply the arrow as an assignment operator.
  1414. The corresponding Python implementation in
  1415. class ``Curve`` reads
  1416. .. code-block:: python
  1417. class Curve:
  1418. ...
  1419. def scale(self, factor):
  1420. self.x = factor*self.x
  1421. self.y = factor*self.y
  1422. Note here that ``self.x`` and ``self.y`` are Numerical Python arrays,
  1423. so that multiplication by a scalar number ``factor`` is
  1424. a vectorized operation.
  1425. An even more efficient implementation is to make use of in-place
  1426. multiplication in the arrays,
  1427. .. code-block:: python
  1428. class Curve:
  1429. ...
  1430. def scale(self, factor):
  1431. self.x *= factor
  1432. self.y *= factor
  1433. as this saves the creation of temporary arrays like ``factor*self.x``.
  1434. In an instance of a subclass of ``Shape``, the meaning of a method
  1435. ``scale`` is to run through all objects in the dictionary ``shapes`` and
  1436. ask each object to scale itself. This is the same delegation of
  1437. actions to subclass instances as we do in the ``draw`` (or ``recurse``)
  1438. method. All objects, except ``Curve`` instances, can share the same
  1439. implementation of the ``scale`` method. Therefore, we place the ``scale``
  1440. method in the superclass ``Shape`` such that all subclasses inherit the
  1441. method. Since ``scale`` and ``draw`` are so similar, we can easily
  1442. implement the ``scale`` method in class ``Shape`` by copying and editing
  1443. the ``draw`` method:
  1444. .. code-block:: python
  1445. class Shape:
  1446. ...
  1447. def scale(self, factor):
  1448. for shape in self.shapes:
  1449. self.shapes[shape].scale(factor)
  1450. This is all we have to do in order to equip all subclasses of
  1451. ``Shape`` with scaling functionality!
  1452. Any piece of the figure will scale itself, in the same manner
  1453. as it can draw itself.
  1454. Translation
  1455. ~~~~~~~~~~~
  1456. A set of coordinates :math:`(x_i, y_i)` can be translated :math:`v_0` units in
  1457. the :math:`x` direction and :math:`v_1` units in the :math:`y` direction using the formulas
  1458. .. math::
  1459. x_i\leftarrow x_i+v_0,\quad y_i\leftarrow y_i+v_1,
  1460. \quad i=0,\ldots,n-1\thinspace .
  1461. The natural specification of the translation is in terms of the
  1462. vector :math:`v=(v_0,v_1)`.
  1463. The corresponding Python implementation in class ``Curve`` becomes
  1464. .. code-block:: python
  1465. class Curve:
  1466. ...
  1467. def translate(self, v):
  1468. self.x += v[0]
  1469. self.y += v[1]
  1470. The translation operation for a shape object is very similar to the
  1471. scaling and drawing operations. This means that we can implement a
  1472. common method ``translate`` in the superclass ``Shape``. The code
  1473. is parallel to the ``scale`` method:
  1474. .. code-block:: python
  1475. class Shape:
  1476. ....
  1477. def translate(self, v):
  1478. for shape in self.shapes:
  1479. self.shapes[shape].translate(v)
  1480. Rotation
  1481. ~~~~~~~~
  1482. Rotating a figure is more complicated than scaling and translating.
  1483. A counter clockwise rotation of :math:`\theta` degrees for a set of
  1484. coordinates :math:`(x_i,y_i)` is given by
  1485. .. math::
  1486. \bar x_i &\leftarrow x_i\cos\theta - y_i\sin\theta,\\
  1487. \bar y_i &\leftarrow x_i\sin\theta + y_i\cos\theta\thinspace .
  1488. This rotation is performed around the origin. If we want the figure
  1489. to be rotated with respect to a general point :math:`(x,y)`, we need to
  1490. extend the formulas above:
  1491. .. math::
  1492. \bar x_i &\leftarrow x + (x_i -x)\cos\theta - (y_i -y)\sin\theta,\\
  1493. \bar y_i &\leftarrow y + (x_i -x)\sin\theta + (y_i -y)\cos\theta\thinspace .
  1494. The Python implementation in class ``Curve``, assuming that :math:`\theta`
  1495. is given in degrees and not in radians, becomes
  1496. .. code-block:: python
  1497. def rotate(self, angle, center):
  1498. angle = radians(angle)
  1499. x, y = center
  1500. c = cos(angle); s = sin(angle)
  1501. xnew = x + (self.x - x)*c - (self.y - y)*s
  1502. ynew = y + (self.x - x)*s + (self.y - y)*c
  1503. self.x = xnew
  1504. self.y = ynew
  1505. The ``rotate`` method in class ``Shape`` follows the principle of the
  1506. ``draw``, ``scale``, and ``translate`` methods.
  1507. We have already seen the ``rotate`` method in action when animating the
  1508. rolling wheel at the end of the section :ref:`sketcher:vehicle1:anim`.