ParseDXF_Spline.py 28 KB

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