ParseDXF_Spline.py 28 KB

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