implementation.do.txt 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. # #ifdef PRIMER_BOOK
  2. ===== Example of classes for geometric objects =====
  3. # #else
  4. ======= Inner workings of the Pysketcher tool =======
  5. # #endif
  6. We shall now explain how we can, quite easily, realize software with
  7. the capabilities demonstrated in the previous examples. Each object in
  8. the figure is represented as a class in a class hierarchy. Using
  9. inheritance, classes can inherit properties from parent classes and
  10. add new geometric features.
  11. # #ifndef PRIMER_BOOK
  12. idx{tree data structure}
  13. Class programming is a key technology for realizing Pysketcher.
  14. As soon as some classes are established, more are easily
  15. added. Enhanced functionality for all the classes is also easy to
  16. implement in common, generic code that can immediately be shared by
  17. all present and future classes. The fundamental data structure
  18. involved in the `pysketcher` package is a hierarchical tree, and much
  19. of the material on implementation issues targets how to traverse tree
  20. structures with recursive function calls in object hierarchies. This
  21. topic is of key relevance in a wide range of other applications as
  22. well. In total, the inner workings of Pysketcher constitute an
  23. excellent example on the power of class programming.
  24. ===== Example of classes for geometric objects =====
  25. # #endif
  26. We introduce class `Shape` as superclass for all specialized objects
  27. in a figure. This class does not store any data, but provides a
  28. series of functions that add functionality to all the subclasses.
  29. This will be shown later.
  30. === Simple geometric objects ===
  31. One simple subclass is `Rectangle`, specified by the coordinates of
  32. the lower left corner and its width and height:
  33. !bc pycod
  34. class Rectangle(Shape):
  35. def __init__(self, lower_left_corner, width, height):
  36. p = lower_left_corner # short form
  37. x = [p[0], p[0] + width,
  38. p[0] + width, p[0], p[0]]
  39. y = [p[1], p[1], p[1] + height,
  40. p[1] + height, p[1]]
  41. self.shapes = {'rectangle': Curve(x,y)}
  42. !ec
  43. Any subclass of `Shape` will have a constructor that takes geometric
  44. information about the shape of the object and creates a dictionary
  45. `self.shapes` with the shape built of simpler shapes. The most
  46. fundamental shape is `Curve`, which is just a collection of $(x,y)$
  47. coordinates in two arrays `x` and `y`. Drawing the `Curve` object is
  48. a matter of plotting `y` versus `x`. For class `Rectangle` the `x`
  49. and `y` arrays contain the corner points of the rectangle in
  50. counterclockwise direction, starting and ending with in the lower left
  51. corner.
  52. Class `Line` is also a simple class:
  53. !bc pycod
  54. class Line(Shape):
  55. def __init__(self, start, end):
  56. x = [start[0], end[0]]
  57. y = [start[1], end[1]]
  58. self.shapes = {'line': Curve(x, y)}
  59. !ec
  60. Here we only need two points, the start and end point on the line.
  61. However, we may want to add some useful functionality, e.g., the ability
  62. to give an $x$ coordinate and have the class calculate the
  63. corresponding $y$ coordinate:
  64. !bc pycod
  65. def __call__(self, x):
  66. """Given x, return y on the line."""
  67. x, y = self.shapes['line'].x, self.shapes['line'].y
  68. self.a = (y[1] - y[0])/(x[1] - x[0])
  69. self.b = y[0] - self.a*x[0]
  70. return self.a*x + self.b
  71. !ec
  72. Unfortunately, this is too simplistic because vertical lines cannot be
  73. handled (infinite `self.a`). The true source code of `Line` therefore
  74. provides a more general solution at the cost of significantly longer
  75. code with more tests.
  76. A circle implies a somewhat increased complexity. Again we represent
  77. the geometric object by a `Curve` object, but this time the `Curve`
  78. object needs to store a large number of points on the curve such that
  79. a plotting program produces a visually smooth curve. The points on
  80. the circle must be calculated manually in the constructor of class
  81. `Circle`. The formulas for points $(x,y)$ on a curve with radius $R$
  82. and center at $(x_0, y_0)$ are given by
  83. !bt
  84. \begin{align*}
  85. x &= x_0 + R\cos (t),\\
  86. y &= y_0 + R\sin (t),
  87. \end{align*}
  88. !et
  89. where $t\in [0, 2\pi]$. A discrete set of $t$ values in this
  90. interval gives the corresponding set of $(x,y)$ coordinates on
  91. the circle. The user must specify the resolution as the number
  92. of $t$ values. The circle's radius and center must of course
  93. also be specified.
  94. We can write the `Circle` class as
  95. !bc pycod
  96. class Circle(Shape):
  97. def __init__(self, center, radius, resolution=180):
  98. self.center, self.radius = center, radius
  99. self.resolution = resolution
  100. t = linspace(0, 2*pi, resolution+1)
  101. x0 = center[0]; y0 = center[1]
  102. R = radius
  103. x = x0 + R*cos(t)
  104. y = y0 + R*sin(t)
  105. self.shapes = {'circle': Curve(x, y)}
  106. !ec
  107. As in class `Line` we can offer the possibility to give an angle
  108. $\theta$ (equivalent to $t$ in the formulas above)
  109. and then get the corresponding $x$ and $y$ coordinates:
  110. !bc pycod
  111. def __call__(self, theta):
  112. """Return (x, y) point corresponding to angle theta."""
  113. return self.center[0] + self.radius*cos(theta), \
  114. self.center[1] + self.radius*sin(theta)
  115. !ec
  116. There is one flaw with this method: it yields illegal values after
  117. a translation, scaling, or rotation of the circle.
  118. A part of a circle, an arc, is a frequent geometric object when
  119. drawing mechanical systems. The arc is constructed much like
  120. a circle, but $t$ runs in $[\theta_s, \theta_s + \theta_a]$. Giving
  121. $\theta_s$ and $\theta_a$ the slightly more descriptive names
  122. `start_angle` and `arc_angle`, the code looks like this:
  123. !bc pycod
  124. class Arc(Shape):
  125. def __init__(self, center, radius,
  126. start_angle, arc_angle,
  127. resolution=180):
  128. self.start_angle = radians(start_angle)
  129. self.arc_angle = radians(arc_angle)
  130. t = linspace(self.start_angle,
  131. self.start_angle + self.arc_angle,
  132. resolution+1)
  133. x0 = center[0]; y0 = center[1]
  134. R = radius
  135. x = x0 + R*cos(t)
  136. y = y0 + R*sin(t)
  137. self.shapes = {'arc': Curve(x, y)}
  138. !ec
  139. Having the `Arc` class, a `Circle` can alternatively be defined as
  140. a subclass specializing the arc to a circle:
  141. !bc pycod
  142. class Circle(Arc):
  143. def __init__(self, center, radius, resolution=180):
  144. Arc.__init__(self, center, radius, 0, 360, resolution)
  145. !ec
  146. === Class curve ===
  147. Class `Curve` sits on the coordinates to be drawn, but how is that
  148. done? The constructor of class `Curve` just stores the coordinates,
  149. while a method `draw` sends the coordinates to the plotting program to
  150. make a graph. Or more precisely, to avoid a lot of (e.g.)
  151. Matplotlib-specific plotting commands in class `Curve` we have created
  152. a small layer with a simple programming interface to plotting
  153. programs. This makes it straightforward to change from Matplotlib to
  154. another plotting program. The programming interface is represented by
  155. the `drawing_tool` object and has a few functions:
  156. * `plot_curve` for sending a curve in terms of $x$ and $y$ coordinates
  157. to the plotting program,
  158. * `set_coordinate_system` for specifying the graphics area,
  159. * `erase` for deleting all elements of the graph,
  160. * `set_grid` for turning on a grid (convenient while constructing the figure),
  161. * `set_instruction_file` for creating a separate file with all
  162. plotting commands (Matplotlib commands in our case),
  163. * a series of `set_X` functions where `X` is some property like
  164. `linecolor`, `linestyle`, `linewidth`, `filled_curves`.
  165. This is basically all we need to communicate to a plotting program.
  166. Any class in the `Shape` hierarchy inherits `set_X` functions for
  167. setting properties of curves. This information is propagated to
  168. all other shape objects in the `self.shapes` dictionary. Class
  169. `Curve` stores the line properties together with the coordinates
  170. of its curve and propagates this information to the plotting program.
  171. When saying `vehicle.set_linewidth(10)`, all objects that make
  172. up the `vehicle` object will get a `set_linewidth(10)` call,
  173. but only the `Curve` object at the end of the chain will actually
  174. store the information and send it to the plotting program.
  175. A rough sketch of class `Curve` reads
  176. !bc pycod
  177. class Curve(Shape):
  178. """General curve as a sequence of (x,y) coordintes."""
  179. def __init__(self, x, y):
  180. self.x = asarray(x, dtype=float)
  181. self.y = asarray(y, dtype=float)
  182. def draw(self):
  183. drawing_tool.plot_curve(
  184. self.x, self.y,
  185. self.linestyle, self.linewidth, self.linecolor, ...)
  186. def set_linewidth(self, width):
  187. self.linewidth = width
  188. det set_linestyle(self, style):
  189. self.linestyle = style
  190. ...
  191. !ec
  192. === Compound geometric objects ===
  193. The simple classes `Line`, `Arc`, and `Circle` could can the geometric
  194. shape through just one `Curve` object. More complicated shapes are
  195. built from instances of various subclasses of `Shape`. Classes used
  196. for professional drawings soon get quite complex in composition and
  197. have a lot of geometric details, so here we prefer to make a very
  198. simple composition: the already drawn vehicle from Figure
  199. ref{sketcher:fig:vehicle0}. That is, instead of composing the drawing
  200. in a Python program as shown above, we make a subclass `Vehicle0` in
  201. the `Shape` hierarchy for doing the same thing.
  202. The `Shape` hierarchy is found in the `pysketcher` package, so to use these
  203. classes or derive a new one, we need to import `pysketcher`. The constructor
  204. of class `Vehicle0` performs approximately the same statements as
  205. in the example program we developed for making the drawing in
  206. Figure ref{sketcher:fig:vehicle0}.
  207. !bc pycod
  208. from pysketcher import *
  209. class Vehicle0(Shape):
  210. def __init__(self, w_1, R, L, H):
  211. wheel1 = Circle(center=(w_1, R), radius=R)
  212. wheel2 = wheel1.copy()
  213. wheel2.translate((L,0))
  214. under = Rectangle(lower_left_corner=(w_1-2*R, 2*R),
  215. width=2*R + L + 2*R, height=H)
  216. over = Rectangle(lower_left_corner=(w_1, 2*R + H),
  217. width=2.5*R, height=1.25*H)
  218. wheels = Composition(
  219. {'wheel1': wheel1, 'wheel2': wheel2})
  220. body = Composition(
  221. {'under': under, 'over': over})
  222. vehicle = Composition({'wheels': wheels, 'body': body})
  223. xmax = w_1 + 2*L + 3*R
  224. ground = Wall(x=[R, xmax], y=[0, 0], thickness=-0.3*R)
  225. self.shapes = {'vehicle': vehicle, 'ground': ground}
  226. !ec
  227. Any subclass of `Shape` *must* define the `shapes` attribute, otherwise
  228. the inherited `draw` method (and a lot of other methods too) will
  229. not work.
  230. The painting of the vehicle, as shown in the right part of
  231. Figure ref{sketcher:fig:vehicle0:v2}, could in class `Vehicle0`
  232. be offered by a method:
  233. !bc pycod
  234. def colorful(self):
  235. wheels = self.shapes['vehicle']['wheels']
  236. wheels.set_filled_curves('blue')
  237. wheels.set_linewidth(6)
  238. wheels.set_linecolor('black')
  239. under = self.shapes['vehicle']['body']['under']
  240. under.set_filled_curves('red')
  241. over = self.shapes['vehicle']['body']['over']
  242. over.set_filled_curves(pattern='/')
  243. over.set_linewidth(14)
  244. !ec
  245. The usage of the class is simple: after having set up an appropriate
  246. coordinate system as previously shown, we can do
  247. !bc pycod
  248. vehicle = Vehicle0(w_1, R, L, H)
  249. vehicle.draw()
  250. drawing_tool.display()
  251. !ec
  252. and go on the make a painted version by
  253. !bc pycod
  254. drawing_tool.erase()
  255. vehicle.colorful()
  256. vehicle.draw()
  257. drawing_tool.display()
  258. !ec
  259. A complete code defining and using class `Vehicle0` is found in the file
  260. "`vehicle2.py`": "${src_path_pysketcher}/vehicle2.py".
  261. The `pysketcher` package contains a wide range of classes for various
  262. geometrical objects, particularly those that are frequently used in
  263. drawings of mechanical systems.
  264. ===== Adding functionality via recursion =====
  265. idx{recursive function calls}
  266. The really powerful feature of our class hierarchy is that we can add
  267. much functionality to the superclass `Shape` and to the ``bottom'' class
  268. `Curve`, and then all other classes for various types of geometrical shapes
  269. immediately get the new functionality. To explain the idea we may
  270. look at the `draw` method, which all classes in the `Shape`
  271. hierarchy must have. The inner workings of the `draw` method explain
  272. the secrets of how a series of other useful operations on figures
  273. can be implemented.
  274. === Basic principles of recursion ===
  275. Note that we work with two types of hierarchies in the
  276. present documentation: one Python *class hierarchy*,
  277. with `Shape` as superclass, and one *object hierarchy* of figure elements
  278. in a specific figure. A subclass of `Shape` stores its figure in the
  279. `self.shapes` dictionary. This dictionary represents the object hierarchy
  280. of figure elements for that class. We want to make one `draw` call
  281. for an instance, say our class `Vehicle0`, and then we want this call
  282. to be propagated to *all* objects that are contained in
  283. `self.shapes` and all is nested subdictionaries. How is this done?
  284. The natural starting point is to call `draw` for each `Shape` object
  285. in the `self.shapes` dictionary:
  286. !bc pycod
  287. def draw(self):
  288. for shape in self.shapes:
  289. self.shapes[shape].draw()
  290. !ec
  291. This general method can be provided by class `Shape` and inherited in
  292. subclasses like `Vehicle0`. Let `v` be a `Vehicle0` instance.
  293. Seemingly, a call `v.draw()` just calls
  294. !bc pycod
  295. v.shapes['vehicle'].draw()
  296. v.shapes['ground'].draw()
  297. !ec
  298. However, in the former call we call the `draw` method of a `Composition` object
  299. whose `self.shapes` attributed has two elements: `wheels` and `body`.
  300. Since class `Composition` inherits the same `draw` method, this method will
  301. run through `self.shapes` and call `wheels.draw()` and `body.draw()`.
  302. Now, the `wheels` object is also a `Composition` with the same `draw`
  303. method, which will run through `self.shapes`, now containing
  304. the `wheel1` and `wheel2` objects. The `wheel1` object is a `Circle`,
  305. so calling `wheel1.draw()` calls the `draw` method in class `Circle`,
  306. but this is the same `draw` method as shown above. This method will
  307. therefore traverse the circle's `shapes` dictionary, which we have seen
  308. consists of one `Curve` element.
  309. The `Curve` object holds the coordinates to be plotted so here `draw`
  310. really needs to do something ``physical'', namely send the coordinates to
  311. the plotting program. The `draw` method is outlined in the short listing
  312. of class `Curve` shown previously.
  313. We can go to any of the other shape objects that appear in the figure
  314. hierarchy and follow their `draw` calls in the similar way. Every time,
  315. a `draw` call will invoke a new `draw` call, until we eventually hit
  316. a `Curve` object at the ``bottom'' of the figure hierarchy, and then that part
  317. of the figure is really plotted (or more precisely, the coordinates
  318. are sent to a plotting program).
  319. When a method calls itself, such as `draw` does, the calls are known as
  320. *recursive* and the programming principle is referred to as
  321. *recursion*. This technique is very often used to traverse hierarchical
  322. structures like the figure structures we work with here. Even though the
  323. hierarchy of objects building up a figure are of different types, they
  324. all inherit the same `draw` method and therefore exhibit the same
  325. behavior with respect to drawing. Only the `Curve` object has a different
  326. `draw` method, which does not lead to more recursion.
  327. === Explaining recursion ===
  328. Understanding recursion is usually a challenge. To get a better idea of
  329. how recursion works, we have equipped class `Shape` with a method `recurse`
  330. that just visits all the objects in the `shapes` dictionary and prints
  331. out a message for each object.
  332. This feature allows us to trace the execution and see exactly where
  333. we are in the hierarchy and which objects that are visited.
  334. The `recurse` method is very similar to `draw`:
  335. !bc pycod
  336. def recurse(self, name, indent=0):
  337. # print message where we are (name is where we come from)
  338. for shape in self.shapes:
  339. # print message about which object to visit
  340. self.shapes[shape].recurse(indent+2, shape)
  341. !ec
  342. The `indent` parameter governs how much the message from this
  343. `recurse` method is intended. We increase `indent` by 2 for every
  344. level in the hierarchy, i.e., every row of objects in Figure
  345. ref{sketcher:fig:Vehicle0:hier2}. This indentation makes it easy to
  346. see on the printout how far down in the hierarchy we are.
  347. A typical message written by `recurse` when `name` is `'body'` and
  348. the `shapes` dictionary has the keys `'over'` and `'under'`,
  349. will be
  350. !bc dat
  351. Composition: body.shapes has entries 'over', 'under'
  352. call body.shapes["over"].recurse("over", 6)
  353. !ec
  354. The number of leading blanks on each line corresponds to the value of
  355. `indent`. The code printing out such messages looks like
  356. !bc pycod
  357. def recurse(self, name, indent=0):
  358. space = ' '*indent
  359. print space, '%s: %s.shapes has entries' % \
  360. (self.__class__.__name__, name), \
  361. str(list(self.shapes.keys()))[1:-1]
  362. for shape in self.shapes:
  363. print space,
  364. print 'call %s.shapes["%s"].recurse("%s", %d)' % \
  365. (name, shape, shape, indent+2)
  366. self.shapes[shape].recurse(shape, indent+2)
  367. !ec
  368. Let us follow a `v.recurse('vehicle')` call in detail, `v` being
  369. a `Vehicle0` instance. Before looking into the output from `recurse`,
  370. let us get an overview of the figure hierarchy in the `v` object
  371. (as produced by `print v`)
  372. !bc dat
  373. ground
  374. wall
  375. vehicle
  376. body
  377. over
  378. rectangle
  379. under
  380. rectangle
  381. wheels
  382. wheel1
  383. arc
  384. wheel2
  385. arc
  386. !ec
  387. The `recurse` method performs the same kind of traversal of the
  388. hierarchy, but writes out and explains a lot more.
  389. The data structure represented by `v.shapes` is known as a *tree*.
  390. As in physical trees, there is a *root*, here the `v.shapes`
  391. dictionary. A graphical illustration of the tree (upside down) is
  392. shown in Figure ref{sketcher:fig:Vehicle0:hier2}.
  393. From the root there are one or more branches, here two:
  394. `ground` and `vehicle`. Following the `vehicle` branch, it has two new
  395. branches, `body` and `wheels`. Relationships as in family trees
  396. are often used to describe the relations in object trees too: we say
  397. that `vehicle` is the parent of `body` and that `body` is a child of
  398. `vehicle`. The term *node* is also often used to describe an element
  399. in a tree. A node may have several other nodes as *descendants*.
  400. FIGURE: [fig-tut/Vehicle0_hier2, width=600 frac=0.8] Hierarchy of figure elements in an instance of class `Vehicle0`. label{sketcher:fig:Vehicle0:hier2}
  401. Recursion is the principal programming technique to traverse tree structures.
  402. Any object in the tree can be viewed as a root of a subtree. For
  403. example, `wheels` is the root of a subtree that branches into
  404. `wheel1` and `wheel2`. So when processing an object in the tree,
  405. we imagine we process the root and then recurse into a subtree, but the
  406. first object we recurse into can be viewed as the root of the subtree, so the
  407. processing procedure of the parent object can be repeated.
  408. A recommended next step is to simulate the `recurse` method by hand and
  409. carefully check that what happens in the visits to `recurse` is
  410. consistent with the output listed below. Although tedious, this is
  411. a major exercise that guaranteed will help to demystify recursion.
  412. A part of the printout of `v.recurse('vehicle')` looks like
  413. !bc dat
  414. Vehicle0: vehicle.shapes has entries 'ground', 'vehicle'
  415. call vehicle.shapes["ground"].recurse("ground", 2)
  416. Wall: ground.shapes has entries 'wall'
  417. call ground.shapes["wall"].recurse("wall", 4)
  418. reached "bottom" object Curve
  419. call vehicle.shapes["vehicle"].recurse("vehicle", 2)
  420. Composition: vehicle.shapes has entries 'body', 'wheels'
  421. call vehicle.shapes["body"].recurse("body", 4)
  422. Composition: body.shapes has entries 'over', 'under'
  423. call body.shapes["over"].recurse("over", 6)
  424. Rectangle: over.shapes has entries 'rectangle'
  425. call over.shapes["rectangle"].recurse("rectangle", 8)
  426. reached "bottom" object Curve
  427. call body.shapes["under"].recurse("under", 6)
  428. Rectangle: under.shapes has entries 'rectangle'
  429. call under.shapes["rectangle"].recurse("rectangle", 8)
  430. reached "bottom" object Curve
  431. ...
  432. !ec
  433. This example should clearly demonstrate the principle that we
  434. can start at any object in the tree and do a recursive set
  435. of calls with that object as root.
  436. ===== Scaling, translating, and rotating a figure =====
  437. label{sketcher:scaling}
  438. With recursion, as explained in the previous section, we can within
  439. minutes equip *all* classes in the `Shape` hierarchy, both present and
  440. future ones, with the ability to scale the figure, translate it,
  441. or rotate it. This added functionality requires only a few lines
  442. of code.
  443. === Scaling ===
  444. We start with the simplest of the three geometric transformations,
  445. namely scaling. For a `Curve` instance containing a set of $n$
  446. coordinates $(x_i,y_i)$ that make up a curve, scaling by a factor $a$
  447. means that we multiply all the $x$ and $y$ coordinates by $a$:
  448. !bt
  449. \[
  450. x_i \leftarrow ax_i,\quad y_i\leftarrow ay_i,
  451. \quad i=0,\ldots,n-1\thinspace .
  452. \]
  453. !et
  454. Here we apply the arrow as an assignment operator.
  455. The corresponding Python implementation in
  456. class `Curve` reads
  457. !bc pycod
  458. class Curve:
  459. ...
  460. def scale(self, factor):
  461. self.x = factor*self.x
  462. self.y = factor*self.y
  463. !ec
  464. Note here that `self.x` and `self.y` are Numerical Python arrays,
  465. so that multiplication by a scalar number `factor` is
  466. a vectorized operation.
  467. An even more efficient implementation is to make use of in-place
  468. multiplication in the arrays,
  469. !bc pycod
  470. class Curve:
  471. ...
  472. def scale(self, factor):
  473. self.x *= factor
  474. self.y *= factor
  475. !ec
  476. as this saves the creation of temporary arrays like `factor*self.x`.
  477. In an instance of a subclass of `Shape`, the meaning of a method
  478. `scale` is to run through all objects in the dictionary `shapes` and
  479. ask each object to scale itself. This is the same delegation of
  480. actions to subclass instances as we do in the `draw` (or `recurse`)
  481. method. All objects, except `Curve` instances, can share the same
  482. implementation of the `scale` method. Therefore, we place the `scale`
  483. method in the superclass `Shape` such that all subclasses inherit the
  484. method. Since `scale` and `draw` are so similar, we can easily
  485. implement the `scale` method in class `Shape` by copying and editing
  486. the `draw` method:
  487. !bc pycod
  488. class Shape:
  489. ...
  490. def scale(self, factor):
  491. for shape in self.shapes:
  492. self.shapes[shape].scale(factor)
  493. !ec
  494. This is all we have to do in order to equip all subclasses of
  495. `Shape` with scaling functionality!
  496. Any piece of the figure will scale itself, in the same manner
  497. as it can draw itself.
  498. === Translation ===
  499. A set of coordinates $(x_i, y_i)$ can be translated $v_0$ units in
  500. the $x$ direction and $v_1$ units in the $y$ direction using the formulas
  501. !bt
  502. \begin{equation*}
  503. x_i\leftarrow x_i+v_0,\quad y_i\leftarrow y_i+v_1,
  504. \quad i=0,\ldots,n-1\thinspace .
  505. \end{equation*}
  506. !et
  507. The natural specification of the translation is in terms of the
  508. vector $v=(v_0,v_1)$.
  509. The corresponding Python implementation in class `Curve` becomes
  510. !bc pycod
  511. class Curve:
  512. ...
  513. def translate(self, v):
  514. self.x += v[0]
  515. self.y += v[1]
  516. !ec
  517. The translation operation for a shape object is very similar to the
  518. scaling and drawing operations. This means that we can implement a
  519. common method `translate` in the superclass `Shape`. The code
  520. is parallel to the `scale` method:
  521. !bc pycod
  522. class Shape:
  523. ....
  524. def translate(self, v):
  525. for shape in self.shapes:
  526. self.shapes[shape].translate(v)
  527. !ec
  528. === Rotation ===
  529. Rotating a figure is more complicated than scaling and translating.
  530. A counter clockwise rotation of $\theta$ degrees for a set of
  531. coordinates $(x_i,y_i)$ is given by
  532. !bt
  533. \begin{align*}
  534. \bar x_i &\leftarrow x_i\cos\theta - y_i\sin\theta,\\
  535. \bar y_i &\leftarrow x_i\sin\theta + y_i\cos\theta\thinspace .
  536. \end{align*}
  537. !et
  538. This rotation is performed around the origin. If we want the figure
  539. to be rotated with respect to a general point $(x,y)$, we need to
  540. extend the formulas above:
  541. !bt
  542. \begin{align*}
  543. \bar x_i &\leftarrow x + (x_i -x)\cos\theta - (y_i -y)\sin\theta,\\
  544. \bar y_i &\leftarrow y + (x_i -x)\sin\theta + (y_i -y)\cos\theta\thinspace .
  545. \end{align*}
  546. !et
  547. The Python implementation in class `Curve`, assuming that $\theta$
  548. is given in degrees and not in radians, becomes
  549. !bc pycod
  550. def rotate(self, angle, center):
  551. angle = radians(angle)
  552. x, y = center
  553. c = cos(angle); s = sin(angle)
  554. xnew = x + (self.x - x)*c - (self.y - y)*s
  555. ynew = y + (self.x - x)*s + (self.y - y)*c
  556. self.x = xnew
  557. self.y = ynew
  558. !ec
  559. The `rotate` method in class `Shape` follows the principle of the
  560. `draw`, `scale`, and `translate` methods.
  561. We have already seen the `rotate` method in action when animating the
  562. rolling wheel at the end of Section ref{sketcher:vehicle1:anim}.