ParseDXF_Spline.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. # Author: vvlachoudis@gmail.com
  2. # Vasilis Vlachoudis
  3. # Date: 20-Oct-2015
  4. import math
  5. import sys
  6. def norm(v):
  7. return math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
  8. def normalize_2(v):
  9. m = norm(v)
  10. return [v[0]/m, v[1]/m, v[2]/m]
  11. # ------------------------------------------------------------------------------
  12. # Convert a B-spline to polyline with a fixed number of segments
  13. #
  14. # FIXME to become adaptive
  15. # ------------------------------------------------------------------------------
  16. def spline2Polyline(xyz, degree, closed, segments, knots):
  17. '''
  18. :param xyz: DXF spline control points
  19. :param degree: degree of the Spline curve
  20. :param closed: closed Spline
  21. :type closed: bool
  22. :param segments: how many lines to use for Spline approximation
  23. :param knots: DXF spline knots
  24. :return: x,y,z coordinates (each is a list)
  25. '''
  26. # Check if last point coincide with the first one
  27. if (Vector(xyz[0]) - Vector(xyz[-1])).length2() < 1e-10:
  28. # it is already closed, treat it as open
  29. closed = False
  30. # FIXME we should verify if it is periodic,.... but...
  31. # I am not sure :)
  32. if closed:
  33. xyz.extend(xyz[:degree])
  34. knots = None
  35. else:
  36. # make base-1
  37. knots.insert(0, 0)
  38. npts = len(xyz)
  39. if degree<1 or degree>3:
  40. #print "invalid degree"
  41. return None,None,None
  42. # order:
  43. k = degree+1
  44. if npts < k:
  45. #print "not enough control points"
  46. return None,None,None
  47. # resolution:
  48. nseg = segments * npts
  49. # WARNING: base 1
  50. b = [0.0]*(npts*3+1) # polygon points
  51. h = [1.0]*(npts+1) # set all homogeneous weighting factors to 1.0
  52. p = [0.0]*(nseg*3+1) # returned curved points
  53. i = 1
  54. for pt in xyz:
  55. b[i] = pt[0]
  56. b[i+1] = pt[1]
  57. b[i+2] = pt[2]
  58. i +=3
  59. #if periodic:
  60. if closed:
  61. _rbsplinu(npts, k, nseg, b, h, p, knots)
  62. else:
  63. _rbspline(npts, k, nseg, b, h, p, knots)
  64. x = []
  65. y = []
  66. z = []
  67. for i in range(1,3*nseg+1,3):
  68. x.append(p[i])
  69. y.append(p[i+1])
  70. z.append(p[i+2])
  71. # for i,xyz in enumerate(zip(x,y,z)):
  72. # print i,xyz
  73. return x,y,z
  74. # ------------------------------------------------------------------------------
  75. # Subroutine to generate a B-spline open knot vector with multiplicity
  76. # equal to the order at the ends.
  77. # c = order of the basis function
  78. # n = the number of defining polygon vertices
  79. # n+2 = index of x[] for the first occurence of the maximum knot vector value
  80. # n+order = maximum value of the knot vector -- $n + c$
  81. # x[] = array containing the knot vector
  82. # ------------------------------------------------------------------------------
  83. def _knot(n, order):
  84. x = [0.0]*(n+order+1)
  85. for i in range(2, n+order+1):
  86. if i>order and i<n+2:
  87. x[i] = x[i-1] + 1.0
  88. else:
  89. x[i] = x[i-1]
  90. return x
  91. # ------------------------------------------------------------------------------
  92. # Subroutine to generate a B-spline uniform (periodic) knot vector.
  93. #
  94. # order = order of the basis function
  95. # n = the number of defining polygon vertices
  96. # n+order = maximum value of the knot vector -- $n + order$
  97. # x[] = array containing the knot vector
  98. # ------------------------------------------------------------------------------
  99. def _knotu(n, order):
  100. x = [0]*(n+order+1)
  101. for i in range(2, n+order+1):
  102. x[i] = float(i-1)
  103. return x
  104. # ------------------------------------------------------------------------------
  105. # Subroutine to generate rational B-spline basis functions--open knot vector
  106. # C code for An Introduction to NURBS
  107. # by David F. Rogers. Copyright (C) 2000 David F. Rogers,
  108. # All rights reserved.
  109. # Name: rbasis
  110. # Subroutines called: none
  111. # Book reference: Chapter 4, Sec. 4. , p 296
  112. # c = order of the B-spline basis function
  113. # d = first term of the basis function recursion relation
  114. # e = second term of the basis function recursion relation
  115. # h[] = array containing the homogeneous weights
  116. # npts = number of defining polygon vertices
  117. # nplusc = constant -- npts + c -- maximum number of knot values
  118. # r[] = array containing the rational basis functions
  119. # r[1] contains the basis function associated with B1 etc.
  120. # t = parameter value
  121. # temp[] = temporary array
  122. # x[] = knot vector
  123. # ------------------------------------------------------------------------------
  124. def _rbasis(c, t, npts, x, h, r):
  125. nplusc = npts + c
  126. temp = [0.0]*(nplusc+1)
  127. # calculate the first order non-rational basis functions n[i]
  128. for i in range(1, nplusc):
  129. if x[i] <= t < x[i+1]:
  130. temp[i] = 1.0
  131. else:
  132. temp[i] = 0.0
  133. # calculate the higher order non-rational basis functions
  134. for k in range(2,c+1):
  135. for i in range(1,nplusc-k+1):
  136. # if the lower order basis function is zero skip the calculation
  137. if temp[i] != 0.0:
  138. d = ((t-x[i])*temp[i])/(x[i+k-1]-x[i])
  139. else:
  140. d = 0.0
  141. # if the lower order basis function is zero skip the calculation
  142. if temp[i+1] != 0.0:
  143. e = ((x[i+k]-t)*temp[i+1])/(x[i+k]-x[i+1])
  144. else:
  145. e = 0.0
  146. temp[i] = d + e
  147. # pick up last point
  148. if t >= x[nplusc]:
  149. temp[npts] = 1.0
  150. # calculate sum for denominator of rational basis functions
  151. s = 0.0
  152. for i in range(1,npts+1):
  153. s += temp[i]*h[i]
  154. # form rational basis functions and put in r vector
  155. for i in range(1, npts+1):
  156. if s != 0.0:
  157. r[i] = (temp[i]*h[i])/s
  158. else:
  159. r[i] = 0
  160. # ------------------------------------------------------------------------------
  161. # Generates a rational B-spline curve using a uniform open knot vector.
  162. #
  163. # C code for An Introduction to NURBS
  164. # by David F. Rogers. Copyright (C) 2000 David F. Rogers,
  165. # All rights reserved.
  166. #
  167. # Name: rbspline.c
  168. # Subroutines called: _knot, rbasis
  169. # Book reference: Chapter 4, Alg. p. 297
  170. #
  171. # b = array containing the defining polygon vertices
  172. # b[1] contains the x-component of the vertex
  173. # b[2] contains the y-component of the vertex
  174. # b[3] contains the z-component of the vertex
  175. # h = array containing the homogeneous weighting factors
  176. # k = order of the B-spline basis function
  177. # nbasis = array containing the basis functions for a single value of t
  178. # nplusc = number of knot values
  179. # npts = number of defining polygon vertices
  180. # p[,] = array containing the curve points
  181. # p[1] contains the x-component of the point
  182. # p[2] contains the y-component of the point
  183. # p[3] contains the z-component of the point
  184. # p1 = number of points to be calculated on the curve
  185. # t = parameter value 0 <= t <= npts - k + 1
  186. # x[] = array containing the knot vector
  187. # ------------------------------------------------------------------------------
  188. def _rbspline(npts, k, p1, b, h, p, x):
  189. nplusc = npts + k
  190. nbasis = [0.0]*(npts+1) # zero and re-dimension the basis array
  191. # generate the uniform open knot vector
  192. if x is None or len(x) != nplusc+1:
  193. x = _knot(npts, k)
  194. icount = 0
  195. # calculate the points on the rational B-spline curve
  196. t = 0
  197. step = float(x[nplusc])/float(p1-1)
  198. for i1 in range(1, p1+1):
  199. if x[nplusc] - t < 5e-6:
  200. t = x[nplusc]
  201. # generate the basis function for this value of t
  202. nbasis = [0.0]*(npts+1) # zero and re-dimension the knot vector and the basis array
  203. _rbasis(k, t, npts, x, h, nbasis)
  204. # generate a point on the curve
  205. for j in range(1, 4):
  206. jcount = j
  207. p[icount+j] = 0.0
  208. # Do local matrix multiplication
  209. for i in range(1, npts+1):
  210. p[icount+j] += nbasis[i]*b[jcount]
  211. jcount += 3
  212. icount += 3
  213. t += step
  214. # ------------------------------------------------------------------------------
  215. # Subroutine to generate a rational B-spline curve using an uniform periodic knot vector
  216. #
  217. # C code for An Introduction to NURBS
  218. # by David F. Rogers. Copyright (C) 2000 David F. Rogers,
  219. # All rights reserved.
  220. #
  221. # Name: rbsplinu.c
  222. # Subroutines called: _knotu, _rbasis
  223. # Book reference: Chapter 4, Alg. p. 298
  224. #
  225. # b[] = array containing the defining polygon vertices
  226. # b[1] contains the x-component of the vertex
  227. # b[2] contains the y-component of the vertex
  228. # b[3] contains the z-component of the vertex
  229. # h[] = array containing the homogeneous weighting factors
  230. # k = order of the B-spline basis function
  231. # nbasis = array containing the basis functions for a single value of t
  232. # nplusc = number of knot values
  233. # npts = number of defining polygon vertices
  234. # p[,] = array containing the curve points
  235. # p[1] contains the x-component of the point
  236. # p[2] contains the y-component of the point
  237. # p[3] contains the z-component of the point
  238. # p1 = number of points to be calculated on the curve
  239. # t = parameter value 0 <= t <= npts - k + 1
  240. # x[] = array containing the knot vector
  241. # ------------------------------------------------------------------------------
  242. def _rbsplinu(npts, k, p1, b, h, p, x=None):
  243. nplusc = npts + k
  244. nbasis = [0.0]*(npts+1) # zero and re-dimension the basis array
  245. # generate the uniform periodic knot vector
  246. if x is None or len(x) != nplusc+1:
  247. # zero and re dimension the knot vector and the basis array
  248. x = _knotu(npts, k)
  249. icount = 0
  250. # calculate the points on the rational B-spline curve
  251. t = k-1
  252. step = (float(npts)-(k-1))/float(p1-1)
  253. for i1 in range(1, p1+1):
  254. if x[nplusc] - t < 5e-6:
  255. t = x[nplusc]
  256. # generate the basis function for this value of t
  257. nbasis = [0.0]*(npts+1)
  258. _rbasis(k, t, npts, x, h, nbasis)
  259. # generate a point on the curve
  260. for j in range(1,4):
  261. jcount = j
  262. p[icount+j] = 0.0
  263. # Do local matrix multiplication
  264. for i in range(1,npts+1):
  265. p[icount+j] += nbasis[i]*b[jcount]
  266. jcount += 3
  267. icount += 3
  268. t += step
  269. # Accuracy for comparison operators
  270. _accuracy = 1E-15
  271. def Cmp0(x):
  272. """Compare against zero within _accuracy"""
  273. return abs(x)<_accuracy
  274. def gauss(A, B):
  275. """Solve A*X = B using the Gauss elimination method"""
  276. n = len(A)
  277. s = [0.0] * n
  278. X = [0.0] * n
  279. p = [i for i in range(n)]
  280. for i in range(n):
  281. s[i] = max([abs(x) for x in A[i]])
  282. for k in range(n - 1):
  283. # select j>=k so that
  284. # |A[p[j]][k]| / s[p[i]] >= |A[p[i]][k]| / s[p[i]] for i = k,k+1,...,n
  285. j = k
  286. ap = abs(A[p[j]][k]) / s[p[j]]
  287. for i in range(k + 1, n):
  288. api = abs(A[p[i]][k]) / s[p[i]]
  289. if api > ap:
  290. j = i
  291. ap = api
  292. if j != k: p[k], p[j] = p[j], p[k] # Swap values
  293. for i in range(k + 1, n):
  294. z = A[p[i]][k] / A[p[k]][k]
  295. A[p[i]][k] = z
  296. for j in range(k + 1, n):
  297. A[p[i]][j] -= z * A[p[k]][j]
  298. for k in range(n - 1):
  299. for i in range(k + 1, n):
  300. B[p[i]] -= A[p[i]][k] * B[p[k]]
  301. for i in range(n - 1, -1, -1):
  302. X[i] = B[p[i]]
  303. for j in range(i + 1, n):
  304. X[i] -= A[p[i]][j] * X[j]
  305. X[i] /= A[p[i]][i]
  306. return X
  307. # Vector class
  308. # Inherits from List
  309. class Vector(list):
  310. """Vector class"""
  311. def __init__(self, x=3, *args):
  312. """Create a new vector,
  313. Vector(size), Vector(list), Vector(x,y,z,...)"""
  314. list.__init__(self)
  315. if isinstance(x, int) and not args:
  316. for i in range(x):
  317. self.append(0.0)
  318. elif isinstance(x, (list, tuple)):
  319. for i in x:
  320. self.append(float(i))
  321. else:
  322. self.append(float(x))
  323. for i in args:
  324. self.append(float(i))
  325. # ----------------------------------------------------------------------
  326. def set(self, x, y, z=None):
  327. """Set vector"""
  328. self[0] = x
  329. self[1] = y
  330. if z: self[2] = z
  331. # ----------------------------------------------------------------------
  332. def __repr__(self):
  333. return "[%s]" % (", ".join([repr(x) for x in self]))
  334. # ----------------------------------------------------------------------
  335. def __str__(self):
  336. return "[%s]" % (", ".join([("%15g" % (x)).strip() for x in self]))
  337. # ----------------------------------------------------------------------
  338. def eq(self, v, acc=_accuracy):
  339. """Test for equality with vector v within accuracy"""
  340. if len(self) != len(v): return False
  341. s2 = 0.0
  342. for a, b in zip(self, v):
  343. s2 += (a - b) ** 2
  344. return s2 <= acc ** 2
  345. def __eq__(self, v):
  346. return self.eq(v)
  347. # ----------------------------------------------------------------------
  348. def __neg__(self):
  349. """Negate vector"""
  350. new = Vector(len(self))
  351. for i, s in enumerate(self):
  352. new[i] = -s
  353. return new
  354. # ----------------------------------------------------------------------
  355. def __add__(self, v):
  356. """Add 2 vectors"""
  357. size = min(len(self), len(v))
  358. new = Vector(size)
  359. for i in range(size):
  360. new[i] = self[i] + v[i]
  361. return new
  362. # ----------------------------------------------------------------------
  363. def __iadd__(self, v):
  364. """Add vector v to self"""
  365. for i in range(min(len(self), len(v))):
  366. self[i] += v[i]
  367. return self
  368. # ----------------------------------------------------------------------
  369. def __sub__(self, v):
  370. """Subtract 2 vectors"""
  371. size = min(len(self), len(v))
  372. new = Vector(size)
  373. for i in range(size):
  374. new[i] = self[i] - v[i]
  375. return new
  376. # ----------------------------------------------------------------------
  377. def __isub__(self, v):
  378. """Subtract vector v from self"""
  379. for i in range(min(len(self), len(v))):
  380. self[i] -= v[i]
  381. return self
  382. # ----------------------------------------------------------------------
  383. # Scale or Dot product
  384. # ----------------------------------------------------------------------
  385. def __mul__(self, v):
  386. """scale*Vector() or Vector()*Vector() - Scale vector or dot product"""
  387. if isinstance(v, list):
  388. return self.dot(v)
  389. else:
  390. return Vector([x * v for x in self])
  391. # ----------------------------------------------------------------------
  392. # Scale or Dot product
  393. # ----------------------------------------------------------------------
  394. def __rmul__(self, v):
  395. """scale*Vector() or Vector()*Vector() - Scale vector or dot product"""
  396. if isinstance(v, Vector):
  397. return self.dot(v)
  398. else:
  399. return Vector([x * v for x in self])
  400. # ----------------------------------------------------------------------
  401. # Divide by floating point
  402. # ----------------------------------------------------------------------
  403. def __div__(self, b):
  404. return Vector([x / b for x in self])
  405. # ----------------------------------------------------------------------
  406. def __xor__(self, v):
  407. """Cross product"""
  408. return self.cross(v)
  409. # ----------------------------------------------------------------------
  410. def dot(self, v):
  411. """Dot product of 2 vectors"""
  412. s = 0.0
  413. for a, b in zip(self, v):
  414. s += a * b
  415. return s
  416. # ----------------------------------------------------------------------
  417. def cross(self, v):
  418. """Cross product of 2 vectors"""
  419. if len(self) == 3:
  420. return Vector(self[1] * v[2] - self[2] * v[1],
  421. self[2] * v[0] - self[0] * v[2],
  422. self[0] * v[1] - self[1] * v[0])
  423. elif len(self) == 2:
  424. return self[0] * v[1] - self[1] * v[0]
  425. else:
  426. raise Exception("Cross product needs 2d or 3d vectors")
  427. # ----------------------------------------------------------------------
  428. def length2(self):
  429. """Return length squared of vector"""
  430. s2 = 0.0
  431. for s in self:
  432. s2 += s ** 2
  433. return s2
  434. # ----------------------------------------------------------------------
  435. def length(self):
  436. """Return length of vector"""
  437. s2 = 0.0
  438. for s in self:
  439. s2 += s ** 2
  440. return math.sqrt(s2)
  441. __abs__ = length
  442. # ----------------------------------------------------------------------
  443. def arg(self):
  444. """return vector angle"""
  445. return math.atan2(self[1], self[0])
  446. # ----------------------------------------------------------------------
  447. def norm(self):
  448. """Normalize vector and return length"""
  449. l = self.length()
  450. if l > 0.0:
  451. invlen = 1.0 / l
  452. for i in range(len(self)):
  453. self[i] *= invlen
  454. return l
  455. normalize = norm
  456. # ----------------------------------------------------------------------
  457. def unit(self):
  458. """return a unit vector"""
  459. v = self.clone()
  460. v.norm()
  461. return v
  462. # ----------------------------------------------------------------------
  463. def clone(self):
  464. """Clone vector"""
  465. return Vector(self)
  466. # ----------------------------------------------------------------------
  467. def x(self):
  468. return self[0]
  469. def y(self):
  470. return self[1]
  471. def z(self):
  472. return self[2]
  473. # ----------------------------------------------------------------------
  474. def orthogonal(self):
  475. """return a vector orthogonal to self"""
  476. xx = abs(self.x())
  477. yy = abs(self.y())
  478. if len(self) >= 3:
  479. zz = abs(self.z())
  480. if xx < yy:
  481. if xx < zz:
  482. return Vector(0.0, self.z(), -self.y())
  483. else:
  484. return Vector(self.y(), -self.x(), 0.0)
  485. else:
  486. if yy < zz:
  487. return Vector(-self.z(), 0.0, self.x())
  488. else:
  489. return Vector(self.y(), -self.x(), 0.0)
  490. else:
  491. return Vector(-self.y(), self.x())
  492. # ----------------------------------------------------------------------
  493. def direction(self, zero=_accuracy):
  494. """return containing the direction if normalized with any of the axis"""
  495. v = self.clone()
  496. l = v.norm()
  497. if abs(l) <= zero: return "O"
  498. if abs(v[0] - 1.0) < zero:
  499. return "X"
  500. elif abs(v[0] + 1.0) < zero:
  501. return "-X"
  502. elif abs(v[1] - 1.0) < zero:
  503. return "Y"
  504. elif abs(v[1] + 1.0) < zero:
  505. return "-Y"
  506. elif abs(v[2] - 1.0) < zero:
  507. return "Z"
  508. elif abs(v[2] + 1.0) < zero:
  509. return "-Z"
  510. else:
  511. # nothing special about the direction, return N
  512. return "N"
  513. # ----------------------------------------------------------------------
  514. # Set the vector directly in polar coordinates
  515. # @param ma magnitude of vector
  516. # @param ph azimuthal angle in radians
  517. # @param th polar angle in radians
  518. # ----------------------------------------------------------------------
  519. def setPolar(self, ma, ph, th):
  520. """Set the vector directly in polar coordinates"""
  521. sf = math.sin(ph)
  522. cf = math.cos(ph)
  523. st = math.sin(th)
  524. ct = math.cos(th)
  525. self[0] = ma * st * cf
  526. self[1] = ma * st * sf
  527. self[2] = ma * ct
  528. # ----------------------------------------------------------------------
  529. def phi(self):
  530. """return the azimuth angle."""
  531. if Cmp0(self.x()) and Cmp0(self.y()):
  532. return 0.0
  533. return math.atan2(self.y(), self.x())
  534. # ----------------------------------------------------------------------
  535. def theta(self):
  536. """return the polar angle."""
  537. if Cmp0(self.x()) and Cmp0(self.y()) and Cmp0(self.z()):
  538. return 0.0
  539. return math.atan2(self.perp(), self.z())
  540. # ----------------------------------------------------------------------
  541. def cosTheta(self):
  542. """return cosine of the polar angle."""
  543. ptot = self.length()
  544. if Cmp0(ptot):
  545. return 1.0
  546. else:
  547. return self.z() / ptot
  548. # ----------------------------------------------------------------------
  549. def perp2(self):
  550. """return the transverse component squared
  551. (R^2 in cylindrical coordinate system)."""
  552. return self.x() * self.x() + self.y() * self.y()
  553. # ----------------------------------------------------------------------
  554. def perp(self):
  555. """@return the transverse component
  556. (R in cylindrical coordinate system)."""
  557. return math.sqrt(self.perp2())
  558. # ----------------------------------------------------------------------
  559. # Return a random 3D vector
  560. # ----------------------------------------------------------------------
  561. # @staticmethod
  562. # def random():
  563. # cosTheta = 2.0 * random.random() - 1.0
  564. # sinTheta = math.sqrt(1.0 - cosTheta ** 2)
  565. # phi = 2.0 * math.pi * random.random()
  566. # return Vector(math.cos(phi) * sinTheta, math.sin(phi) * sinTheta, cosTheta)
  567. # #===============================================================================
  568. # # Cardinal cubic spline class
  569. # #===============================================================================
  570. # class CardinalSpline:
  571. # def __init__(self, A=0.5):
  572. # # The default matrix is the Catmull-Rom spline
  573. # # which is equal to Cardinal matrix
  574. # # for A = 0.5
  575. # #
  576. # # Note: Vasilis
  577. # # The A parameter should be the fraction in t where
  578. # # the second derivative is zero
  579. # self.setMatrix(A)
  580. #
  581. # #-----------------------------------------------------------------------
  582. # # Set the matrix according to Cardinal
  583. # #-----------------------------------------------------------------------
  584. # def setMatrix(self, A=0.5):
  585. # self.M = []
  586. # self.M.append([ -A, 2.-A, A-2., A ])
  587. # self.M.append([2.*A, A-3., 3.-2.*A, -A ])
  588. # self.M.append([ -A, 0., A, 0.])
  589. # self.M.append([ 0., 1., 0, 0.])
  590. #
  591. # #-----------------------------------------------------------------------
  592. # # Evaluate Cardinal spline at position t
  593. # # @param P list or tuple with 4 points y positions
  594. # # @param t [0..1] fraction of interval from points 1..2
  595. # # @param k index of starting 4 elements in P
  596. # # @return spline evaluation
  597. # #-----------------------------------------------------------------------
  598. # def __call__(self, P, t, k=1):
  599. # T = [t*t*t, t*t, t, 1.0]
  600. # R = [0.0]*4
  601. # for i in range(4):
  602. # for j in range(4):
  603. # R[i] += T[j] * self.M[j][i]
  604. # y = 0.0
  605. # for i in range(4):
  606. # y += R[i]*P[k+i-1]
  607. #
  608. # return y
  609. #
  610. # #-----------------------------------------------------------------------
  611. # # Return the coefficients of a 3rd degree polynomial
  612. # # f(x) = a t^3 + b t^2 + c t + d
  613. # # @return [a, b, c, d]
  614. # #-----------------------------------------------------------------------
  615. # def coefficients(self, P, k=1):
  616. # C = [0.0]*4
  617. # for i in range(4):
  618. # for j in range(4):
  619. # C[i] += self.M[i][j] * P[k+j-1]
  620. # return C
  621. #
  622. # #-----------------------------------------------------------------------
  623. # # Evaluate the value of the spline using the coefficients
  624. # #-----------------------------------------------------------------------
  625. # def evaluate(self, C, t):
  626. # return ((C[0]*t + C[1])*t + C[2])*t + C[3]
  627. #
  628. # #===============================================================================
  629. # # Cubic spline ensuring that the first and second derivative are continuous
  630. # # adapted from Penelope Manual Appending B.1
  631. # # It requires all the points (xi,yi) and the assumption on how to deal
  632. # # with the second derivative on the extremities
  633. # # Option 1: assume zero as second derivative on both ends
  634. # # Option 2: assume the same as the next or previous one
  635. # #===============================================================================
  636. # class CubicSpline:
  637. # def __init__(self, X, Y):
  638. # self.X = X
  639. # self.Y = Y
  640. # self.n = len(X)
  641. #
  642. # # Option #1
  643. # s1 = 0.0 # zero based = s0
  644. # sN = 0.0 # zero based = sN-1
  645. #
  646. # # Construct the tri-diagonal matrix
  647. # A = []
  648. # B = [0.0] * (self.n-2)
  649. # for i in range(self.n-2):
  650. # A.append([0.0] * (self.n-2))
  651. #
  652. # for i in range(1,self.n-1):
  653. # hi = self.h(i)
  654. # Hi = 2.0*(self.h(i-1) + hi)
  655. # j = i-1
  656. # A[j][j] = Hi
  657. # if i+1<self.n-1:
  658. # A[j][j+1] = A[j+1][j] = hi
  659. #
  660. # if i==1:
  661. # B[j] = 6.*(self.d(i) - self.d(j)) - hi*s1
  662. # elif i<self.n-2:
  663. # B[j] = 6.*(self.d(i) - self.d(j))
  664. # else:
  665. # B[j] = 6.*(self.d(i) - self.d(j)) - hi*sN
  666. #
  667. #
  668. # self.s = gauss(A,B)
  669. # self.s.insert(0,s1)
  670. # self.s.append(sN)
  671. # # print ">> s <<"
  672. # # pprint(self.s)
  673. #
  674. # #-----------------------------------------------------------------------
  675. # def h(self, i):
  676. # return self.X[i+1] - self.X[i]
  677. #
  678. # #-----------------------------------------------------------------------
  679. # def d(self, i):
  680. # return (self.Y[i+1] - self.Y[i]) / (self.X[i+1] - self.X[i])
  681. #
  682. # #-----------------------------------------------------------------------
  683. # def coefficients(self, i):
  684. # """return coefficients of cubic spline for interval i a*x**3+b*x**2+c*x+d"""
  685. # hi = self.h(i)
  686. # si = self.s[i]
  687. # si1 = self.s[i+1]
  688. # xi = self.X[i]
  689. # xi1 = self.X[i+1]
  690. # fi = self.Y[i]
  691. # fi1 = self.Y[i+1]
  692. #
  693. # a = 1./(6.*hi)*(si*xi1**3 - si1*xi**3 + 6.*(fi*xi1 - fi1*xi)) + hi/6.*(si1*xi - si*xi1)
  694. # b = 1./(2.*hi)*(si1*xi**2 - si*xi1**2 + 2*(fi1 - fi)) + hi/6.*(si - si1)
  695. # c = 1./(2.*hi)*(si*xi1 - si1*xi)
  696. # d = 1./(6.*hi)*(si1-si)
  697. #
  698. # return [d,c,b,a]
  699. #
  700. # #-----------------------------------------------------------------------
  701. # def __call__(self, i, x):
  702. # # FIXME should interpolate to find the interval
  703. # C = self.coefficients(i)
  704. # return ((C[0]*x + C[1])*x + C[2])*x + C[3]
  705. #
  706. # #-----------------------------------------------------------------------
  707. # # @return evaluation of cubic spline at x using coefficients C
  708. # #-----------------------------------------------------------------------
  709. # def evaluate(self, C, x):
  710. # return ((C[0]*x + C[1])*x + C[2])*x + C[3]
  711. #
  712. # #-----------------------------------------------------------------------
  713. # # Return evaluated derivative at x using coefficients C
  714. # #-----------------------------------------------------------------------
  715. # def derivative(self, C, x):
  716. # a = 3.0*C[0] # derivative coefficients
  717. # b = 2.0*C[1] # ... for sampling with rejection
  718. # c = C[2]
  719. # return (3.0*C[0]*x + 2.0*C[1])*x + C[2]
  720. #