ParseDXF_Spline.py 28 KB

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