b94fda278707c4ed5672bd3b94e1d2b281aead18
1 #!/usr/bin/env python
2 '''
3 Copyright (C) 2007 Tavmjong Bah, tavmjong@free.fr
4 Copyright (C) 2006 Georg Wiora, xorx@quarkbox.de
5 Copyright (C) 2006 Johan Engelen, johan@shouraizou.nl
6 Copyright (C) 2005 Aaron Spike, aaron@ekips.org
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 Changes:
23 * This program is a modified version of wavy.py by Aaron Spike.
24 * 22-Dec-2006: Wiora : Added axis and isotropic scaling
25 * 21-Jun-2007: Tavmjong: Added polar coordinates
27 '''
28 import inkex, simplepath, simplestyle
29 from math import *
30 from random import *
32 def drawfunction(xstart, xend, ybottom, ytop, samples, width, height, left, bottom,
33 fx = "sin(x)", fpx = "cos(x)", fponum = True, times2pi = False, polar = False, isoscale = True, drawaxis = True, endpts = False):
35 if times2pi == True:
36 xstart = 2 * pi * xstart
37 xend = 2 * pi * xend
39 # coords and scales based on the source rect
40 scalex = width / (xend - xstart)
41 xoff = left
42 coordx = lambda x: (x - xstart) * scalex + xoff #convert x-value to coordinate
43 if polar : # Set scale so that left side of rectangle is -1, right side is +1.
44 # (We can't use xscale for both range and scale.)
45 centerx = left + width/2.0
46 polar_scalex = width/2.0
47 coordx = lambda x: x * polar_scalex + centerx #convert x-value to coordinate
49 scaley = height / (ytop - ybottom)
50 yoff = bottom
51 coordy = lambda y: (ybottom - y) * scaley + yoff #convert y-value to coordinate
53 # Check for isotropic scaling and use smaller of the two scales, correct ranges
54 if isoscale and not polar:
55 if scaley<scalex:
56 # compute zero location
57 xzero = coordx(0)
58 # set scale
59 scalex = scaley
60 # correct x-offset
61 xstart = (left-xzero)/scalex
62 xend = (left+width-xzero)/scalex
63 else :
64 # compute zero location
65 yzero = coordy(0)
66 # set scale
67 scaley = scalex
68 # correct x-offset
69 ybottom = (yzero-bottom)/scaley
70 ytop = (bottom+height-yzero)/scaley
72 # functions specified by the user
73 try:
74 if fx != "":
75 f = eval('lambda x: ' + fx.strip('"'))
76 if fpx != "":
77 fp = eval('lambda x: ' + fpx.strip('"'))
78 # handle incomplete/invalid function gracefully
79 except SyntaxError:
80 return []
82 # step is the distance between nodes on x
83 step = (xend - xstart) / (samples-1)
84 third = step / 3.0
85 ds = step * 0.001 # Step used in calculating derivatives
87 a = [] # path array
88 # add axis
89 if drawaxis :
90 # check for visibility of x-axis
91 if ybottom<=0 and ytop>=0:
92 # xaxis
93 a.append(['M ',[left, coordy(0)]])
94 a.append([' l ',[width, 0]])
95 # check for visibility of y-axis
96 if xstart<=0 and xend>=0:
97 # xaxis
98 a.append([' M ',[coordx(0),bottom]])
99 a.append([' l ',[0, -height]])
101 # initialize function and derivative for 0;
102 # they are carried over from one iteration to the next, to avoid extra function calculations.
103 x0 = xstart
104 y0 = f(xstart)
105 if polar :
106 xp0 = y0 * cos( x0 )
107 yp0 = y0 * sin( x0 )
108 x0 = xp0
109 y0 = yp0
110 if fponum or polar: # numerical derivative, using 0.001*step as the small differential
111 x1 = xstart + ds # Second point AFTER first point (Good for first point)
112 y1 = f(x1)
113 if polar :
114 xp1 = y1 * cos( x1 )
115 yp1 = y1 * sin( x1 )
116 x1 = xp1
117 y1 = yp1
118 dx0 = (x1 - x0)/ds
119 dy0 = (y1 - y0)/ds
120 else: # derivative given by the user
121 dx0 = 1 # Only works for rectangular coordinates
122 dy0 = fp(xstart)
124 # Start curve
125 if endpts:
126 a.append([' M ',[left, coordy(0)]])
127 a.append([' L ',[coordx(x0), coordy(y0)]])
128 else:
129 a.append([' M ',[coordx(x0), coordy(y0)]]) # initial moveto
131 for i in range(int(samples-1)):
132 x1 = (i+1) * step + xstart
133 x2 = x1 - ds # Second point BEFORE first point (Good for last point)
134 y1 = f(x1)
135 y2 = f(x2)
136 if polar :
137 xp1 = y1 * cos( x1 )
138 yp1 = y1 * sin( x1 )
139 xp2 = y2 * cos( x2 )
140 yp2 = y2 * sin( x2 )
141 x1 = xp1
142 y1 = yp1
143 x2 = xp2
144 y2 = yp2
145 if fponum or polar: # numerical derivative
146 dx1 = (x1 - x2)/ds
147 dy1 = (y1 - y2)/ds
148 else: # derivative given by the user
149 dx1 = 1 # Only works for rectangular coordinates
150 dy1 = fp(x1)
151 # create curve
152 a.append([' C ',
153 [coordx(x0 + (dx0 * third)), coordy(y0 + (dy0 * third)),
154 coordx(x1 - (dx1 * third)), coordy(y1 - (dy1 * third)),
155 coordx(x1), coordy(y1)]
156 ])
157 x0 = x1 # Next segment's start is this segments end
158 y0 = y1
159 dx0 = dx1 # Assume the function is smooth everywhere, so carry over the derivative too
160 dy0 = dy1
161 if endpts:
162 a.append([' L ',[left + width, coordy(0)]])
163 return a
165 class FuncPlot(inkex.Effect):
166 def __init__(self):
167 inkex.Effect.__init__(self)
168 self.OptionParser.add_option("--xstart",
169 action="store", type="float",
170 dest="xstart", default=0.0,
171 help="Start x-value")
172 self.OptionParser.add_option("--xend",
173 action="store", type="float",
174 dest="xend", default=1.0,
175 help="End x-value")
176 self.OptionParser.add_option("--times2pi",
177 action="store", type="inkbool",
178 dest="times2pi", default=True,
179 help="Multiply x-range by 2*pi")
180 self.OptionParser.add_option("--polar",
181 action="store", type="inkbool",
182 dest="polar", default=False,
183 help="Plot using polar coordinates")
184 self.OptionParser.add_option("--ybottom",
185 action="store", type="float",
186 dest="ybottom", default=-1.0,
187 help="y-value of rectangle's bottom")
188 self.OptionParser.add_option("--ytop",
189 action="store", type="float",
190 dest="ytop", default=1.0,
191 help="y-value of rectangle's top")
192 self.OptionParser.add_option("-s", "--samples",
193 action="store", type="int",
194 dest="samples", default=8,
195 help="Samples")
196 self.OptionParser.add_option("--fofx",
197 action="store", type="string",
198 dest="fofx", default="sin(x)",
199 help="f(x) for plotting")
200 self.OptionParser.add_option("--fponum",
201 action="store", type="inkbool",
202 dest="fponum", default=True,
203 help="Calculate the first derivative numerically")
204 self.OptionParser.add_option("--fpofx",
205 action="store", type="string",
206 dest="fpofx", default="cos(x)",
207 help="f'(x) for plotting")
208 self.OptionParser.add_option("--remove",
209 action="store", type="inkbool",
210 dest="remove", default=True,
211 help="If True, source rectangle is removed")
212 self.OptionParser.add_option("--isoscale",
213 action="store", type="inkbool",
214 dest="isoscale", default=True,
215 help="If True, isotropic scaling is used")
216 self.OptionParser.add_option("--drawaxis",
217 action="store", type="inkbool",
218 dest="drawaxis", default=True,
219 help="If True, axis are drawn")
220 self.OptionParser.add_option("--endpts",
221 action="store", type="inkbool",
222 dest="endpts", default=False,
223 help="If True, end points are added")
224 self.OptionParser.add_option("--tab",
225 action="store", type="string",
226 dest="tab", default="sampling",
227 help="The selected UI-tab when OK was pressed")
228 self.OptionParser.add_option("--funcplotuse",
229 action="store", type="string",
230 dest="funcplotuse", default="",
231 help="dummy")
232 self.OptionParser.add_option("--pythonfunctions",
233 action="store", type="string",
234 dest="pythonfunctions", default="",
235 help="dummy")
237 def effect(self):
238 for id, node in self.selected.iteritems():
239 if node.tag == inkex.addNS('rect','svg'):
240 # create new path with basic dimensions of selected rectangle
241 newpath = inkex.etree.Element(inkex.addNS('path','svg'))
242 x = float(node.get('x'))
243 y = float(node.get('y'))
244 w = float(node.get('width'))
245 h = float(node.get('height'))
247 #copy attributes of rect
248 s = node.get('style')
249 if s:
250 newpath.set('style', s)
252 t = node.get('transform')
253 if t:
254 newpath.set('transform', t)
256 # top and bottom were exchanged
257 newpath.set('d', simplepath.formatPath(
258 drawfunction(self.options.xstart,
259 self.options.xend,
260 self.options.ybottom,
261 self.options.ytop,
262 self.options.samples,
263 w,h,x,y+h,
264 self.options.fofx,
265 self.options.fpofx,
266 self.options.fponum,
267 self.options.times2pi,
268 self.options.polar,
269 self.options.isoscale,
270 self.options.drawaxis,
271 self.options.endpts)))
272 newpath.set('title', self.options.fofx)
274 #newpath.setAttribute('desc', '!func;' + self.options.fofx + ';'
275 # + self.options.fpofx + ';'
276 # + `self.options.fponum` + ';'
277 # + `self.options.xstart` + ';'
278 # + `self.options.xend` + ';'
279 # + `self.options.samples`)
281 # add path into SVG structure
282 node.getparent().append(newpath)
283 # option wether to remove the rectangle or not.
284 if self.options.remove:
285 node.getparent().remove(node)
287 if __name__ == '__main__':
288 e = FuncPlot()
289 e.affect()
292 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 encoding=utf-8 textwidth=99