diff --git a/ai_docs/Quadratic_Approximation_Approach.md b/ai_docs/Quadratic_Approximation_Approach.md
new file mode 100644
index 000000000000..e77ff043ab82
--- /dev/null
+++ b/ai_docs/Quadratic_Approximation_Approach.md
@@ -0,0 +1,241 @@
+
+
+# Fast and Reliable Iterative Cable-Driven Parallel Robot Forward Kinematics: A Quadratic Approximation Approach
+
+Henry Mahnke and Ryan J. Caverly(B[\)](http://orcid.org/0000-0001-7315-7322)
+
+Department of Aerospace Engineering and Mechanics, University of Minnesota, Minneapolis, MN 55455, USA {mahnk040,rcaverly}@umn.edu
+
+Abstract. This paper presents iterative forward kinematics algorithms for cable-driven parallel robots (CDPRs) that are based on Halley's method. In contrast to other iterative forward kinematics methods that use a linearization of the CDPRs loop-closure equations, such as Newton's method or the Levenberg-Marquardt method, Halley's method uses a second-order Taylor series approximation of these equations. A hybrid method is also proposed that performs a Halley update for the first few iterations and then switches to a Levenberg-Marquardt update. The proposed algorithms are applied to a six degree-of-freedom suspended CDPR and are shown to reduce the number of iterations and increase the rate of successful convergence to the truth pose compared to the Levenberg-Marquardt method. The proposed hybrid method reduces the computation time required for convergence compared to the Levenberg-Marquardt method in the presence of large initial estimation errors.
+
+Keywords: Cable-driven parallel robots · Pose estimation · Forward kinematics · Halley's method
+
+# 1 Introduction
+
+Cable-driven parallel robots (CDPRs) use the actuation of cables to transmit actuating forces to an end-effector or payload. Compared to traditional serial manipulators, CDPRs can feature significantly larger workspaces and payloadto-weight ratios. Forward kinematics is typically used to determine a CDPR's end-effector pose (position and orientation) during operation through measurements of the CDPR's cable lengths obtained from winch encoders. It is critical that the CDPR's pose be estimated accurately and quickly in order to control the end-effector motion precisely, especially during high-acceleration maneuvers.
+
+Forward kinematics algorithms are computed based on the CDPR's loopclosure equations that describe how cable-length measurements relate to the CDPR's geometry. In their simplest form, these loop-closure equations assume straight, inelastic, and massless cables. More complex features can be incorporated into the loop-closure equations, such as cable sag [8], pulley kinematics [17], and cable elasticity [9]. Even the simplest of loop-closure equations are nonlinear functions of the CDPR end-effector's pose, and these nonlinearities typically become more pronounced with more complex models. This highlights one of the challenges of CDPR forward kinematics, which in essence is a nonlinear root solving problem that may have multiple feasible pose solutions. This challenge is exacerbated when significant measurement noise and/or calibration errors are present [3,12]. A common practical method of solving a CDPR's forward kinematics involves linearizing the CDPR's nonlinear loop-closure equations about an initial pose estimate and iteratively solving for an improved estimate using Newton's method or a damped version of this, known as the Levenberg-Marquardt method [2,11–14,17]. Although these approaches can be effective in practice, they can potentially suffer from a large number of iterations and computation time, or not even converge within a reasonable tolerance of the true pose, especially when the initial pose estimation error is relatively large, such as on startup of a CDPR.
+
+Recently, Halley's method, also known as the method of tangent hyperbolas [15, pp. 122–124], [18], was proposed as a faster alternative to Newton's method when solving the inverse kinematics of overactuated serial manipulators [7]. Halley's method uses a second-order Taylor series expansion of the loop-closure equations, rather than the first-order expansion used with Netwon's method. This quadratic approximation of the nonlinearities in the loop-closure equations allows for convergence of an iterative method with fewer iterations and increases the rate of successful convergence for larger initial errors.
+
+This paper adapts the work of [7] to yield novel CDPR iterative forward kinematics algorithms based on Halley's method that are both fast and have a high success rate. The first algorithm proposed is directly based on Halley's method, while the second algorithm is a hybrid method that implements Halley's method for the first few iterations, then switches to the Levenberg-Marquardt method for subsequent iterations. Although the proposed algorithms are adaptable to any form of loop-closure equations that are twice differentiable with respect to the end-effector pose, the preliminary investigation in this paper focuses on an .8-cable .6-degree-of-freedom (DOF) CDPR. Analytic matrix expressions for the majority of the quadratic terms involved in the algorithm are derived, which assist in speeding up the computation time. Confidence intervals on the pose estimates obtained with the proposed algorithms are also computed in the form of covariance matrices leveraging the work of [11,12]. This allows for the methods to be used effectively within a sensor fusion scheme with additional measurements [5,10]. The contributions of this paper are the formulation and numerical evaluation of two novel CDPR iterative forward kinematics algorithms that are faster and have a higher rate of successful convergence compared to the Levenberg-Marquardt method. It is worth noting that unlike the work of [1,8], the algorithms proposed in this paper are not aimed at solving for all possible forward kinematics solutions. Rather, they are aimed at quickly and reliably solving for a local solution within a reasonable neighborhood of an initial pose estimate, with the intention of accounting for relatively large errors on startup.
+
+The remainder of this section presents important notation and a description of the CDPR considered in this paper.
+
+
+
+Fig. 1. A suspended 6-DOF CDPR with a rigid-body end-effector payload.
+
+#### 1.1 Notation and System Description
+
+In this paper, an $n \times n$ identity matrix is denoted as $\mathbf{1}\_{n \times n}$ and an $n \times m$ matrix of zeros is $\mathbf{0}\_{n \times m}$ . The cross operator, $(\cdot)^{\times} : \mathbb{R}^3 \to \mathfrak{so}(3)$ , satisfies $\mathbf{u}^{\times} \mathbf{w} = -\mathbf{w}^{\times} \mathbf{u}$ for all $\mathbf{u}, \mathbf{w} \in \mathbb{R}^3$ , where $\mathfrak{so}(3) = {\mathbf{S} \in \mathbb{R}^{3 \times 3} | \mathbf{S} + \mathbf{S}^\mathsf{T} = \mathbf{0}}$ [\[6\]](#page-2-6), pp. 525–526.This work considers an overconstrained 6-DOF CDPR with $m$ cables, where
+
+ $m > 6$ . An example of a 6-DOF CDPR with 8 cables is shown in Fig. 1. The
+
+reference frame $\mathcal{F}\_o$ is an inertial frame with point $o$ at its origin, while $\mathcal{F}\_p$ is an
+
+end-effector-fixed frame centered at point $p$ , the end-effector's center of mass.
+
+The position vector of point $p$ relative to $o$ is $\underline{r}$ , which is resolved in $\mathcal{F}\_o$ as
+
+ $\mathbf{r} \in \mathbb{R}^3$ . The position vector of the $i$ th cable's anchoring pulley relative to point
+
+ $o$ is $\underline{a}\_i$ , which is resolved in $\mathcal{F}\_o$ as $\mathbf{a}\_i$ . The position vector of the $i$ th cable's
+
+attachment point on the end-effector relative to its anchoring point is $\underline{l}\_i$ , which
+
+is resolved in $\mathcal{F}\_o$ as $\mathbf{l}\_i$ . The position vector of the $i$ th cable's attachment point
+
+on the end-effector relative to point $p$ is $\underline{b}\_i$ , which is resolved in $\mathcal{F}\_p$ as $\mathbf{b}\_i$ . The
+
+pose of the CDPR's end-effector is described by $\rho \in \mathbb{R}^6$ , where $\rho^\text{T} = [\mathbf{r}^\text{T} \,\mathbf{\theta}^\text{T}]$
+
+and $\mathbf{\theta} \in \mathbb{R}^3$ represents an unconstrained parameterization of the rotation matrix
+
+ $\mathbf{R}\_{po}(\mathbf{\theta})$ or direction cosine matrix (DCM) $(\mathbf{C}\_{po}(\mathbf{\theta}) = \mathbf{R}\_{po}^\text{T}(\mathbf{\theta}))$ that describes the
+
+orientation of $\mathcal{F}\_p$ relative to $\mathcal{F}\_o$ . In this paper a 3-2-1 Euler angle sequence (yaw-
+
+pitch-roll) is used to parameterize the end-effector orientation, although other
+
+unconstrained parameterizations could be used, such as those discussed in [\[11\]](#page-2-1).### 2 Forward Kinematics Formulation
+
+This section presents the proposed iterative forward kinematics methods, including the loop-closure and measurement equations, a second-order Taylor series expansion of the measurement equations, and the two proposed algorithms.
+
+### 2.1 Loop-Closure and Measurement Equations
+
+Assuming that the cables are inelastic and pulley kinematics can be ignored, the pose-dependent position vector of the $i^{th}$ cable's attachment point on the end-effector relative to its attachment is given by the loop-closure equation
+
+$$\ell\_i(\rho) = \mathbf{r} + \mathbf{C}\_{po}^{\top}(\theta)\mathbf{b}\_i - \mathbf{a}\_i \dots$$
+
+It is also assumed that measurements of the CDPR's cable lengths are avail-able through the use of incremental encoders and calibration. Each cable-lengthmeasurement satisfies $y\_i = ||l\_i(\rho)||\_2 + v\_i$ , where $y\_i$ is the length measurement ofthe $i^{th}$ cable and $v\_i$ represents uncertainty or noise in the cable-length measurement. For the purpose of simplicity in this preliminary study, it is assumed that $v\_i \in N(0, \sigma\_i2)$ is zero-mean Gaussian white noise with standard deviation $\sigma\_i$ .The measurements for all .m cables are concatenated together to form the measurement equation
+
+$$\mathbf{f}(\mathbf{y}, \boldsymbol{\rho}, \mathbf{v}) = \mathbf{0}\_{m \times 1},\tag{1}$$
+
+where $\mathbf{f}^{\text{T}}(\mathbf{y}, \boldsymbol{\rho}, \mathbf{v}) = [f\_1(y\_1, \boldsymbol{\rho}, v\_1) \cdots f\_m(y\_m, \boldsymbol{\rho}, v\_m)], \mathbf{y}^{\text{T}} = [y\_1 \cdots y\_m], \mathbf{v}^{\text{T}} = [v\_1 \cdots v\_m]$ , and
+$$f\_{i}(y\_{i}, \rho, v\_{i}) = -y\_{i} + ||\ell\_{i}(\rho)||\_{2} + v\_{i}.$$
+
+Although cable-length measurement equations are used in this paper, it is
+worth noting that the formulation presented in this section can be adapted to
+other measurement equations, such as the cable-length-squared equations used
+in [\[11\]](#page-3-1), provided that the equations are twice differentiable with respect the
+CDPR pose.### 2.2 Taylor Series Expansion
+
+Performing a Taylor series expansion of [\(1\)](#page-3-1) about $\rho = \bar{\rho}$ and $\mathbf{v} = \mathbb{E}[\mathbf{v}] = \mathbf{0}\_{m \times 1}$ results in
+$$\mathbf{f}(\mathbf{y},\rho,\mathbf{v}) \approx \mathbf{f}(\mathbf{y},\bar{\rho},\mathbf{0}) + \mathbf{J}\_{\rho}(\bar{\rho})\delta\rho + \frac{1}{2}\bar{\mathbf{H}}\_{\rho\rho}(\bar{\rho},\delta\rho)\delta\rho + \mathbf{v},\tag{2}$$
+
+where $\mathbf{J}\_{\rho}(\bar{\rho}) = \frac{\partial \mathbf{f}}{\partial \rho}|\_{\mathbf{y},\bar{\rho},\mathbf{0}}$ is the Jacobian of $\mathbf{f}(\mathbf{y}, \rho, \mathbf{v})$ evaluated at $\bar{\rho}$ , while
+
+ $\mathbf{\bar{H}}\_{\rho\rho}(\bar{\rho}, \delta\rho)$ is based on the Hessian of the individual entries of $\mathbf{f}(\mathbf{y}, \rho, \mathbf{v})$ . Specifically,
+$$\mathbf{J}\_{\rho}(\boldsymbol{\rho}) = \begin{bmatrix} \frac{\ell\_{1}^{\mathsf{T}}(\boldsymbol{\rho})}{\|\ell\_{1}(\boldsymbol{\rho})\|} \begin{bmatrix} \mathbf{1}\_{3\times3} & -\mathbf{C}\_{po}^{\mathsf{T}}(\boldsymbol{\theta})\mathbf{b}\_{1}^{\mathsf{X}}\mathbf{S}(\boldsymbol{\theta}) \end{bmatrix} \\ \vdots \\ \frac{\ell\_{m}^{\mathsf{T}}(\boldsymbol{\rho})}{\|\ell\_{m}(\boldsymbol{\rho})\|} \begin{bmatrix} \mathbf{1}\_{3\times3} & -\mathbf{C}\_{po}^{\mathsf{T}}(\boldsymbol{\theta})\mathbf{b}\_{m}^{\mathsf{X}}\mathbf{S}(\boldsymbol{\theta}) \end{bmatrix} \end{bmatrix}, \quad \bar{\mathbf{H}}\_{\rho\rho}(\boldsymbol{\rho},\boldsymbol{\delta}\boldsymbol{\rho}) = \begin{bmatrix} \boldsymbol{\delta}\boldsymbol{\rho}^{\mathsf{T}}\mathbf{H}\_{\rho\rho,1}(\boldsymbol{\rho}) \\ \vdots \\ \boldsymbol{\delta}\boldsymbol{\rho}^{\mathsf{T}}\mathbf{H}\_{\rho\rho,m}(\boldsymbol{\rho}) \end{bmatrix},$$
+
+where $J\_p(\rho)$ was derived in [\[11\]](#page-3-1) and the entries of $\overline{H}\_{\rho\rho}(\rho, \delta\rho)$ are computed through the Hessian matrices
+$$\mathbf{H}\_{\rho\rho,i}(\rho) = \begin{bmatrix} \frac{\partial^2 f\_i}{\partial \mathbf{r} \partial \mathbf{r}^\mathsf{T}} & \frac{\partial^2 f\_i}{\partial \theta \partial \mathbf{r}^\mathsf{T}}\\ \left(\frac{\partial^2 f\_i}{\partial \theta \partial \mathbf{r}^\mathsf{T}}\right)^\mathsf{T} & \frac{\partial^2 f\_i}{\partial \theta \partial \theta^\mathsf{T}} \end{bmatrix}, \quad i = 1, \cdots, m,$$
+
+where
+
+$$\frac{\partial^2 f\_i}{\partial \mathbf{r} \partial \mathbf{r}^\mathsf{T}} = \frac{\mathbf{1}\_{3 \times 3}}{\left\| \ell\_i(\rho) \right\|} - \frac{\ell\_i(\rho) \ell\_i^\mathsf{T}(\rho)}{\left\| \ell\_i(\rho) \right\|^3}, \quad \frac{\partial^2 f\_i}{\partial \theta \partial \mathbf{r}^\mathsf{T}} = \frac{\partial^2 f\_i}{\partial \mathbf{r} \partial \mathbf{r}^\mathsf{T}} (-\mathbf{C}\_{po}^\mathsf{T}(\theta) \mathbf{b}\_i^\times \mathbf{S}(\theta)),$$
+
+$$\frac{\partial^2 f\_i}{\partial \theta \partial \theta^\mathsf{T}} = \mathbf{S}^\mathsf{T}(\theta) \mathbf{b}\_i^\times \mathbf{C}\_{po}(\theta) \frac{\partial^2 f\_i}{\partial \theta \partial \mathbf{r}^\mathsf{T}} + \frac{1}{\left\| \ell\_i(\bar{\rho}) \right\|} \frac{\partial}{\partial \theta} \left( \mathbf{S}^\mathsf{T}(\theta) \mathbf{b}\_i^\times \mathbf{C}\_{po}(\theta) \ell\_i(\bar{\rho}) \right).$$
+
+The term $S(\theta)$ is a mapping matrix based on the orientation kinematics $\omega =$
+ $S(\theta)\dot{\theta}$ , where $\omega$ is the angular velocity of $\mathcal{F}\_p$ relative to $\mathcal{F}\_o$ resolved in $\mathcal{F}\_p$ and
+expressions for $S(\theta)$ with different orientation parameterizations can be found
+in [\[11\]](#page-4-0). For the 3-2-1 Euler angle sequence used in this paper, $S(\theta)$ is given by
+$$\mathbf{S}(\boldsymbol{\theta}) = \begin{bmatrix} 1 & 0 & -\sin(\theta\_2) \\ 0 & \cos(\theta\_1) & \sin(\theta\_1)\cos(\theta\_2) \\ 0 & -\sin(\theta\_1) & \cos(\theta\_1)\cos(\theta\_2) \end{bmatrix}.$$
+
+Note that the use of $\ell\_i(\bar{\rho})$ in the final partial derivative of $\frac{\partial^2 f\_i}{\partial \theta \partial \theta^\top}$ denotes that $\ell\_i(\bar{\rho})$ is held constant in this partial derivative. The derivations of the terms within the Hessian matrix are provided in the Appendix. Note that the partial derivative $\frac{\partial}{\partial \theta} \left(\mathbf{S}^\top(\theta) \mathbf{b}\_i^\times \mathbf{C}\_{po} \ell\_i(\bar{\rho})\right)$ in the term $\frac{\partial^2 f\_i}{\partial \theta \partial \theta^\top}$ is not known to be representable through simple matrix expressions like the other partial derivatives. Instead, it can be derived for a given Euler angle sequence using a symbolic manipulation software package.#### 2.3 Forward Kinematics Algorithm 1: Halley's Method
+
+A numerically-damped version of Halley's method inspired by the DQuIK method in [\[7\]](#page-4-0) begins with an initial end-effector pose estimate $\rho^{(0)}$ and starts the *jth* iteration with the computation
+$$\delta \boldsymbol{\rho}^{(j)} = \left(\mathbf{J}\_{\rho}^{\mathsf{T}}(\boldsymbol{\rho}^{(j)})\mathbf{J}\_{\rho}(\boldsymbol{\rho}^{(j)}) + \eta \mathbf{1}\right)^{-1} \mathbf{J}\_{\rho}^{\mathsf{T}}(\boldsymbol{\rho}^{(j)}) \mathbf{f}(\mathbf{y}, \boldsymbol{\rho}^{(j)}, \mathbf{0}\_{m \times 1}), \tag{3}$$
+
+where $\eta > 0$ is a tunable parameter that provides numerical damping to the calculation, especially if $\rho^{(j)}$ is near a singularity. This is then followed by the update
+$$\boldsymbol{\rho}^{(j+1)} = \boldsymbol{\rho}^{(j)} + \left(\bar{\mathbf{J}}\_{\rho}^{\mathsf{T}} \bar{\mathbf{J}}\_{\rho} + \eta \mathbf{1}\right)^{-1} \bar{\mathbf{J}}\_{\rho}^{\mathsf{T}} \mathbf{f}(\mathbf{y}, \boldsymbol{\rho}^{(j)}, \mathbf{0}\_{m \times 1}),\tag{4}$$
+
+where $\overline{\mathbf{J}}\_{\rho} = \mathbf{J}\_{\rho}(\rho^{(j)}) + \frac{1}{2}\overline{\mathbf{H}}(\rho^{(j)}, \delta\rho^{(j)})$ . The iteration index *j* is increased and the iteration proceeds until a specified stopping criterion is satisfied, such as $\|\rho^{(j+1)} - \rho^{(j)}\|\_{2} < \epsilon$ or a maximum number of iterations is reached.The first step of Halley's method in (3) is derived by setting (2) equal to $\mathbf{0}\_{m \times 1}$ , dropping the second-order term, and isolating for $\delta \boldsymbol{\rho}$ . The second step in (4) is found through the same procedure with the inclusion of the second-order term in (2). It is worth noting that if only the second step in (4) is performed with $\delta \boldsymbol{\rho}^{(j)} = \mathbf{0}\_{6 \times 1}$ , the damped version of Halley's method reverts to the Levenberg-Marquardt method.If it is desired to compute the covariance of the error in the pose estimate, for example to use the forward kinematics solution within a sensor fusion algorithm [\[5,10\]](#page-5-1), then (3) and (4) are respectively modified as
+$$\delta\boldsymbol{\rho}^{(j)} = \left(\mathbf{J}\_{\rho}^{\mathrm{T}}(\boldsymbol{\rho}^{(j)})\mathbf{V}^{-1}\mathbf{J}\_{\rho}(\boldsymbol{\rho}^{(j)}) + \eta\mathbf{1}\right)^{-1}\mathbf{J}\_{\rho}^{\mathrm{T}}(\boldsymbol{\rho}^{(j)})\mathbf{V}^{-1}\mathbf{f}(\mathbf{y},\boldsymbol{\rho}^{(j)},\mathbf{0}\_{m\times 1}),$$
+
+$$\boldsymbol{\rho}^{(j+1)} = \boldsymbol{\rho}^{(j)} + \left(\bar{\mathbf{J}}\_{\rho}^{\mathrm{T}}\mathbf{V}^{-1}\bar{\mathbf{J}}\_{\rho} + \eta\mathbf{1}\right)^{-1}\bar{\mathbf{J}}\_{\rho}^{\mathrm{T}}\mathbf{V}^{-1}\mathbf{f}(\mathbf{y},\boldsymbol{\rho}^{(j)},\mathbf{0}\_{m\times 1}),$$
+
+where $\mathbf{V} = \mathbb{E}[\mathbf{v}\mathbf{v}^{\mathsf{T}}] = \text{diag}\{\sigma\_1^2, ..., \sigma\_m^2\}$ is the measurement covariance. The covariance matrix is then computed at the $j$ th iteration as [\[4, p. 84\]](#page-4-1)
+$$\mathbf{P}^{(j)} = \mathbb{E}[(\rho\_{\text{true}} - \rho^{(j)})(\rho\_{\text{true}} - \rho^{(j)})^\mathsf{T}] = \left(\bar{\mathbf{J}}\_{\rho}^{\mathsf{T}} \mathbf{V}^{-1} \bar{\mathbf{J}}\_{\rho}\right)^{-1}.\tag{5}$$
+
+If the measurement noise on each individual cable is the same (i.e., $\sigma\_i = \sigma$ , $i = 1,...,m$ , and $\mathbf{V} = \sigma \mathbf{1}\_{m \times m}$ ), then (3) and (4) can be used directly and the covariance of the pose estimation error is simply $\mathbf{P}^{(j)} = \sigma (\overline{\mathbf{J}}\_{\rho}^T \overline{\mathbf{J}}\_{\rho})^{-1}$ .### 2.4 Forward Kinematics Algorithm 2: Hybrid Method
+
+A potential disadvantage of Halley's method in comparison to Newton's method
+or the Levenberg-Marquardt method is that it requires the additional computa-
+tion of the term $\bar{H}\_{\rho\rho}(\bar{\rho}, \delta\rho)$ and it involves two matrix inversions within the same
+iteration by solving both (3) and (4). To reduce the need for unnecessary higher-
+order computations, a hybrid method is proposed that follows Halley's method
+for a prescribed number of iterations, then sets $\bar{H}\_{\rho\rho}(\bar{\rho}, \delta\rho) = 0\_{m\times6}$ and follows
+the Levenberg-Marquardt for all subsequent iterations by only solving for (4).
+This proposed hybrid method is designed to take advantage of Halley's method's
+ability to converge relatively quickly in the presence of large initial pose estima-
+tion errors, as well as the computational efficiency of the Levenberg-Marquardt
+method when the pose estimation error becomes smaller in later iterations.
+
+### 3 Results
+
+The proposed forward kinematics algorithms are implemented in a numerical simulation of a 6-DOF suspended CDPR with 8 cables modeled after CoGiRo [\[19\]](#page-5-1) whose dimensions are provided in Table 1. All computations presented in this section are performed on a laptop computer with an AMD Ryzen 8945HS @ 4.0 GHz with 16 GB memory and the code is run in Python.A Monte-Carlo assessment is performed with end-effector poses randomly selected from uniform distributions $\mathbf{r}\_{\text{min}} \leq \mathbf{r} \leq \mathbf{r}\_{\text{max}}$ and $-\boldsymbol{\theta}\_{\text{max}} \leq \boldsymbol{\theta} \leq \boldsymbol{\theta}\_{\text{max}}$ , where $\mathbf{r}\_{\text{min}} = \begin{bmatrix} -6.75 & -4.75 & 0 \end{bmatrix}^{\text{T}}$ m, $\mathbf{r}\_{\text{max}} = \begin{bmatrix} 6.75 & 4.75 & 4.75 \end{bmatrix}^{\text{T}}$ m, and $\boldsymbol{\theta}\_{\text{max}} = \begin{bmatrix} 30 & 30 & 30 \end{bmatrix}^{\text{T}}$ degrees are chosen based on a rough estimate of the bounds on the static workspace values of the CDPR. Each of these randomly-generated poses is assessed for static feasibility with a payload mass of 100 kg, a maximum cable
+
+| Cable | Pulley position, $aiT$ (m) | Cable End-Effector Attachment Point, $biT$ (m) |
+|-------|----------------------------|------------------------------------------------|
+| 1 | [-7.20 -5.44 5.39] | [0.503 -0.493 0.000] |
+| 2 | [-7.48 -5.15 5.40] | [-0.510 0.351 0.998] |
+| 3 | [-7.41 5.19 5.40] | [-0.503 -0.270 0.000] |
+| 4 | [-7.12 5.47 5.41] | [0.496 0.356 1.000] |
+| 5 | [7.22 5.37 5.41] | [-0.503 0.493 0.000] |
+| 6 | [7.51 5.08 5.42] | [0.500 -0.340 0.999] |
+| 7 | [7.43 -5.26 5.39] | [0.502 0.275 -0.001] |
+| 8 | [7.14 -5.54 5.40] | [-0.505 -0.346 0.998] |
+
+Table 1. Dimensions used for the numerical simulations based on CoGiRo [19].
+
+tension of 6,000 N, and a minimum cable tension of 10 N. This process is repeated until 10,000 statically-feasible poses are randomly generated. The inverse kinematics of each pose is then solved assuming straight and rigid cables to obtain the cable lengths associated with each pose. Perfect measurements with no noise are then used with the proposed forward kinematics algorithm and the Levenberg-Marquardt method using a stopping tolerance of $\epsilon = 10^{-9}$ , a maximum of 30 iterations, numerical damping of $\eta = 10^{-6}$ , and 3 iterations of Halley's method when using the proposed hybrid method. All methods are initialized with a pose estimate of $\rho^{(0)} = \rho\_{true} + \delta\rho^{(0)}$ , where $\rho\_{true}$ is the randomly-generated truth pose within the static feasible workspace and $\delta\rho^{(0)} = {\begin{bmatrix} \delta\mathbf{r}^{(0)T} & \delta\mathbf{\theta}^{(0)T} \end{bmatrix}}^T$ is an initial perturbation. To assess the performance of these methods as a function of the initial pose estimation error, $\delta\mathbf{r}^{(0)}$ and $\delta\mathbf{\theta}^{(0)}$ are drawn from uniform distributions $-\delta\mathbf{r}\_{max}^{(0)} \leq \delta\mathbf{r}^{(0)} \leq \delta\mathbf{r}\_{max}^{(0)}$ and $-\delta\mathbf{\theta}\_{max}^{(0)} \leq \delta\mathbf{\theta}^{(0)} \leq \delta\mathbf{\theta}\_{max}^{(0)}$ . The Monte Carlo assessment is performed for each of the three forward kinematics algorithms with $\mathbf{r}\_{max}^{(0)} = {\begin{bmatrix} 1 & 1 & 1 \end{bmatrix}}^T$ m and ten different values of $\mathbf{\theta}\_{max}^{(0)}$ ranging from a small initial maximum orientation error of $\mathbf{\theta}\_{max}^{(0)} = {\begin{bmatrix} 2 & 2 & 2 \end{bmatrix}}^T$ deg to a large initial maximum orientation error of $\mathbf{\theta}\_{max}^{(0)} = {\begin{bmatrix} 40 & 40 & 40 \end{bmatrix}}^T$ deg.The results of this Monte-Carlo assessment are shown in Fig. 2, which include the mean and . 99th percentile of the number of iterations and computation time required to meet the specified stopping conditions, as well as the percentage of runs that successfully converge within .0.1 m and . 1 deg of the true end-effector pose. It is observed in Fig. 2 that for small initial pose estimation errors the proposed forward kinematics algorithms provide a small reduction in the number of iterations required and an increase in the computation time compared to the Levenberg-Marquardt method, with a small improvement in the success rate of accurate convergence. However, for large errors (roughly larger than .20 deg) the number of iterations is substantially decreased and the success rate is greatly increased with the proposed methods in comparison to the Levenberg-Marquardt method. Additionally, the . 99th-percentile computation times with the proposed hybrid method are reduced with large initial estimation errors compared to the
+
+
+
+Fig. 2. Monte-Carlo assessment of the proposed forward kinematics methods (labeled
+"Halley" and "Hybrid"), as well as the Levenberg-Marquardt method (labeled "LM")
+with no noise or cable elasticity, including (a) number of iterations, (b) computation
+time required, and (c) success rate of convergence.
+
+Levenberg-Marquardt method. Further assessment of the Monte Carlo simula-
+
+sions with the three methods is provided in Fig. 3, which includes the mean and
+
+99th-percentile errors in the final position and orientation estimates. These errors
+
+are computed as $\|\mathbf{r}\_{true} - \mathbf{r}^{(j)}\|\_{2}$ and $\|\boldsymbol{\theta}\_{true} - \boldsymbol{\theta}^{(j)}\|\_{2}$ , respectively, where $j$ repre-
+
+sents the number of iterations required to meet the stopping criteria. Figure 3
+
+demonstrates that the estimation errors obtained with the proposed methods
+
+are considerably lower than those with the Levenberg-Marquardt method. Inter-
+
+estingly, even in situations where Fig. 2c shows less than a percent difference
+
+in the success rates between the three methods, there is a notable reduction in
+
+Fig. 3. Monte-Carlo assessment of the proposed forward kinematics methods (labeled "Halley" and "Hybrid"), as well as the Levenberg-Marquardt method (labeled "LM") with no noise or cable elasticity, including (a) position estimation error and (b) orientation estimation error. Note that (b) uses a linear y-axis scale below . 5 deg and a logarithmic scale above this.
+
+the orientation estimation error with the proposed methods compared to the Levenberg-Marquardt method. This seems to suggest that when the Levenberg-Marquardt method fails to converge, it tends to incur very large errors. In contrast, the proposed methods appear less prone to large errors, even when they fail to converge correctly.
+
+To assess the robustness of the proposed algorithms to model uncertainty, measurement noise and cable elasticity are added to the simulation. In particular, the cable-length measurements are adjusted to be $y\_i = ||l\_i(\rho)||\_2/(1+\frac{T\_i}{EA\_0}) + v\_i$ , where $T\_i$ is the tension in the *i*th cable, $E$ is the cable's elastic modulus, and $A\_0$ is the cross-sectional area of the cable [\[9\]](#page-8-1). Numerical values of $E = 35$ GPa and $A\_0 = 8.205 \times 10^{-6}$ m2 are used to match the CoGiRo values from [\[9\]](#page-8-1), while the zero-mean Gaussian white noise $v\_i$ has a standard deviation of 5 mm. A quadratic program is solved to determine the cable tensions associated with each statically-feasible pose. The Monte-Carlo assessment is performed again with the noisy and elastic cable measurements and the results are included in Fig. 4. It is demonstrated in Fig. 4 that the trends seen with the idealized cable model in Fig. 2 also hold with elastic and noisy cable measurements. The only notable differences are that the number of iterations and computation time of all algorithms increases, the number of successful convergences decreases, and there is less of a distinction in successful convergence rate between the methods for small initial pose estimation error. This assessment provides confidence that the proposed algorithms can substantially improve the rate of successful convergence
+
+Fig. 4. Monte-Carlo assessment of the proposed forward kinematics methods (labeled "Halley" and "Hybrid"), as well as the Levenberg-Marquardt method (labeled "LM") with noise and cable elasticity, including (a) number of iterations, (b) computation time required, and (c) success rate of convergence.
+
+and in the case of the hybrid method reduce the computation time required in the presence of modeling errors and measurement uncertainty.
+
+### 4 Conclusion
+
+This paper presented two iterative forward kinematic algorithms for overconstrained CDPRs based on Halley's method that make use of second-order terms in the Taylor series expansion of the CDPR's loop-closure equations. It was shown through a numerical example of a suspended .6-DOF CDPR with. 8 cables that both proposed algorithms reduce the number of iterations required to reach a convergence tolerance and have a greater success rate of convergence to the true CDPR pose compared to the standard iterative Levenberg-Marquardt method. This trend is amplified as the initial pose estimation error increases. The proposed hybrid method also demonstrated quicker computation times compared to the Levenberg-Marquardt method in the presence of relatively large initial pose estimation errors. Future work on this topic will involve experimental implementation and validation of the proposed algorithms in a real-time framework, as well as comparisons to other forward kinematics algorithms in the literature.
+
+Disclosure of Interests. The authors have no competing interests to declare that are relevant to the content of this article.
+
+# Appendix: Derivation of Terms in Hessian
+
+.
+
+This appendix presents the derivation of the terms in the Hessian matrix from
+in Sect. 2.2. Knowing that $\frac{\partial^2 f\_i}{\partial \mathbf{r} \partial \mathbf{r}^\top} = \frac{\partial}{\partial \mathbf{r}} \left( \frac{\partial f\_i}{\partial \mathbf{r}} \right)^\top$ , the first Hessian term is
+$$\begin{split} \frac{\partial^2 f\_i}{\partial \mathbf{r} \partial \mathbf{r}^\mathsf{T}} &= \frac{\partial}{\partial \mathbf{r}} \left( \frac{\ell\_i(\rho)}{\|\ell\_i(\rho)\|} \right) = \frac{\partial}{\partial \mathbf{r}} \left( \ell\_i(\rho) \right) \frac{1}{\|\ell\_i(\rho)\|} + \ell\_i(\rho) \frac{\partial}{\partial \mathbf{r}} \left( \frac{1}{\|\ell\_i(\rho)\|} \right) \\ &= \left( \mathbf{1}\_{3 \times 3} \right) \frac{1}{\|\ell\_i(\rho)\|} + \ell\_i(\rho) \left( -\frac{\ell\_i^\mathsf{T}(\rho)}{\|\ell\_i(\rho)\|^3} \right) = \frac{\mathbf{1}\_{3 \times 3}}{\|\ell\_i(\rho)\|} - \frac{\ell\_i(\rho) \ell\_i^\mathsf{T}(\rho)}{\|\ell\_i(\rho)\|^3}. \end{split}$$
+
+Starting with $\frac{\partial^2 f\_i}{\partial \theta \partial \mathbf{r}^\mathsf{T}} = \frac{\partial}{\partial \theta} \left( \frac{\partial f\_i}{\partial \mathbf{r}} \right)^\mathsf{T}$ and using the DCM identity $\frac{\partial}{\partial \theta} (\mathbf{C}\_{po}^\mathsf{T}(\theta) \mathbf{u}) = -\mathbf{C}\_{po}^\mathsf{T}(\theta) \mathbf{u}^\times \mathbf{S}(\theta)$ ) [\[16\]](#page-10-573), the second Hessian term is computed as
+$$\begin{split} \frac{\partial^2 f\_i}{\partial \boldsymbol{\theta} \partial \mathbf{r}^{\mathsf{T}}} &= \frac{\partial}{\partial \boldsymbol{\theta}} \left( \ell\_i(\boldsymbol{\rho}) \right) \frac{1}{\|\ell\_i(\boldsymbol{\rho})\|} + \ell\_i(\boldsymbol{\rho}) \frac{\partial}{\partial \boldsymbol{\theta}} \left( \frac{1}{\|\ell\_i(\boldsymbol{\rho})\|} \right) \\ &= \frac{\partial}{\partial \boldsymbol{\theta}} \left( \mathbf{C}\_{po}^{\mathsf{T}}(\boldsymbol{\theta}) \mathbf{b}\_i \right) \frac{1}{\|\ell\_i(\boldsymbol{\rho})\|} + \ell\_i(\boldsymbol{\rho}) \left( -\frac{\ell\_i^{\mathsf{T}}(\boldsymbol{\rho})}{\|\ell\_i(\boldsymbol{\rho})\|^3} \frac{\partial}{\partial \boldsymbol{\theta}} \left( \mathbf{C}\_{po}^{\mathsf{T}}(\boldsymbol{\theta}) \mathbf{b}\_i \right) \right) \\ &= -\left( \frac{\mathbf{1}\_{3 \times 3}}{\|\ell\_i(\boldsymbol{\rho})\|} - \frac{\ell\_i(\boldsymbol{\rho}) \ell\_i^{\mathsf{T}}(\boldsymbol{\rho})}{\|\ell\_i(\boldsymbol{\rho})\|^3} \right) \mathbf{C}\_{po}^{\mathsf{T}}(\boldsymbol{\theta}) \mathbf{b}\_i^{\mathsf{X}} \mathbf{S}(\boldsymbol{\theta}) = \frac{\partial^2 f\_i}{\partial \mathbf{r} \partial \mathbf{r}^{\mathsf{T}}} (-\mathbf{C}\_{po}^{\mathsf{T}}(\boldsymbol{\theta}) \mathbf{b}\_i^{\mathsf{X}} \mathbf{S}(\boldsymbol{\theta})). \end{split}$$
+
+The final Hessian term is found starting with $\frac{\partial^2 f\_i}{\partial \theta \partial \theta^\mathsf{T}} = \frac{\partial}{\partial \theta} \left( \frac{\partial f\_i}{\partial \theta} \right)^\mathsf{T}$ , resulting in
+$$
+\begin{split}
+\frac{\partial^2 f\_i}{\partial \theta \partial \theta^{\mathsf{T}}} &= \mathbf{S}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{C}\_{po}(\theta) \ell\_i(\rho) \frac{\partial}{\partial \theta} \left( \frac{1}{\|\ell\_i(\rho)\|} \right) \\
+&+ \frac{\partial}{\partial \theta} \left( \mathbf{S}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{C}\_{po}(\theta) \ell\_i(\rho) \right) \frac{1}{\|\ell\_i(\rho)\|} \\
+&= -\mathbf{S}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{C}\_{po}(\theta) \left( \frac{\mathbf{1}\_{3 \times 3}}{\|\ell\_i(\rho)\|} - \frac{\ell\_i(\rho) \ell\_i^{\mathsf{T}}(\rho)}{\|\ell\_i(\rho)\|^3} \right) \mathbf{C}\_{po}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{S}(\theta) \\
+&+ \frac{1}{\|\ell\_i(\bar{\rho})\|} \frac{\partial}{\partial \theta} \left( \mathbf{S}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{C}\_{po}(\theta) \ell\_i(\bar{\rho}) \right) \\
+&= \mathbf{S}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{C}\_{po}(\theta) \frac{\partial^2 f\_i}{\partial \theta \partial \mathbf{r}^{\mathsf{T}}} + \frac{1}{\|\ell\_i(\bar{\rho})\|} \frac{\partial}{\partial \theta} \left( \mathbf{S}^{\mathsf{T}}(\theta) \mathbf{b}\_i^{\times} \mathbf{C}\_{po}(\theta) \ell\_i(\bar{\rho}) \right).
+\end{split}
+$$
+
+# References
+
+.
+
+- 1. Baskar, A., Plecnik, M., Hauenstein, J.D., Wampler, C.W.: A numerical continuation approach using monodromy to solve the forward kinematics of cable-driven parallel robots with sagging cables. Mech. Mach. Theory 195, 105609 (2024)
+- 2. Bieber, J., Pallmer, S., Beitelschmidt, M.: Computationally efficient implementation of the Gauss-Newton method for solving the forward kinematics of redundant cable-driven parallel robots. PMM-J. Appl. Math. Mech. 23(3), e202300231 (2023)
+- 3. Caverly, R.J., Cheah, S.K., Bunker, K.R., Patel, S., Sexton, N., Nguyen, V.L.: Online self-calibration of cable-driven parallel robots using covariance-based data quality assessment metrics. J. Mech. Robot. 17(1), 010904 (2025)
+- 4. Crassidis, J.L., Junkins, J.L.: Optimal Estimation of Dynamic Systems. CRC Press, Boca Raton (2004)
+- 5. Garant, X., Campeau-Lecours, A., Cardou, P., Gosselin, C.: Improving the forward kinematics of cable-driven parallel robots through cable angle sensors. In: Cable-Driven Parallel Robots, pp. 167–179. Springer, Cham (2018)
+- 6. Hughes, P.C.: Spacecraft Attitude Dynamics. Dover, Mineola (2004)
+- 7. Lloyd, S., Irani, R.A., Ahmadi, M.: Fast and robust inverse kinematics of serial robots using Halley's method. IEEE T. Robot. 38(5), 2768–2780 (2022)
+- 8. Merlet, J.P.: Some properties of the Irvine cable model and their use for the kinematic analysis of cable-driven parallel robots. Mech. Mach. Theory 135, 271–280 (2019)
+- 9. Nguyen, D.Q., Gouttefarde, M., Company, O., Pierrot, F.: On the simplifications of cable model in static analysis of large-dimension cable-driven parallel robots. In: IEEE International Conference on Intelligent Robots, pp. 928–934 (2013)
+- 10. Nguyen, V.L., Caverly, R.J.: Cable-driven parallel robot pose estimation using extended Kalman filtering with inertial payload measurements. IEEE Rob. Autom. Lett. 6(2), 3615–3622 (2021)
+- 11. Nguyen, V.L., Caverly, R.J.: CDPR forward kinematics with error covariance bounds for unconstrained end-effector attitude parameterizations. In: International Conference on Cable-Driven Parallel Robots, pp. 37–49. Springer, Cham (2021)
+- 12. Patel, S., Nguyen, V.L., Caverly, R.J.: Forward kinematics of a cable-driven parallel robot with pose estimation error covariance bounds. Mech. Mach. Theory 183, 105231 (2023)
+- 13. Pott, A., Schmidt, V.: On the forward kinematics of cable-driven parallel robots. In: IEEE International Conference on Intelligent Robots, pp. 3182–3187 (2015)
+- 14. Pott, A.: An algorithm for real-time forward kinematics of cable-driven parallel robots. In: Advances in Robot Kinematics: Motion in Man and Machine, pp. 529– 538. Springer, Dordrecht (2010)
+- 15. Rheinboldt, W.C.: Methods for Solving Systems of Nonlinear Equations, 2nd edn. SIAM, Philadelphia (1998)
+- 16. de Ruiter, A.H., Forbes, J.R.: General identities for parameterizations of SO(3) with applications. J. Appl. Mech. 81(7) (2014)
+- 17. Santos, J.C., Gouttefarde, M.: A real-time capable forward kinematics algorithm for cable-driven parallel robots considering pulley kinematics. In: Advances in Robot Kinematics 2020, pp. 199–208. Springer, Cham (2021)
+- 18. Scavo, T., Thoo, J.: On the geometry of Halley's method. Am. Math. Mon. 102(5), 417–426 (1995)
+- 19. Tempel, P., Herve, P.E., Tempier, O., Gouttefarde, M., Pott, A.: Estimating inertial parameters of suspended cable-driven parallel robots—use case on CoGiRo. In: IEEE International Conference on Robotics and Automation, pp. 6093–6098 (2017)
\ No newline at end of file
diff --git a/ai_docs/Quadratic_Approximation_Implementation_help_from_chatgpt.md b/ai_docs/Quadratic_Approximation_Implementation_help_from_chatgpt.md
new file mode 100644
index 000000000000..63b77e15e651
--- /dev/null
+++ b/ai_docs/Quadratic_Approximation_Implementation_help_from_chatgpt.md
@@ -0,0 +1,690 @@
+Here’s the markdown version, organized to be friendly for an LLM that will implement the forward kinematics / forward transform.
+
+---
+
+# Fast and Reliable Iterative CDPR Forward Kinematics
+
+## A Quadratic Approximation (Halley) Approach
+
+*Source: Mahnke & Caverly, “Fast and Reliable Iterative Cable-Driven Parallel Robot Forward Kinematics: A Quadratic Approximation Approach” *
+
+This document restates the paper in implementation-oriented form. It focuses on:
+
+* The forward kinematics problem formulation for an overconstrained CDPR
+* The loop-closure and measurement equations
+* The Jacobian and Hessian terms needed for Halley’s method
+* Two iterative algorithms:
+
+ * A Halley-based forward kinematics solver
+ * A hybrid Halley + Levenberg–Marquardt solver
+
+All notation assumes a 6-DOF end-effector pose, but the formulation generalizes to any twice-differentiable measurement model.
+
+---
+
+## 1. System and Notation
+
+### 1.1 Frames and Pose
+
+* Inertial/world frame: ( F_o ), origin at point ( o )
+* End-effector frame: ( F_p ), origin at the end-effector CoM ( p )
+
+**Pose vector**
+
+[
+\rho \in \mathbb{R}^6, \quad \rho^T = \begin{bmatrix} r^T & \theta^T \end{bmatrix}
+]
+
+* ( r \in \mathbb{R}^3 ): position of ( p ) expressed in ( F_o )
+* ( \theta \in \mathbb{R}^3 ): orientation parameterization (here: 3-2-1 / yaw–pitch–roll Euler angles)
+
+**Rotation / Direction Cosine Matrix**
+
+* ( R_{po}(\theta) ): rotation from ( F_o ) to ( F_p )
+* ( C_{po}(\theta) = R_{po}^T(\theta) ): DCM describing orientation of ( F_p ) w.r.t. ( F_o )
+
+**Cross-operator**
+
+* For ( u \in \mathbb{R}^3 ):
+ [
+ u_\times \in \text{so}(3), \quad u_\times w = u \times w
+ ]
+
+---
+
+### 1.2 CDPR Geometry
+
+For cable ( i \in {1,\dots,m} ) (with ( m > 6 ), i.e. overconstrained 6-DOF CDPR):
+
+* Pulley/anchor position (in ( F_o )):
+
+ [
+ a_i \in \mathbb{R}^3
+ ]
+
+* End-effector attachment point (in ( F_p )):
+
+ [
+ b_i \in \mathbb{R}^3
+ ]
+
+* Pose-dependent attachment point position in ( F_o ):
+
+ [
+ i(\rho) = r + C_{po}^T(\theta), b_i - a_i ;\in \mathbb{R}^3
+ ]
+
+This is the vector from pulley anchor ( a_i ) to end-effector attachment point expressed in the world frame.
+
+---
+
+### 1.3 Orientation Kinematics Mapping (S(\theta))
+
+Angular velocity mapping (for Euler 3-2-1, yaw–pitch–roll):
+
+[
+\omega = S(\theta) \dot\theta
+]
+
+For 3-2-1 Euler angles ( \theta = [\theta_1, \theta_2, \theta_3]^T ):
+
+[
+S(\theta) =
+\begin{bmatrix}
+1 & 0 & -\sin(\theta_2) \
+0 & \cos(\theta_1) & \sin(\theta_1)\cos(\theta_2) \
+0 & -\sin(\theta_1) & \cos(\theta_1)\cos(\theta_2)
+\end{bmatrix}
+]
+
+In code, you can generalize this or swap for another unconstrained attitude parameterization with its own ( S(\theta) ).
+
+---
+
+## 2. Forward Kinematics: Model
+
+### 2.1 Measurement Model (Cable Lengths)
+
+Assume:
+
+* Cables are straight, massless, inelastic (for the main derivation).
+* Cable length measurements are available from encoders.
+
+Cable ( i ) measured length:
+
+[
+y_i = | i(\rho) |_2 + v_i
+]
+
+* ( y_i ): measured cable length
+* ( v_i \sim \mathcal{N}(0, \sigma_i^2) ): measurement noise
+
+Define stacked vectors:
+
+* ( y = [y_1, \dots, y_m]^T \in \mathbb{R}^m )
+* ( v = [v_1, \dots, v_m]^T \in \mathbb{R}^m )
+
+Define residual functions:
+
+[
+f_i(y_i, \rho, v_i) = -y_i + | i(\rho) |_2 + v_i
+]
+
+Stacked:
+
+[
+f(y,\rho,v) =
+\begin{bmatrix}
+f_1(y_1,\rho,v_1)\
+\vdots\
+f_m(y_m,\rho,v_m)
+\end{bmatrix}
+\in \mathbb{R}^m
+]
+
+The **forward kinematics problem** is:
+
+> Find ( \rho ) such that
+> [
+> f(y,\rho,v) = 0
+> ]
+>
+> (in practice, ( v ) is unknown and we solve for ( f(y,\rho,0) \approx 0 )).
+
+---
+
+### 2.2 Taylor Expansion Around a Nominal Pose
+
+Let:
+
+* Linearization point ( \bar{\rho} ) (current pose estimate)
+* ( \delta\rho = \rho - \bar{\rho} )
+
+Taylor expand ( f(y,\rho,v) ) around ( \rho = \bar{\rho} ), ( v = 0 ):
+
+[
+f(y,\rho,v) \approx f(y,\bar{\rho},0) + J_\rho(\bar{\rho}) , \delta\rho + \frac{1}{2} \bar{H}_{\rho\rho}(\bar{\rho},\delta\rho), \delta\rho + v
+\tag{TS}
+]
+
+Where:
+
+* ( J_\rho(\rho) = \dfrac{\partial f}{\partial \rho} \in \mathbb{R}^{m \times 6} ) is the Jacobian
+* ( \bar{H}*{\rho\rho}(\rho,\delta\rho) \in \mathbb{R}^{m \times 6} ) is constructed from the Hessians ( H*{\rho\rho,i} ):
+
+ For each cable ( i ),
+
+ [
+ H_{\rho\rho,i}(\rho) =
+ \begin{bmatrix}
+ \dfrac{\partial^2 f_i}{\partial r \partial r^T} &
+ \dfrac{\partial^2 f_i}{\partial \theta \partial r^T} \
+ \left(\dfrac{\partial^2 f_i}{\partial \theta \partial r^T}\right)^T &
+ \dfrac{\partial^2 f_i}{\partial \theta \partial \theta^T}
+ \end{bmatrix}
+ \in \mathbb{R}^{6 \times 6}
+ ]
+
+ and
+
+ [
+ \bar{H}*{\rho\rho}(\rho,\delta\rho) =
+ \begin{bmatrix}
+ \delta\rho^T H*{\rho\rho,1}(\rho) \
+ \vdots \
+ \delta\rho^T H_{\rho\rho,m}(\rho)
+ \end{bmatrix}
+ \in \mathbb{R}^{m \times 6}
+ ]
+
+Then ( \bar{H}*{\rho\rho}(\rho,\delta\rho) \delta\rho \in \mathbb{R}^m ) has elements ( \delta\rho^T H*{\rho\rho,i}(\rho) \delta\rho ).
+
+---
+
+## 3. Derivatives Needed for Halley’s Method
+
+This section gives expressions for:
+
+* Jacobian ( J_\rho(\rho) )
+* Hessian terms ( H_{\rho\rho,i}(\rho) )
+
+You must implement the following building blocks.
+
+### 3.1 Jacobian ( J_\rho(\rho) )
+
+Recall:
+
+[
+f_i(y_i,\rho,0) = -y_i + | i(\rho) |
+]
+
+Let:
+
+* ( i = i(\rho) \in \mathbb{R}^3 )
+* ( \ell_i = | i(\rho) | )
+
+Then:
+
+1. Derivative w.r.t. position ( r ):
+
+ [
+ \frac{\partial f_i}{\partial r} =
+ \frac{i^T}{\ell_i} \quad \in \mathbb{R}^{1 \times 3}
+ ]
+
+2. Derivative w.r.t. orientation ( \theta ):
+
+ * First note:
+ [
+ i(\rho) = r + C_{po}^T(\theta)b_i - a_i
+ ]
+
+ * Use identity (DCM derivative w.r.t. parameter vector ( \theta )):
+
+ [
+ \frac{\partial}{\partial \theta}
+ \left[ C_{po}^T(\theta) u \right]
+ = - C_{po}^T(\theta) u_\times S(\theta)
+ ]
+ for any vector ( u \in \mathbb{R}^3 ).
+
+ * So:
+ [
+ \frac{\partial i}{\partial \theta} =
+ \frac{\partial}{\partial \theta} \left[ C_{po}^T(\theta) b_i \right]
+ = - C_{po}^T(\theta) (b_i)_\times S(\theta)
+ \in \mathbb{R}^{3 \times 3}
+ ]
+
+ * Then:
+
+ [
+ \frac{\partial f_i}{\partial \theta} =
+ \frac{i^T}{\ell_i} \frac{\partial i}{\partial \theta}
+ =====================================================
+
+ \frac{i^T}{\ell_i} \left( - C_{po}^T(\theta) (b_i)_\times S(\theta) \right)
+ \quad \in \mathbb{R}^{1 \times 3}
+ ]
+
+**Jacobian row ( i ):**
+
+[
+\left[ \frac{\partial f_i}{\partial r} ;; \frac{\partial f_i}{\partial \theta} \right]
+======================================================================================
+
+\left[
+\frac{i^T}{\ell_i}
+;;
+\frac{i^T}{\ell_i}
+\left(-C_{po}^T(\theta) (b_i)_\times S(\theta)\right)
+\right]
+]
+
+Stack all rows for ( i = 1,\dots,m ) to form ( J_\rho(\rho) \in \mathbb{R}^{m \times 6} ).
+
+---
+
+### 3.2 Hessian Terms
+
+We need:
+
+* ( \dfrac{\partial^2 f_i}{\partial r \partial r^T} )
+* ( \dfrac{\partial^2 f_i}{\partial \theta \partial r^T} )
+* ( \dfrac{\partial^2 f_i}{\partial \theta \partial \theta^T} )
+
+Again, let ( i = i(\rho) ), ( \ell_i = | i(\rho) | ).
+
+#### 3.2.1 ( \partial^2 f_i / \partial r \partial r^T )
+
+From the appendix:
+
+[
+\frac{\partial^2 f_i}{\partial r \partial r^T}
+==============================================
+
+\frac{1}{\ell_i} I_{3\times 3}
+
+* \frac{1}{\ell_i^3} i, i^T
+ \in \mathbb{R}^{3 \times 3}
+ ]
+
+#### 3.2.2 ( \partial^2 f_i / \partial \theta \partial r^T )
+
+Using identity:
+
+[
+\frac{\partial^2 f_i}{\partial \theta \partial r^T}
+===================================================
+
+\frac{\partial^2 f_i}{\partial r \partial r^T}
+\left( - C_{po}^T(\theta) (b_i)_\times S(\theta) \right)
+]
+
+So:
+
+[
+\frac{\partial^2 f_i}{\partial \theta \partial r^T}
+===================================================
+
+\left( \frac{1}{\ell_i} I - \frac{1}{\ell_i^3} i i^T \right)
+\left( - C_{po}^T(\theta) (b_i)_\times S(\theta) \right)
+\in \mathbb{R}^{3 \times 3}
+]
+
+#### 3.2.3 ( \partial^2 f_i / \partial \theta \partial \theta^T )
+
+From the appendix:
+
+[
+\frac{\partial^2 f_i}{\partial \theta \partial \theta^T}
+========================================================
+
+S^T(\theta) (b_i)*\times C*{po}(\theta)
+\frac{\partial^2 f_i}{\partial \theta \partial r^T}
++
+\frac{1}{|i(\bar{\rho})|}
+\frac{\partial}{\partial \theta}
+\left[ S^T(\theta) (b_i)*\times C*{po}(\theta), i(\bar{\rho}) \right]
+]
+
+Important notes for implementation:
+
+* The last term depends on ( i(\bar{\rho}) ) held constant while differentiating w.r.t ( \theta ).
+* The paper suggests deriving this term symbolically for the chosen attitude parameterization (e.g. with a CAS tool).
+* **Practical option for implementation:**
+
+ * Either (a) pre-generate closed-form code for this term symbolically and paste it, or
+ * (b) approximate ( \partial^2 f_i / \partial \theta \partial \theta^T ) via finite differences of ( \partial f_i / \partial \theta ) if performance allows.
+
+#### 3.2.4 Building ( H_{\rho\rho,i} ) and ( \bar{H}_{\rho\rho} )
+
+For each cable ( i ):
+
+[
+H_{\rho\rho,i}(\rho) =
+\begin{bmatrix}
+\dfrac{\partial^2 f_i}{\partial r \partial r^T} &
+\dfrac{\partial^2 f_i}{\partial \theta \partial r^T} \
+\left(\dfrac{\partial^2 f_i}{\partial \theta \partial r^T}\right)^T &
+\dfrac{\partial^2 f_i}{\partial \theta \partial \theta^T}
+\end{bmatrix}
+\in \mathbb{R}^{6 \times 6}
+]
+
+Given ( \delta\rho \in \mathbb{R}^6 ), build:
+
+[
+\bar{H}*{\rho\rho}(\rho,\delta\rho) =
+\begin{bmatrix}
+\delta\rho^T H*{\rho\rho,1}(\rho) \
+\vdots \
+\delta\rho^T H_{\rho\rho,m}(\rho)
+\end{bmatrix}
+\in \mathbb{R}^{m \times 6}
+]
+
+This is what Halley’s method needs.
+
+---
+
+## 4. Halley-Based Forward Kinematics Algorithm
+
+We solve for the pose ( \rho ) that makes ( f(y,\rho,0) \approx 0 ).
+
+Define:
+
+* Residual vector at iteration ( j ): ( r^{(j)} := f(y,\rho^{(j)},0) )
+* Jacobian: ( J^{(j)} := J_\rho(\rho^{(j)}) )
+* Hessian-based matrix: ( \bar{H}^{(j)} := \bar{H}_{\rho\rho}(\rho^{(j)},\delta\rho^{(j)}) ) (for the second step)
+
+A small positive scalar ( \eta > 0 ) adds numerical damping (Levenberg–Marquardt style).
+
+### 4.1 Baseline Halley Update
+
+Algorithm parameters:
+
+* Damping ( \eta > 0 ) (e.g. ( \eta = 10^{-6} ))
+* Initial pose guess ( \rho^{(0)} )
+* Tolerances:
+
+ * Pose update norm threshold ( \varepsilon )
+ * Maximum iterations ( j_{\max} )
+
+#### Step 0: Initialization
+
+* Set ( j = 0 )
+* Set ( \rho^{(0)} ) (e.g. nominal pose or approximate initial estimate)
+
+#### Step 1: First (Newton/LM-like) update to get ( \delta\rho^{(j)} )
+
+Compute:
+
+1. Residual:
+ [
+ r^{(j)} = f(y,\rho^{(j)},0)
+ ]
+
+2. Jacobian:
+ [
+ J^{(j)} = J_\rho(\rho^{(j)})
+ ]
+
+3. Damped least-squares step (LM-like):
+
+ [
+ \delta\rho^{(j)} =
+ \left( {J^{(j)}}^T J^{(j)} + \eta I_6 \right)^{-1} {J^{(j)}}^T r^{(j)}
+ \tag{H1}
+ ]
+
+#### Step 2: Form second-order Jacobian ( \bar{J} ) and update ( \rho )
+
+1. Build Hessian-based matrix:
+
+ [
+ \bar{H}^{(j)} =
+ \bar{H}_{\rho\rho}(\rho^{(j)}, \delta\rho^{(j)})
+ \in \mathbb{R}^{m \times 6}
+ ]
+
+2. Define effective Jacobian:
+
+ [
+ \bar{J}^{(j)} = J^{(j)} + \frac{1}{2}\bar{H}^{(j)}
+ ]
+
+3. Second (Halley) step:
+
+ [
+ \Delta\rho^{(j)} =
+ \left( {\bar{J}^{(j)}}^T \bar{J}^{(j)} + \eta I_6 \right)^{-1}
+ {\bar{J}^{(j)}}^T r^{(j)}
+ ]
+
+4. Update pose:
+
+ [
+ \rho^{(j+1)} = \rho^{(j)} + \Delta\rho^{(j)}
+ \tag{H2}
+ ]
+
+#### Step 3: Check stopping criterion
+
+If:
+
+[
+|\rho^{(j+1)} - \rho^{(j)}|_2 < \varepsilon
+]
+
+or ( j+1 \geq j_{\max} ), then stop and return ( \rho^{(j+1)} ).
+
+Otherwise, set ( j \leftarrow j+1 ) and repeat from Step 1.
+
+---
+
+### 4.2 Covariance-Aware Variant
+
+If you know the measurement covariance:
+
+* ( V = E[v v^T] = \operatorname{diag}{\sigma_1^2,\dots,\sigma_m^2} )
+
+replace (H1) and (H2) with:
+
+1. First step:
+
+ [
+ \delta\rho^{(j)} =
+ \left( {J^{(j)}}^T V^{-1} J^{(j)} + \eta I_6 \right)^{-1}
+ {J^{(j)}}^T V^{-1} r^{(j)}
+ ]
+
+2. Halley step:
+
+ [
+ \Delta\rho^{(j)} =
+ \left( {\bar{J}^{(j)}}^T V^{-1} \bar{J}^{(j)} + \eta I_6 \right)^{-1}
+ {\bar{J}^{(j)}}^T V^{-1} r^{(j)}
+ ]
+
+The covariance of the pose estimate at iteration ( j ) can be approximated by:
+
+[
+P^{(j)} = \left( {\bar{J}^{(j)}}^T V^{-1} \bar{J}^{(j)} \right)^{-1}
+]
+
+If ( \sigma_i = \sigma ) for all ( i ) so ( V = \sigma^2 I ), then:
+
+[
+P^{(j)} = \sigma^2 \left( {\bar{J}^{(j)}}^T \bar{J}^{(j)} \right)^{-1}
+]
+
+---
+
+### 4.3 Pseudocode (Halley Method)
+
+```pseudo
+function forward_kinematics_halley(y, rho0, eta, eps, max_iter):
+ rho = rho0
+
+ for j in 0 .. max_iter-1:
+ # Residual and Jacobian
+ r = f(y, rho) # size m
+ J = J_rho(rho) # size m x 6
+
+ # First (LM-like) step
+ A1 = J^T * J + eta * I6 # 6x6
+ b1 = J^T * r # 6x1
+ delta_rho = solve(A1, b1) # 6x1
+
+ # Build Hessian-based matrix
+ Hbar = compute_Hbar(rho, delta_rho) # m x 6
+
+ # Effective Jacobian
+ Jbar = J + 0.5 * Hbar # m x 6
+
+ # Halley step
+ A2 = Jbar^T * Jbar + eta * I6
+ b2 = Jbar^T * r
+ Delta_rho = solve(A2, b2)
+
+ # Update pose
+ rho_new = rho + Delta_rho
+
+ # Convergence check
+ if norm(rho_new - rho, 2) < eps:
+ return rho_new
+
+ rho = rho_new
+
+ return rho # last iterate if not converged
+```
+
+---
+
+## 5. Hybrid Halley + Levenberg–Marquardt Method
+
+Halley’s method is more expensive per iteration (needs Hessian terms and two solves per iteration), but converges more robustly from larger initial errors.
+
+A **hybrid** method:
+
+1. Run a fixed number ( N_H ) of Halley iterations as above.
+2. Then switch to standard Levenberg–Marquardt (LM) iterations (no Hessian term).
+
+### 5.1 LM Update (for this problem)
+
+LM iteration (same f/J as above):
+
+[
+\Delta\rho^{(j)} =
+\left( {J^{(j)}}^T J^{(j)} + \eta I_6 \right)^{-1}
+{J^{(j)}}^T r^{(j)}
+]
+
+[
+\rho^{(j+1)} = \rho^{(j)} + \Delta\rho^{(j)}
+]
+
+### 5.2 Hybrid Algorithm Outline
+
+Parameters:
+
+* ( N_H ): number of initial Halley iterations (e.g. 3)
+* ( \eta, \varepsilon, j_{\max} ): as before
+
+Algorithm:
+
+```pseudo
+function forward_kinematics_hybrid(y, rho0, eta, eps, max_iter, N_H):
+ rho = rho0
+
+ # Phase 1: Halley iterations
+ for j in 0 .. N_H-1:
+ r = f(y, rho)
+ J = J_rho(rho)
+ A1 = J^T * J + eta * I6
+ b1 = J^T * r
+ delta_rho = solve(A1, b1)
+
+ Hbar = compute_Hbar(rho, delta_rho)
+ Jbar = J + 0.5 * Hbar
+
+ A2 = Jbar^T * Jbar + eta * I6
+ b2 = Jbar^T * r
+ Delta_rho = solve(A2, b2)
+
+ rho_new = rho + Delta_rho
+ if norm(rho_new - rho, 2) < eps:
+ return rho_new
+
+ rho = rho_new
+
+ # Phase 2: Levenberg–Marquardt iterations
+ for j in N_H .. max_iter-1:
+ r = f(y, rho)
+ J = J_rho(rho)
+
+ A = J^T * J + eta * I6
+ b = J^T * r
+ Delta_rho = solve(A, b)
+
+ rho_new = rho + Delta_rho
+ if norm(rho_new - rho, 2) < eps:
+ return rho_new
+
+ rho = rho_new
+
+ return rho
+```
+
+The paper finds that:
+
+* For small initial errors, Halley and LM behave similarly.
+* For large initial orientation errors (e.g. >~ 20°), Halley and Hybrid converge more often and with fewer iterations than LM.
+* Hybrid typically has better worst-case runtime than pure LM when initial errors are large.
+
+---
+
+## 6. Example CDPR Geometry (CoGiRo-Like System)
+
+The paper evaluates the algorithms on a suspended 6-DOF CDPR with 8 cables (CoGiRo-like). The anchor positions ( a_i ) and attachment points ( b_i ) are given by:
+
+| Cable | Pulley position (a_i^T) [m] | End-effector attachment (b_i^T) [m] |
+| ----- | --------------------------- | ----------------------------------- |
+| 1 | ([-7.20,\ -5.44,\ 5.39]) | ([0.503,\ -0.493,\ 0.000]) |
+| 2 | ([-7.48,\ -5.15,\ 5.40]) | ([-0.510,\ 0.351,\ 0.998]) |
+| 3 | ([-7.41,\ 5.19,\ 5.40]) | ([-0.503,\ -0.270,\ 0.000]) |
+| 4 | ([-7.12,\ 5.47,\ 5.41]) | ([0.496,\ 0.356,\ 1.000]) |
+| 5 | ([7.22,\ 5.37,\ 5.41]) | ([-0.503,\ 0.493,\ 0.000]) |
+| 6 | ([7.51,\ 5.08,\ 5.42]) | ([0.500,\ -0.340,\ 0.999]) |
+| 7 | ([7.43,\ -5.26,\ 5.39]) | ([0.502,\ 0.275,\ -0.001]) |
+| 8 | ([7.14,\ -5.54,\ 5.40]) | ([-0.505,\ -0.346,\ 0.998]) |
+
+These values can be used to build a test harness for the forward kinematics implementation.
+
+---
+
+## 7. Extensions: Elastic Cables and Noise
+
+To model elastic cables with tension ( T_i ), Young’s modulus ( E ), and cross-sectional area ( A_0 ), the “effective measured length” can be approximated as:
+
+[
+y_i = \frac{| i(\rho) |}{1 + \dfrac{T_i}{E A_0}} + v_i
+]
+
+Implementation notes:
+
+* You can:
+
+ * Solve a static equilibrium + tension distribution (e.g. via QP) for ( T_i ), then plug into the above equation when simulating measurements.
+ * For the forward kinematics solver itself, the measurement model simply changes from ( y_i = | i(\rho) | + v_i ) to the elastic form. The derivatives must be updated accordingly if you want exact consistency.
+
+The paper shows that the proposed methods retain their robustness and relative benefits under elastic/noisy cable measurements.
+
+---
+
+This markdown should be directly suitable as a spec for an LLM to implement:
+
+* A CDPR forward kinematics function mapping cable lengths ( y ) to pose ( \rho ).
+* Both pure Halley and hybrid Halley+LM solvers.
+* Optional covariance output, and optional extension to elastic cable models.
diff --git a/ai_docs/dataset_usage.md b/ai_docs/dataset_usage.md
new file mode 100644
index 000000000000..b9c2017920c9
--- /dev/null
+++ b/ai_docs/dataset_usage.md
@@ -0,0 +1,30 @@
+## Synthetic Dataset Usage
+
+Paths:
+- `datasets/_.jsonl`
+
+Each `.jsonl` file has one JSON object per line:
+- `dataset`: scenario name (`clean_baseline`, `larger_baseline`, `near_singularities`, `at_singularities`, `outside_singularities`, `systematic_bias`)
+- `geometry`: `HP5`, `Slideprinter`, `Spidercam`, or `CubeCorners`
+- `anchor_set`: 0-based set index (only `larger_baseline` has three sets; others use set 0)
+- `anchors`: list of anchor `[x, y, z]` in mm; length depends on geometry (HP5=5, Slideprinter=3, Spidercam=4, CubeCorners=8)
+- `real_xyz`: list of mover poses (mm) to feed forward transforms
+- `config`: overrides for generation; only `systematic_bias` sets `{"min_force": 50.0}`; others are `{}`. See `generate_synthetic_data.py` for available keys (spool radii, buildup factor, gear teeth, mechanical_advantage, lines_per_spool, spring_k_per_unit_length, mover_weight, min/max force, guy_wire_lengths, use_flex, ignore_gravity, ignore_pretension, lambda_reg, tol, max_iters_target, g).
+- `config_used`: fully resolved values passed to `pos_to_motor_pos_samples` (arrays are lists). Includes `spool_buildup_factor`, `spool_r_in_origin`, `spool_gear_teeth`, `motor_gear_teeth`, `spool_to_motor_gearing_factor`, `mechanical_advantage`, `lines_per_spool`, `min_force`, `max_force`, `spring_k_per_unit_length`, `mover_weight`, `use_flex`, `ignore_gravity`, `ignore_pretension`, `lambda_reg`, `tol`, `max_iters_target`, `g`, and optional `guy_wire_lengths`.
+- `motor_samples`: generated motor positions in degrees (360° per rotation), matching `real_xyz` order; five columns for HP5, etc.
+
+Scenarios mapped to the suggested comparison suite:
+- Clean baseline → suite #1 (no noise, flex enabled); HP5 positions mirror `simulation_data_for_hangprinter_forward_transform.py`; Slideprinter is Z=0 projection of those points.
+- Larger baseline → suite #2 (3 anchor sets per geometry, 10 random poses each; ≥1000×1000 mm reach).
+- Near/At/Outside singularities → suite #6 boundary stress: HP5/Slideprinter points projected radially to the reachable boundary (−0.1 mm inside, exactly on, +0.1 mm outside). Spidercam/CubeCorners use rectangle footprints similarly.
+- Systematic bias → suite #4 pretension variant (min_force=50).
+Noise/quantization/bias for other suites (#3, #5, #8, #9, #10) should be injected in the C++ tests themselves.
+
+Practical hints for the C++ forward-transform tests:
+- Inputs are degrees, not steps; convert if your harness assumes steps (gear ratio 255/20, mechAdv HP5 default [2,2,2,2,4]). For non-HP5 geometries, check the anchor count and use the corresponding motor column count.
+- Each line is standalone JSON; your loader can stream line by line. The JSON is compact (no extra spacing), and keys stay in the order written by the generator (`dataset`, `geometry`, `anchor_set`, `anchors`, `real_xyz`, `config`, `motor_samples`).
+- To add noise or biases, perturb `motor_samples` or derived lengths in your test harness (e.g., Gaussian σ=1–5 mm on lengths, per-line constant offset for bias, 2–5% mislength for infeasible mixes, quantize to encoder resolution).
+- Flex is enabled in these datasets (generation default `use_flex=true`); if you need non-flex variants, re-run generation with `config.use_flex=false`.
+- Anchor set 0 is the canonical geometry per type; sets 1 and 2 (only in `larger_baseline`) are larger/smaller variants to test generality.
+
+Files on disk are compact JSONL (one object per line, no extra whitespace); keep that form for downstream parsers.***
diff --git a/ai_docs/datasets/at_singularities_CubeCorners.jsonl b/ai_docs/datasets/at_singularities_CubeCorners.jsonl
new file mode 100644
index 000000000000..21ceb34ceb08
--- /dev/null
+++ b/ai_docs/datasets/at_singularities_CubeCorners.jsonl
@@ -0,0 +1 @@
+{"dataset":"at_singularities","geometry":"CubeCorners","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0],[1500.0,1500.0,0.0],[-1500.0,1500.0,0.0],[-1500.0,-1500.0,0.0],[1500.0,-1500.0,0.0]],"real_xyz":[[1500.0,-1475.7074893007994,-500.0],[-1500.0,-1434.6510897842825,-500.0],[-1499.9999999999998,-1477.4397373943698,-500.0],[-1500.0,-1.5353490874818543,-500.0],[-1500.0,-9.42442257496202,-500.0],[-1500.0,52.72898285313941,-500.0],[-1500.0,1387.7040127989687,-500.0],[-1500.0,1356.4642153348086,-500.0],[-1500.0,1465.912202258873,-500.0],[25.88357625122502,-1500.0,-500.0],[-16.102421315081216,-1500.0,-500.0],[-117.5353775741511,-1500.0,-500.0],[-1500.0,-1376.9177241851523,-500.0],[-1274.5237097081742,1500.0,-500.0],[1500.0,999.3115321366655,-500.0],[31.484684683491597,1500.0,-500.0],[-57.58974622372378,1500.0,-500.0],[-125.46339174933684,1500.0,-500.0],[1402.3214868906655,-1500.0,-500.0],[1392.1033893951999,-1500.0,-500.0],[1378.0814405933565,-1500.0,-500.0],[1500.0,-67.29939930998059,-500.0],[1500.0,-93.00241568210704,-500.0],[1500.0,-94.63056608703553,-500.0],[1406.728664775464,1500.0,-500.0],[1500.0,1453.0479907013555,-500.0],[1500.0,1312.8950794518394,-500.0]],"config":{},"motor_samples":[[17437.06867073222,33827.37110992802,17723.35194503629,-1814.9935422014457,35137.76209790635,84506.10094674573,36088.16720817524,-62390.271393639996],[33415.04633562591,16958.658266709215,-1806.0400066986274,17730.570275146536,83353.59850633644,33539.27056034673,-62251.583378724004,36112.07254187102],[33844.862534935,17457.350003002928,-1815.1910003703897,17723.192757800163,84554.91954972122,35205.24136640759,-62393.3285304037,36087.639987245646],[22052.655847069207,3479.1075789541965,3457.9814618679425,22035.319606134395,49971.21731757407,-20912.763184286916,-21025.31837435969,49917.24853685196],[22097.3449396304,3533.557891080122,3403.879848915154,21990.93016161332,50110.2833263984,-20623.464737889364,-21314.360314319725,49779.00808376808],[21751.12274938293,3111.3986077581562,3836.893792337119,22346.480088864228,49030.846818021586,-22897.57194555284,-19032.261954603484,50884.14363863506],[17746.925566077385,-1785.7544367090932,16417.027837907568,32948.87721940392,36166.22675650995,-61940.258314223494,31713.44936110378,82046.59620183405],[17762.596378843453,-1766.3195841380027,16059.861062648974,32641.849277575064,36218.100952513945,-61646.28633780091,30499.710283420933,81183.41317904124],[17724.473559689894,-1813.6022800628373,17322.530639637745,33728.606741257776,36091.88190609562,-62368.70813836491,34756.24370004291,84230.33964964212],[21899.015225682793,22191.27389216587,3647.964611731622,3291.816831574651,49492.51567153711,50402.32454271165,-20019.310702703904,-21916.78996917152],[22135.342005480736,21953.523877165415,3358.2801045701854,3579.845125344129,50228.46379205113,49662.4552729338,-21558.884390174047,-20378.434900664786],[22731.341671305367,21404.498596676214,2690.2754843072007,4302.981186376009,52074.96271506987,47945.38338159655,-25256.548150796894,-16641.42273076076],[32842.58052031656,16293.412176585072,-1779.5800647317997,17751.90396820773,81747.96687515217,31294.2668762778,-61846.40961148304,36182.70792182582],[15135.584712282669,-1692.833222911314,17821.86279225338,31848.734740636275,27320.812265782275,-60570.80349665593,36414.16683046754,78944.69631017093],[-1215.607390494998,18212.718239822854,29318.35390181836,12170.165916620945,-54509.8072354959,37702.49405910009,71710.07950400066,16696.244512503366],[3253.931835036688,3687.1454913783195,22223.451603330872,21867.951106494267,-22121.609600261047,-19813.537378670753,50502.29230309483,49395.615974399414],[3871.4097263985996,3079.0452165503575,21724.61355111112,22374.847623187114,-18853.3275424441,-23074.912829478664,48948.00270203448,50972.10777459916],[4361.17477354718,2639.893968872192,21363.109178360857,22779.406633047543,-16348.195158868462,-25544.108769790135,47815.446303681616,52223.29405849972],[17740.906711190797,33093.41233861184,16585.0450465328,-1793.219442588572,36146.299339657846,82452.29021092653,32281.705538361344,-62054.29469967801],[17745.025975207052,32992.31913200444,16467.535708525418,-1788.1104151449215,36159.937743048,82168.57656932963,31884.453439649966,-61976.18106084599],[17751.344910160584,32854.034121167664,16306.733932673145,-1780.2734175882797,36180.85720872515,81780.1554507036,31339.486274035,-61856.92713850649],[3940.638604601255,22431.75622892506,21671.907322509553,3014.7066415261856,-18495.702672366122,51148.481977049116,48783.2068329081,-23428.932338923703],[4124.464291741546,22583.96138301971,21533.980492678027,2847.82586387787,-17547.791721665148,51619.6031142953,48351.42614271441,-24365.29583983347],[4136.238424516516,22593.678834468807,21525.32168178165,2837.2929754927836,-17487.68788843394,51649.65200449898,48324.2941402773,-24424.509323503065],[-1795.2663437577014,16635.81361626338,33137.09853141384,17739.256379646846,-62085.67241429259,32453.076572494407,82574.83079294892,36140.83502534755],[-1811.066004912419,17726.51828491738,33599.27091608768,17172.485484948847,-62329.38382950358,36098.65369610835,83868.93620960353,34255.33409210631],[-1731.3003459439967,17790.836768422996,32217.92353150707,15566.125728402789,-61126.90538675613,36311.54986922107,79988.42708706319,28808.58520243823]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/at_singularities_HP5.jsonl b/ai_docs/datasets/at_singularities_HP5.jsonl
new file mode 100644
index 000000000000..519300827cfc
--- /dev/null
+++ b/ai_docs/datasets/at_singularities_HP5.jsonl
@@ -0,0 +1 @@
+{"dataset":"at_singularities","geometry":"HP5","anchor_set":0,"anchors":[[0.0,-2000.0,-120.0],[2000.0,0.0,-120.0],[0.0,2000.0,-120.0],[-2000.0,0.0,-120.0],[0.0,0.0,2000.0]],"real_xyz":[[964.173982925749,-948.5591783950058,-27.497151],[-719.5698727769299,-688.2211347702399,507.741532],[-497.59098246182526,-490.10712697213705,953.040004],[-1859.9179585591871,-1.9037488936433073,26.4689901],[-1371.5533098398869,-8.617398650679272,537.019049],[-868.3705268565786,30.52552974719478,1047.17018],[-1000.9316453031034,925.997907149727,-42.5453256],[-726.5145875398869,656.9940266110565,533.480869],[-462.61901198441126,452.10590310992825,1030.39159],[32.431590292563676,-1879.469242065927,-26.6148823],[-14.852991064627272,-1383.6109589353725,517.628213],[-69.1030097619738,-881.9005543889695,991.936222],[-968.1382530857868,-888.6978134236471,31.7537695],[-667.9365658325002,786.1013813373113,458.719776],[539.7356098337328,359.57601280777675,1046.72968],[39.64758253318758,1888.898504070586,-44.2588518],[-51.728036433774484,1347.3241286605653,517.004705],[-74.62140930128558,892.149593528903,975.222737],[899.7710296374892,-962.444458758737,26.0515823],[665.0383748320579,-716.5829563000176,535.481389],[467.42323006399454,-508.7760595586472,965.228753],[1843.7079896425694,-82.72029347063788,-42.0139801],[1308.209812190019,-81.11111516847154,527.319817],[888.8665588797583,-56.07596376175122,998.360926],[894.2185351344076,953.5085452429507,41.4092948],[727.0015723778614,704.2454493202517,482.878157],[512.2978253267424,448.39552939023866,981.665044]],"config":{},"motor_samples":[[-11161.785756584035,-11588.674906673723,21509.95229566201,21707.30209100096,16983.94906715591],[-7417.339089264703,17017.560761047895,16588.293617252977,-8177.298342126261,-8076.430532936487],[-1672.2036426752459,14812.407207681428,14706.142048668882,-1824.6020079093303,-28774.15710064263],[14254.781745250219,36465.951554055384,14309.316643123353,-34856.266297866925,27515.667802476466],[9792.378118345609,28028.35751124722,10060.637324909429,-21300.375176982874,-146.21970859831129],[9639.785415959723,21378.728522602254,8674.700811360699,-7513.350340573007,-27830.242762762708],[21310.69729541663,22255.127995660085,-10375.000071382161,-12425.952390619394,17756.869519480682],[16160.972716573315,17115.674994998775,-6672.41380241526,-8342.447888880522,-9256.752708461827],[14530.315888781939,14680.011854637747,-401.57649918961243,-608.9305757675588,-32350.82276051901],[-35749.60327694614,14036.938705771845,36822.30024751685,14962.298516799605,29691.54362527155],[-21753.366525961974,10189.337169927065,28190.120168626952,9727.257402445071,609.6678156000286],[-8388.971048630947,9858.276491083969,21238.273630767566,7655.636609580142,-25777.676067000608],[-10151.749742055214,21479.780289048773,20465.447761543306,-12312.447808872379,14223.711356917127],[17963.564852947766,16355.481256266588,-9767.734867563426,-6855.7516348093,-5721.317239796874],[13340.88714156134,-1964.8230935607257,1563.0619071709013,15905.355601513094,-32842.52618569491],[37002.34003326686,14052.061514935005,-36049.263854482815,15180.913130181447,30513.70535719528],[27492.82541032661,10382.759196111907,-21227.31806613562,8760.981265825116,-225.66080805020746],[21311.59680424533,9874.482419011001,-8744.908258781066,7492.357654240011,-25012.591920339],[-12101.863907131818,-10396.183816877669,21430.173304668057,20630.676756235654,14481.718476397918],[-8104.875744086904,-6867.489535474943,16976.574270129484,16268.535237754275,-9361.671439430062],[-1973.2994341951694,-1135.2084655347433,15026.842006714855,14439.384307010543,-29326.41951380864],[12832.51913957585,-35029.022292882706,15213.414124935824,36123.9707561352,29348.409273104306],[7940.355447843805,-20483.41721705022,10501.443304144148,26786.677971343404,-1395.5088144503088],[7969.056516549221,-8427.132692751042,9752.666971949771,21406.180170443524,-25844.368344962673],[21245.787986587027,-10397.174410228257,-12008.097847387826,20487.4470364071,13758.678690596622],[16816.562041743175,-8344.736380932023,-7788.346025928425,17127.253857151478,-6918.281487895771],[14246.251022786995,-1933.1456939201748,-646.8557594345224,15154.584426050804,-30068.70235374119]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/at_singularities_Slideprinter.jsonl b/ai_docs/datasets/at_singularities_Slideprinter.jsonl
new file mode 100644
index 000000000000..893bccc56abf
--- /dev/null
+++ b/ai_docs/datasets/at_singularities_Slideprinter.jsonl
@@ -0,0 +1 @@
+{"dataset":"at_singularities","geometry":"Slideprinter","anchor_set":0,"anchors":[[-1000.0,-577.0,0.0],[1000.0,-577.0,0.0],[0.0,1154.0,0.0]],"real_xyz":[[586.498344878686,-577.0,0.0],[-603.2825724407588,-577.0,0.0],[-585.8106954171992,-577.0,0.0],[-667.061109827178,-0.6827811108451938,0.0],[-669.0952576356099,-4.203890967240714,0.0],[-653.3976531299176,22.968662432112634,0.0],[-434.46570367362887,401.93986694094826,0.0],[-437.89923351314417,395.9964267887475,0.0],[-426.1015164924649,416.4182749515432,0.0],[9.956548997971224,-577.0,0.0],[-6.194064732534575,-577.0,0.0],[-45.21194190685679,-577.0,0.0],[-628.5778625677834,-576.9999999999999,0.0],[-396.8485635172984,467.0551365515564,0.0],[481.3934169045349,320.7079953382502,0.0],[23.372998634595458,1113.5413393635154,0.0],[-41.54470955852095,1082.0861077542004,0.0],[-84.31556154283355,1008.049762969355,0.0],[539.4263319572759,-576.9999999999999,0.0],[535.4957704540202,-577.0,0.0],[530.1019941482446,-577.0000000000001,0.0],[684.4059737799156,-30.706740613033762,0.0],[691.432662385265,-42.86993858889359,0.0],[691.8826284602262,-43.648829864651525,0.0],[412.54011646201144,439.89305840425806,0.0],[427.4551144904945,414.0751968169539,0.0],[442.7795003626787,387.5486848722031,0.0]],"config":{},"motor_samples":[[8424.366080798447,-14396.488070050933,13151.878764377623],[-14721.54187160913,8752.388851473012,13258.682932264875],[-14383.169724247906,8410.92789798837,13147.560657523356],[-9509.601488150784,11892.958917937582,3495.558933129163],[-9588.512576573257,11908.155323163246,3574.873728258839],[-8979.487751415605,11795.480865617556,2962.8621661640086],[-470.23782707688315,11360.713111599463,-5557.66335048461],[-603.9029359569694,11350.916901644348,-5424.2489941178665],[-144.59605587871926,11386.785074108604,-5882.635076371577],[-2817.6770772516734,-3205.0931780721503,11260.666916215825],[-3131.893619393746,-2890.8794057708274,11260.32352315572],[-3890.8865030792576,-2131.651363115419,11271.656285441224],[-15211.346678918857,9246.827748953023,13424.715923595078],[994.6326339949983,11502.493245252073,-7018.860095757798],[11272.676913798947,-2296.4971155518115,-3733.606753073781],[16050.751403026565,15584.322833337561,-21480.015580248764],[14872.506713965979,15712.854223801458,-20778.31939975644],[13197.890236746342,14958.913082863804,-19125.963822435875],[7504.639523200938,-13484.637326258822,12866.882577298216],[7427.856470398634,-13408.481844307857,12844.065934386534],[7322.493466792355,-13303.97249071178,12813.003776030795],[12028.190285904971,-10182.38417277858,4171.943285343415],[12086.60250849877,-10454.887915189081,4446.008859528104],[12090.413894868843,-10472.33714825671,4463.560125354254],[11435.694946645364,383.4765522188637,-6409.4428935594005],[11382.353635048512,-197.29832633773995,-5830.04693461216],[11337.90217430448,-793.8765247260836,-5234.607471473708]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/at_singularities_Spidercam.jsonl b/ai_docs/datasets/at_singularities_Spidercam.jsonl
new file mode 100644
index 000000000000..03f2bfb0949d
--- /dev/null
+++ b/ai_docs/datasets/at_singularities_Spidercam.jsonl
@@ -0,0 +1 @@
+{"dataset":"at_singularities","geometry":"Spidercam","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0]],"real_xyz":[[1500.0,-1475.7074893007994,200.0],[-1500.0,-1434.6510897842825,507.741532],[-1499.9999999999998,-1477.4397373943698,953.040004],[-1500.0,-1.5353490874818543,200.0],[-1500.0,-9.42442257496202,537.019049],[-1500.0,52.72898285313941,1047.17018],[-1500.0,1387.7040127989687,200.0],[-1500.0,1356.4642153348086,533.480869],[-1500.0,1465.912202258873,1030.39159],[25.88357625122502,-1500.0,200.0],[-16.102421315081216,-1500.0,517.628213],[-117.5353775741511,-1500.0,991.936222],[-1500.0,-1376.9177241851523,200.0],[-1274.5237097081742,1500.0,458.719776],[1500.0,999.3115321366655,1046.72968],[31.484684683491597,1500.0,200.0],[-57.58974622372378,1500.0,517.004705],[-125.46339174933684,1500.0,975.222737],[1402.3214868906655,-1500.0,200.0],[1392.1033893951999,-1500.0,535.481389],[1378.0814405933565,-1500.0,965.228753],[1500.0,-67.29939930998059,200.0],[1500.0,-93.00241568210704,527.319817],[1500.0,-94.63056608703553,998.360926],[1406.728664775464,1500.0,200.0],[1500.0,1453.0479907013555,482.878157],[1500.0,1312.8950794518394,981.665044]],"config":{},"motor_samples":[[6830.726370035398,24821.084129577255,7150.466472058351,-15436.164040171658],[20748.511031923597,1906.9031321023708,-21373.118212998226,2813.8068510927733],[16443.485424836876,-3408.4129137324057,-29968.48656503151,-3073.13030990197],[11958.417314565515,-9113.442095482562,-9138.161867267294,11939.260766554517],[7515.484890217693,-14933.376061868361,-15098.538536100481,7392.074595773321],[842.5502057441818,-24159.89057124091,-23096.877817962373,1584.3435463889737],[7176.784514491375,-15401.060357598852,5689.521198689969,23870.461198642624],[2497.928858785262,-21816.956479823668,485.3506636510025,19587.36945105853],[-4036.507061874086,-31454.013974519603,-4549.974976294212,15532.500482302956],[11788.61879026506,12111.563913405764,-8915.945905676454,-9332.674019874083],[7810.5037960523005,7600.231082533141,-14820.741102535254,-14539.968103636953],[2696.2142917592773,1055.7094598668439,-23854.620778879496,-21523.531479972884],[23755.349418471607,5551.010526289217,-15393.633586041482,7182.342293850535],[456.35598840962246,-20279.154981243297,3597.8370703596493,19563.75820377869],[-30800.407522325364,-3614.5303332074172,10111.793649466683,-11488.017289937045],[-9377.042618188185,-8870.14105420703,12147.107484868247,11754.280720682254],[-14160.480837834657,-15164.387025801618,7343.439512214597,8095.356572640793],[-21169.095839871236,-23645.384227950584,1201.8338105924047,2948.8663511641657],[7170.065101335824,24026.951916401562,5877.709440948587,-15410.036928447178],[2449.823103774553,19958.488295964795,940.6186448061297,-21884.630964418575],[-3190.832375721002,15156.585520122444,-5022.907573481285,-30148.775822274467],[-8573.985064795757,12377.1405876855,11537.520394300906,-9657.385056863326],[-14015.712659655905,8203.945040533416,6988.011759250662,-15640.981629065689],[-21867.081746589956,2452.20853303707,1130.0699725012514,-23747.733318378883],[-15412.497613349173,5934.556222963954,24074.244817225677,7168.222663008924],[-20899.688384404257,3152.138134546163,21238.347913647678,2504.113632982195],[-30387.962222487975,-3346.712655006151,14238.792608785132,-6182.3350120608675]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/clean_baseline_CubeCorners.jsonl b/ai_docs/datasets/clean_baseline_CubeCorners.jsonl
new file mode 100644
index 000000000000..6d8ec6a435fb
--- /dev/null
+++ b/ai_docs/datasets/clean_baseline_CubeCorners.jsonl
@@ -0,0 +1 @@
+{"dataset":"clean_baseline","geometry":"CubeCorners","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0],[1500.0,1500.0,0.0],[-1500.0,1500.0,0.0],[-1500.0,-1500.0,0.0],[1500.0,-1500.0,0.0]],"real_xyz":[[17.9255679,-17.6352632,-500.0],[-523.885148,-501.061599,-500.0],[-538.35251,-530.255594,-500.0],[-545.189816,-0.558037791,-500.0],[-520.999273,-3.27341154,-500.0],[-470.799477,16.5498517,-500.0],[-505.362595,467.529134,-500.0],[-513.234032,464.122399,-500.0],[-538.29312,526.060302,-500.0],[8.98405788,-520.642383,-500.0],[-5.52678502,-514.840431,-500.0],[-38.6000122,-492.617793,-500.0],[-507.629503,-465.97604,-500.0],[-30.5601452,35.9665477,-500.0],[43.2898928,28.8400594,-500.0],[10.5874156,504.407891,-500.0],[-19.9804722,520.41744,-500.0],[-37.9958866,454.266612,-500.0],[455.930483,-487.688259,-500.0],[482.712486,-520.125685,-500.0],[495.517745,-539.35609,-500.0],[500.096373,-22.437457,-500.0],[490.657689,-30.4215669,-500.0],[506.742907,-31.9689121,-500.0],[490.590662,523.118645,-500.0],[517.848381,501.639033,-500.0],[525.399857,459.863258,-500.0]],"config":{},"motor_samples":[[8466.867241201064,8699.462230409057,8470.638789531788,8237.465712045685,2250.9013601556476,3207.7696920988506,2266.4807749610445,1299.2551543991888],[15942.0919029542,9450.944133296029,2782.2935689070746,9744.290173130054,30097.752773302134,6250.525514965458,-24748.694187909798,7414.955836630397],[16293.736709172856,9642.922727452655,2585.2190632346633,9746.894811318105,31295.368600437396,7014.526847783119,-25871.69139364689,7425.907951677289],[12559.247694971635,5530.919813550275,5523.450035760177,12552.32899107857,18131.844589919463,-10661.642425939264,-10696.814605021125,18106.436550944385],[12372.67212455935,5653.019801134435,5609.252743116174,12332.001480837276,17445.160365962234,-10086.354885783956,-10291.314670879377,17295.053941201593],[11833.716776689083,5744.9057932594305,5965.6393414753065,12040.23489454843,15443.463391930518,-9652.960863458673,-8631.061636568871,16213.71697214607],[9730.513931408748,3022.8076252961173,9243.739441621596,15526.58535260624,7359.89649727652,-23403.280677254257,5420.443349772899,28672.467273234233],[9813.195642903747,3003.168999444744,9181.374928847605,15563.13868247069,7686.361714554387,-23512.103350865706,5169.784273753325,28798.305887865594],[9763.8351743305,2604.2953291365448,9606.739894610639,16259.396733690948,7492.736397017355,-25762.141455352405,6870.966553797451,31178.755089571507],[12293.667664494638,12405.293803069248,5692.885933944107,5572.767074970287,17153.433350081395,17565.45063674925,-9900.030627870923,-10462.496998124274],[12335.241440950786,12266.53683976386,5621.097472052109,5694.9713016958585,17307.01747608628,17053.11935995736,-10235.219894336364,-9889.754078574948],[12359.31071462637,11878.554103210105,5501.481596990356,6016.854447478518,17395.863025108836,15611.042256637293,-10795.303403651895,-8397.466390985413],[15532.574890601067,9220.916154480246,3019.8325644542283,9756.830684852925,28693.092927213114,5328.756779083525,-23419.749339727154,7463.893197986841],[8437.075612350729,8039.053032832067,8507.311375862815,8903.324159326314,2127.792490694394,469.64106306020585,2417.884382593368,4040.027785301464],[8003.516301065585,8567.045407516682,8940.57271247654,8379.326407004197,320.3999165480505,2664.033010321396,4191.461793005599,1888.7278199318455],[5633.337715094351,5774.782769220366,12279.993725673852,12148.260249628194,-10176.912911565247,-9517.023826118873,17102.883575607262,16615.00413302111],[5768.003272476094,5500.864634474527,12224.064391124493,12472.323356666897,-9550.02192259016,-10800.84588413681,16895.944324294756,17812.314198692857],[6186.914454155754,5680.625852991177,11566.389964701533,12041.498916569097,-7617.420783735557,-9952.436050939737,14441.48870707517,16218.471973689117],[9631.100856566783,15293.615569425247,9222.262955853164,3159.430814915827,6965.9890075363155,27868.353745995373,5333.753373503466,-22650.690536722486],[9790.95862281057,15765.6611891781,9309.880229500122,2884.3262486053777,7598.92832248762,29493.921765848252,5686.237482846579,-24174.6381125366],[9902.334014449361,16023.318711405915,9339.013245629669,2738.860296295645,8037.938862254604,30375.08166144457,5803.467605090044,-24994.490796247093],[5873.768821227739,12318.68850401851,12039.409159759902,5574.075964794701,-9057.633221993334,17245.8857372081,16210.645331240577,-10454.413467369026],[5969.892785467247,12291.14810789335,11912.184319348187,5563.749706991842,-8613.229960953195,17144.12035631601,15736.60724579435,-10502.044445315818],[5909.118622717847,12434.09297931792,12036.408743208141,5481.9824316465065,-8894.866023923909,17671.565209062184,16199.483573602753,-10888.611107017088],[2834.133027266243,9364.492125954182,15852.42221232235,9782.662177435013,-24456.417028941098,5905.048913330231,29791.109618497663,7566.323073583888],[2806.852190384542,9689.64173018397,15897.989049101647,9481.282505968074,-24610.091043951794,7198.78304024813,29946.998644189534,6371.37763416404],[2968.658817288775,9936.993038053206,15628.083932603937,9094.012451471428,-23703.74617753289,8173.588856618724,29021.6693944135,4817.806525733636]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/clean_baseline_HP5.jsonl b/ai_docs/datasets/clean_baseline_HP5.jsonl
new file mode 100644
index 000000000000..e191bc270946
--- /dev/null
+++ b/ai_docs/datasets/clean_baseline_HP5.jsonl
@@ -0,0 +1 @@
+{"dataset":"clean_baseline","geometry":"HP5","anchor_set":0,"anchors":[[0.0,-2000.0,-120.0],[2000.0,0.0,-120.0],[0.0,2000.0,-120.0],[-2000.0,0.0,-120.0],[0.0,0.0,2000.0]],"real_xyz":[[17.9255679,-17.6352632,-27.497151],[-523.885148,-501.061599,507.741532],[-538.35251,-530.255594,953.040004],[-545.189816,-0.558037791,26.4689901],[-520.999273,-3.27341154,537.019049],[-470.799477,16.5498517,1047.17018],[-505.362595,467.529134,-42.5453256],[-513.234032,464.122399,533.480869],[-538.29312,526.060302,1030.39159],[8.98405788,-520.642383,-26.6148823],[-5.52678502,-514.840431,517.628213],[-38.6000122,-492.617793,991.936222],[-507.629503,-465.97604,31.7537695],[-30.5601452,35.9665477,458.719776],[43.2898928,28.8400594,1046.72968],[10.5874156,504.407891,-44.2588518],[-19.9804722,520.41744,517.004705],[-37.9958866,454.266612,975.222737],[455.930483,-487.688259,26.0515823],[482.712486,-520.125685,535.481389],[495.517745,-539.35609,965.228753],[500.096373,-22.437457,-42.0139801],[490.657689,-30.4215669,527.319817],[506.742907,-31.9689121,998.360926],[490.590662,523.118645,41.4092948],[517.848381,501.639033,482.878157],[525.399857,459.863258,981.665044]],"config":{},"motor_samples":[[-376.22359902271086,-381.9286947057644,310.4309961108531,316.0302122492248,997.8918020428947],[-5816.156617203316,12588.517230557962,12250.083341769674,-6340.3786301768605,-13411.216594917458],[-2067.011657588064,15678.882536698533,15565.68001153369,-2233.454277467298,-27516.079948988805],[1436.1017828435238,10647.367156313412,1457.0392091923877,-10540.51860470919,1761.4827219031847],[3152.304509629339,11739.205023261318,3270.2193631944956,-7518.348023731693,-17448.366745358173],[7278.714057992026,14234.262742441244,6728.945444350567,-1614.5251923877925,-36351.64551486047],[10071.169789485262,10654.961146129563,-7569.372426505517,-8492.626595635757,5970.2320237495705],[11646.073385538373,12379.968702885772,-5057.795504295804,-6170.677574886364,-14853.594774164309],[16090.52146430405,16259.880967720845,-1133.7452906585336,-1379.3395991233451,-29967.71946617988],[-10148.59562994118,1094.236281002262,10119.061248980306,1433.0713834498317,3517.388052458588],[-7558.518970704551,3169.2933453244073,11528.094754768767,2969.5151059356235,-16818.5926170673],[-2591.4541804663145,7215.202802454421,14175.546521117092,5921.024086238325,-34061.91953392273],[-7426.392145196267,10758.200670230868,10116.406781516434,-8439.682464192923,3231.2119086226066],[2200.8010180983897,2101.1048452442683,852.9181377881728,955.872642910887,-17851.550579171617],[6570.455277510523,5347.460853544822,5595.542697511844,6810.928525557428,-40455.64003506627],[9790.312216246832,971.0013323538597,-9853.024580275624,1371.2020227270793,4031.1487001169676],[11632.27415601377,3452.637741026999,-7661.100626395297,2730.6088668140455,-16721.337219741497],[13356.22203625303,6902.858920206154,-2168.8179353176874,5621.254080760609,-34092.360396841585],[-8137.586434090859,-7369.365371954516,10333.188598925328,9840.456048114704,3170.6998882981807],[-6175.837263477687,-5324.740395312487,12583.278140319782,12027.302994262353,-14637.297893208104],[-2296.649898287508,-1402.6801321052108,15664.108271311317,15048.28849736858,-28418.31108001737],[727.941958285674,-9764.767794946161,1576.4694383648682,9708.929121529007,3909.5807346207375],[2465.0178988291354,-7047.322860791975,3566.279159154566,11120.378754188941,-17463.25500717965],[6151.869995626571,-2742.719942938496,7221.179352397897,14477.793856636701,-34052.486502452615],[11156.608720510168,-7764.36570239462,-8561.418078093702,10660.037071729907,3243.7631936886883],[12123.49480917015,-6406.634511320441,-6032.739861739486,12364.652702635609,-12600.97639212031],[14496.076634463157,-2077.5342758141346,-755.0038571959427,15423.284668959133,-29691.726258059014]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/clean_baseline_Slideprinter.jsonl b/ai_docs/datasets/clean_baseline_Slideprinter.jsonl
new file mode 100644
index 000000000000..921599da429a
--- /dev/null
+++ b/ai_docs/datasets/clean_baseline_Slideprinter.jsonl
@@ -0,0 +1 @@
+{"dataset":"clean_baseline","geometry":"Slideprinter","anchor_set":0,"anchors":[[-1000.0,-577.0,0.0],[1000.0,-577.0,0.0],[0.0,1154.0,0.0]],"real_xyz":[[17.9255679,-17.6352632,0.0],[-523.885148,-501.061599,0.0],[-538.35251,-530.255594,0.0],[-545.189816,-0.558037791,0.0],[-520.999273,-3.27341154,0.0],[-470.799477,16.5498517,0.0],[-505.362595,467.529134,0.0],[-513.234032,464.122399,0.0],[-538.29312,526.060302,0.0],[8.98405788,-520.642383,0.0],[-5.52678502,-514.840431,0.0],[-38.6000122,-492.617793,0.0],[-507.629503,-465.97604,0.0],[-30.5601452,35.9665477,0.0],[43.2898928,28.8400594,0.0],[10.5874156,504.407891,0.0],[-19.9804722,520.41744,0.0],[-37.9958866,454.266612,0.0],[455.930483,-487.688259,0.0],[482.712486,-520.125685,0.0],[495.517745,-539.35609,0.0],[500.096373,-22.437457,0.0],[490.657689,-30.4215669,0.0],[506.742907,-31.9689121,0.0],[490.590662,523.118645,0.0],[517.848381,501.639033,0.0],[525.399857,459.863258,0.0]],"config":{},"motor_samples":[[132.27389762093313,-477.1851463451662,342.8150915856804],[-13071.381337343959,7223.998123637882,11357.864523409773],[-13425.247199942185,7473.816227512569,11988.045788515024],[-8183.027974822014,9650.208249319552,2378.2726500584904],[-7926.6291715687,9188.769509925303,2231.3581797260917],[-6997.046676180387,8415.591647484405,1491.0133203474463],[20.049962311896163,13231.549924537023,-5870.520248349846],[-105.26544457521996,13320.430605091444,-5726.306351678355],[800.5010264396506,14419.30908164655,-6362.983019165819],[-2825.6748372290167,-3174.3537158812856,10158.231679577793],[-3098.9889826361755,-2884.5449979578148,10044.48127259869],[-3703.1758494070627,-2207.511897069298,9618.626406411337],[-12631.850532924835,6954.869597154399,10607.69667603044],[-150.68397367548215,864.5043111273931,-695.9196705923148],[1007.9868660158947,-434.4628764240917,-549.0793121883387],[6346.177251786931,6065.2979255786695,-9808.437693261765],[6174.003316871508,6699.937631023797,-10114.676252053463],[4982.847071144873,6015.927729176594,-8817.21257205198],[5915.000729772868,-11730.006693455804,10728.46974302379],[6397.663394257236,-12332.387048418072,11481.745728675265],[6626.441589794871,-12616.642366555332,11912.995720251352],[8674.968595776982,-7940.409093794306,2412.5051597174115],[8447.954100517269,-7930.42875326688,2485.589415701789],[8732.98828628916,-8164.1754360306095,2634.249895977454],[13629.898696479715,1122.8898148823614,-6905.051560330329],[13815.489617400748,521.9989967640006,-6249.752525362634],[13469.986219477603,-280.0381739980005,-5518.183702461478]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/clean_baseline_Spidercam.jsonl b/ai_docs/datasets/clean_baseline_Spidercam.jsonl
new file mode 100644
index 000000000000..cbb078fc9153
--- /dev/null
+++ b/ai_docs/datasets/clean_baseline_Spidercam.jsonl
@@ -0,0 +1 @@
+{"dataset":"clean_baseline","geometry":"Spidercam","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0]],"real_xyz":[[17.9255679,-17.6352632,200.0],[-523.885148,-501.061599,507.741532],[-538.35251,-530.255594,953.040004],[-545.189816,-0.558037791,200.0],[-520.999273,-3.27341154,537.019049],[-470.799477,16.5498517,1047.17018],[-505.362595,467.529134,200.0],[-513.234032,464.122399,533.480869],[-538.29312,526.060302,1030.39159],[8.98405788,-520.642383,200.0],[-5.52678502,-514.840431,517.628213],[-38.6000122,-492.617793,991.936222],[-507.629503,-465.97604,200.0],[-30.5601452,35.9665477,458.719776],[43.2898928,28.8400594,1046.72968],[10.5874156,504.407891,200.0],[-19.9804722,520.41744,517.004705],[-37.9958866,454.266612,975.222737],[455.930483,-487.688259,200.0],[482.712486,-520.125685,535.481389],[495.517745,-539.35609,965.228753],[500.096373,-22.437457,200.0],[490.657689,-30.4215669,527.319817],[506.742907,-31.9689121,998.360926],[490.590662,523.118645,200.0],[517.848381,501.639033,482.878157],[525.399857,459.863258,981.665044]],"config":{},"motor_samples":[[-3325.912722806161,-3059.293528673302,-3321.587646866706,-3589.096097825171],[708.2043377344967,-7080.901742466329,-15384.64960523493,-6724.627073032733],[-4882.617250506216,-13552.251976926795,-23350.22209496733,-13413.644166800339],[1340.0750902617494,-6718.189460549174,-6726.878263189216,1332.2236221501316],[-3982.489284152605,-12248.495809935801,-12303.544583893667,-4031.681226163052],[-11949.801691753672,-20338.61527109634,-20024.135985521156,-11673.360598313968],[-1879.4793066907785,-9652.11279581792,-2435.0055942977447,4690.737683912944],[-7039.758696689657,-15551.897515219012,-7811.751644070163,-104.5194435458366],[-14504.778302568764,-24632.35553105331,-14717.732075102293,-5914.844118467768],[1038.6004364083838,1165.3574653756953,-6529.347047188326,-6669.0023665136],[-3739.842746944733,-3822.6587473364643,-11966.51610628793,-11874.048324283272],[-10495.252910457199,-11130.897780305197,-19818.981976603118,-19094.181682612947],[4697.464185546105,-2461.067378929046,-9655.618889435407,-1849.4649918323507],[-7540.640042440785,-8023.276979441836,-7455.582834488998,-6976.607520888482],[-17156.03475510989,-16377.2750123864,-15863.628366088487,-16636.170844231932],[-6598.2370138046845,-6433.839150755364,1023.0908909414228,873.4372609986615],[-11772.462458247197,-12106.845784506148,-3864.585778651235,-3565.44162266155],[-18595.511471170175,-19303.11758071314,-11311.909781995235,-10684.56456220859],[-1993.2105508462287,4429.015283457251,-2459.9197867378048,-9491.119960854314],[-7097.4725293850515,107.94810871279901,-7685.313725342818,-15739.48213420934],[-13383.156127494643,-5384.368408358726,-14136.669026851765,-23333.954883829607],[-6318.760813930769,1067.0423914634164,749.7364648518607,-6667.055452256417],[-11689.827098173433,-3937.0764088548485,-4395.177843212501,-12198.983125244766],[-19346.02020113531,-10484.387769427458,-11010.344432402655,-19948.177472462055],[-9874.622362547449,-2296.5642197695347,5056.503353915475,-1819.5188153911686],[-14917.068934796667,-6404.414801608711,1008.015564212901,-6656.191339137965],[-23277.26197868322,-13573.686877668404,-6103.3589231369515,-14706.528338130072]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/larger_baseline_CubeCorners.jsonl b/ai_docs/datasets/larger_baseline_CubeCorners.jsonl
new file mode 100644
index 000000000000..ae128c96723f
--- /dev/null
+++ b/ai_docs/datasets/larger_baseline_CubeCorners.jsonl
@@ -0,0 +1,3 @@
+{"dataset":"larger_baseline","geometry":"CubeCorners","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0],[1500.0,1500.0,0.0],[-1500.0,1500.0,0.0],[-1500.0,-1500.0,0.0],[1500.0,-1500.0,0.0]],"real_xyz":[[802.9851537615568,-904.7991579176248,537.3819696124713],[-581.2656135858514,-195.76078199768085,1510.2713313774227],[-186.43942831918275,-1210.1972306474247,1811.9844030572065],[629.0941137686191,1244.7600874499726,1696.2318599395915],[1122.8580268059409,1175.1118829028592,773.467439769466],[-1127.412211300106,-858.8790672305458,2209.9702390734237],[-621.4803345791836,-1008.180417893958,2747.146397969696],[477.33241977062585,1191.267295195547,1089.6763918397842],[-800.1284540323497,-944.3492019937278,2747.1197801459675],[-873.1705022044939,786.1155910862576,771.5443424509402]],"config":{},"motor_samples":[[-4174.374936297109,7092.0130853297915,-5728.642537633374,-19292.21967904724,17165.256612440702,49213.42941457104,12377.496323618618,-40939.35693809334],[-14604.98353823149,-25648.331289961174,-29906.432507073638,-18105.95233870314,37622.30440710973,12808.473814876244,2930.5243188026234,29846.9381436724],[-9378.448049487384,-12449.981060435333,-37415.394944337386,-32703.575238904494,61067.91275821543,54862.03117031578,5266.968447034401,14478.728357929971],[-40087.44050865514,-25028.507902989208,-3487.4455866563635,-13508.985698207242,-7697.050590774257,23972.002005375944,68872.76595942542,47993.97483912793],[-25631.420786525116,-5760.5962491487,10544.384463938237,-4962.052819174964,-46395.4204770341,24744.57438825909,67259.06076955014,26962.198938627917],[-6498.494920050728,-26720.465999849956,-50252.74301661683,-21275.710620716585,80904.43153101094,44491.40564799705,8171.050184754827,53978.15949200895],[-14061.419661312246,-25810.30328159983,-54688.45283821184,-34647.5323450575,85608.93559381683,67132.03203789565,31522.588414851965,54496.17325571612],[-28227.65062000514,-18643.68397965337,491.9719307942164,-6587.132094324215,-23100.052755448785,6126.423553727575,54784.19337199452,37545.08834629917],[-12713.487847286697,-27944.46153908538,-56375.76411282753,-31198.13426588891,87824.89968451545,63970.23702436353,30062.800315506458,59282.380344486766],[-7927.621608920044,-23359.05088226357,-9317.009357615285,3603.5546574037703,18528.49329166749,-34736.55899178733,14503.635903087017,49671.79648324669]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"CubeCorners","anchor_set":1,"anchors":[[1800.0,1800.0,4000.0],[-1800.0,1800.0,4000.0],[-1800.0,-1800.0,4000.0],[1800.0,-1800.0,4000.0],[1800.0,1800.0,0.0],[-1800.0,1800.0,0.0],[-1800.0,-1800.0,0.0],[1800.0,-1800.0,0.0]],"real_xyz":[[1161.3418856001845,-1418.6413526679598,1420.535712047434],[-313.82081587383254,1523.974772699636,3072.7274607172108],[-369.7541352651897,-241.01493350882106,2488.465323778944],[448.3660064683545,1261.2880256622884,2399.020074936873],[48.997988245731676,1282.189600045791,1259.1753529079049],[-424.1712432486129,-475.41605742360116,1766.4380808365547],[-1488.8658348133965,-150.69838266637407,1213.1762206266708],[-821.8078698853514,-808.2337882335771,2752.141251500835],[-366.1085914744699,1538.3803421478847,1520.8059247929118],[632.6635679563319,-622.8074250286376,2844.786880640213]],"config":{},"motor_samples":[[-11042.323304584466,6546.290742750478,-15465.051951662801,-39776.261555003344,40433.42472986638,81256.49230174389,29800.831187582735,-36452.96195430553],[-46710.860785706,-57228.74882121281,-19108.187100199848,-13504.743869640533,46938.334932307276,34452.87489916309,87935.73921726823,97294.08722382445],[-27178.59466388487,-35375.431881767436,-41417.947160407144,-32395.19924797316,52568.29985333378,38305.837503027185,28215.7193758903,43421.808929895196],[-49743.19016126023,-37317.01566212036,-12050.646781592282,-20029.3897398233,10141.443224968702,30797.11828471064,76988.09997102428,61972.629794941786],[-28075.67612574314,-27051.38892709645,-4319.872944888931,-5082.333401395021,-12742.979559560292,-9711.979245889012,49663.971220611995,47813.20054575335],[-16597.80717265688,-24626.07918867935,-34917.772439816814,-25660.212715729762,42954.53628241422,25303.424538455474,2163.715180888397,23009.714733739256],[-202.49819299168948,-25710.476619614856,-28847.037108861285,-2463.398457148281,57752.154787520114,-8859.200448816167,-18438.037265379466,52273.91238704941],[-16303.443239694045,-32727.185644585134,-55374.030252074896,-32419.56245195244,81710.64258884589,53935.74356764831,21069.638970794582,54431.64494466951],[-27890.433548102676,-36099.40014993205,-6682.746051104981,-1039.761960567709,4429.382554675874,-17062.430691371013,54846.17777843577,67678.86759176034],[-35143.20544820572,-21736.898437737458,-34910.45818798246,-52507.38267719752,53892.32971875413,75636.5020527448,54252.6444097092,29253.570425350194]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"CubeCorners","anchor_set":2,"anchors":[[1200.0,1200.0,3200.0],[-1200.0,1200.0,3200.0],[-1200.0,-1200.0,3200.0],[1200.0,-1200.0,3200.0],[1200.0,1200.0,0.0],[-1200.0,1200.0,0.0],[-1200.0,-1200.0,0.0],[1200.0,-1200.0,0.0]],"real_xyz":[[-573.8601389570656,-449.6258723988558,902.0440388016362],[-741.2877469533365,501.1910434630256,1235.6378001315516],[-748.109583013746,72.42734524870684,1371.9733318536553],[10.501250050808608,424.99922336738086,359.67593474892556],[-16.11595350015091,-896.7910629675362,2542.6206374937155],[319.7984835529264,-661.6294559727589,2406.95223078884],[-650.0220673746192,-290.822307105532,313.9711703512429],[-257.4710811093644,462.8179227764947,492.48841357960293],[553.969138761458,-145.83561173740293,2125.586990409093],[-652.1452147966063,804.6934824290217,1945.4295403063882]],"config":{},"motor_samples":[[-5521.159180691129,-14096.120096568924,-21838.063900674726,-12135.116540025587,34812.74266995719,11101.316986458794,-14270.26602416368,16786.58903685592],[-15030.745692353086,-28821.63407174415,-19094.836264882786,-7371.979176477161,27716.604902586485,-7992.0991834804,17776.038687381068,45771.028027890796],[-14044.072588307512,-27666.11233672651,-26165.799088265125,-12893.972133909527,36835.85462271953,5270.5022128655,8884.801427094473,39411.80405911671],[-8707.071652247385,-8553.12218644672,-2608.2414277022644,-2749.002806754519,-9051.276508664821,-8387.071350192427,14089.116776413532,13608.010392538969],[-21558.61837820621,-21856.758268494737,-43200.83830903742,-42672.371900515674,71736.1384096722,71294.14642066201,44158.99763922133,44701.25753666882],[-27446.974095018817,-21193.557408604433,-35344.82998385682,-44848.06298758725,57935.05354168947,67267.42997874506,47173.8574313463,36152.61478545593],[2251.117916628189,-6399.279994943354,-10658.582727439412,-1481.8326168007254,27388.352849377632,-3019.440074408754,-22857.800998618448,15152.625049865677],[-8969.627121920541,-12890.718123184364,-6007.607756149724,-2472.729294126168,335.86312856526104,-15665.104177411768,10793.400604649407,22224.353130089075],[-34526.08357778009,-22593.86965730209,-25428.192094857,-38394.18375369854,35309.843951198236,53922.808772616234,49297.44887371269,29847.07585303538],[-26179.964244333587,-42456.05018188386,-23173.726646148443,-12025.08864088696,39958.973305075255,14144.351321589353,45174.78386236217,65283.72556410963]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/larger_baseline_HP5.jsonl b/ai_docs/datasets/larger_baseline_HP5.jsonl
new file mode 100644
index 000000000000..0d76ca0beacc
--- /dev/null
+++ b/ai_docs/datasets/larger_baseline_HP5.jsonl
@@ -0,0 +1,3 @@
+{"dataset":"larger_baseline","geometry":"HP5","anchor_set":0,"anchors":[[0.0,-2000.0,-120.0],[2000.0,0.0,-120.0],[0.0,2000.0,-120.0],[-2000.0,0.0,-120.0],[0.0,0.0,2000.0]],"real_xyz":[[-576.5595949917629,592.7458989886723,332.3847597668903],[-179.36706696996282,-215.41772144174416,1126.970767229225],[-597.5654793465059,123.07208962332584,989.006493849326],[-191.43249959513935,169.46574460400814,1596.9910715277888],[-677.8161815912724,-18.710569564673847,1111.0102919876592],[186.62356390895195,-99.24100885948312,1499.0694572097063],[-407.09652577420286,-267.95696906462183,1229.0528490942177],[-539.1293146899854,-79.82639646010671,213.0152139028341],[952.3546904036702,-340.81289963895085,401.56522007466464],[-1418.2636804247322,62.76369114770591,159.16026483364448]],"config":{},"motor_samples":[[13483.639377704085,13247.852740980856,-8160.560391518396,-7766.815165968442,-5553.292289786245],[3487.9820687992897,10074.627157628172,10631.021495308756,4131.518104311476,-41930.08202222839],[9069.143889860852,16084.446785734544,4969.561977755122,-4223.901075672851,-31902.170079948995],[15030.809513403286,15340.333007146912,9879.164663811358,9518.368293241076,-58761.53737319916],[8288.747346463564,18441.525504823498,8893.041655297437,-4018.1778642302684,-34390.16824082197],[9713.432296379853,8296.04093118247,12765.255041348031,14037.321542072705,-56187.98337900224],[4350.785740500128,15011.631531526638,13008.774567083206,1802.6059664267098,-42249.58766701236],[349.4861183846457,10896.120466660415,3319.667562109588,-9800.731977372092,-5219.388545606791],[-484.9783201099131,-15323.887225389532,11253.576314388185,19817.313678802686,-4488.58267527903],[10049.071045429466,27934.48451814451,8042.977373714195,-26296.48479752229,12441.190076351726]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"HP5","anchor_set":1,"anchors":[[0.0,-2500.0,-150.0],[2500.0,0.0,-150.0],[0.0,2500.0,-150.0],[-2500.0,0.0,-150.0],[0.0,0.0,2300.0]],"real_xyz":[[125.4798355094448,424.99875596519007,1694.9579991854027],[646.0190309384813,214.54666339748184,1422.040858293242],[1119.200659416533,-1.5976476440060594,1046.9906190729414],[-179.6072223508204,555.4271254745756,474.9236832289738],[1403.961521921532,-163.2296722106178,594.8709539808148],[-829.9185736161514,-257.5531569536049,613.6395089816716],[627.1316866722686,-788.2471600705229,-89.45309919402325],[538.1323543865246,-1142.5325148800948,42.984147924686056],[-212.41955197057996,-1108.3683095053045,539.2156131611382],[-101.74297492132928,-88.86474068228017,357.65061247941355]],"config":{},"motor_samples":[[18682.360024529287,10309.882892540913,5107.88205011744,14298.654866450432,-59863.3183178738],[13628.891349519135,-1480.284981605932,6610.691073250778,19917.56441406424,-46168.64889164411],[9425.242845737257,-13346.973024541043,9477.487794814619,25588.406735965054,-24428.70602556539],[12084.846862863487,5891.818299200182,-8858.738026203744,-759.1573641704423,-15016.487307906338],[6191.783059043646,-22820.735585301467,11645.737752067866,28851.279435383258,-3818.7050773231167],[73.64056026671267,18006.051756104313,9256.84357059009,-12687.38948830424,-15805.594686361836],[-13253.413469014953,-9202.9231085686,16476.65986494015,14075.322666525231,11330.439160003696],[-20062.12007873462,-4452.917956013649,23132.45922439056,14586.161949560912,11028.760278177766],[-18255.05496738173,9859.785022892296,22987.286960235397,2477.9144342973295,-8325.156739594438],[-758.3106210936004,2873.0924199426036,2635.8579760847656,-1013.6096943679287,-13800.119313143037]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"HP5","anchor_set":2,"anchors":[[0.0,-1800.0,-100.0],[1800.0,0.0,-100.0],[0.0,1800.0,-100.0],[-1800.0,0.0,-100.0],[0.0,0.0,2100.0]],"real_xyz":[[-555.78938929645,-360.99219607099644,422.1798545660755],[-47.04943078063252,-759.0039648611917,432.07154310890047],[-511.9870026771316,336.383662208861,866.9166038451252],[1076.6462526440346,-263.6609141582357,283.2415916758149],[138.4692227261213,-281.8812223074427,1338.4829640839016],[-305.3606989372959,-251.60742634737437,1355.7639790793912],[60.89259195949546,205.20305991804696,1093.4049362884682],[-753.0646916701655,274.3095518069641,272.59210107906824],[1227.7514052697493,-58.317904624863445,99.61254556417884],[-307.6533719660548,-330.93381834819246,1094.029261485149]],"config":{},"motor_samples":[[-3422.438660423864,12433.224192774567,9533.84285186396,-7930.629630893466,-11645.687907269417],[-12323.185617136543,5138.321813833412,15847.803455206025,3502.00901461686,-10506.41475640405],[11658.76972601541,14169.735032967668,389.5585231811592,-3174.31674433144,-28279.978565415495],[2098.214215429306,-18366.650452018832,10851.18444398293,21731.729210845933,784.2023188946994],[5634.4140968940155,8008.264125642871,14282.97805670722,12246.83812833262,-49360.331278915364],[6595.178165442686,15021.362232646852,14278.92237010737,5684.595842986176,-48710.46214701609],[10367.857034831506,6158.154743294255,3679.731020504765,8137.980539045317,-41455.54402160036],[8486.21421307809,15465.515588929758,-1216.4146454974887,-12818.833746404975,-4208.959077563526],[6566.863796845106,-23170.112488195045,8450.715484975199,24107.34757786675,9510.940282915748],[2157.077967747324,12532.179749567767,12866.527625043896,2584.7240066584463,-38742.60432245676]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/larger_baseline_Slideprinter.jsonl b/ai_docs/datasets/larger_baseline_Slideprinter.jsonl
new file mode 100644
index 000000000000..15b098d0b2ef
--- /dev/null
+++ b/ai_docs/datasets/larger_baseline_Slideprinter.jsonl
@@ -0,0 +1,3 @@
+{"dataset":"larger_baseline","geometry":"Slideprinter","anchor_set":0,"anchors":[[-1000.0,-577.0,0.0],[1000.0,-577.0,0.0],[0.0,1154.0,0.0]],"real_xyz":[[176.76235468171672,806.6212284216593,0.0],[-628.3080789679709,-311.73204060879743,0.0],[822.9826004034139,-451.5641372586201,0.0],[92.72422894295104,518.1123723801613,0.0],[84.37983548581741,104.03865844449979,0.0],[-161.1942828606986,-304.9045687899181,0.0],[-85.7251335177038,-269.2450826120734,0.0],[92.2748316503351,-199.60410560039327,0.0],[863.4406402474013,-392.49544255808405,0.0],[60.84532501289118,-173.87089019578605,0.0]],"config":{},"motor_samples":[[12920.433583403035,8843.573732133018,-14855.680504407312],[-13561.553558156142,9661.216220124952,8593.755308249347],[13134.403200807603,-18200.65902756822,12690.720694855852],[7653.280907812094,5211.8387275308005,-9946.276566341732],[2451.592267972931,-264.8890782573829,-1963.8353932933076],[-5311.561575876864,736.650285301055,6115.714899055682],[-3700.4108786162446,-512.3139841165361,5296.632341794783],[17.081441012467497,-3342.3507020832085,3948.6945198267945],[14020.67437665543,-17960.18017981915,12021.019169555131],[-387.35337916580085,-2584.040989020828,3412.6462086764723]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"Slideprinter","anchor_set":1,"anchors":[[-1200.0,-692.4,0.0],[1200.0,-692.4,0.0],[0.0,1384.8,0.0]],"real_xyz":[[-364.40435286328176,121.37453016666075,0.0],[-712.2257186386287,149.03739498222137,0.0],[-115.01061856460902,411.8206480985151,0.0],[-210.1433327494264,-403.4326779043622,0.0],[-674.7741403006316,-195.81785829216255,0.0],[17.281092904569107,53.48268204312774,0.0],[441.3240709174626,-551.7632659511835,0.0],[632.2084233344635,-315.2770279293172,0.0],[-286.79441456424576,681.6360494245703,0.0],[641.8570299798251,254.85043731088075,0.0]],"config":{},"motor_samples":[[-4270.292962150596,7368.617555114241,-1368.1019013107216],[-8033.297922115864,13740.14899716644,803.9118182947014],[3164.0308761416873,6464.994289107552,-7882.988700858607],[-6898.166931223412,1044.2617669504505,8106.440233525148],[-12880.828798874922,10809.398021201208,6500.823336005608],[817.9391682645189,245.99720015440553,-1043.6245032302343],[5091.020761279984,-11937.974510642118,11737.102929258026],[9463.822442849189,-13677.208085042355,8364.956239920728],[5134.035176515089,12473.724312310738,-12164.627354369732],[13387.593317772713,-5587.482172237825,-1687.2724241423173]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"Slideprinter","anchor_set":2,"anchors":[[-1500.0,-865.5,0.0],[1500.0,-865.5,0.0],[0.0,1731.0,0.0]],"real_xyz":[[-280.4232228980667,454.87093541941476,0.0],[-709.5065216885973,-597.4011395386945,0.0],[409.1258184663736,697.812957794552,0.0],[-345.4863346057438,-357.89022180566684,0.0],[1062.5651889535773,-467.4954078885564,0.0],[-242.23010677517487,587.6606072938107,0.0],[-598.094577704399,-776.4560686240792,0.0],[577.054714682534,-179.1356021423652,0.0],[-953.7373647141476,-44.43134166540142,0.0],[-518.8569150036393,185.27486567631695,0.0]],"config":{},"motor_samples":[[1269.5981832540417,9455.345469031561,-8262.075537633988],[-17421.344391005307,9628.046514561149,13726.679111311336],[14365.970292406655,3379.4869993559773,-12058.274168362717],[-9157.087749652788,3545.13206794716,7529.654081627579],[16830.52861691736,-22123.691290690276,13870.029233609466],[3695.788816756669,10474.424099511041,-10937.119106826012],[-16047.486571127252,7145.207092716193,16542.306115816424],[8887.057380957998,-11310.483732375715,5147.840067328306],[-14508.220611195862,16716.360020516284,5496.654986796774],[-5733.891880696404,10615.883178241671,-1968.2979409865643]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/larger_baseline_Spidercam.jsonl b/ai_docs/datasets/larger_baseline_Spidercam.jsonl
new file mode 100644
index 000000000000..66e0a2592e95
--- /dev/null
+++ b/ai_docs/datasets/larger_baseline_Spidercam.jsonl
@@ -0,0 +1,3 @@
+{"dataset":"larger_baseline","geometry":"Spidercam","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0]],"real_xyz":[[980.0803451631423,-14.377673494448572,1120.4313374021765],[1297.9455472925224,119.53472895415666,1018.9940391345198],[-336.3055778169024,509.25388293853416,524.6657353245921],[671.3750892387893,997.795777807185,1482.8540908980017],[-163.0077670877963,-927.9015895009527,1341.4040977064235],[687.4704053858272,-223.64344226665116,1873.8136153281382],[-1186.173348874489,-728.714028231471,750.3375286437315],[1251.051107672089,-1184.170307062321,781.3599408189854],[-1218.3619917244473,362.7916543974434,1963.560138855575],[-401.6440960914779,-1205.47823569393,1374.5281995677879]],"config":{},"motor_samples":[[-23771.0198425873,-6563.891920085681,-6787.334575664288,-24062.355323198473],[-24191.77419782323,-2085.5429521876526,-353.4624679730875,-21808.21108728209],[-8941.48794133275,-14554.447673321196,-6217.374096963969,-1183.064016890008],[-35911.13728143184,-21098.85152723464,-4230.413065066947,-15099.089147443492],[-8626.75389760051,-11276.713614770646,-28887.7921796729,-25385.474338957523],[-30763.40959041437,-16861.988925719765,-21025.516376540963,-36224.19136381537],[6827.434602737422,-10499.29552923243,-23687.212190838138,-3361.511843332865],[-5151.427288211521,11998.846405928858,-4139.400304823014,-26095.21396342807],[-14956.460730238832,-41771.797935487026,-32189.770480279334,-8892.39730070145],[-3157.2642974969976,-9365.053980265793,-32589.207033067774,-23784.021922224514]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"Spidercam","anchor_set":1,"anchors":[[1800.0,1800.0,4000.0],[-1800.0,1800.0,4000.0],[-1800.0,-1800.0,4000.0],[1800.0,-1800.0,4000.0]],"real_xyz":[[-1051.7483719467841,-234.48244635150172,1392.9928083836057],[-892.5237232873144,1093.251023963489,2416.3681585780205],[-93.93538200713829,-321.0069980728954,548.9276370977148],[329.723365576383,13.286236897906292,3097.2194109633547],[1500.5117400258468,990.7049313952843,2973.4280392453966],[-13.472875736242713,-403.8969406995616,1732.7686200408082],[99.9762407367432,1016.6297424239565,683.220356026899],[321.78846394611264,1299.167305488315,911.884858791474],[-678.8375865689652,1095.086720561279,2285.9772598185787],[1489.487815658274,454.667953124429,3237.8652561832837]],"config":{},"motor_samples":[[-7299.864362358216,-26208.664957042627,-31198.334970275733,-11141.159643035435],[-29822.477981456304,-53697.280655612245,-25613.088448508912,-9416.281958326494],[-5269.315847257814,-6753.416692044081,-12024.822947144572,-10448.258949390429],[-43643.38330719093,-35218.18947694507,-34904.564249113406,-43275.90913712308],[-65422.90188616545,-23113.753908486487,-5829.776171015476,-33948.93891479089],[-21288.888970818447,-21546.571187885696,-29753.509643218644,-29462.74863025275],[-18141.58630645718,-16332.380057255274,118.21060674434874,-1370.148390611675],[-24873.499490007194,-18684.18016027671,2346.508103934017,-2413.448575180072],[-31895.850244310335,-49711.96949848872,-23190.98080775515,-10944.349515643604],[-60948.79444897398,-21477.163021243497,-13255.358255105422,-45251.406601613744]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
+{"dataset":"larger_baseline","geometry":"Spidercam","anchor_set":2,"anchors":[[1200.0,1200.0,3200.0],[-1200.0,1200.0,3200.0],[-1200.0,-1200.0,3200.0],[1200.0,-1200.0,3200.0]],"real_xyz":[[653.6967704781443,349.33596986727184,655.9705966420397],[-572.9336267776469,726.0594238281737,1001.417437406767],[372.8715650534441,-129.24856227007137,1302.437023095733],[-978.8499199394845,644.6448896863099,947.4787141114076],[-325.73309839702415,-856.7961975114675,1699.1049836013992],[557.2243008774553,22.082524568488793,1346.5037193969517],[544.2142512612888,-806.5539866170868,1498.2040109360544],[497.76731441978313,-267.3845829188999,2302.7131431788634],[-86.36964483213205,-768.2072112781044,2544.536753337394],[-88.19853421893527,505.5782571908551,387.8076939336375]],"config":{},"motor_samples":[[-17204.181449206713,-7041.897230392676,-2225.693055566364,-11557.997471359695],[-14741.097601324018,-24984.3668841343,-12304.87800043853,-3972.418052379557],[-22556.71107829217,-15972.551972006524,-18162.175872018466,-25058.034003471315],[-8555.508595960026,-25069.83702425823,-13654.958082503841,268.3774077080312],[-12713.90019487138,-18061.700375630866,-35840.52897311078,-28197.51417031425],[-25873.896377767116,-15732.951642736009,-15369.017750534078,-25429.14235344995],[-17685.91592879683,-9060.740919256765,-22389.78915142723,-34013.79470292624],[-34160.80441980736,-23389.693098879543,-28828.07374887042,-41559.50352153291],[-22922.916905397033,-24590.750662329145,-43670.28551931022,-40902.3583656439],[-8812.005052868693,-10123.830343509124,-2939.9515251076677,-1761.5903252334763]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/near_singularities_CubeCorners.jsonl b/ai_docs/datasets/near_singularities_CubeCorners.jsonl
new file mode 100644
index 000000000000..c7bc8e082930
--- /dev/null
+++ b/ai_docs/datasets/near_singularities_CubeCorners.jsonl
@@ -0,0 +1 @@
+{"dataset":"near_singularities","geometry":"CubeCorners","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0],[1500.0,1500.0,0.0],[-1500.0,1500.0,0.0],[-1500.0,-1500.0,0.0],[1500.0,-1500.0,0.0]],"real_xyz":[[1499.9287144429502,-1475.6373582138544,-500.0],[-1499.9277326493143,-1434.5819708286708,-500.0],[-1499.9287555873939,-1477.369564510202,-500.0],[-1499.9000000523845,-1.535246730929641,-500.0],[-1499.9000019737134,-9.423794292524429,-500.0],[-1499.9000617282557,52.72546975752796,-500.0],[-1499.9265950329577,1387.6361032207526,-500.0],[-1499.925829729717,1356.3971424564882,-500.0],[-1499.9284813539134,1465.842308888215,-500.0],[25.881850936320518,-1499.9000148846656,-500.0],[-16.101347882175816,-1499.900005761457,-500.0],[-117.52756582692406,-1499.9003055838814,-500.0],[-1499.926331517984,-1376.850100559418,-500.0],[-1274.4589589151092,1499.9237941288518,-500.0],[1499.9167773451923,999.2560885642092,-500.0],[31.482586166734894,1499.9000220212874,-500.0],[-57.58590973382795,1499.9000736203734,-500.0],[-125.45505662877093,1499.9003479766127,-500.0],[1402.2531946675983,-1499.926950891391,-500.0],[1392.035364066166,-1499.926702287827,-500.0],[1378.0137859685065,-1499.9263599854946,-500.0],[1499.900100497393,-67.29491719230272,-500.0],[1499.900191657584,-92.99622740414043,-500.0],[1499.9001984067122,-94.62426989952272,-500.0],[1406.660258275214,1499.9270578947137,-500.0],[1499.9281741349218,1452.9784130820674,-500.0],[1499.9247521532968,1312.8292177667217,-500.0]],"config":{},"motor_samples":[[17436.247742453597,33825.93759654397,17722.519734440775,-1814.9852281093138,35135.03025400555,84502.09974910154,36085.41094906294,-62390.14373404514],[33413.61777959018,16957.856577472034,-1806.018006495104,17729.737604897775,83349.59977961838,33536.58089603623,-62251.24444760865,36109.31508751255],[33843.428814325074,17456.52827112874,-1815.18327279603,17722.36055725018,84550.91825217071,35202.5077772285,-62393.210010296774,36084.88375419206],[22051.526233622073,3479.1065745643955,3457.981864878323,22034.190965339447,49967.70111788888,-20912.766814518665,-21025.314500696448,49913.73460319807],[22096.212830377,3533.553247745141,3403.883844398913,21989.804022645385,50106.761322786864,-20623.48766326804,-21314.337179712446,49775.49998932447],[21750.010408239574,3111.421708895947,3836.868597650247,22345.33436871876,49027.37119332589,-22897.44361981903,-19032.391136816495,50880.59026174042],[17746.09183810375,-1785.7173190220385,16416.24860385926,32947.45444622191,36163.46654078661,-61939.69399898687,31710.809897687068,82042.6005653515],[17761.761623957485,-1766.272742881065,16059.097041611365,32640.430425334886,36215.33804726388,-61645.584009633756,30497.105432301545,81179.4197741341],[17723.64127815573,-1813.5906629820179,17321.71426779346,33727.17440255568,36089.1254628531,-62368.52910401702,34753.521776940615,84226.33902335037],[21897.89431900826,22190.136591062397,3647.9522706759394,3291.8282124788143,49489.01983771928,50398.790515528264,-20019.37395315777,-21916.726739424794],[22134.207787171563,21952.39985912191,3358.287114545788,3579.837375900487,50224.93689597103,49658.9521405122,-21558.84497247345,-20378.474176574517],[22730.175927805718,21403.407035199187,2691.0162020058447,4302.3753734351885,52071.36409824124,47941.95745376407,-25256.57810826766,-16641.711466396166],[32841.159094106566,16292.638170699169,-1779.5395584493706,17751.069915211523,81743.97199248848,31291.63925264792,-61845.79647765925,36179.94685560735],[15134.86162441423,-1692.7622661816806,17821.024076069163,31847.32647930571,27318.303005754544,-60569.79217259106,36411.393504359585,78940.70952854444],[-1215.4705757510098,18211.851916436586,29316.98536341008,12169.590951619088,-54508.31302393668,37699.64743121209,71706.1263447788,16694.112743722188],[3253.9456949450173,3687.130498676918,22222.3125404198,21866.83198397026,-22121.532756115055,-19813.614370699826,50498.75421140728,49392.12433608417],[3871.3821658605143,3079.0703957271558,21723.502764391127,22373.700385745607,-18853.468678836773,-23074.772762120414,48944.53076263699,50968.5509304169],[4360.561976153046,2640.640506425865,21362.020163413596,22778.238473422196,-16348.503413603927,-25544.119765454067,47812.026527984955,52219.69006143473],[17740.07337443759,33091.98775118616,16584.258768512645,-1793.1869684948063,36143.54014655989,82448.29357979842,32279.050213979874,-62053.79840003143],[17744.19237091955,32990.895811456445,16466.75434949073,-1788.0746888540505,36157.17785077035,82164.580630278,31881.809180409102,-61975.6369958754],[17750.510893723906,32852.61254929314,16305.95936148598,-1780.233275326191,36178.0962382091,81776.16048588153,31336.857367433644,-61856.31921386018],[3939.4141970163687,22430.605967573843,21670.79964351808,3016.2515179411266,-18495.867698915845,51144.91824131032,48779.742277538564,-23429.476320694946],[4123.879868572939,22582.803164535955,21532.88105415798,2848.5483979095816,-17548.020035856407,51616.02136526622,48347.98126840412,-24365.38475843414],[4135.652592427331,22592.520114394163,21524.222765771592,2838.016724457615,-17487.920212757686,51646.06912598317,48320.85051877051,-24424.5943166123],[-1795.235281129935,16635.025223771187,33135.67339946502,17738.423149798917,-62085.19702315352,32450.416507241294,82570.8338678464,36138.07611145942],[-1811.0500855439534,17725.685873515074,33597.840127673124,17171.675129086903,-62329.13819125953,36095.89691539811,83864.93635064716,34252.62533288352],[-1731.2404219303,17790.000139112886,32216.510252751512,15565.383286578148,-61126.0288061895,36308.78204038669,79984.43705578453,28806.03029398178]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/near_singularities_HP5.jsonl b/ai_docs/datasets/near_singularities_HP5.jsonl
new file mode 100644
index 000000000000..6be3aaea50a2
--- /dev/null
+++ b/ai_docs/datasets/near_singularities_HP5.jsonl
@@ -0,0 +1 @@
+{"dataset":"near_singularities","geometry":"HP5","anchor_set":0,"anchors":[[0.0,-2000.0,-120.0],[2000.0,0.0,-120.0],[0.0,2000.0,-120.0],[-2000.0,0.0,-120.0],[0.0,0.0,2000.0]],"real_xyz":[[964.1235747453284,-948.5095865754266,-27.497151],[-719.5187593752305,-688.1722481719395,507.741532],[-497.5406036084379,-490.0575058255245,953.040004],[-1859.8180608111313,-1.9036466416990947,26.4689901],[-1371.4539342118287,-8.616774278737623,537.019049],[-868.2739227475189,30.522133856254673,1047.17018],[-1000.8797009212224,925.9498515316079,-42.5453256],[-726.4620750668811,656.9465390840625,533.480869],[-462.56843732482224,452.0564777695172,1030.39159],[32.42989399170206,-1879.3709383667888,-26.6148823],[-14.851928971388142,-1383.5120210286118,517.628213],[-69.09574343697072,-881.8078207139725,991.936222],[-968.0861139513448,-888.6499525580892,31.7537695],[-667.8906291657761,786.0473180040354,458.719776],[539.6755933059526,359.536029335557,1046.72968],[39.64552670559763,1888.8005598981758,-44.2588518],[-51.72433907082231,1347.2278260235173,517.004705],[-74.61369067825252,892.057312151936,975.222737],[899.7227124027092,-962.392775993517,26.0515823],[664.9902401977811,-716.5310909342946,535.481389],[467.3753481166266,-508.72394150601525,965.228753],[1843.6122836146938,-82.71599949851364,-42.0139801],[1308.1156503742407,-81.10527698424995,527.319817],[888.7724932051186,-56.07002943639088,998.360926],[894.1701395382921,953.4569408390662,41.4092948],[726.950777402476,704.1962442956373,482.878157],[512.2444994842339,448.34885523274727,981.665044]],"config":{},"motor_samples":[[-11161.737693472285,-11588.603609099539,21508.7191833734,21706.062559807022,16982.413058946484],[-7417.011706250797,17016.383086339174,16587.137712823627,-8176.910045967866,-8077.958038967336],[-1671.6976749617181,14811.342262855685,14705.085822618135,-1824.0819790847688,-28775.672567091846],[14253.451944580484,36463.978951386525,14307.985239143874,-34855.56495200253,27495.95099339441],[9791.324255415735,28026.436492669112,10059.569704794807,-21299.83908526662,-152.34814120698198],[9639.074857748097,21376.970352583623,8674.08462773652,-7512.053062294377,-27832.737891983536],[21309.474353972157,22253.87467135436,-10375.00506486851,-12425.848197009735,17755.326067665377],[16159.834922345659,17114.487582565853,-6672.114047892819,-8342.009904817127,-9258.282342048624],[14529.285067673623,14678.967488348046,-401.0549863559952,-608.387576844186,-32352.33640802336],[-35748.16130341724,14035.633628779355,36820.35779962462,14960.967232275316,29688.610284671366],[-21752.04698020673,10188.260831039377,28188.205167797336,9726.2042923916,607.0525719347571],[-8387.791111599938,9857.522017102965,21236.57155381921,7655.084297060481,-25780.174983177643],[-10151.714225518252,21478.530981901993,20464.232890417636,-12312.288392646838,14222.17443075793],[17962.3480781512,16354.342310160511,-9767.284947214603,-6855.531746475502,-5722.854291997391],[13339.963632944318,-1964.0796047920746,1563.3723690381082,15904.195421391214,-32844.09211245218],[37000.404255145426,14050.759998446038,-36047.791303988364,15179.58007300062,30510.88616589706],[27490.961744690263,10381.700041726417,-21226.07241330118,8760.004837018405,-228.49928412971568],[21309.898533991298,9873.716305448854,-8743.719621544758,7491.805765842469,-25015.058272902334],[-12101.721413693595,-10396.138647117537,21428.92749258739,20629.457975514393,14480.182328620034],[-8104.454801757123,-6867.1707175798865,16975.39400536101,16267.391846745024,-9363.199474992534],[-1972.7370133419358,-1134.7394679081199,15025.760061958437,14438.351289566795,-29327.937148530887],[12831.281636019452,-35027.57434536561,15212.108621784682,36122.07882366046,29345.809135634743],[7939.447967365655,-20482.14040192068,10500.402043333514,26784.856695684713,-1398.0808589532498],[7968.4727833785455,-8425.982447422655,9751.918738891605,21404.455259695646,-25846.985136985655],[21244.544147598892,-10397.11746676472,-12007.947760588275,20486.229131087675,13757.143036639143],[16815.39845959438,-8344.368005792414,-7788.021077231383,17126.0748843605,-6919.80928953442],[14245.236329414882,-1932.5528207053603,-646.410084294978,15153.492520982467,-30070.223131602375]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/near_singularities_Slideprinter.jsonl b/ai_docs/datasets/near_singularities_Slideprinter.jsonl
new file mode 100644
index 000000000000..8834964aec10
--- /dev/null
+++ b/ai_docs/datasets/near_singularities_Slideprinter.jsonl
@@ -0,0 +1 @@
+{"dataset":"near_singularities","geometry":"Slideprinter","anchor_set":0,"anchors":[[-1000.0,-577.0,0.0],[1000.0,-577.0,0.0],[0.0,1154.0,0.0]],"real_xyz":[[586.4270593216361,-576.929868913055,0.0],[-603.2103050900729,-576.9308810443885,0.0],[-585.7394510045932,-576.9298271158324,0.0],[-666.9611098795624,-0.6826787542929805,0.0],[-668.9952596093234,-4.203262684803123,0.0],[-653.2977148581732,22.965149336501185,0.0],[-434.3922987065864,401.87195736273213,0.0],[-437.82506324286135,395.9293539104272,0.0],[-426.0299978463784,416.3483815808851,0.0],[9.954823683066722,-576.9000148846653,0.0],[-6.192991299629174,-576.9000057614569,0.0],[-45.20413015962975,-576.9003055838813,0.0],[-628.5041940857675,-576.9323763742656,0.0],[-396.7838127242334,466.97893068040815,0.0],[481.31019424972703,320.6525517657939,0.0],[23.370900117838755,1113.4413613848028,0.0],[-41.54087306862511,1081.9861813745736,0.0],[-84.30722642226766,1007.9501109459678,0.0],[539.3580397342089,-576.9269508913909,0.0],[535.4277451249861,-576.9267022878269,0.0],[530.0343395233945,-576.9263599854945,0.0],[684.3060742773087,-30.702258495355885,0.0],[691.332854042849,-42.86375031092699,0.0],[691.7828268669383,-43.642533677138715,0.0],[412.4717099617616,439.8201162989721,0.0],[427.38328862541647,414.0056191976659,0.0],[442.7042525159753,387.48282318708567,0.0]],"config":{},"motor_samples":[[8422.97303122711,-14395.107511357844,13150.130444098626],[-14720.142473686305,8750.976431855051,13256.939348679205],[-14381.78995532293,8409.53565988737,13145.812137474179],[-9508.62919588482,11891.110084464386,3494.5815960618925],[-9587.531495817593,11906.308408815976,3573.8874964739866],[-8978.576621500139,11793.619096490449,2961.9466863423986],[-470.66779645911186,11358.777924126312,-5557.234316031442],[-604.3113190220336,11348.979644996745,-5423.841460914485],[-145.0779162091821,11384.855291994323,-5882.154375654776],[-2817.710548907215,-3205.0598065546956,11258.710636427457],[-3131.872929544772,-2890.9001933520026,11258.36716430817],[-3890.7347620398127,-2131.8032978255933,11269.702520948105],[-15209.920417561041,9245.38766247929,13422.978975620757],[993.9780779740931,11500.585807954269,-7018.207666684972],[11270.722293219644,-2296.6211383611403,-3733.48289025277],[16049.0536751061,15582.64685757531,-21478.363457570795],[14870.849118454236,15711.155611020735,-20776.684707512202],[13196.282449894536,14957.209429200333,-19124.37631424999],[7503.305456772669,-13483.314274946775,12865.119544229658],[7426.527658267272,-13407.163925110084,12842.301577949042],[7321.1719514546785,-13302.661700942868,12811.237580037863],[12026.357679491066,-10181.339535061616,4170.892676238711],[12084.776353592542,-10453.815614546493,4444.930199704881],[12088.588150001875,-10471.263107850102,4462.479700711125],[11433.77492491108,382.9128349331639,-6408.880750649555],[11380.422944411503,-197.77185834063852,-5829.574524209625],[11335.962135349258,-794.2539591371271,-5234.2307733745165]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/near_singularities_Spidercam.jsonl b/ai_docs/datasets/near_singularities_Spidercam.jsonl
new file mode 100644
index 000000000000..45ec2b4a8031
--- /dev/null
+++ b/ai_docs/datasets/near_singularities_Spidercam.jsonl
@@ -0,0 +1 @@
+{"dataset":"near_singularities","geometry":"Spidercam","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0]],"real_xyz":[[1499.9287144429502,-1475.6373582138544,200.0],[-1499.9277326493143,-1434.5819708286708,507.741532],[-1499.9287555873939,-1477.369564510202,953.040004],[-1499.9000000523845,-1.535246730929641,200.0],[-1499.9000019737134,-9.423794292524429,537.019049],[-1499.9000617282557,52.72546975752796,1047.17018],[-1499.9265950329577,1387.6361032207526,200.0],[-1499.925829729717,1356.3971424564882,533.480869],[-1499.9284813539134,1465.842308888215,1030.39159],[25.881850936320518,-1499.9000148846656,200.0],[-16.101347882175816,-1499.900005761457,517.628213],[-117.52756582692406,-1499.9003055838814,991.936222],[-1499.926331517984,-1376.850100559418,200.0],[-1274.4589589151092,1499.9237941288518,458.719776],[1499.9167773451923,999.2560885642092,1046.72968],[31.482586166734894,1499.9000220212874,200.0],[-57.58590973382795,1499.9000736203734,517.004705],[-125.45505662877093,1499.9003479766127,975.222737],[1402.2531946675983,-1499.926950891391,200.0],[1392.035364066166,-1499.926702287827,535.481389],[1378.0137859685065,-1499.9263599854946,965.228753],[1499.900100497393,-67.29491719230272,200.0],[1499.900191657584,-92.99622740414043,527.319817],[1499.9001984067122,-94.62426989952272,998.360926],[1406.660258275214,1499.9270578947137,200.0],[1499.9281741349218,1452.9784130820674,482.878157],[1499.9247521532968,1312.8292177667217,981.665044]],"config":{},"motor_samples":[[6829.809161635718,24819.53395787215,7149.537347005144,-15436.154278144284],[20746.912199524693,1905.9597816271335,-21373.089318249025,2812.8300622991906],[16441.806319277905,-3409.4501459948783,-29968.474918497774,-3074.1790262006534],[11957.169113947428,-9113.443006993459,-9138.161131093528,11938.013592905256],[7514.172210243705,-14933.381702078068,-15098.533167592763,7390.768358263814],[841.1619676784758,-24159.856239799825,-23096.91428390186,1582.91836149037],[7175.8537518386265,-15401.01585604269,5688.648216317641,23868.920562233623],[2496.9456800105795,-21816.894118373133,484.44435150960317,19585.774145127318],[-4037.568861065683,-31453.995740737515,-4551.019262007715,15530.80928980023],[11787.379788750002,12110.307602062727,-8915.960078008682,-9332.660420632916],[7809.192472298244,7598.930753012906,-14820.731933146348,-14539.97764790721],[2694.7779852543986,1054.3550558055015,-23854.548072244233,-21523.61350367204],[23753.809985381034,5550.143110721706,-15393.584999102131,7181.411180274391],[455.505855671342,-20279.062684654782,3596.8612629456848,19562.185008487613],[-30800.19437782146,-3615.634865855482,10110.14728240807,-11488.784484870605],[-9377.026111515917,-8870.158325371838,12145.849316353155,11753.043605873283],[-14160.515401180417,-15164.35473785916,7342.153602998031,8094.031378858041],[-21169.18325307928,-23645.30736818057,1200.4854534403678,2947.4306784054374],[7169.13476102649,24025.40966190566,5876.828965733478,-15409.998026036492],[2448.8408936533483,19956.888952435944,939.6930792352846,-21884.583431588748],[-3191.8852405700695,15154.912939046328,-5023.89451265762,-30148.713549632674],[-8574.02256039675,12375.870629011084,11536.295393774342,-9657.350431310697],[-14015.769486504196,8202.606147901542,6986.736249959381,-15640.930395302532],[-21867.147331655684,2450.7786130867253,1128.7061065308292,-23747.673886811488],[-15412.460412998695,5933.673500195986,24072.70207767447,7167.292438097652],[-20899.667726007556,3151.165540416032,21236.751536360163,2503.1647806620426],[-30387.868576149303,-3347.771321505079,14237.123196439286,-6183.288438229188]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/outside_singularities_CubeCorners.jsonl b/ai_docs/datasets/outside_singularities_CubeCorners.jsonl
new file mode 100644
index 000000000000..8b329851e87e
--- /dev/null
+++ b/ai_docs/datasets/outside_singularities_CubeCorners.jsonl
@@ -0,0 +1 @@
+{"dataset":"outside_singularities","geometry":"CubeCorners","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0],[1500.0,1500.0,0.0],[-1500.0,1500.0,0.0],[-1500.0,-1500.0,0.0],[1500.0,-1500.0,0.0]],"real_xyz":[[1500.0712855570498,-1475.7776203877443,-500.0],[-1500.072267350686,-1434.720208739894,-500.0],[-1500.071244412606,-1477.5099102785375,-500.0],[-1500.0999999476157,-1.5354514440340674,-500.0],[-1500.0999980262864,-9.42505085739961,-500.0],[-1500.0999382717441,52.73249594875085,-500.0],[-1500.0734049670425,1387.7719223771846,-500.0],[-1500.0741702702828,1356.5312882131288,-500.0],[-1500.0715186460866,1465.9820956295314,-500.0],[25.885301566129517,-1500.0999851153347,-500.0],[-16.103494747986616,-1500.0999942385429,-500.0],[-117.54318932137812,-1500.0996944161188,-500.0],[-1500.073668482016,-1376.9853478108869,-500.0],[-1274.588460501239,1500.0762058711482,-500.0],[1500.0832226548077,999.3669757091218,-500.0],[31.486783200248304,1500.0999779787126,-500.0],[-57.59358271361962,1500.0999263796266,-500.0],[-125.47172686990272,1500.099652023387,-500.0],[1402.3897791137324,-1500.073049108609,-500.0],[1392.171414724234,-1500.0732977121731,-500.0],[1378.1490952182066,-1500.0736400145056,-500.0],[1500.099899502607,-67.30388142765847,-500.0],[1500.099808342416,-93.00860396007364,-500.0],[1500.0998015932878,-94.63686227454835,-500.0],[1406.797071275714,1500.072942105286,-500.0],[1500.0718258650782,1453.1175683206434,-500.0],[1500.0752478467034,1312.9609411369568,-500.0]],"config":{},"motor_samples":[[17437.889631722308,33828.80464016293,17724.184188070958,-1815.0018076365377,35140.49401306688,84510.10215219756,36090.92353701913,-62390.39829429184],[33416.474908680524,16959.459989117502,-1806.0619582547674,17731.402977824793,83357.59724088726,33541.96029857392,-62251.92156150725,36114.83006589785],[33846.296272389016,17458.17176756878,-1815.1986792862613,17724.0249907893,84558.92085507844,35207.97502673681,-62393.446291326676,36090.39629003181],[22053.785486216308,3479.108629046186,3457.9811045703723,22036.44827265297,49974.73354761746,-20912.75930991152,-21025.32200343895,49920.76250098186],[22098.477074520513,3533.5625800883217,3403.8758991722093,21992.056326367645,50113.80536006783,-20623.441569497798,-21314.38320321564,49782.51620899043],[21752.235116656924,3111.375552505542,3836.919032536914,22347.62583430168,49034.32247518058,-22897.700019415486,-19032.13253561319,50887.697043963875],[17747.759326458305,-1785.791505772905,16417.807105654218,32950.30000979939,36168.98704175534,-61940.821903417345,31716.088901621355,82050.59184619234],[17763.4311661145,-1766.3663767929422,16060.625117737385,32643.268147160026,36220.86392714363,-61646.987959427315,30502.315213849124,81187.40659186033],[17725.30587366176,-1813.6138484880655,17323.34704430213,33730.03909685129,36094.63841905961,-62368.88641545675,34758.965695028244,84234.34028374635],[21900.13615827456,22192.41121877522,3647.9769984006543,3291.8054964663434,49496.01153677004,50405.85859933008,-20019.247211601032,-21916.852950858934],[22136.476249373998,21954.64792104842,3358.273140357606,3579.852920437814,50231.990717935645,49665.95843639149,-21558.923561209718,-20378.39538269912],[22732.507439581834,21405.590184795674,2689.5346771658737,4303.587153723762,52078.56135799921,47948.80934447395,-25256.51787360587,-16641.133767769807],[32844.00196378539,16294.18621629099,-1779.6205223967802,17752.738053603498,81751.96176570222,31296.894577762712,-61847.02202564015,36185.469057521455],[15136.307835126025,-1692.904131118614,17822.701540739632,31850.14301966457,27323.32161126316,-60571.814175523636,36416.940225406644,78948.68309984505],[-1215.7441612121797,18213.584594932738,29319.722459216384,12170.740919665066,-54511.300988872055,37705.34075200738,71714.0326723164,16698.376391451748],[3253.9180209435262,3687.160529673275,22224.590691702917,21869.07025498041,-22121.686195551076,-19813.46014679801,50505.83042400693,49399.107644347016],[3871.437332430295,3079.0200832737037,21725.72436400086,22375.994885881013,-18853.18616997713,-23075.052644276762,48951.474674086465,50975.66464703597],[4361.787726590538,2639.1473405741563,21364.198220013313,22780.574817387907,-16347.88667793621,-25544.097453193102,47818.86611474282,52226.89808138828],[17741.740080359497,33094.83694319013,16585.83135808714,-1793.2518680504045,36149.058602331446,82456.2868499154,32284.360938835554,-62054.79026532929],[17745.859611903772,32993.74246974659,16468.317101208242,-1788.1460928091703,36162.6977048646,82172.57251625168,31887.09777568607,-61976.72439729309],[17752.178958998753,32855.4557102962,16307.508537666805,-1780.3135112329196,36183.618248723666,81784.15042341157,31342.11525840979,-61857.534342778315],[3940.670971018682,22432.9065154519,21673.015027748028,3014.6773984458464,-18495.537411148067,51152.04574068663,48786.67142131597,-23429.09556154857],[4125.747950351423,22585.11962647485,21535.079957648344,2846.2183360482627,-17547.563176539676,51623.18489029416,48354.87105108516,-24364.799509689157],[4137.5595518657565,22594.837579502775,21526.420624254533,2835.638841865909,-17487.45533341353,51653.234909926636,48327.73779590973,-24423.996435891044],[-1795.2973577506375,16636.60204223954,33138.52368049694,17740.089641912204,-62086.14706920719,32455.736713538012,82578.8277259074,36143.594008825814],[-1811.0818756277072,17727.350728754496,33600.701721445315,17173.295873775733,-62329.628713529,36101.4105465217,83872.93607638011,34258.04292404066],[-1731.3602213943204,17791.67343007859,32219.336827793784,15566.86820476926,-61127.781292181164,36314.31776717483,79992.41712631802,28811.140193406012]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/outside_singularities_HP5.jsonl b/ai_docs/datasets/outside_singularities_HP5.jsonl
new file mode 100644
index 000000000000..bdfd26812bc6
--- /dev/null
+++ b/ai_docs/datasets/outside_singularities_HP5.jsonl
@@ -0,0 +1 @@
+{"dataset":"outside_singularities","geometry":"HP5","anchor_set":0,"anchors":[[0.0,-2000.0,-120.0],[2000.0,0.0,-120.0],[0.0,2000.0,-120.0],[-2000.0,0.0,-120.0],[0.0,0.0,2000.0]],"real_xyz":[[964.2243911061697,-948.6087702145851,-27.497151],[-719.6209861786293,-688.2700213685404,507.741532],[-497.6413613152127,-490.1567481187497,953.040004],[-1860.0178563072427,-1.9038511455875198,26.4689901],[-1371.6526854679453,-8.618023022620921,537.019049],[-868.4671309656386,30.52892563813489,1047.17018],[-1000.9835896849843,926.045962767846,-42.5453256],[-726.5671000128928,657.0415141380506,533.480869],[-462.6695866440002,452.1553284503393,1030.39159],[32.433286593425294,-1879.5675457650655,-26.6148823],[-14.854053157866401,-1383.7098968421333,517.628213],[-69.11027608697687,-881.9932880639665,991.936222],[-968.1903922202289,-888.7456742892051,31.7537695],[-667.9825024992241,786.1554446705873,458.719776],[539.7956263615132,359.6159962799965,1046.72968],[39.649638360777516,1888.9964482429957,-44.2588518],[-51.73173379672665,1347.4204312976128,517.004705],[-74.62912792431862,892.2418749058698,975.222737],[899.8193468722692,-962.496141523957,26.0515823],[665.0865094663349,-716.6348216657407,535.481389],[467.4711120113626,-508.8281776112792,965.228753],[1843.8036956704452,-82.72458744276214,-42.0139801],[1308.3039740057973,-81.11695335269314,527.319817],[888.9606245543979,-56.081898087111554,998.360926],[894.2669307305229,953.5601496468353,41.4092948],[727.052367353247,704.2946543448661,482.878157],[512.3511511692511,448.4422035477301,981.665044]],"config":{},"motor_samples":[[-11161.833751947603,-11588.746135552434,21511.18541525905,21708.541629232954,16985.48513182135],[-7417.666415759829,17018.738445822426,16589.449532699768,-8177.6865818059505,-8074.902950931188],[-1672.7095664001097,14813.472167463937,14707.198290037059,-1825.1219929542885,-28772.641527036107],[14256.11158509588,36467.92415834749,14310.64808616481,-34856.96236004908,27535.528725974276],[9793.43203610826,28030.278533361496,10061.704998990648,-21300.908803951635,-140.07991792812246],[9640.496037168592,21380.486702292234,8675.317061782873,-7514.647558887461,-27827.747479571903],[21311.920244634006,22256.38132646117,-10374.995011821564,-12426.056513470012,17758.413027513485],[16162.110522691353,17116.862417153738,-6672.713501055276,-8342.88581736712,-9255.22299748254],[14531.346726218708,14681.056236705486,-402.0979698543101,-609.4735328599854,-32349.30899748624],[-35751.0447181981,14038.24382103208,36824.24269694347,14963.629837741957,29694.479044353007],[-21754.68595996782,10190.41356160955,28192.035172834854,9728.310566759663,612.2831618874906],[-8390.1506726186,9859.031021114934,21239.975716126148,7656.188986241811,-25775.17654688714],[-10151.785193047095,21481.029602919283,20466.66264085566,-12312.607155182846,14225.248341203373],[17964.78163628395,16356.620214322435,-9768.184729754299,-6855.97146542886,-5719.780113624157],[13341.810672200698,-1965.5665432268404,1562.7514916031298,15906.515793968103,-32840.96013784039],[37004.27581290484,14053.363069354224,-36050.735885509996,15182.246223072525,30516.52557157177],[27494.689079243715,10383.81839994964,-21228.563328258522,8761.957749125182,-222.8208617470887],[21313.295082623754,9875.248587652164,-8746.096635083213,7492.90960637882,-25010.125048194455],[-12102.006331058603,-10396.228920609901,21431.419123593158,20631.895544949017,14483.254682120349],[-8105.296630862094,-6867.808297582691,16977.754544894244,16269.678640370494,-9360.143326441785],[-1973.8618121813272,-1135.6774187579615,15027.923965779608,14440.41734078419,-29324.901770481592],[12833.756681856255,-35030.46989295319,15214.719662131009,36125.86269008061,29351.0096012883],[7941.262983293784,-20484.693856768277,10502.484612055216,26788.499250302648,-1392.9362731286558],[7969.640314575026,-8428.28243001152,9753.415263168785,21407.905089800064,-25841.750607507875],[21247.031832510376,-10397.23128771073,-12008.247865005224,20488.66494976449,13760.214402926422],[16817.725634553575,-8345.104698815103,-7788.6709174066,17128.432839931014,-6916.75361150372],[14247.265733323322,-1933.738525066496,-647.3013900475427,15155.67634510061,-30067.181465309168]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/outside_singularities_Slideprinter.jsonl b/ai_docs/datasets/outside_singularities_Slideprinter.jsonl
new file mode 100644
index 000000000000..2725b864de7e
--- /dev/null
+++ b/ai_docs/datasets/outside_singularities_Slideprinter.jsonl
@@ -0,0 +1 @@
+{"dataset":"outside_singularities","geometry":"Slideprinter","anchor_set":0,"anchors":[[-1000.0,-577.0,0.0],[1000.0,-577.0,0.0],[0.0,1154.0,0.0]],"real_xyz":[[586.5696304357359,-577.070131086945,0.0],[-603.3548397914448,-577.0691189556117,0.0],[-585.8819398298053,-577.0701728841677,0.0],[-667.1611097747937,-0.6828834673974071,0.0],[-669.1952556618963,-4.204519249678304,0.0],[-653.4975914016618,22.972175527724087,0.0],[-434.5391086406714,402.0077765191644,0.0],[-437.97340378342705,396.06349966706773,0.0],[-426.17303513855137,416.4881683222013,0.0],[9.958274312875727,-577.0999851153347,0.0],[-6.1951381654399755,-577.0999942385431,0.0],[-45.21975365408382,-577.0996944161187,0.0],[-628.6515310497994,-577.0676236257343,0.0],[-396.9133143103633,467.1313424227047,0.0],[481.47663955934274,320.76343891070655,0.0],[23.375097151352165,1113.6413173422277,0.0],[-41.54854604841679,1082.186034133827,0.0],[-84.32389666339944,1008.1494149927422,0.0],[539.494624180343,-577.073049108609,0.0],[535.5637957830543,-577.0732977121731,0.0],[530.1696487730947,-577.0736400145056,0.0],[684.5058732825225,-30.71122273071164,0.0],[691.5324707276808,-42.87612686686019,0.0],[691.982430053514,-43.655126052164334,0.0],[412.60852296226136,439.9660005095441,0.0],[427.5269403555726,414.14477443624196,0.0],[442.8547482093821,387.61454655732064,0.0]],"config":{},"motor_samples":[[8425.7591917182,-14397.86839756116,13153.62710756541],[-14722.94103549322,8753.801330116066,13260.42653915718],[-14384.549262099139,8412.320197534831,13149.309200463942],[-9510.573561623985,11894.807764671881,3496.536380106292],[-9589.493438537125,11910.00225097054,3575.8600689628065],[-8980.398662548932,11797.34264665677,2963.7777626979127],[-469.80769377087995,11362.648302988275,-5558.092171905046],[-603.4943871556286,11352.854161974894,-5424.65631489397],[-144.11403608862545,11388.714860744967,-5883.115562731273],[-2817.6434130093303,-3205.126353043206,11262.623197527488],[-3131.9141133988232,-2890.8584248530337,11262.279883517871],[-3891.038041552035,-2131.4992433368993,11273.610051745398],[-15212.772701034115,9248.267891135365,13426.452895417273],[995.2873335468562,11504.40068955027,-7019.512307363683],[11274.631536091774,-2296.3729057954897,-3733.730414497029],[16052.44915686185,15585.998837172352,-21481.66659125988],[14874.164339619623,15714.552862614808,-20779.953429778358],[13199.49805944938,14960.616762555559,-19127.55095605376],[7505.973658044645,-13485.960152342615,12868.645631993199],[7429.185351574546,-13409.7995386588,12845.830312331675],[7323.815052047519,-13305.283056129236,12814.769993365771],[12030.022907245704,-10183.42859167333,4172.993996121087],[12088.428678984597,-10455.959996953934,4447.08761782369],[12092.23965535597,-10473.410969781236,4464.640648267927],[11437.614973990489,384.04042161472523,-6410.00482039572],[11384.284330105731,-196.82463414760232,-5830.519130857959],[11339.842216628327,-793.4989220304453,-5234.983958070703]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[3.0,3.0,3.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/outside_singularities_Spidercam.jsonl b/ai_docs/datasets/outside_singularities_Spidercam.jsonl
new file mode 100644
index 000000000000..cde2f5b6b05b
--- /dev/null
+++ b/ai_docs/datasets/outside_singularities_Spidercam.jsonl
@@ -0,0 +1 @@
+{"dataset":"outside_singularities","geometry":"Spidercam","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0]],"real_xyz":[[1500.0712855570498,-1475.7776203877443,200.0],[-1500.072267350686,-1434.720208739894,507.741532],[-1500.071244412606,-1477.5099102785375,953.040004],[-1500.0999999476157,-1.5354514440340674,200.0],[-1500.0999980262864,-9.42505085739961,537.019049],[-1500.0999382717441,52.73249594875085,1047.17018],[-1500.0734049670425,1387.7719223771846,200.0],[-1500.0741702702828,1356.5312882131288,533.480869],[-1500.0715186460866,1465.9820956295314,1030.39159],[25.885301566129517,-1500.0999851153347,200.0],[-16.103494747986616,-1500.0999942385429,517.628213],[-117.54318932137812,-1500.0996944161188,991.936222],[-1500.073668482016,-1376.9853478108869,200.0],[-1274.588460501239,1500.0762058711482,458.719776],[1500.0832226548077,999.3669757091218,1046.72968],[31.486783200248304,1500.0999779787126,200.0],[-57.59358271361962,1500.0999263796266,517.004705],[-125.47172686990272,1500.099652023387,975.222737],[1402.3897791137324,-1500.073049108609,200.0],[1392.171414724234,-1500.0732977121731,535.481389],[1378.1490952182066,-1500.0736400145056,965.228753],[1500.099899502607,-67.30388142765847,200.0],[1500.099808342416,-93.00860396007364,527.319817],[1500.0998015932878,-94.63686227454835,998.360926],[1406.797071275714,1500.072942105286,200.0],[1500.0718258650782,1453.1175683206434,482.878157],[1500.0752478467034,1312.9609411369568,981.665044]],"config":{},"motor_samples":[[6831.643613022776,24822.63431613387,7151.395631337143,-15436.173743501773],[20750.10987817892,1907.846518541822,-21373.147043190675,2814.783674728499],[16445.164542092138,-3407.3756455202033,-29968.498135949532,-3072.081558104511],[11959.665540464965,-9113.441130412566,-9138.162549863611,11940.507965517489],[7516.797594793717,-14933.370363394002,-15098.543846197734,7393.380858101651],[843.9384677572223,-24159.92483490967,-23096.841285508795,1585.7687538067337],[7177.71531132577,-15401.104800517624,5690.3942169762995,23872.00185027684],[2498.9120723793953,-21817.01877628147,486.25701318141427,19588.96477107309],[-4035.445227116118,-31454.032130371335,-4548.930654309905,15534.19168616834],[11789.857817342481,12112.820249780549,-8915.931679933832,-9332.687565395854],[7811.8151443741135,7601.531436990006,-14820.750213760417,-14539.958501448222],[2697.650620149371,1057.0638889314457,-23854.6934181847,-21523.449391625727],[23756.88886683471,5551.87797793537,-15393.682114355997,7183.273441599151],[457.20615974154856,-20279.247214574327,3598.812912330894,19565.33141382809],[-30800.62059085337,-3613.4257663583935,10113.440029941867,-11487.250048074937],[-9377.059071109672,-8870.123729666591,12148.365678358596,11755.51786111201],[-14160.446216914677,-15164.419255292089,7344.725446845302,8096.681790521037],[-21169.00836241737,-23645.461020650775,1203.1821929041346,2950.302045771414],[7170.995475838392,24028.494186059423,5878.589951856083,-15410.075772205508],[2450.805348756731,19960.087653413797,941.5442471436337,-21884.678432152825],[-3189.7794754315787,15158.258113222199,-5021.920596302274,-30148.838019102106],[-8573.947516050408,12378.410570968712,11538.74542081568,-9657.41962846915],[-14015.655775387413,8205.283956836933,6989.287294344752,-15641.032803974671],[-21867.016096456657,2453.6384751425253,1131.4338631461333,-23747.792682711814],[-15412.534755042949,5935.438981357196,24075.78757192002,7169.152922115845],[-20899.708978749724,3153.110763479812,21239.94430481575,2505.0625208991364],[-30388.05579274501,-3345.653953155224,14240.462033343398,-6181.3815464636245]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[3.0,3.0,3.0,3.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/systematic_bias_CubeCorners.jsonl b/ai_docs/datasets/systematic_bias_CubeCorners.jsonl
new file mode 100644
index 000000000000..d989a4c45534
--- /dev/null
+++ b/ai_docs/datasets/systematic_bias_CubeCorners.jsonl
@@ -0,0 +1 @@
+{"dataset":"systematic_bias","geometry":"CubeCorners","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0],[1500.0,1500.0,0.0],[-1500.0,1500.0,0.0],[-1500.0,-1500.0,0.0],[1500.0,-1500.0,0.0]],"real_xyz":[[17.9255679,-17.6352632,-500.0],[-523.885148,-501.061599,-500.0],[-538.35251,-530.255594,-500.0],[-545.189816,-0.558037791,-500.0],[-520.999273,-3.27341154,-500.0],[-470.799477,16.5498517,-500.0],[-505.362595,467.529134,-500.0],[-513.234032,464.122399,-500.0],[-538.29312,526.060302,-500.0],[8.98405788,-520.642383,-500.0],[-5.52678502,-514.840431,-500.0],[-38.6000122,-492.617793,-500.0],[-507.629503,-465.97604,-500.0],[-30.5601452,35.9665477,-500.0],[43.2898928,28.8400594,-500.0],[10.5874156,504.407891,-500.0],[-19.9804722,520.41744,-500.0],[-37.9958866,454.266612,-500.0],[455.930483,-487.688259,-500.0],[482.712486,-520.125685,-500.0],[495.517745,-539.35609,-500.0],[500.096373,-22.437457,-500.0],[490.657689,-30.4215669,-500.0],[506.742907,-31.9689121,-500.0],[490.590662,523.118645,-500.0],[517.848381,501.639033,-500.0],[525.399857,459.863258,-500.0]],"config":{"min_force":50.0},"motor_samples":[[8266.753607006394,8498.011579784878,8270.503489882074,8038.668731361746,2051.190320083494,3005.734345820461,2066.7318985065976,1101.8548435732298],[15715.94669021355,9245.998446806874,2603.068447833393,9537.23757571668,29830.027646677143,6041.093093883088,-24874.521360309824,7202.690217990383],[16066.733617676366,9436.777100755791,2406.5532515607492,9539.98978435552,31024.700905656187,6803.235671605359,-25994.503552740494,7213.6156788801345],[12341.349042997743,5342.7793269762,5335.332116294328,12334.447193590986,17893.440350695593,-10824.462373033288,-10859.537749504865,17868.094417598593],[12155.227968182626,5464.880723423482,5421.2473473821865,12114.656393021021,17208.434389066202,-10251.328297614838,-10455.720712455905,17058.694762918843],[11617.585314432938,5557.23881716805,5777.283726161823,11823.600465255704,15211.626890838095,-9820.210110271231,-8801.172498416485,15979.999473006432],[9523.405095880027,2842.895400121563,9040.059439486495,15301.453658083548,7147.764874730133,-23532.746783847004,5213.029800319023,28408.24220679338],[9605.51118244182,2823.320851663908,8978.148338479261,15337.917832674335,7473.435540620523,-23641.271220932136,4962.980227358942,28533.771883631867],[9556.788624784826,2425.575944276801,9400.838854458052,16032.47742402165,7280.281481294738,-25885.246707501177,6660.024692488794,30908.373980765828],[12076.415951520265,12187.770183210567,5504.630598744002,5384.878691722878,16917.42021385669,17328.430703443028,-10065.528870594335,-10626.438081658616],[12117.888461060877,12049.351212114494,5433.149877269467,5506.797455031687,17070.62906465139,16817.351323271043,-10399.919571655055,-10055.411460308122],[12141.899105140912,11662.31344494077,5314.243381887866,5828.022452026025,17159.25751320453,15378.796569913617,-10958.9377217269,-8567.782889681748],[15307.428587407261,9017.398576080002,2839.9311707195175,9549.537137712186,28428.81722523717,5121.566182044173,-23549.169891676822,7251.508479594572],[8237.139923181963,7841.40000464051,8306.972124956117,8700.706775852974,1928.3804261419828,274.2544455426973,2217.7677928237968,3835.9700885009674],[7806.068850560537,8366.36479573992,8737.742745385178,8179.7244576554685,125.37547523662467,2463.318552326402,3987.0360449379955,1689.8962923488907],[5445.511251975901,5586.521142787696,12062.775319802135,11931.36271183913,-10342.003830845946,-9683.948552195885,16866.9939500963,16380.30643572599],[5579.522268538775,5313.199829713386,12006.982216497092,12254.636455516025,-9716.498431927439,-10963.859294319172,16660.56029685552,17574.690953260357],[5997.917420924138,5493.174618200711,11351.238054060499,11824.875650859887,-7790.497057746664,-10119.037500627648,14212.098192934138,15984.742860756654],[9424.621712723545,15069.052067793884,9018.633070605722,2979.1184014044043,6754.815937248875,27606.10242497653,5126.550626558363,-22782.20792453337],[9583.500754026525,15539.946353454498,9105.848952459779,2704.8142723938117,7386.214954363584,29227.67971290521,5478.177560230858,-24302.012924673774],[9694.171068393995,15796.975347279435,9134.911571191864,2559.77057507049,7824.156901660214,30106.675261322733,5595.122573511327,-25119.652309543766],[5685.267166076614,12101.37584457935,11822.776741596657,5386.498072743332,-9225.93499090762,17009.646700976413,15976.935334378966,-10618.829673227214],[5781.234043311292,12073.902532091759,11695.861757351016,5376.3478920646385,-8782.980700395741,16908.12997517203,15504.054942439294,-10666.529365767525],[5720.410304513958,12216.499206372,11819.783632746427,5294.587060737494,-9063.478834194297,17434.285948848334,15965.80083851041,-11051.686035857738],[2654.763053726322,9160.11729268364,15626.495739599797,9575.296641543599,-24583.031247026418,5696.456820450427,29524.137686569487,7353.6890620659815],[2627.5545858069704,9482.963707903516,15671.951421753116,9276.09789860532,-24736.29262052388,6987.04349698518,29679.643820523717,6161.6512277569],[2788.9245128659213,9728.444812500593,15402.70467503766,8891.429380765669,-23832.38890907583,7959.476672783857,28756.586986151495,4611.858244532203]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0,4.0,4.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],"min_force":[50.0,50.0,50.0,50.0,50.0,50.0,50.0,50.0],"max_force":[120.0,120.0,120.0,120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/systematic_bias_HP5.jsonl b/ai_docs/datasets/systematic_bias_HP5.jsonl
new file mode 100644
index 000000000000..aac9e732f553
--- /dev/null
+++ b/ai_docs/datasets/systematic_bias_HP5.jsonl
@@ -0,0 +1 @@
+{"dataset":"systematic_bias","geometry":"HP5","anchor_set":0,"anchors":[[0.0,-2000.0,-120.0],[2000.0,0.0,-120.0],[0.0,2000.0,-120.0],[-2000.0,0.0,-120.0],[0.0,0.0,2000.0]],"real_xyz":[[17.9255679,-17.6352632,-27.497151],[-523.885148,-501.061599,507.741532],[-538.35251,-530.255594,953.040004],[-545.189816,-0.558037791,26.4689901],[-520.999273,-3.27341154,537.019049],[-470.799477,16.5498517,1047.17018],[-505.362595,467.529134,-42.5453256],[-513.234032,464.122399,533.480869],[-538.29312,526.060302,1030.39159],[8.98405788,-520.642383,-26.6148823],[-5.52678502,-514.840431,517.628213],[-38.6000122,-492.617793,991.936222],[-507.629503,-465.97604,31.7537695],[-30.5601452,35.9665477,458.719776],[43.2898928,28.8400594,1046.72968],[10.5874156,504.407891,-44.2588518],[-19.9804722,520.41744,517.004705],[-37.9958866,454.266612,975.222737],[455.930483,-487.688259,26.0515823],[482.712486,-520.125685,535.481389],[495.517745,-539.35609,965.228753],[500.096373,-22.437457,-42.0139801],[490.657689,-30.4215669,527.319817],[506.742907,-31.9689121,998.360926],[490.590662,523.118645,41.4092948],[517.848381,501.639033,482.878157],[525.399857,459.863258,981.665044]],"config":{"min_force":50.0},"motor_samples":[[-601.9102780799459,-607.5743318282515,84.69770564020128,90.34710091027762,880.0482024524102],[-5962.010829804277,12466.666728965309,12129.044448988761,-6482.532220158997,-13636.229199399795],[-2153.8166616778976,15549.61582942396,15436.685128311015,-2319.862443914838,-27637.700993170165],[1273.2175415121596,10499.180439469745,1294.2257273243752,-10695.85388051941,1649.863498281558],[3053.2090447299083,11619.391074926107,3170.675245633119,-7681.977587227829,-17709.14584897739],[7169.58448538464,14108.463955224806,6623.735825796074,-1749.3486666599003,-36496.59035974947],[9933.927171156673,10526.301281867716,-7737.318852835859,-8654.865425495056,5853.297440109958],[11526.482713980247,12258.618341021913,-5208.8374807787095,-6316.968714106849,-15078.42317980809],[15960.266217466386,16129.218961150358,-1222.7759028789333,-1467.7844500763667,-30085.219794511944],[-10306.997149801911,872.3515456178682,10003.130296767498,1210.6319279384538,3400.136596170831],[-7722.32199026571,3069.990372968797,11408.786916993882,2869.2231609921046,-17077.398496045047],[-2729.2150865861154,7106.225223016439,14049.888644087363,5821.248117029038,-34215.07221704778],[-7574.512902496974,10640.738194657344,10000.48218919352,-8586.216647632315,3125.3413189986345],[2103.8115973507643,2004.3535298365011,752.9409143603216,856.5755615473938,-18012.18596869828],[6463.020469565602,5233.909285907158,5486.872817419853,6702.918352377927,-40625.83901628996],[9675.168868761319,737.2470911197094,-10013.51442077564,1137.104917456039,3912.0436414968117],[11512.716566462335,3352.6577418033094,-7824.186988305312,2627.186063077834,-16981.175844796075],[13232.53006921838,6794.628776341332,-2313.455304106017,5521.378100833025,-34255.675163216474],[-8290.876875234482,-7523.9026653198935,10208.256011853702,9716.531970459675,3063.4651773268706],[-6318.253597027638,-5472.872958139194,12461.440203591581,11906.798297801352,-14854.928941077329],[-2382.9073986445574,-1491.069317068311,15534.877040985455,14920.535826932408,-28542.989726621945],[496.05842675724926,-9925.732458199729,1344.340343185978,9592.118834325227,3790.7573746452163],[2357.954796177349,-7212.339088479129,3466.0276021376662,11002.04824346042,-17722.922433250496],[6050.647370795601,-2878.2121505918135,7112.187470230372,14351.410595524289,-34202.54099683658],[11038.191370194314,-7917.957051369212,-8713.558423663426,10542.80984394806,3130.9670223353723],[12002.75946395865,-6552.486642250147,-6181.191420002448,12243.339069854292,-12838.696939822712],[14369.649492434133,-2170.342830746769,-844.9379087664839,15294.631690558497,-29826.2295655883]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0,4.0],"lines_per_spool":[1.0,1.0,1.0,1.0,1.0],"min_force":[50.0,50.0,50.0,50.0,50.0],"max_force":[120.0,120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/systematic_bias_Slideprinter.jsonl b/ai_docs/datasets/systematic_bias_Slideprinter.jsonl
new file mode 100644
index 000000000000..ec6ca024beb5
--- /dev/null
+++ b/ai_docs/datasets/systematic_bias_Slideprinter.jsonl
@@ -0,0 +1 @@
+{"dataset":"systematic_bias","geometry":"Slideprinter","anchor_set":0,"anchors":[[-1000.0,-577.0,0.0],[1000.0,-577.0,0.0],[0.0,1154.0,0.0]],"real_xyz":[[17.9255679,-17.6352632,0.0],[-523.885148,-501.061599,0.0],[-538.35251,-530.255594,0.0],[-545.189816,-0.558037791,0.0],[-520.999273,-3.27341154,0.0],[-470.799477,16.5498517,0.0],[-505.362595,467.529134,0.0],[-513.234032,464.122399,0.0],[-538.29312,526.060302,0.0],[8.98405788,-520.642383,0.0],[-5.52678502,-514.840431,0.0],[-38.6000122,-492.617793,0.0],[-507.629503,-465.97604,0.0],[-30.5601452,35.9665477,0.0],[43.2898928,28.8400594,0.0],[10.5874156,504.407891,0.0],[-19.9804722,520.41744,0.0],[-37.9958866,454.266612,0.0],[455.930483,-487.688259,0.0],[482.712486,-520.125685,0.0],[495.517745,-539.35609,0.0],[500.096373,-22.437457,0.0],[490.657689,-30.4215669,0.0],[506.742907,-31.9689121,0.0],[490.590662,523.118645,0.0],[517.848381,501.639033,0.0],[525.399857,459.863258,0.0]],"config":{"min_force":50.0},"motor_samples":[[78.64875557034719,-530.7118777185126,289.1654865916417],[-13121.160521367468,7086.556329672424,11278.037197806796],[-13470.300332844728,7344.039696009991,11906.717343098475],[-8259.44666348627,9574.422594655065,2253.295425962827],[-8005.852941028248,9114.082041394518,2105.030814831446],[-7082.823673989789,8342.743826750497,1365.8458481395573],[-32.85835698231401,13147.234107471022,-5909.453838109196],[-157.87664000891635,13235.90293405589,-5765.58109780886],[745.741920191339,14332.161527860033,-6400.751771181213],[-2921.0339340392547,-3267.99018471621,10081.26089145413],[-3194.5627300806864,-2981.195798269076,9967.781273446742],[-3800.1625780878535,-2312.371922755775,9542.94006885766],[-12685.748622409285,6815.2101154807415,10529.655792305326],[-205.7695215393487,809.5934000930579,-750.7503196448042],[952.7356250809601,-489.92758928608146,-604.4451020496136],[6278.250477377526,5995.155587766675,-9852.840115270115],[6100.413058866906,6631.169904604985,-10159.32032740405],[4907.929176038495,5948.785910688223,-8866.836026951001],[5780.108595367764,-11787.354228332644,10650.141287627133],[6268.178740797528,-12383.7649687827,11401.623342298846],[6505.115571151312,-12663.549164253038,11831.846067214627],[8601.503693887536,-8020.84865977243,2284.6879137830615],[8375.029290062641,-8011.35928376258,2357.5124403394943],[8659.385341612628,-8243.370928031676,2505.8041504886546],[13544.633325702553,1067.3660188193653,-6941.538401106192],[13729.781797449596,467.90040474289486,-6287.789085081149],[13385.102054119703,-332.2350064059609,-5557.950823374304]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0],"min_force":[50.0,50.0,50.0],"max_force":[120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/datasets/systematic_bias_Spidercam.jsonl b/ai_docs/datasets/systematic_bias_Spidercam.jsonl
new file mode 100644
index 000000000000..c6efece231d2
--- /dev/null
+++ b/ai_docs/datasets/systematic_bias_Spidercam.jsonl
@@ -0,0 +1 @@
+{"dataset":"systematic_bias","geometry":"Spidercam","anchor_set":0,"anchors":[[1500.0,1500.0,3500.0],[-1500.0,1500.0,3500.0],[-1500.0,-1500.0,3500.0],[1500.0,-1500.0,3500.0]],"real_xyz":[[17.9255679,-17.6352632,200.0],[-523.885148,-501.061599,507.741532],[-538.35251,-530.255594,953.040004],[-545.189816,-0.558037791,200.0],[-520.999273,-3.27341154,537.019049],[-470.799477,16.5498517,1047.17018],[-505.362595,467.529134,200.0],[-513.234032,464.122399,533.480869],[-538.29312,526.060302,1030.39159],[8.98405788,-520.642383,200.0],[-5.52678502,-514.840431,517.628213],[-38.6000122,-492.617793,991.936222],[-507.629503,-465.97604,200.0],[-30.5601452,35.9665477,458.719776],[43.2898928,28.8400594,1046.72968],[10.5874156,504.407891,200.0],[-19.9804722,520.41744,517.004705],[-37.9958866,454.266612,975.222737],[455.930483,-487.688259,200.0],[482.712486,-520.125685,535.481389],[495.517745,-539.35609,965.228753],[500.096373,-22.437457,200.0],[490.657689,-30.4215669,527.319817],[506.742907,-31.9689121,998.360926],[490.590662,523.118645,200.0],[517.848381,501.639033,482.878157],[525.399857,459.863258,981.665044]],"config":{"min_force":50.0},"motor_samples":[[-3494.4664578362604,-3228.9060564614015,-3490.15854667054,-3756.60607221311],[519.1064177212844,-7242.344113493544,-15513.220271079383,-6887.467248245399],[-5058.176023110867,-13697.669009583296,-23461.3031202962,-13559.567750309856],[1153.2387091534329,-6872.636455446931,-6881.2914134195535,1145.4190795300942],[-4155.730490282748,-12390.503171223752,-12445.350684696066,-4204.735332700443],[-12102.136576487586,-20461.98114015116,-20148.55232415423,-11826.652997216754],[-2054.0976568497945,-9793.803826942418,-2607.3350155516905,4491.976726894311],[-7201.492051703716,-15681.019315837202,-7970.490711447109,-291.64731656647535],[-14647.814049683495,-24740.8059276368,-14860.000221671657,-6087.9065025150685],[852.9538610768759,979.1974053285877,-6684.6038133074535,-6823.714742059691],[-3913.63758985234,-3996.1375400079064,-12109.136506143366,-12017.008100240719],[-10651.967679680483,-11285.38810427881,-19943.19179166594,-19220.833594190794],[4498.686894483239,-2633.2960351147285,-9797.287282950945,-2024.2138787276824],[-7699.020199976108,-8179.833229442251,-7614.284907241217,-7137.124658583639],[-17290.430772050957,-16514.32848242848,-16002.439484105611,-16772.339707405732],[-6753.271645054455,-6589.514940333757,837.4862618253457,688.4384592930048],[-11915.766690647777,-12248.922851861533,-4037.8882809272677,-3739.886128708204],[-18723.651300533118,-19428.861512648105,-11465.530925155106,-10840.38571264607],[-2167.0880525433113,4230.88983554379,-2631.8817037893523,-9633.77178596396],[-7259.246768698317,-79.69472448853209,-7844.800391796163,-15867.724544579865],[-13529.096149639037,-5558.713591845474,-14279.876251402991,-23445.610978924793],[-6474.8970353308505,881.2550425906725,565.2334244395698,-6821.8331074147945],[-11833.73757856749,-4110.321013968698,-4566.6787687500055,-12341.026503390276],[-19471.898428253793,-10641.229245114751,-11165.346919466396,-20072.03066844889],[-10014.986908501218,-2469.8280038298076,4856.854139193482,-1994.7588077669138],[-15046.72638086064,-6567.931643367992,818.1907369706508,-6818.716729968563],[-23389.508832196723,-13719.210462934096,-6275.395069531717,-14847.972465580333]],"config_used":{"spool_buildup_factor":0.043003,"spool_r_in_origin":[75.0,75.0,75.0,75.0],"spool_gear_teeth":255.0,"motor_gear_teeth":20.0,"spool_to_motor_gearing_factor":12.75,"mechanical_advantage":[2.0,2.0,2.0,2.0],"lines_per_spool":[1.0,1.0,1.0,1.0],"min_force":[50.0,50.0,50.0,50.0],"max_force":[120.0,120.0,120.0,120.0],"spring_k_per_unit_length":20000.0,"mover_weight":2.0,"use_flex":true,"ignore_gravity":false,"ignore_pretension":false,"lambda_reg":0.001,"tol":0.001,"max_iters_target":100,"g":9.81,"guy_wire_lengths":null}}
diff --git a/ai_docs/make.sh b/ai_docs/make.sh
new file mode 100755
index 000000000000..01ec9cb01272
--- /dev/null
+++ b/ai_docs/make.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+target="${1:-motorstepstocartesiantest_quadratic.cpp}"
+g++ -g -fconcepts -I../../../hangprinter-flex-compensation -I. ../../../hangprinter-flex-compensation/flex.cpp ../../../hangprinter-flex-compensation/flex_qp.cpp "$target" && ./a.out
diff --git a/ai_docs/motorstepstocartesiantest_quadratic.cpp b/ai_docs/motorstepstocartesiantest_quadratic.cpp
new file mode 100644
index 000000000000..a8f03b1633f8
--- /dev/null
+++ b/ai_docs/motorstepstocartesiantest_quadratic.cpp
@@ -0,0 +1,598 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+static inline void Set3(float dest[3], float x, float y, float z) {
+ dest[0] = x;
+ dest[1] = y;
+ dest[2] = z;
+}
+
+static inline void Copy3(const float src[3], float dest[3]) {
+ dest[0] = src[0];
+ dest[1] = src[1];
+ dest[2] = src[2];
+}
+
+static inline void Zero3(float dest[3]) {
+ dest[0] = 0.0F;
+ dest[1] = 0.0F;
+ dest[2] = 0.0F;
+}
+
+// Quadratic (Halley) forward transform following Quadratic_Approximation_Approach.md,
+// specialized to a translational (T3) effector.
+
+static float g_stepsPerDegree = 25.0F / 360.0F;
+
+// Borrowed from hangprinter-flex-compensation (cross shaped lower anchors + top anchor)
+constexpr float fourAnchors[4][3] = {
+ {16.4F, -1610.98F, -131.53F},
+ {1314.22F, 1268.14F, -121.28F},
+ {-1415.73F, 707.61F, -121.82F},
+ {0.0F, 0.0F, 2299.83F},
+};
+
+constexpr float fiveAnchors[5][3] = {
+ {0.0F, -2000.0F, -120.0F},
+ {2000.0F, 0.0F, -120.0F},
+ {0.0F, 2000.0F, -120.0F},
+ {-2000.0F, 0.0F, -120.0F},
+ {0.0F, 0.0F, 2000.0F},
+};
+
+static float activeAnchors[HANGPRINTER_MAX_ANCHORS][3] = {
+ {fiveAnchors[A_AXIS][0], fiveAnchors[A_AXIS][1], fiveAnchors[A_AXIS][2]},
+ {fiveAnchors[B_AXIS][0], fiveAnchors[B_AXIS][1], fiveAnchors[B_AXIS][2]},
+ {fiveAnchors[C_AXIS][0], fiveAnchors[C_AXIS][1], fiveAnchors[C_AXIS][2]},
+ {fiveAnchors[D_AXIS][0], fiveAnchors[D_AXIS][1], fiveAnchors[D_AXIS][2]},
+ {fiveAnchors[I_AXIS][0], fiveAnchors[I_AXIS][1], fiveAnchors[I_AXIS][2]},
+ {0.0F, 0.0F, 0.0F},
+ {0.0F, 0.0F, 0.0F},
+ {0.0F, 0.0F, 0.0F}};
+static size_t activeNumAnchors = 5;
+static FlexConfig g_flexConfig{};
+static bool g_hasConfig{false};
+static size_t g_configAnchors{0};
+
+static void setActiveAnchors(const std::vector> &anchors) {
+ for (size_t i{0}; i < HANGPRINTER_MAX_ANCHORS; ++i) {
+ Zero3(activeAnchors[i]);
+ }
+ activeNumAnchors = std::min(anchors.size(), static_cast(HANGPRINTER_MAX_ANCHORS));
+ for (size_t i{0}; i < activeNumAnchors; ++i) {
+ activeAnchors[i][0] = anchors[i][0];
+ activeAnchors[i][1] = anchors[i][1];
+ activeAnchors[i][2] = anchors[i][2];
+ }
+}
+
+static bool parseConfigLine(const std::string &line) {
+ std::istringstream iss(line);
+ std::string tag;
+ if (!(iss >> tag) || tag != "CFG") {
+ return false;
+ }
+
+ size_t count = 0;
+ float stepsPerRev = 25.0F;
+ int useFlexInt = 1;
+ int ignoreGravity = 0;
+ int ignorePretension = 0;
+
+ FlexConfig cfg{};
+ if (!(iss >> count >> cfg.spoolBuildupFactor >> cfg.springKPerUnitLength >> cfg.moverWeightKg >> cfg.spoolGearTeeth >>
+ cfg.motorGearTeeth >> stepsPerRev >> useFlexInt >> ignoreGravity >> ignorePretension >> cfg.lambdaReg >>
+ cfg.tol >> cfg.maxItersTarget >> cfg.gravity)) {
+ return false;
+ }
+
+ cfg.ignoreGravity = ignoreGravity != 0;
+ cfg.ignorePretension = ignorePretension != 0;
+ cfg.stepsPerRevolution = stepsPerRev;
+ cfg.providedAnchors = count;
+
+ auto loadArray = [&](std::array &dest, bool *hasExplicit) -> bool {
+ size_t const limit = std::min(count, static_cast(HANGPRINTER_MAX_ANCHORS));
+ float last = 0.0F;
+ bool explicitValues = true;
+ for (size_t i{0}; i < limit; ++i) {
+ float val = 0.0F;
+ if (!(iss >> val)) {
+ return false;
+ }
+ if (std::isnan(val)) {
+ val = 0.0F;
+ explicitValues = false;
+ }
+ dest[i] = val;
+ last = val;
+ }
+ if (limit > 0) {
+ for (size_t i{limit}; i < HANGPRINTER_MAX_ANCHORS; ++i) {
+ dest[i] = last;
+ }
+ }
+ if (hasExplicit) {
+ *hasExplicit = explicitValues;
+ }
+ return true;
+ };
+
+ bool hasGuyWireLengths = true;
+ if (!loadArray(cfg.spoolRadii, nullptr) || !loadArray(cfg.mechanicalAdvantage, nullptr) || !loadArray(cfg.linesPerSpool, nullptr) ||
+ !loadArray(cfg.minPlannedForce, nullptr) || !loadArray(cfg.maxPlannedForce, nullptr) || !loadArray(cfg.guyWireLengths, &hasGuyWireLengths)) {
+ return false;
+ }
+
+ cfg.hasGuyWireLengths = hasGuyWireLengths && count > 0;
+
+ g_configAnchors = count;
+ g_flexConfig = cfg;
+ g_hasConfig = true;
+ g_stepsPerDegree = stepsPerRev / 360.0F;
+ return true;
+}
+
+static Flex makeFlex(size_t numAnchors) {
+ std::array, HANGPRINTER_MAX_ANCHORS> anchors{};
+ for (size_t i{0}; i < HANGPRINTER_MAX_ANCHORS; ++i) {
+ anchors[i][0] = 0.0F;
+ anchors[i][1] = 0.0F;
+ anchors[i][2] = 0.0F;
+ }
+ size_t const limit = std::min(numAnchors, activeNumAnchors);
+ for (size_t i{0}; i < limit; ++i) {
+ anchors[i][0] = activeAnchors[i][0];
+ anchors[i][1] = activeAnchors[i][1];
+ anchors[i][2] = activeAnchors[i][2];
+ }
+ Flex flex{anchors, numAnchors};
+ if (g_hasConfig) {
+ g_flexConfig.providedAnchors = g_configAnchors;
+ flex.ApplyConfig(g_flexConfig, numAnchors);
+ }
+ return flex;
+}
+
+static std::array originLengths(size_t numAnchors) {
+ std::array lengths{};
+ lengths.fill(0.0F);
+ size_t const limit = std::min(numAnchors, activeNumAnchors);
+ float origin[3] = {0.0F, 0.0F, 0.0F};
+ for (size_t i = 0; i < limit; ++i) {
+ lengths[i] = hyp3(activeAnchors[i], origin);
+ }
+ return lengths;
+}
+
+struct SolverResult {
+ float pos[3] = {0.0F, 0.0F, 0.0F};
+ bool converged{false};
+ size_t iterations{0};
+ float cost{std::numeric_limits::infinity()};
+};
+
+
+float Flex::ResidualsAndDerivatives(
+ const float linePositions[HANGPRINTER_MAX_ANCHORS],
+ float const pos[3],
+ float residuals[HANGPRINTER_MAX_ANCHORS],
+ float jacobian[HANGPRINTER_MAX_ANCHORS][3],
+ float (*hessians)[3][3]) const noexcept {
+ float baseImpact[HANGPRINTER_MAX_ANCHORS] = { 0.0F };
+ float impactPlus[HANGPRINTER_MAX_ANCHORS][3] = { 0.0F };
+ float impactMinus[HANGPRINTER_MAX_ANCHORS][3] = { 0.0F };
+ constexpr float impactStep = 1e-3F;
+ constexpr bool flexEnabled = true;
+
+ if (flexEnabled) {
+ FlexDistances(pos, baseImpact);
+ for (size_t axis = 0; axis < 3; ++axis) {
+ float shifted[3] = { pos[0], pos[1], pos[2] };
+ shifted[axis] += impactStep;
+ FlexDistances(shifted, impactPlus[axis]);
+ shifted[axis] = pos[axis];
+ shifted[axis] -= impactStep;
+ FlexDistances(shifted, impactMinus[axis]);
+ }
+ }
+
+ float cost = 0.0F;
+ for (size_t i = 0; i < numAnchors; ++i) {
+ float diff[3] = { pos[0] - anchors[i][0], pos[1] - anchors[i][1], pos[2] - anchors[i][2] };
+ float distance = norm(diff);
+ if (distance < 1e-6F) {
+ distance = 1e-6F;
+ }
+ const float invLen = 1.0F / distance;
+ const float invLen3 = invLen * invLen * invLen;
+
+ const float flex = baseImpact[i];
+ const float foundLinePos = distance - distancesOrigin[i] + flex;
+ residuals[i] = foundLinePos - linePositions[i];
+
+ if (hessians) {
+ float (&H)[3][3] = hessians[i];
+ for (size_t r = 0; r < 3; ++r) {
+ for (size_t c = 0; c < 3; ++c) {
+ const float id = (r == c) ? invLen : 0.0F;
+ H[r][c] = id - diff[r] * diff[c] * invLen3;
+ }
+ }
+ }
+
+ for (size_t axis = 0; axis < 3; ++axis) {
+ const float impactDeriv = (impactPlus[axis][i] - impactMinus[axis][i]) / (2.0F * impactStep);
+ jacobian[i][axis] = diff[axis] * invLen + impactDeriv;
+ }
+
+ cost += 0.5F * residuals[i] * residuals[i];
+ }
+ return cost;
+}
+
+static bool solveNormalSystem(const float JTJ[3][3], const float rhs[3], float delta[3]) {
+ FixedMatrix system{};
+ for (size_t r = 0; r < 3; ++r) {
+ for (size_t c = 0; c < 3; ++c) {
+ system(r, c) = JTJ[r][c];
+ }
+ system(r, 3) = rhs[r];
+ }
+ if (!system.GaussJordan(3, 4)) {
+ return false;
+ }
+ delta[0] = system(0, 3);
+ delta[1] = system(1, 3);
+ delta[2] = system(2, 3);
+ return true;
+}
+
+
+void Flex::AccumulateJtJandGrad(
+ float const J[HANGPRINTER_MAX_ANCHORS][3],
+ float const residuals[HANGPRINTER_MAX_ANCHORS],
+ float JTJ[3][3], float grad[3]) const noexcept {
+ for (size_t i = 0; i < 3; ++i) {
+ grad[i] = 0.0F;
+ for (size_t j = 0; j < 3; ++j) {
+ JTJ[i][j] = 0.0F;
+ }
+ }
+
+ for (size_t i = 0; i < numAnchors; ++i) {
+ grad[0] += J[i][0] * residuals[i];
+ grad[1] += J[i][1] * residuals[i];
+ grad[2] += J[i][2] * residuals[i];
+
+ JTJ[0][0] += J[i][0] * J[i][0];
+ JTJ[0][1] += J[i][0] * J[i][1];
+ JTJ[0][2] += J[i][0] * J[i][2];
+ JTJ[1][0] += J[i][1] * J[i][0];
+ JTJ[1][1] += J[i][1] * J[i][1];
+ JTJ[1][2] += J[i][1] * J[i][2];
+ JTJ[2][0] += J[i][2] * J[i][0];
+ JTJ[2][1] += J[i][2] * J[i][1];
+ JTJ[2][2] += J[i][2] * J[i][2];
+ }
+}
+
+SolverResult SolveHybrid(const Flex &flex,
+ const float linePositions[HANGPRINTER_MAX_ANCHORS],
+ float initial[3],
+ float eta,
+ float tol,
+ size_t halleyIters,
+ size_t maxIters,
+ size_t numAnchors) noexcept {
+ SolverResult result{};
+ result.pos[0] = initial[0];
+ result.pos[1] = initial[1];
+ result.pos[2] = initial[2];
+ size_t iter = 0;
+ for (; iter < halleyIters && iter < maxIters; ++iter) {
+ float residuals[HANGPRINTER_MAX_ANCHORS] = { 0.0F };
+ float J[HANGPRINTER_MAX_ANCHORS][3];
+ float H[HANGPRINTER_MAX_ANCHORS][3][3];
+ result.cost =
+ flex.ResidualsAndDerivatives(linePositions, result.pos, residuals, J, H);
+
+ float JTJ[3][3];
+ float grad[3];
+ flex.AccumulateJtJandGrad(J, residuals, JTJ, grad);
+ JTJ[0][0] += eta;
+ JTJ[1][1] += eta;
+ JTJ[2][2] += eta;
+
+ float deltaLm[3] = { 0.0F };
+ float rhs1[3] = {-grad[0], -grad[1], -grad[2]};
+ if (!solveNormalSystem(JTJ, rhs1, deltaLm)) {
+ break;
+ }
+
+ float Hbar[HANGPRINTER_MAX_ANCHORS][3];
+ for (size_t i = 0; i < numAnchors; ++i) {
+ Hbar[i][0] = deltaLm[0] * H[i][0][0] + deltaLm[1] * H[i][1][0] + deltaLm[2] * H[i][2][0];
+ Hbar[i][1] = deltaLm[0] * H[i][0][1] + deltaLm[1] * H[i][1][1] + deltaLm[2] * H[i][2][1];
+ Hbar[i][2] = deltaLm[0] * H[i][0][2] + deltaLm[1] * H[i][1][2] + deltaLm[2] * H[i][2][2];
+ }
+
+ float Jbar[HANGPRINTER_MAX_ANCHORS][3];
+ for (size_t i = 0; i < numAnchors; ++i) {
+ Jbar[i][0] = J[i][0] + 0.5F * Hbar[i][0];
+ Jbar[i][1] = J[i][1] + 0.5F * Hbar[i][1];
+ Jbar[i][2] = J[i][2] + 0.5F * Hbar[i][2];
+ }
+
+ float JTJ2[3][3];
+ float grad2[3];
+ flex.AccumulateJtJandGrad(Jbar, residuals, JTJ2, grad2);
+ JTJ2[0][0] += eta;
+ JTJ2[1][1] += eta;
+ JTJ2[2][2] += eta;
+
+ float delta[3] = { 0.0F };
+ float rhs2[3] = {-grad2[0], -grad2[1], -grad2[2]};
+ if (!solveNormalSystem(JTJ2, rhs2, delta)) {
+ break;
+ }
+
+ result.pos[0] = result.pos[0] + delta[0];
+ result.pos[1] = result.pos[1] + delta[1];
+ result.pos[2] = result.pos[2] + delta[2];
+ result.iterations = iter + 1;
+ if (norm(delta) < tol) {
+ result.converged = true;
+ break;
+ }
+ }
+
+ for (; iter < maxIters && !result.converged; ++iter) {
+ float residuals[HANGPRINTER_MAX_ANCHORS] = { 0.0F };
+ float J[HANGPRINTER_MAX_ANCHORS][3];
+ result.cost =
+ flex.ResidualsAndDerivatives(linePositions, result.pos, residuals, J, nullptr);
+
+ float JTJ[3][3];
+ float grad[3];
+ flex.AccumulateJtJandGrad(J, residuals, JTJ, grad);
+ JTJ[0][0] += eta;
+ JTJ[1][1] += eta;
+ JTJ[2][2] += eta;
+
+ float delta[3] = { 0.0F };
+ float rhs3[3] = {-grad[0], -grad[1], -grad[2]};
+ if (!solveNormalSystem(JTJ, rhs3, delta)) {
+ break;
+ }
+
+ result.pos[0] = result.pos[0] + delta[0];
+ result.pos[1] = result.pos[1] + delta[1];
+ result.pos[2] = result.pos[2] + delta[2];
+ result.iterations = iter + 1;
+ if (norm(delta) < tol) {
+ result.converged = true;
+ break;
+ }
+ }
+
+ float residuals[HANGPRINTER_MAX_ANCHORS] = { 0.0F };
+ float Jtmp[HANGPRINTER_MAX_ANCHORS][3];
+ result.cost =
+ flex.ResidualsAndDerivatives(linePositions, result.pos, residuals, Jtmp, nullptr);
+ return result;
+}
+
+static SolverResult SolveHalley(const Flex &flex, const std::vector &linePositions, float seed[3],
+ float eta, float tol, size_t maxIters) {
+ return SolveHybrid(flex, linePositions.data(), seed, eta, tol, maxIters, maxIters, linePositions.size());
+}
+
+static SolverResult solveLm(const std::vector> & /*anchors*/,
+ const std::vector &linePositions,
+ const std::array & /*origins*/,
+ const Flex &flex, float seed[3], float eta, float tol, size_t maxIters) {
+ return SolveHybrid(flex, linePositions.data(), seed, eta, tol, 0, maxIters, linePositions.size());
+}
+
+static std::vector motorPosToLinePositions(const Flex &flex, const std::array &motorPos,
+ size_t numAnchors) {
+ std::vector linePositions(numAnchors, 0.0F);
+ for (size_t i = 0; i < numAnchors; ++i) {
+ const float steps = motorPos[i] * g_stepsPerDegree;
+ linePositions[i] = flex.MotorPosToLinePos(steps, i);
+ }
+ return linePositions;
+}
+
+#ifndef RUN_DATASET_CLI
+int main() {
+ constexpr size_t numAnchors = 5;
+ Flex const flex = makeFlex(numAnchors);
+ auto const origins = originLengths(numAnchors);
+
+ // Dataset from motorstepstocartesiantest.cpp ("With flex max 120 target 20")
+ std::vector> motorPoss = {
+ {-369.47366890F, -375.18362935F, 318.27641438F, 323.88876891F, 1076.68163402F},
+ {-5980.29607895F, 12630.56774248F, 12288.67350302F, -6506.18962476F, -13348.06053879F},
+ {-2353.64278337F, 15870.99892165F, 15755.46225500F, -2522.71380922F, -27477.49741579F},
+ {1433.28912224F, 10685.68516553F, 1454.31086905F, -10542.99803343F, 1813.47411829F},
+ {3112.53568603F, 11779.51141393F, 3231.55807349F, -7609.55533435F, -17364.20990461F},
+ {7221.24317502F, 14331.47424095F, 6657.95387927F, -1853.21287105F, -36135.10874008F},
+ {10106.78583366F, 10693.29200030F, -7583.66231627F, -8505.26876850F, 6010.84493879F},
+ {11680.14400927F, 12421.57492733F, -5209.71780789F, -6326.70127134F, -14780.55685279F},
+ {16309.54520647F, 16482.81831770F, -1424.01387322F, -1674.11174073F, -29909.99659944F},
+ {-10145.44532568F, 1094.96136691F, 10156.51947369F, 1434.73615456F, 3572.60726310F},
+ {-7640.99960502F, 3134.81886277F, 11567.99443696F, 2933.32488052F, -16735.05779004F},
+ {-2825.34894707F, 7163.91339055F, 14266.90144144F, 5840.37464568F, -33865.11200386F},
+ {-7448.08057312F, 10796.70751776F, 10151.74389637F, -8459.78905687F, 3271.18757879F},
+ {2211.41905092F, 2111.20882241F, 858.18022603F, 961.42598207F, -17727.66189890F},
+ {6585.49993026F, 5349.29768666F, 5599.61645498F, 6829.22955353F, -40179.35611831F},
+ {9827.26906637F, 973.41612678F, -9847.89764725F, 1374.65365736F, 4088.32777321F},
+ {11672.37320821F, 3419.76976053F, -7745.30493425F, 2691.62201517F, -16638.39998295F},
+ {13421.03929287F, 6834.73758758F, -2414.14469240F, 5523.60605573F, -33907.52745615F},
+ {-8153.62357389F, -7386.54442994F, 10370.98726659F, 9875.86705528F, 3214.03835550F},
+ {-6347.85480184F, -5493.48884529F, 12625.31736324F, 12063.42984255F, -14568.06462464F},
+ {-2585.49492187F, -1676.70121477F, 15851.52670557F, 15223.11520330F, -28367.04177068F},
+ {730.23171944F, -9759.54189457F, 1580.93148691F, 9745.76583762F, 3967.14372473F},
+ {2429.55959648F, -7123.34974121F, 3539.66195357F, 11159.52316296F, -17372.69974680F},
+ {6079.30436810F, -2972.78187516F, 7172.81870678F, 14578.78537233F, -33851.97153806F},
+ {11195.81863308F, -7791.69855043F, -8587.42819506F, 10696.72883673F, 3279.60983059F},
+ {12162.75651477F, -6552.47720614F, -6177.61954587F, 12406.22670936F, -12538.57963324F},
+ {14653.37178962F, -2366.53557957F, -1021.48237225F, 15599.48126071F, -29623.47054342F},
+ };
+
+ std::vector> expectedPoss = {
+ {{17.9255679F, -17.6352632F, -27.497151F}},
+ {{-523.885148F, -501.061599F, 507.741532F}},
+ {{-538.35251F, -530.255594F, 953.040004F}},
+ {{-545.189816F, -0.55803779F, 26.4689901F}},
+ {{-520.999273F, -3.27341154F, 537.019049F}},
+ {{-470.799477F, 16.5498517F, 1047.17018F}},
+ {{-505.362595F, 467.529134F, -42.5453256F}},
+ {{-513.234032F, 464.122399F, 533.480869F}},
+ {{-538.29312F, 526.060302F, 1030.39159F}},
+ {{8.98405788F, -520.642383F, -26.6148823F}},
+ {{-5.52678502F, -514.840431F, 517.628213F}},
+ {{-38.6000122F, -492.617793F, 991.936222F}},
+ {{-507.629503F, -465.97604F, 31.7537695F}},
+ {{-30.5601452F, 35.9665477F, 458.719776F}},
+ {{43.2898928F, 28.8400594F, 1046.72968F}},
+ {{10.5874156F, 504.407891F, -44.2588518F}},
+ {{-19.9804722F, 520.41744F, 517.004705F}},
+ {{-37.9958866F, 454.266612F, 975.222737F}},
+ {{455.930483F, -487.688259F, 26.0515823F}},
+ {{482.712486F, -520.125685F, 535.481389F}},
+ {{495.517745F, -539.35609F, 965.228753F}},
+ {{500.096373F, -22.437457F, -42.0139801F}},
+ {{490.657689F, -30.4215669F, 527.319817F}},
+ {{506.742907F, -31.9689121F, 998.360926F}},
+ {{490.590662F, 523.118645F, 41.4092948F}},
+ {{517.848381F, 501.639033F, 482.878157F}},
+ {{525.399857F, 459.863258F, 981.665044F}},
+ };
+
+ float totalErrHalley = 0.0F;
+ float totalErrHybrid = 0.0F;
+ float totalErrLm = 0.0F;
+
+ std::cout << "idx, halley_err(mm), hybrid_err(mm), lm_err(mm), halley_it, hybrid_it, lm_it\n";
+ float seed[3] = {0.0F, 0.0F, 0.0F};
+ for (size_t i = 0; i < motorPoss.size(); ++i) {
+ auto linePositions = motorPosToLinePositions(flex, motorPoss[i], numAnchors);
+ std::vector> anchorVec;
+ anchorVec.reserve(numAnchors);
+ for (size_t k = 0; k < numAnchors; ++k) {
+ anchorVec.push_back({fiveAnchors[k][0], fiveAnchors[k][1], fiveAnchors[k][2]});
+ }
+
+ SolverResult halley =
+ SolveHalley(linePositions, seed, 1e-3F, 1e-3F, 20);
+ SolverResult hybrid =
+ SolveHybrid(flex, linePositions.data(), seed, 1e-3F, 1e-3F, 3, 30, numAnchors);
+ SolverResult lm = solveLm(anchorVec, linePositions, origins, flex, seed, 1e-3F, 1e-3F, 30);
+
+ float halleyErr[3] = { 0.0F };
+ halleyErr[0] = expectedPoss[i][0] - halley.pos[0];
+ halleyErr[1] = expectedPoss[i][1] - halley.pos[1];
+ halleyErr[2] = expectedPoss[i][2] - halley.pos[2];
+ float hybridErr[3] = { 0.0F };
+ hybridErr[0] = expectedPoss[i][0] - hybrid.pos[0];
+ hybridErr[1] = expectedPoss[i][1] - hybrid.pos[1];
+ hybridErr[2] = expectedPoss[i][2] - hybrid.pos[2];
+ float lmErr[3] = { 0.0F };
+ lmErr[0] = expectedPoss[i][0] - lm.pos[0];
+ lmErr[1] = expectedPoss[i][1] - lm.pos[1];
+ lmErr[2] = expectedPoss[i][2] - lm.pos[2];
+ float halleyNorm = norm(halleyErr);
+ float hybridNorm = norm(hybridErr);
+ float lmNorm = norm(lmErr);
+ totalErrHalley += halleyNorm;
+ totalErrHybrid += hybridNorm;
+ totalErrLm += lmNorm;
+
+ std::cout << i << ", " << halleyNorm << ", " << hybridNorm << ", " << lmNorm << ", " << halley.iterations << ", "
+ << hybrid.iterations << ", " << lm.iterations << '\n';
+
+ // Warm start from previous pose to mirror controller behaviour
+ Copy3(halley.pos, seed);
+ }
+
+ const float n = static_cast(motorPoss.size());
+ std::cout << "Mean error (Halley): " << (totalErrHalley / n) << " mm\n";
+ std::cout << "Mean error (Hybrid Halley->LM): " << (totalErrHybrid / n) << " mm\n";
+ std::cout << "Mean error (LM baseline): " << (totalErrLm / n) << " mm\n";
+ return 0;
+}
+#else
+int main() {
+ std::ios::sync_with_stdio(false);
+ std::string line;
+ while (std::getline(std::cin, line)) {
+ if (line.empty()) {
+ continue;
+ }
+ if (line.rfind("CFG", 0) == 0) {
+ parseConfigLine(line);
+ continue;
+ }
+
+ std::istringstream iss(line);
+ size_t numAnchors = 0;
+ int useFlexInt = 1;
+ if (!(iss >> numAnchors >> useFlexInt)) {
+ std::cout << "fail 0 0 0 0 0 0\n";
+ continue;
+ }
+ if (numAnchors == 0 || numAnchors > HANGPRINTER_MAX_ANCHORS) {
+ std::cout << "fail 0 0 0 0 0 0\n";
+ continue;
+ }
+
+ std::array motorPos{};
+ motorPos.fill(0.0F);
+ for (size_t i{0}; i < numAnchors; ++i) {
+ if (!(iss >> motorPos[i])) {
+ std::cout << "fail 0 0 0 0 0 0\n";
+ continue;
+ }
+ }
+
+ std::vector> anchors(numAnchors);
+ for (size_t i{0}; i < numAnchors; ++i) {
+ if (!(iss >> anchors[i][0] >> anchors[i][1] >> anchors[i][2])) {
+ std::cout << "fail 0 0 0 0 0 0\n";
+ continue;
+ }
+ }
+ setActiveAnchors(anchors);
+
+ Flex const flex = makeFlex(numAnchors);
+ auto const origins = originLengths(numAnchors);
+ auto linePositions = motorPosToLinePositions(flex, motorPos, numAnchors);
+ std::vector> anchorVec = anchors;
+
+ float seed[3] = {0.0F, 0.0F, 0.0F};
+ auto const start = std::chrono::steady_clock::now();
+ SolverResult hybrid =
+ SolveHybrid(flex, linePositions.data(), seed, 1e-3F, 1e-3F, 3, 30, numAnchors);
+ auto const end = std::chrono::steady_clock::now();
+ double const ms = std::chrono::duration(end - start).count();
+
+ std::cout << (hybrid.converged ? "ok" : "fail") << ' ' << hybrid.pos[0] << ' ' << hybrid.pos[1] << ' '
+ << hybrid.pos[2] << ' ' << hybrid.iterations << ' ' << hybrid.cost << ' ' << ms << '\n';
+ }
+ return 0;
+}
+#endif
diff --git a/ai_docs/run_tests.py b/ai_docs/run_tests.py
new file mode 100644
index 000000000000..c323488f9ae1
--- /dev/null
+++ b/ai_docs/run_tests.py
@@ -0,0 +1,511 @@
+#!/usr/bin/env python3
+"""
+Synthetic dataset test harness for the Hangprinter forward transforms.
+Reads the JSONL datasets, feeds them to the three solver binaries, and prints a brief report.
+"""
+from __future__ import annotations
+
+import json
+import math
+import random
+import statistics
+import subprocess
+import sys
+from collections import defaultdict
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, Iterable, List, Sequence
+
+ROOT = Path(__file__).parent
+DATASETS = ROOT / "datasets"
+BUILD = ROOT / "build"
+MAX_ANCHORS = 8 # solver supports up to CubeCorners
+MM_TO_DEG = 360.0 / (2.0 * math.pi * 75.0) # approx conversion for 75 mm spool
+GEOMETRY_ORDER = ["HP5", "Slideprinter", "Spidercam", "CubeCorners"]
+# Treat solutions with larger error as failures in summary stats.
+MAX_SUCCESS_ERR_MM = 10.0
+
+
+@dataclass
+class Sample:
+ anchors: List[List[float]]
+ motor_deg: List[float]
+ gt: List[float]
+ geometry: str
+ dataset: str
+ anchor_set: int
+ config: Dict[str, Any] = field(default_factory=dict)
+ unsupported: bool = False
+
+
+@dataclass
+class SolverResult:
+ ok: bool
+ pos: List[float]
+ iterations: int
+ cost: float
+ runtime_ms: float
+ unsupported: bool = False
+
+
+@dataclass
+class Stats:
+ total: int
+ supported: int
+ success_rate: float
+ mae: float
+ med_err: float
+ std_err: float
+ mean_cost: float
+ mean_iters: float
+ mean_ms: float
+ skipped: int
+
+
+@dataclass
+class SolverSummary:
+ overall: Stats
+ by_geo: dict[str, Stats]
+
+
+SOLVERS = {
+ "quadratic": {
+ "path": BUILD / "solver_quadratic",
+ "supports_no_flex": False,
+ "label": "quadratic (reference)",
+ "type": "binary",
+ },
+ "calc_position": {
+ "path": BUILD / "solver_calc_position",
+ "supports_no_flex": False,
+ "label": "calc_position",
+ "type": "binary",
+ },
+}
+
+
+def load_samples(pattern: str) -> List[Sample]:
+ samples: List[Sample] = []
+ for path in sorted(DATASETS.glob(pattern)):
+ with path.open() as fh:
+ for line in fh:
+ obj = json.loads(line)
+ anchors = obj["anchors"]
+ motors = obj["motor_samples"]
+ poses = obj["real_xyz"]
+ config = obj.get("config_used", {}) or {}
+ unsupported = len(anchors) > MAX_ANCHORS
+ for pose, motor in zip(poses, motors):
+ samples.append(
+ Sample(
+ anchors=anchors,
+ motor_deg=motor,
+ gt=pose,
+ geometry=obj.get("geometry", path.stem),
+ dataset=obj.get("dataset", path.stem),
+ anchor_set=obj.get("anchor_set", 0),
+ config=config,
+ unsupported=unsupported,
+ )
+ )
+ return samples
+
+
+def add_gaussian_noise(samples: Sequence[Sample], sigma_mm: float, rng: random.Random) -> List[Sample]:
+ noisy: List[Sample] = []
+ sigma_deg = sigma_mm * MM_TO_DEG
+ for s in samples:
+ motors = [m + rng.gauss(0.0, sigma_deg) for m in s.motor_deg]
+ noisy.append(
+ Sample(
+ anchors=s.anchors,
+ motor_deg=motors,
+ gt=s.gt,
+ geometry=s.geometry,
+ dataset=s.dataset,
+ anchor_set=s.anchor_set,
+ config=s.config,
+ unsupported=s.unsupported,
+ )
+ )
+ return noisy
+
+
+def add_bias(samples: Sequence[Sample], biases_mm: Sequence[float]) -> List[Sample]:
+ biases_deg = [b * MM_TO_DEG for b in biases_mm]
+ biased: List[Sample] = []
+ for s in samples:
+ motors = [m + biases_deg[i % len(biases_deg)] for i, m in enumerate(s.motor_deg)]
+ biased.append(
+ Sample(
+ anchors=s.anchors,
+ motor_deg=motors,
+ gt=s.gt,
+ geometry=s.geometry,
+ dataset=s.dataset,
+ anchor_set=s.anchor_set,
+ config=s.config,
+ unsupported=s.unsupported,
+ )
+ )
+ return biased
+
+
+DEFAULT_CONFIG = {
+ "spool_buildup_factor": 0.043003,
+ "spool_r_in_origin": [75.0],
+ "spool_gear_teeth": 255.0,
+ "motor_gear_teeth": 20.0,
+ "mechanical_advantage": [2.0, 2.0, 2.0, 2.0, 4.0],
+ "lines_per_spool": [1.0],
+ "min_force": 3.0,
+ "max_force": 120.0,
+ "spring_k_per_unit_length": 20000.0,
+ "mover_weight": 2.0,
+ "lambda_reg": 1e-3,
+ "tol": 1e-3,
+ "max_iters_target": 100,
+ "g": 9.81,
+ "guy_wire_lengths": 0.0,
+}
+
+
+def _broadcast_array(value: Any, count: int, default: Any) -> List[float]:
+ if value is None:
+ base = default
+ else:
+ base = value
+ if isinstance(base, (list, tuple)):
+ arr = list(base)
+ else:
+ arr = [base]
+ if not arr:
+ arr = [default] if not isinstance(default, (list, tuple)) else list(default)
+ if len(arr) < count:
+ arr += [arr[-1]] * (count - len(arr))
+ elif len(arr) > count:
+ arr = arr[:count]
+ return [float(x) for x in arr]
+
+
+def make_config_header(cfg: Dict[str, Any], num_anchors: int) -> str:
+ spool_buildup = float(cfg.get("spool_buildup_factor", DEFAULT_CONFIG["spool_buildup_factor"]))
+ spring_k = float(cfg.get("spring_k_per_unit_length", DEFAULT_CONFIG["spring_k_per_unit_length"]))
+ mover_weight = float(cfg.get("mover_weight", DEFAULT_CONFIG["mover_weight"]))
+ spool_gear = float(cfg.get("spool_gear_teeth", DEFAULT_CONFIG["spool_gear_teeth"]))
+ motor_gear = float(cfg.get("motor_gear_teeth", DEFAULT_CONFIG["motor_gear_teeth"]))
+ steps_per_rev = 360.0 # motor_samples are in degrees
+ use_flex = bool(cfg.get("use_flex", True))
+ ignore_gravity = bool(cfg.get("ignore_gravity", False))
+ ignore_pretension = bool(cfg.get("ignore_pretension", False))
+ lambda_reg = float(cfg.get("lambda_reg", DEFAULT_CONFIG["lambda_reg"]))
+ tol = float(cfg.get("tol", DEFAULT_CONFIG["tol"]))
+ max_iters_target = int(cfg.get("max_iters_target", DEFAULT_CONFIG["max_iters_target"]))
+ g = float(cfg.get("g", DEFAULT_CONFIG["g"]))
+
+ spool_r = _broadcast_array(cfg.get("spool_r_in_origin") or cfg.get("spool_r"), num_anchors, DEFAULT_CONFIG["spool_r_in_origin"])
+ mech_adv = _broadcast_array(cfg.get("mechanical_advantage"), num_anchors, DEFAULT_CONFIG["mechanical_advantage"])
+ lines = _broadcast_array(cfg.get("lines_per_spool"), num_anchors, DEFAULT_CONFIG["lines_per_spool"])
+ min_force = _broadcast_array(cfg.get("min_force"), num_anchors, DEFAULT_CONFIG["min_force"])
+ max_force = _broadcast_array(cfg.get("max_force"), num_anchors, DEFAULT_CONFIG["max_force"])
+ guy_wires = _broadcast_array(cfg.get("guy_wire_lengths"), num_anchors, DEFAULT_CONFIG["guy_wire_lengths"])
+
+ def fmt(val: float) -> str:
+ return f"{val:.9g}"
+
+ parts = [
+ "CFG",
+ str(num_anchors),
+ fmt(spool_buildup),
+ fmt(spring_k),
+ fmt(mover_weight),
+ fmt(spool_gear),
+ fmt(motor_gear),
+ fmt(steps_per_rev),
+ "1" if use_flex else "0",
+ "1" if ignore_gravity else "0",
+ "1" if ignore_pretension else "0",
+ fmt(lambda_reg),
+ fmt(tol),
+ str(max_iters_target),
+ fmt(g),
+ ]
+ for arr in (spool_r, mech_adv, lines, min_force, max_force, guy_wires):
+ parts.extend(fmt(v) for v in arr)
+ return " ".join(parts)
+
+
+def make_input_lines(samples: Sequence[Sample], use_flex: bool) -> tuple[List[str], List[int], int]:
+ lines: List[str] = []
+ idx_map: List[int] = []
+ skipped = 0
+ for idx, sample in enumerate(samples):
+ if sample.unsupported:
+ skipped += 1
+ continue
+ num = len(sample.anchors)
+ motor_str = " ".join(f"{m:.6f}" for m in sample.motor_deg[:num])
+ anchor_flat = [coord for anchor in sample.anchors[:num] for coord in anchor]
+ anchor_str = " ".join(f"{a:.6f}" for a in anchor_flat)
+ lines.append(f"{num} {1 if use_flex else 0} {motor_str} {anchor_str}")
+ idx_map.append(idx)
+ return lines, idx_map, skipped
+
+
+def run_solver(samples: Sequence[Sample], solver_key: str, use_flex: bool) -> List[SolverResult]:
+ solver = SOLVERS[solver_key]
+ exe = solver["path"]
+ if not exe.exists():
+ raise FileNotFoundError(f"Solver binary missing: {exe}")
+
+ grouped: Dict[str, List[int]] = defaultdict(list)
+ headers: Dict[str, str] = {}
+ for idx, sample in enumerate(samples):
+ header = make_config_header(sample.config, len(sample.anchors))
+ grouped[header].append(idx)
+ headers[header] = header
+
+ results = [
+ SolverResult(ok=False, pos=[0.0, 0.0, 0.0], iterations=0, cost=0.0, runtime_ms=0.0, unsupported=s.unsupported)
+ for s in samples
+ ]
+
+ for header, indices in grouped.items():
+ subset = [samples[i] for i in indices]
+ lines, idx_map, skipped = make_input_lines(subset, use_flex)
+ if not lines:
+ continue
+ payload = [header] + lines if header else lines
+ proc = subprocess.run(
+ [str(exe)],
+ input="\n".join(payload) + "\n",
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ output_lines = [l for l in proc.stdout.splitlines() if l.strip()]
+ if len(output_lines) != len(idx_map):
+ raise RuntimeError(f"{solver_key} returned {len(output_lines)} lines for {len(idx_map)} samples (header {header})")
+
+ for raw, subset_idx in zip(output_lines, idx_map):
+ parts = raw.strip().split()
+ if len(parts) < 7:
+ continue
+ status, x, y, z, iters, cost, runtime = parts[:7]
+ ok = status == "ok"
+ sample_idx = indices[subset_idx]
+ results[sample_idx] = SolverResult(
+ ok=ok,
+ pos=[float(x), float(y), float(z)],
+ iterations=int(float(iters)),
+ cost=float(cost),
+ runtime_ms=float(runtime),
+ unsupported=False,
+ )
+ return results
+
+
+def summarise(samples: Sequence[Sample], results: Sequence[SolverResult]) -> SolverSummary:
+ records_by_geo: dict[str, list[tuple[bool, float | None, float, int, float]]] = defaultdict(list)
+ skipped_by_geo: dict[str, int] = defaultdict(int)
+ skipped_total = 0
+
+ for sample, res in zip(samples, results):
+ geo = sample.geometry
+ if res.unsupported or sample.unsupported:
+ skipped_total += 1
+ skipped_by_geo[geo] += 1
+ continue
+
+ err = None
+ if res.ok:
+ dx = res.pos[0] - sample.gt[0]
+ dy = res.pos[1] - sample.gt[1]
+ dz = res.pos[2] - sample.gt[2]
+ err = math.sqrt(dx * dx + dy * dy + dz * dz)
+
+ ok = res.ok
+ if res.ok and err is not None and err > MAX_SUCCESS_ERR_MM:
+ ok = False
+ err = None
+
+ records_by_geo[geo].append((ok, err, res.cost, res.iterations, res.runtime_ms))
+
+ def build_stats(records: list[tuple[bool, float | None, float, int, float]], skipped: int) -> Stats:
+ supported = len(records)
+ success = sum(1 for r in records if r[0])
+ errs = [r[1] for r in records if r[0] and r[1] is not None]
+ costs = [r[2] for r in records if r[0]]
+ iters = [r[3] for r in records if r[0]]
+ runtimes = [r[4] for r in records if r[0]]
+ return Stats(
+ total=supported + skipped,
+ supported=supported,
+ success_rate=(success / supported) * 100 if supported else 0.0,
+ mae=statistics.mean(errs) if errs else float("nan"),
+ med_err=statistics.median(errs) if errs else float("nan"),
+ std_err=statistics.pstdev(errs) if errs else float("nan"),
+ mean_cost=statistics.mean(costs) if costs else float("nan"),
+ mean_iters=statistics.mean(iters) if iters else float("nan"),
+ mean_ms=statistics.mean(runtimes) if runtimes else float("nan"),
+ skipped=skipped,
+ )
+
+ overall_records: list[tuple[bool, float | None, float, int, float]] = []
+ for recs in records_by_geo.values():
+ overall_records.extend(recs)
+
+ overall = build_stats(overall_records, skipped_total)
+ by_geo = {geo: build_stats(recs, skipped_by_geo.get(geo, 0)) for geo, recs in records_by_geo.items()}
+ return SolverSummary(overall=overall, by_geo=by_geo)
+
+
+def summarise_difference(samples: Sequence[Sample], ref: Sequence[SolverResult], alt: Sequence[SolverResult]) -> SolverSummary:
+ records_by_geo: dict[str, list[tuple[bool, float | None, float, int, float]]] = defaultdict(list)
+ skipped_by_geo: dict[str, int] = defaultdict(int)
+ skipped_total = 0
+
+ for sample, r_ref, r_alt in zip(samples, ref, alt):
+ geo = sample.geometry
+ if r_ref.unsupported or r_alt.unsupported or sample.unsupported:
+ skipped_total += 1
+ skipped_by_geo[geo] += 1
+ continue
+ if not (r_ref.ok and r_alt.ok):
+ records_by_geo[geo].append((False, None, 0.0, 0, 0.0))
+ continue
+ dx = r_ref.pos[0] - r_alt.pos[0]
+ dy = r_ref.pos[1] - r_alt.pos[1]
+ dz = r_ref.pos[2] - r_alt.pos[2]
+ err = math.sqrt(dx * dx + dy * dy + dz * dz)
+ ok = err <= MAX_SUCCESS_ERR_MM
+ cost = abs(r_ref.cost - r_alt.cost)
+ iters = abs(r_ref.iterations - r_alt.iterations)
+ dt_ms = abs(r_ref.runtime_ms - r_alt.runtime_ms)
+ records_by_geo[geo].append((ok, err, cost, iters, dt_ms))
+
+ def build_stats(records: list[tuple[bool, float | None, float, int, float]], skipped: int) -> Stats:
+ supported = len(records)
+ success = sum(1 for r in records if r[0])
+ errs = [r[1] for r in records if r[0] and r[1] is not None]
+ costs = [r[2] for r in records if r[0]]
+ iters = [r[3] for r in records if r[0]]
+ runtimes = [r[4] for r in records if r[0]]
+ return Stats(
+ total=supported + skipped,
+ supported=supported,
+ success_rate=(success / supported) * 100 if supported else 0.0,
+ mae=statistics.mean(errs) if errs else float("nan"),
+ med_err=statistics.median(errs) if errs else float("nan"),
+ std_err=statistics.pstdev(errs) if errs else float("nan"),
+ mean_cost=statistics.mean(costs) if costs else float("nan"),
+ mean_iters=statistics.mean(iters) if iters else float("nan"),
+ mean_ms=statistics.mean(runtimes) if runtimes else float("nan"),
+ skipped=skipped,
+ )
+
+ overall_records: list[tuple[bool, float | None, float, int, float]] = []
+ for recs in records_by_geo.values():
+ overall_records.extend(recs)
+ overall = build_stats(overall_records, skipped_total)
+ by_geo = {geo: build_stats(recs, skipped_by_geo.get(geo, 0)) for geo, recs in records_by_geo.items()}
+ return SolverSummary(overall=overall, by_geo=by_geo)
+
+
+def print_summary(title: str, summaries: dict):
+ print(f"\n{title}")
+ for solver, stats in summaries.items():
+ overall = stats.overall
+ geo_cols = []
+ for geo in GEOMETRY_ORDER:
+ if geo in stats.by_geo:
+ g = stats.by_geo[geo]
+ geo_cols.append(f"{geo} {g.success_rate:.1f}%/{g.mae:.3f}mm/±{g.std_err:.3f}mm")
+ geo_suffix = f" | {' | '.join(geo_cols)}" if geo_cols else ""
+ print(
+ f"- {solver:10s} success {overall.success_rate:.1f}% | mae {overall.mae:.3f} mm | "
+ f"median {overall.med_err:.3f} mm | iters {overall.mean_iters:.1f} | "
+ f"cost {overall.mean_cost:.2e} | {overall.mean_ms:.3f} ms/solve "
+ f"(unsupported {overall.skipped}){geo_suffix}"
+ )
+
+
+def run_suite(name: str, sample_patterns: Iterable[str], use_flex: bool = True, samples: List[Sample] | None = None) -> dict:
+ if samples is None:
+ combined: List[Sample] = []
+ for pat in sample_patterns:
+ combined.extend(load_samples(pat))
+ samples = combined
+ summaries = {}
+ results_store: dict[str, List[SolverResult]] = {}
+ for key, meta in SOLVERS.items():
+ results = run_solver(samples, key, use_flex=use_flex)
+ label = meta["label"]
+ if not use_flex and meta["supports_no_flex"]:
+ label = f"{label} (noflex)"
+ summaries[label] = summarise(samples, results)
+ results_store[label] = results
+
+ # Pairwise difference between reference and calc_position if available
+ ref_label = SOLVERS["quadratic"]["label"]
+ alt_label = SOLVERS.get("calc_position", {}).get("label")
+ if ref_label in results_store and alt_label in results_store:
+ diff_stats = summarise_difference(samples, results_store[ref_label], results_store[alt_label])
+ summaries["difference"] = diff_stats
+ print_summary(name, summaries)
+ return summaries
+
+
+def main() -> int:
+ rng = random.Random(42)
+ baseline_patterns = [
+ "clean_baseline_*.jsonl",
+ "larger_baseline_*.jsonl",
+ "near_singularities_*.jsonl",
+ "at_singularities_*.jsonl",
+ "outside_singularities_*.jsonl",
+ "systematic_bias_*.jsonl",
+ ]
+
+ for pat in baseline_patterns:
+ run_suite(f"Dataset {pat}", [pat])
+
+ noise_levels = [1.0, 3.0, 5.0]
+ clean_samples = load_samples("clean_baseline_*.jsonl")
+ for sigma in noise_levels:
+ noisy = add_gaussian_noise(clean_samples, sigma_mm=sigma, rng=rng)
+ run_suite(f"Noise σ={sigma} mm", [], samples=noisy)
+
+ bias_pattern = [5.0, -5.0, 2.5, -2.5, 0.0]
+ biased = add_bias(clean_samples, bias_pattern)
+ run_suite("Per-line bias (+/-5 mm)", [], samples=biased)
+
+ # Flex vs no-flex (Pott supports the toggle; other solvers keep flex enabled)
+ flex_summaries = {}
+ for use_flex in (True, False):
+ summaries = {}
+ for key, meta in SOLVERS.items():
+ if not use_flex and not meta["supports_no_flex"]:
+ continue
+ results = run_solver(clean_samples, key, use_flex=use_flex)
+ label = meta["label"]
+ if not use_flex and meta["supports_no_flex"]:
+ label = f"{label} (noflex)"
+ summaries[label] = summarise(clean_samples, results)
+ print_summary(f"Flex toggle (clean baseline, use_flex={use_flex})", summaries)
+ flex_summaries.update(summaries)
+
+ # Performance microbench: mix of clean + larger
+ perf_samples = load_samples("clean_baseline_*.jsonl") + load_samples("larger_baseline_*.jsonl")
+ perf_samples = perf_samples[:1000]
+ perf_summaries = {}
+ for key, meta in SOLVERS.items():
+ results = run_solver(perf_samples, key, use_flex=True)
+ perf_summaries[meta["label"]] = summarise(perf_samples, results)
+ print_summary("Performance microbench (<=1000 samples)", perf_summaries)
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/ai_docs/solver_calc_position.c b/ai_docs/solver_calc_position.c
new file mode 100644
index 000000000000..5906ac7232e8
--- /dev/null
+++ b/ai_docs/solver_calc_position.c
@@ -0,0 +1,274 @@
+// CLI wrapper around klipper's winch_forward_solve for dataset evaluation.
+// Matches the input format used by solver_quadratic: optional CFG line
+// followed by rows of: N use_flex motor_deg... anchor_xyz...
+
+#include
+#include
+#include
+#include
+#include
+
+#include "../klippy/chelper/kin_winch.c"
+
+// Stub out move_get_coord so kin_winch.c links; not used by this tool.
+struct coord
+move_get_coord(struct move *m, double move_time)
+{
+ struct coord c = { 0.0, 0.0, 0.0 };
+ return c;
+}
+
+struct cfg_state {
+ size_t count;
+ double spool_buildup;
+ double spring_k_per_unit_length;
+ double mover_weight;
+ double spool_gear;
+ double motor_gear;
+ double steps_per_rev;
+ int use_flex;
+ int ignore_gravity;
+ int ignore_pretension;
+ double lambda_reg;
+ double tol;
+ int max_iters_target;
+ double g;
+ double spool_r[WINCH_MAX_ANCHORS];
+ double mech_adv[WINCH_MAX_ANCHORS];
+ double lines_per_spool[WINCH_MAX_ANCHORS];
+ double min_force[WINCH_MAX_ANCHORS];
+ double max_force[WINCH_MAX_ANCHORS];
+ double guy_wires[WINCH_MAX_ANCHORS];
+ int has_cfg;
+};
+
+static void
+init_cfg(struct cfg_state *cfg)
+{
+ memset(cfg, 0, sizeof(*cfg));
+ cfg->count = 0;
+ cfg->spool_buildup = 0.043003;
+ cfg->spring_k_per_unit_length = 20000.0;
+ cfg->mover_weight = 2.0;
+ cfg->spool_gear = 255.0;
+ cfg->motor_gear = 20.0;
+ cfg->steps_per_rev = 360.0;
+ cfg->use_flex = 1;
+ cfg->ignore_gravity = 0;
+ cfg->ignore_pretension = 0;
+ cfg->lambda_reg = 1e-3;
+ cfg->tol = 1e-3;
+ cfg->max_iters_target = 100;
+ cfg->g = 9.81;
+ for (int i = 0; i < WINCH_MAX_ANCHORS; ++i) {
+ cfg->spool_r[i] = 75.0;
+ cfg->mech_adv[i] = 2.0;
+ cfg->lines_per_spool[i] = 1.0;
+ cfg->min_force[i] = 3.0;
+ cfg->max_force[i] = 120.0;
+ cfg->guy_wires[i] = 0.0;
+ }
+ cfg->has_cfg = 0;
+}
+
+static void
+broadcast_tail(double *arr, size_t count)
+{
+ if (!count || count >= WINCH_MAX_ANCHORS)
+ return;
+ double last = arr[count - 1];
+ for (size_t i = count; i < WINCH_MAX_ANCHORS; ++i)
+ arr[i] = last;
+}
+
+static int
+parse_cfg_line(const char *line, struct cfg_state *cfg)
+{
+ init_cfg(cfg);
+ char tag[8] = {0};
+ double steps_per_rev = 0.;
+ int use_flex = 1, ignore_grav = 0, ignore_pre = 0;
+ int max_iters = 0;
+ int nread = sscanf(line,
+ "%7s %zu %lf %lf %lf %lf %lf %lf %d %d %d %lf %lf %d %lf",
+ tag, &cfg->count, &cfg->spool_buildup,
+ &cfg->spring_k_per_unit_length, &cfg->mover_weight,
+ &cfg->spool_gear, &cfg->motor_gear, &steps_per_rev,
+ &use_flex, &ignore_grav, &ignore_pre, &cfg->lambda_reg,
+ &cfg->tol, &max_iters, &cfg->g);
+ if (nread != 15 || strcmp(tag, "CFG") != 0)
+ return 0;
+
+ cfg->steps_per_rev = steps_per_rev;
+ cfg->use_flex = use_flex;
+ cfg->ignore_gravity = ignore_grav;
+ cfg->ignore_pretension = ignore_pre;
+ cfg->max_iters_target = max_iters;
+ size_t limit = cfg->count > WINCH_MAX_ANCHORS ? WINCH_MAX_ANCHORS : cfg->count;
+ const char *p = line;
+ for (int i = 0; i < 15; ++i) {
+ p = strchr(p, ' ');
+ if (!p)
+ return 0;
+ while (*p == ' ')
+ p++;
+ }
+ for (size_t i = 0; i < limit; ++i) {
+ cfg->spool_r[i] = strtod(p, (char **)&p);
+ }
+ for (size_t i = 0; i < limit; ++i) {
+ cfg->mech_adv[i] = strtod(p, (char **)&p);
+ }
+ for (size_t i = 0; i < limit; ++i) {
+ cfg->lines_per_spool[i] = strtod(p, (char **)&p);
+ }
+ for (size_t i = 0; i < limit; ++i) {
+ cfg->min_force[i] = strtod(p, (char **)&p);
+ }
+ for (size_t i = 0; i < limit; ++i) {
+ cfg->max_force[i] = strtod(p, (char **)&p);
+ }
+ for (size_t i = 0; i < limit; ++i) {
+ cfg->guy_wires[i] = strtod(p, (char **)&p);
+ }
+ broadcast_tail(cfg->spool_r, limit);
+ broadcast_tail(cfg->mech_adv, limit);
+ broadcast_tail(cfg->lines_per_spool, limit);
+ broadcast_tail(cfg->min_force, limit);
+ broadcast_tail(cfg->max_force, limit);
+ broadcast_tail(cfg->guy_wires, limit);
+ cfg->has_cfg = 1;
+ return 1;
+}
+
+static double
+gear_ratio(const struct cfg_state *cfg)
+{
+ double motor_gear = cfg->motor_gear;
+ if (motor_gear == 0.)
+ motor_gear = 1.;
+ double gear = cfg->spool_gear / motor_gear;
+ if (gear <= 0.)
+ gear = 1.;
+ return gear;
+}
+
+static double
+rotation_distance_for_axis(const struct cfg_state *cfg, size_t idx)
+{
+ double r = cfg->spool_r[idx];
+ double ma = cfg->mech_adv[idx];
+ if (ma == 0.)
+ ma = 1.;
+ // Use circumference/mechanical advantage; gear ratio is handled via steps_per_rotation.
+ return (2.0 * M_PI * r) / ma;
+}
+
+static int
+solve_sample(const struct cfg_state *cfg, size_t num, int use_flex,
+ const double *motor_deg, const double *anchors, double *pos_out,
+ int *iters_out, double *cost_out, double *runtime_ms_out)
+{
+ struct winch_flex *wf = winch_flex_alloc();
+ if (!wf)
+ return 0;
+
+ double min_force[WINCH_MAX_ANCHORS], max_force[WINCH_MAX_ANCHORS];
+ double guy[WINCH_MAX_ANCHORS];
+ int mech_adv[WINCH_MAX_ANCHORS];
+ for (size_t i = 0; i < num; ++i) {
+ min_force[i] = cfg->min_force[i];
+ max_force[i] = cfg->max_force[i];
+ guy[i] = cfg->guy_wires[i];
+ mech_adv[i] = (int)(cfg->mech_adv[i] + 0.5);
+ if (mech_adv[i] <= 0)
+ mech_adv[i] = 1;
+ }
+ double attachments[3 * WINCH_MAX_ANCHORS] = { 0. };
+ winch_flex_configure(
+ wf, (int)num, anchors, attachments, cfg->spool_buildup, cfg->mover_weight,
+ cfg->spring_k_per_unit_length, min_force, max_force, guy,
+ WINCH_FORCE_ALGO_QP, cfg->ignore_gravity, cfg->ignore_pretension,
+ mech_adv, NULL, 0., 0);
+ winch_flex_set_enabled(wf, use_flex ? 1 : 0);
+
+ double gear = gear_ratio(cfg);
+ double motor_mm[WINCH_MAX_ANCHORS];
+ for (size_t i = 0; i < num; ++i) {
+ double rd = rotation_distance_for_axis(cfg, i);
+ double steps_per_rotation = cfg->steps_per_rev * gear;
+ winch_flex_set_spool_params(wf, (int)i, rd, steps_per_rotation);
+ motor_mm[i] = motor_deg[i] / cfg->steps_per_rev * (rd / gear);
+ }
+
+ struct timespec t0, t1;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ int iters = 0;
+ double cost = 0.0;
+ int ok = winch_forward_solve(
+ wf, motor_mm, NULL, 1e-3, 1e-3, 3, 30, pos_out, &cost, &iters);
+ clock_gettime(CLOCK_MONOTONIC, &t1);
+ double dt_ms = (t1.tv_sec - t0.tv_sec) * 1000.0
+ + (t1.tv_nsec - t0.tv_nsec) / 1e6;
+
+ winch_flex_free(wf);
+ if (iters_out)
+ *iters_out = iters;
+ if (cost_out)
+ *cost_out = cost;
+ if (runtime_ms_out)
+ *runtime_ms_out = dt_ms;
+ return ok;
+}
+
+int
+main(void)
+{
+ char buf[4096];
+ struct cfg_state cfg;
+ init_cfg(&cfg);
+
+ while (fgets(buf, sizeof(buf), stdin)) {
+ if (buf[0] == '\0' || buf[0] == '\n')
+ continue;
+ if (strncmp(buf, "CFG", 3) == 0) {
+ parse_cfg_line(buf, &cfg);
+ continue;
+ }
+
+ size_t num = 0;
+ int use_flex = 1;
+ const char *p = buf;
+ if (sscanf(p, "%zu %d", &num, &use_flex) != 2 || num == 0
+ || num > WINCH_MAX_ANCHORS) {
+ printf("fail 0 0 0 0 0 0\n");
+ continue;
+ }
+
+ // advance past num/use_flex
+ for (int i = 0; i < 2; ++i) {
+ p = strchr(p, ' ');
+ if (!p)
+ break;
+ while (*p == ' ')
+ p++;
+ }
+ double motor_deg[WINCH_MAX_ANCHORS];
+ for (size_t i = 0; i < num; ++i) {
+ motor_deg[i] = strtod(p, (char **)&p);
+ }
+ double anchors[WINCH_MAX_ANCHORS * 3];
+ for (size_t i = 0; i < num * 3; ++i) {
+ anchors[i] = strtod(p, (char **)&p);
+ }
+
+ double pos[3] = {0., 0., 0.};
+ int iters = 0;
+ double cost = 0., ms = 0.;
+ int ok = solve_sample(&cfg, num, use_flex, motor_deg, anchors, pos,
+ &iters, &cost, &ms);
+ printf("%s %.9g %.9g %.9g %d %.9g %.9g\n",
+ ok ? "ok" : "fail", pos[0], pos[1], pos[2], iters, cost, ms);
+ }
+ return 0;
+}
diff --git a/ai_docs/test.sh b/ai_docs/test.sh
new file mode 100755
index 000000000000..a2e62487e048
--- /dev/null
+++ b/ai_docs/test.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+cd "$(dirname "$0")"
+mkdir -p build
+
+compile() {
+ local src="$1"
+ local out="$2"
+ echo "Building $out from $src"
+ g++ -O2 -std=c++17 -fconcepts -DRUN_DATASET_CLI -I../../../hangprinter-flex-compensation -I. \
+ ../../../hangprinter-flex-compensation/flex.cpp ../../../hangprinter-flex-compensation/flex_qp.cpp "$src" -o "build/$out"
+}
+
+compile motorstepstocartesiantest_quadratic.cpp solver_quadratic
+echo "Building solver_calc_position from solver_calc_position.c"
+gcc -O2 -std=gnu11 -D_GNU_SOURCE -I../klippy/chelper solver_calc_position.c -lm -o build/solver_calc_position
+
+echo "Running solver comparison..."
+python3 run_tests.py
diff --git a/config/example-winch.cfg b/config/example-winch.cfg
index d6d62b8a6194..d97e79c55736 100644
--- a/config/example-winch.cfg
+++ b/config/example-winch.cfg
@@ -83,3 +83,11 @@ serial: /dev/ttyACM0
kinematics: winch
max_velocity: 300
max_accel: 3000
+winch_mover_weight: 0.0
+winch_spring_constant: 0.0
+winch_min_force: 0.0, 0.0, 0.0, 0.0
+winch_max_force: 120.0, 120.0, 120.0, 120.0
+winch_guy_wire_lengths: 0.0, 0.0, 0.0, 0.0
+flex_compensation_algorithm: qp
+ignoreGravity: false
+ignorePretension: false
diff --git a/docs/Config_Reference.md b/docs/Config_Reference.md
index 8c0574de25e6..357738908d28 100644
--- a/docs/Config_Reference.md
+++ b/docs/Config_Reference.md
@@ -697,9 +697,135 @@ cable winch kinematics. In order to home the printer, manually send
movement commands until the toolhead is at 0, 0, 0 and then issue a
`G28` command.
+#### Cable Winch Flex Compensation
+
+Use `M666 F0` to disable and `M666 F1` to enable flex compensation at
+runtime without restarting the printer.
+
+When the machine starts, flex compensation is disabled. To enable:
+ 1. Tighten lines so they are just barely not sagging.
+ 2. Issue `M666 F1` (or have it near the top of your .gcode file)
+
+If you don't want/need flex compensation, simply avoid issuing `M666 F1`,
+and the machine will use non-flex-compensating kinematics equations.
+
+
```
[printer]
kinematics: winch
+winch_anchor_mode: none
+# Workspace policy: none, last_on_top, all_on_top, or cube_corner.
+# last_on_top: cyclic low anchors followed by the high anchor; includes
+# the lower prism. all_on_top: cyclic perimeter prism, no height limit.
+# cube_corner: exactly eight anchors, upper four followed by corresponding
+# lower four in cyclic order; enclosed volume plus lower-face projection down.
+# Moves outside the workspace are rejected. Boundaries are included.
+# Runtime M666 A0/A1/A2/A3 selects the same modes as RepRapFirmware.
+# Planar forward kinematics selects the solution below the anchor plane
+# using negative-Z gravity, even when the workspace mode is none.
+# These are all flex compensation related configs.
+winch_mover_weight:
+# The mover weight in kilograms. The default is 0.
+winch_spring_constant:
+# Approximate axial stiffness EA of the line in Newton. A line of
+# length L then has spring constant winch_spring_constant/L.
+# A rough approximation for Garda 1.1 mm line is 20000.0 N.
+# The default is 0.
+winch_min_force:
+# Minimum permitted force per anchor in Newton. Provide one value
+# per defined anchor (comma separated).
+# A machine with only one high anchor should typically set this to
+# 9.81 x mover_weight (in kg) on that high anchor
+# (plus extra pretension if desired).
+# A SpiderCam-like machine (only high anchors) will typically set zero,
+# or a few Newtons here, just so lines don't go completely slack.
+# Desired pretension in non-weight-carrying directions is most
+# often in the 0-40 N range.
+# The default is 0 for each anchor.
+winch_max_force:
+# Maximum permitted force per anchor in Newton. Provide one value
+# per defined anchor (comma separated).
+# This can be set fairly close to your axis' max force (incluing
+# any gearing down from running lines back and forth between
+# anchor and effector).
+# A SpiderCam-like machine (only high anchors) will typically set this
+# to 9.81 x mover_weight (in kg) on all axes.
+# On machines that work with pretension, it's important that you
+# don't put it higher than you're comfortable with.
+# It must however be higher than the corresponding winch_min_force.
+# The default is 120 for each anchor.
+winch_guy_wire_lengths:
+# Optional guy wire lengths in millimeters for each anchor.
+# All line that's not on the spool or suspended between anchor point
+# and mover point is defined to be "guy wire".
+# The default is 0 for each anchor.
+winch_home_tension:
+# Optional tension, in Newtons, in the lines towards each anchor when
+# the motor positions were zeroed at the origin. Flex compensation then
+# only adds the stretch beyond it, instead of tensioning the lines
+# from slack. The default is 0 for each anchor.
+winch_buildup_factor:
+# Optional spool buildup factor for the whole machine.
+# This is the change in spool radius, in millimeters, per millimeter
+# of line wound onto the spool. Set this to 0 to use the constant
+# radius spool model.
+# The default is 0.
+winch_spool_flattening:
+# Optional radial compliance of line on a constant radius spool, in
+# mm^2/N. Line wound at tension T onto a spool of radius R sinks
+# T*winch_spool_flattening/R mm into the layers below, so each spool
+# turn stores less line. 0.015 fits braided Dyneema on a 30-50 mm
+# spool. Only used by flex compensation, and cannot be combined
+# with winch_buildup_factor. The default is 0.
+winch_strained_spool_storage:
+# Optional. Set to true if line keeps the stretch it was wound with
+# on the spool (T/winch_spring_constant). Both this and
+# winch_spool_flattening assume that the line on the spool was wound
+# at the tension it is paid out with. Only used by flex
+# compensation, and cannot be combined with winch_buildup_factor.
+# The default is false.
+winch_mechanical_advantage:
+# Optional mechanical advantage for each anchor.
+# If the winch force is geared by winding the line back and forth to the
+# effector in a block-and-tackle system, then tell Klipper how many times
+# back plus how many times forth.
+# This factor is used by the flex compensation and buildup model.
+# The default is 1 for each anchor (no gearing).
+winch_lines_per_axis:
+# Optional number of parallel lines pulling the effector towards each
+# anchor, for example 2 if two lines run side by side to keep the
+# effector from rotating. The lines share the flex compensation force,
+# so each one is stretched less. Only used by flex compensation.
+# The default is 1 for each anchor.
+flex_compensation_algorithm:
+# Solver used when computing how much force is required to counteract
+# gravity and pretension. Choices are 'tikhonov' and 'qp'.
+# Both algorithms will respect the max/min limits at all times and
+# compute the same forces most of the time.
+# They behave differently near the outskirts of the build volume.
+#
+# 'tikhonov' will treat force equilibrium (perfect gravity/pretension counteraction)
+# as a "best-effort target", prioritizing making the resulting
+# forces low, smooth, and safe.
+#
+# 'qp' will use the whole min/max force range to enforce exact force
+# equilibrium whenever theoretically possible.
+#
+# The default is 'qp'.
+ignore_gravity:
+# Tell the flex compensation algorithm to
+# only solve for pretension forces, not gravity counteracting forces.
+# This is a special setting used for debugging, testing, and a small subset of machines
+# that drag their effector on a gravity-supporting surface, eg a Slideprinter.
+# Choices are 'true' and 'false'.
+# The default is 'false'.
+ignore_pretension:
+# Tell the flex compensation algorithm to
+# only solve for gravity counteracting forces, not pretension forces.
+# This is a special setting only used for debugging.
+# It should never be used on any practical machine.
+# Choices are 'true' and 'false'.
+# The default is 'false'.
# The stepper_a section describes the stepper connected to the first
# cable winch. A minimum of 3 and a maximum of 26 cable winches may be
@@ -709,11 +835,51 @@ rotation_distance:
# The rotation_distance is the nominal distance (in mm) the toolhead
# moves towards the cable winch for each full rotation of the
# stepper motor. This parameter must be provided.
+# For buildup compensation, set this to the effective distance at the
+# origin. If winch_mechanical_advantage is used, divide the physical
+# origin circumference by that factor (for example, a 2:1 tackle halves
+# the configured value for the same spool radius).
+# There is no separate spool_radius config option; Klipper derives the
+# internal radius from rotation_distance.
+# If the spool itself is geared, use the regular stepper gear_ratio
+# option in the stepper section. The winch buildup code already sees
+# the geared step count via the stepper's steps_per_rotation value.
+m569_address:
+# Optional RepRapFirmware-style motor address used by the Hangprinter
+# M569 compatibility layer in this repository. For example, the hp3
+# example maps the four winch steppers to 40.0, 41.0, 42.0, and 43.0.
+# If omitted, M569.3 and M569.4 match steppers by their section names
+# such as stepper_a, stepper_b, stepper_c, and stepper_d.
anchor_x:
anchor_y:
anchor_z:
# The X, Y, and Z position of the cable winch in cartesian space.
# These parameters must be provided.
+attachment_x:
+attachment_y:
+attachment_z:
+# Optional X, Y, and Z position (in mm) of the point where this
+# winch's line attaches to the mover, measured from the mover's
+# centre of mass. When set, flex compensation also balances the
+# moments that the line forces apply to the mover, instead of
+# treating the mover as a point. Set them on every winch stepper.
+# Use this on machines where single lines attach to spread out points
+# and together stop the mover from rotating, such as a mover held by
+# eight lines from its eight corners. Leave them out when parallel
+# line pairs (winch_lines_per_axis) keep the mover from rotating.
+# The default is 0 for each, which treats the mover as a point.
+#pulley_radius: 0
+# Optional radius (in mm) of a swivel pulley at this anchor. The line
+# arrives at the pulley along swivel_axis, wraps the wheel and leaves
+# from a tangent point that moves as the mover moves, while the pulley
+# fork turns about the axis. anchor_x/y/z are then the point where the
+# line enters the pulley. The default is 0, a fixed point anchor.
+#swivel_axis_x:
+#swivel_axis_y:
+#swivel_axis_z:
+# Direction the line travels as it enters the swivel pulley, which is
+# also the axis the fork turns about. Required when pulley_radius is
+# set; it need not be a unit vector.
```
### Generic Cartesian Kinematics
diff --git a/klippy/chelper/__init__.py b/klippy/chelper/__init__.py
index 087acbd56c7f..d7e6d485f552 100644
--- a/klippy/chelper/__init__.py
+++ b/klippy/chelper/__init__.py
@@ -26,7 +26,7 @@
DEST_LIB = "c_helper.so"
OTHER_FILES = [
'list.h', 'serialqueue.h', 'stepcompress.h', 'steppersync.h',
- 'itersolve.h', 'pyhelper.h', 'trapq.h', 'pollreactor.h', 'msgblock.h'
+ 'itersolve.h', 'pyhelper.h', 'trapq.h', 'pollreactor.h', 'msgblock.h', 'forward_workspace.h', 'swivel_pulley.h', 'line_transforms.h'
]
defs_stepcompress = """
@@ -151,8 +151,33 @@
"""
defs_kin_winch = """
- struct stepper_kinematics *winch_stepper_alloc(double anchor_x
- , double anchor_y, double anchor_z);
+ struct winch_flex *winch_flex_alloc(void);
+ void winch_flex_free(struct winch_flex *wf);
+ void winch_flex_configure(struct winch_flex *wf, int num_anchors,
+ const double *anchors, const double *attachments,
+ double buildup_factor, double mover_weight, double spring_constant,
+ const double *min_force,
+ const double *max_force, const double *guy_wires,
+ int flex_compensation_algorithm, int ignore_gravity, int ignore_pretension,
+ const int* mechanical_advantage, const int* lines_per_axis,
+ double spool_flattening, int strained_spool_storage);
+ void winch_flex_set_swivels(struct winch_flex *wf, const double *radii,
+ const double *axes, const double *home_tension);
+ void winch_flex_set_spool_params(struct winch_flex *wf, int index,
+ double rotation_distance, double steps_per_rotation);
+ void winch_flex_calc_arrays(struct winch_flex *wf, double x, double y,
+ double z, double *distances_out, double *flex_out);
+ int winch_flex_set_anchor_mode(struct winch_flex *wf, int mode);
+ int winch_flex_is_reachable(struct winch_flex *wf, double x, double y, double z);
+ void winch_flex_set_enabled(struct winch_flex *wf, int enabled);
+ double winch_flex_motor_to_line_pos(struct winch_flex *wf, int index,
+ double motor_pos);
+ int winch_forward_solve(struct winch_flex *wf, const double *motor_pos,
+ const double *initial_guess, double eta, double tol,
+ int halley_iters, int max_iters,
+ double *out_pos, double *out_cost, int *out_iters);
+ struct stepper_kinematics *winch_stepper_alloc(struct winch_flex *wf,
+ int index);
"""
defs_kin_extruder = """
diff --git a/klippy/chelper/forward_workspace.h b/klippy/chelper/forward_workspace.h
new file mode 100644
index 000000000000..d936340dfd54
--- /dev/null
+++ b/klippy/chelper/forward_workspace.h
@@ -0,0 +1,171 @@
+// Shared by the development solver, RepRapFirmware and Klipper.
+// Coordinates use a fixed orientation and gravity points along negative Z.
+#ifndef HANGPRINTER_FORWARD_WORKSPACE_H
+#define HANGPRINTER_FORWARD_WORKSPACE_H
+#include
+#include
+
+enum { HP_ANCHORS_NONE, HP_ANCHORS_LAST_TOP, HP_ANCHORS_ALL_TOP, HP_ANCHORS_CUBE_CORNER };
+
+static inline double hp_dot(const double *a, const double *b) {
+ return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
+}
+static inline void hp_cross(const double *a, const double *b, double *out) {
+ out[0]=a[1]*b[2]-a[2]*b[1]; out[1]=a[2]*b[0]-a[0]*b[2]; out[2]=a[0]*b[1]-a[1]*b[0];
+}
+static inline void hp_difference(const double *a, const double *b, double *out) {
+ for (int j=0;j<3;++j) out[j]=a[j]-b[j];
+}
+// Closed half-spaces include boundary points. Degenerate faces are invalid.
+static inline int hp_same_side(const double *a, const double *b, const double *c,
+ const double *inside, const double *p) {
+ double u[3],v[3],n[3],ref[3],q[3];
+ hp_difference(b,a,u); hp_difference(c,a,v); hp_cross(u,v,n);
+ hp_difference(inside,a,ref); hp_difference(p,a,q);
+ double length=sqrt(hp_dot(n,n)), side=hp_dot(n,ref);
+ if (length < 1e-12 || fabs(side) < 1e-10*length) return 0;
+ return hp_dot(n,q)*(side>0 ? 1 : -1) >= -1e-6*length;
+}
+static inline int hp_in_prism(const double a[][3], size_t count, const double *p) {
+ double center[3]={0,0,0};
+ if (count<3) return 0;
+ for (size_t i=0;i1e-12 && fabs(n[2])>length*1e-6 && height<=length*extent*1e-7) {
+ hp_difference(p,a[0],q);
+ return hp_dot(q,n)*(n[2]>0 ? 1 : -1)<=1e-6*length;
+ }
+ double center[3]={0,0,0};
+ for (size_t i=0;ifabs(s[pivot][j])) pivot=r;
+ if (fabs(s[pivot][j])<=scale*1e-14) return 0;
+ for (int c=0;c<4;++c) { double t=s[j][c];s[j][c]=s[pivot][c];s[pivot][c]=t; }
+ double divisor=s[j][j];
+ for (int c=j;c<4;++c) s[j][c]/=divisor;
+ for (int r=0;r<3;++r) if (r!=j) {
+ double factor=s[r][j];
+ for (int c=j;c<4;++c) s[r][c]-=factor*s[j][c];
+ }
+ }
+ for (int j=0;j<3;++j) { if (!isfinite(s[j][3])) return 0; out[j]=s[j][3]; }
+ return 1;
+}
+
+// Produce a full-rank seed and, for flat/nearly flat layouts, both sphere mirrors.
+// Exact planes carry an upward normal so the caller can select the gravity side.
+static inline int hp_range_candidates(const double a[][3], const double *distance, size_t count,
+ double candidates[3][3], double *normal, int *planar) {
+ if (count<3) return 0;
+ double u[3]={0,0,0},v[3]={0,0,0},largest=0,area=0;
+ for (size_t i=1;ilargest) { largest=square;for (int j=0;j<3;++j) u[j]=d[j]; }
+ }
+ if (largest<1e-12) return 0;
+ for (int j=0;j<3;++j) u[j]/=sqrt(largest);
+ for (size_t i=1;iarea) { area=square;for (int j=0;j<3;++j) normal[j]=cross[j]; }
+ }
+ if (areasqrt(largest)*1e-3) return found;
+ double det=projected[0][0]*projected[1][1]-projected[0][1]*projected[1][0];
+ if (det<=0) return found;
+ double x=(projected[0][2]*projected[1][1]-projected[0][1]*projected[1][2])/det;
+ double y=(projected[0][0]*projected[1][2]-projected[1][0]*projected[0][2])/det;
+ double flat[3],square=0;
+ for (int j=0;j<3;++j) flat[j]=a[0][j]+x*u[j]+y*v[j];
+ for (size_t i=0;i0) for (int j=0;j<3;++j) p[j]-=2*height*normal[j];
+}
+#endif
diff --git a/klippy/chelper/kin_winch.c b/klippy/chelper/kin_winch.c
index c6501d27095b..7c2ec84fc701 100644
--- a/klippy/chelper/kin_winch.c
+++ b/klippy/chelper/kin_winch.c
@@ -1,42 +1,1216 @@
-// Cable winch stepper kinematics
+// Cable winch stepper kinematics with flex compensation
//
// Copyright (C) 2018-2019 Kevin O'Connor
+// Copyright (C) 2024 Contributors
//
// This file may be distributed under the terms of the GNU GPLv3 license.
-#include // sqrt
+#include "forward_workspace.h"
+#include "swivel_pulley.h"
+#include "line_transforms.h"
+#include // sqrt, fabs, fmax, fmin
#include // offsetof
#include // malloc
#include // memset
#include "compiler.h" // __visible
+#include "pyhelper.h" // errorf
#include "itersolve.h" // struct stepper_kinematics
#include "trapq.h" // move_get_coord
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+#define WINCH_MAX_ANCHORS 26
+// Three force rows, plus three moment rows when attachments are configured
+#define WINCH_MAX_ROWS 6
+#define EPSILON 1e-9
+#define G_ACCEL 9.81
+// LAMBDA is Tikhonov regularization weight in both the Tikhonov and the QP solver.
+#define LAMBDA 1e-3
+// Regularization of the force and moment equations. Balancing moments can
+// take tension changes that are large compared to the moment they correct,
+// so these equations are held much harder than LAMBDA would.
+#define LAMBDA_MOMENTS 1e-5
+
+enum winch_force_algorithm {
+ WINCH_FORCE_ALGO_TIKHONOV = 0,
+ WINCH_FORCE_ALGO_QP = 1,
+};
+
+struct winch_flex {
+ struct coord anchors[WINCH_MAX_ANCHORS];
+ // Line attachment points on the mover, relative to its centre of mass
+ struct coord attachments[WINCH_MAX_ANCHORS];
+ // 1 / (RMS attachment distance). Zero means no moment equations.
+ double inv_attachment_radius;
+ int num_anchors;
+ int enabled;
+ int anchor_mode;
+ int flex_compensation_algorithm;
+ double buildup_factor;
+ // Rope on a drum of radius R sinks by spool_flattening * T / R under
+ // tension T (mm^2/N); strained storage keeps its winding strain.
+ double spool_flattening;
+ int strained_spool_storage;
+ double mover_weight;
+ double spring_constant;
+ double min_force[WINCH_MAX_ANCHORS];
+ double max_force[WINCH_MAX_ANCHORS];
+ double guy_wires[WINCH_MAX_ANCHORS];
+ int ignore_gravity;
+ int ignore_pretension;
+ double distances_origin[WINCH_MAX_ANCHORS];
+ int mechanical_advantage[WINCH_MAX_ANCHORS];
+ int lines_per_axis[WINCH_MAX_ANCHORS];
+ double spool_radius[WINCH_MAX_ANCHORS];
+ double spool_radius_sq[WINCH_MAX_ANCHORS];
+ double k0[WINCH_MAX_ANCHORS];
+ double k2[WINCH_MAX_ANCHORS];
+ double steps_per_mm[WINCH_MAX_ANCHORS];
+ double inv_steps_per_mm[WINCH_MAX_ANCHORS];
+ int use_constant_spool_model[WINCH_MAX_ANCHORS];
+ // Swivel pulley at each anchor: wheel radius (0 is a pinhole) and the unit
+ // direction the line travels as it enters. Anchors are then the entry points.
+ double pulley_radius[WINCH_MAX_ANCHORS];
+ struct coord swivel_axis[WINCH_MAX_ANCHORS];
+ // Direction-total tension in each line when the motors were zeroed at the origin
+ double home_tension[WINCH_MAX_ANCHORS];
+ // Stretch present at the origin because of home_tension
+ double home_flex[WINCH_MAX_ANCHORS];
+};
+
struct winch_stepper {
struct stepper_kinematics sk;
- struct coord anchor;
+ struct winch_flex *wf;
+ int index;
};
-static double
-winch_stepper_calc_position(struct stepper_kinematics *sk, struct move *m
- , double move_time)
+static inline double
+hypot3(double dx, double dy, double dz)
{
- struct winch_stepper *hs = container_of(sk, struct winch_stepper, sk);
- struct coord c = move_get_coord(m, move_time);
- double dx = hs->anchor.x - c.x, dy = hs->anchor.y - c.y;
- double dz = hs->anchor.z - c.z;
return sqrt(dx*dx + dy*dy + dz*dz);
}
+static int
+invert3x3(const double M[3][3], double Minv[3][3])
+{
+ double a = M[0][0], b = M[0][1], c = M[0][2];
+ double d = M[1][0], e = M[1][1], f = M[1][2];
+ double g = M[2][0], h = M[2][1], i = M[2][2];
+
+ double A = (e * i - f * h);
+ double B = -(d * i - f * g);
+ double C = (d * h - e * g);
+ double D = -(b * i - c * h);
+ double E = (a * i - c * g);
+ double F = -(a * h - b * g);
+ double G = (b * f - c * e);
+ double H = -(a * f - c * d);
+ double I = (a * e - b * d);
+
+ double det = a * A + b * B + c * C;
+ if (fabs(det) < EPSILON)
+ return 0;
+ double invdet = 1. / det;
+
+ Minv[0][0] = A * invdet;
+ Minv[0][1] = D * invdet;
+ Minv[0][2] = G * invdet;
+ Minv[1][0] = B * invdet;
+ Minv[1][1] = E * invdet;
+ Minv[1][2] = H * invdet;
+ Minv[2][0] = C * invdet;
+ Minv[2][1] = F * invdet;
+ Minv[2][2] = I * invdet;
+ return 1;
+}
+
+// Line length from the anchor (a swivel pulley's entry point) to pos, and
+// where the line leaves the anchor towards it
+static double
+line_length(const struct winch_flex *wf, int i, const struct coord *pos,
+ struct coord *exit)
+{
+ const struct coord *a = &wf->anchors[i];
+ if (!(wf->pulley_radius[i] > 0.)) {
+ *exit = *a;
+ return hypot3(a->x - pos->x, a->y - pos->y, a->z - pos->z);
+ }
+ double entry[3] = {a->x, a->y, a->z};
+ double axis[3] = {wf->swivel_axis[i].x, wf->swivel_axis[i].y,
+ wf->swivel_axis[i].z};
+ double p[3] = {pos->x, pos->y, pos->z}, out[3];
+ double length = hp_swivel_length(entry, axis, wf->pulley_radius[i], p, out);
+ exit->x = out[0];
+ exit->y = out[1];
+ exit->z = out[2];
+ return length;
+}
+
+static int
+build_direction_matrix(struct winch_flex *wf, const struct coord *pos,
+ double *A)
+{
+ int N = wf->num_anchors;
+ int valid = 0;
+ for (int j = 0; j < N; ++j) {
+ struct coord exit;
+ line_length(wf, j, pos, &exit);
+ double dx = exit.x - pos->x;
+ double dy = exit.y - pos->y;
+ double dz = exit.z - pos->z;
+ double norm = hypot3(dx, dy, dz);
+ if (norm < EPSILON) {
+ A[0 * N + j] = 0.;
+ A[1 * N + j] = 0.;
+ A[2 * N + j] = 0.;
+ continue;
+ }
+ double inv = 1.0 / norm;
+ A[0 * N + j] = dx * inv;
+ A[1 * N + j] = dy * inv;
+ A[2 * N + j] = dz * inv;
+ valid++;
+ }
+ return valid >= 3;
+}
+
+static inline int
+has_attachments(const struct winch_flex *wf)
+{
+ return wf->inv_attachment_radius > 0.;
+}
+
+// Columns hold the force and the moment about the centre of mass that a unit
+// tension applies to the mover. Moments are divided by the RMS attachment
+// distance so that all six rows are forces of comparable size.
+static int
+build_wrench_matrix(struct winch_flex *wf, const struct coord *pos, double *A)
+{
+ int N = wf->num_anchors;
+ if (!build_direction_matrix(wf, pos, A))
+ return 0;
+ for (int j = 0; j < N; ++j) {
+ double ux = A[0 * N + j], uy = A[1 * N + j], uz = A[2 * N + j];
+ double rx = wf->attachments[j].x * wf->inv_attachment_radius;
+ double ry = wf->attachments[j].y * wf->inv_attachment_radius;
+ double rz = wf->attachments[j].z * wf->inv_attachment_radius;
+ A[3 * N + j] = ry * uz - rz * uy;
+ A[4 * N + j] = rz * ux - rx * uz;
+ A[5 * N + j] = rx * uy - ry * ux;
+ }
+ return 1;
+}
+
+static int chol_decompose_spd(double *G, int k);
+static void chol_solve_spd(const double *L, int k, const double *b, double *x);
+
+// Cholesky factor of A_f A_f^T + lambda I (M x M), where A_f holds the
+// columns of A listed in cols
+static void
+factor_gram(const double *A, int M, int N, const int *cols, int k,
+ double lambda, double *S)
+{
+ for (int r = 0; r < M; ++r) {
+ for (int c = 0; c <= r; ++c) {
+ double acc = r == c ? lambda : 0.;
+ for (int p = 0; p < k; ++p)
+ acc += A[r * N + cols[p]] * A[c * N + cols[p]];
+ S[r * M + c] = acc;
+ S[c * M + r] = acc;
+ }
+ }
+ chol_decompose_spd(S, M);
+}
+
+static void
+solve_min_norm_T(const double *A, int M, int N, const double *Fext,
+ double lambda, double *T)
+{
+ int cols[WINCH_MAX_ANCHORS] = { 0 };
+ for (int j = 0; j < N; ++j)
+ cols[j] = j;
+ double S[WINCH_MAX_ROWS * WINCH_MAX_ROWS];
+ factor_gram(A, M, N, cols, N, lambda, S);
+ double y[WINCH_MAX_ROWS];
+ chol_solve_spd(S, M, Fext, y);
+ for (int j = 0; j < N; ++j) {
+ double acc = 0.;
+ for (int r = 0; r < M; ++r)
+ acc += A[r * N + j] * y[r];
+ T[j] = acc;
+ }
+}
+
+static void
+build_null_projector(const double *A, int M, int N, double lambda, double *P)
+{
+ int cols[WINCH_MAX_ANCHORS] = { 0 };
+ for (int j = 0; j < N; ++j)
+ cols[j] = j;
+ double S[WINCH_MAX_ROWS * WINCH_MAX_ROWS];
+ factor_gram(A, M, N, cols, N, lambda, S);
+ for (int c = 0; c < N; ++c) {
+ double col[WINCH_MAX_ROWS], B[WINCH_MAX_ROWS];
+ for (int r = 0; r < M; ++r)
+ col[r] = A[r * N + c];
+ chol_solve_spd(S, M, col, B);
+ for (int r = 0; r < N; ++r) {
+ double Mrc = 0.;
+ for (int k = 0; k < M; ++k)
+ Mrc += A[k * N + r] * B[k];
+ P[r * N + c] = (r == c ? 1.0 : 0.0) - Mrc;
+ }
+ }
+}
+
+static void
+project_nullspace(const double *P, int N, const double *v, double *out)
+{
+ for (int r = 0; r < N; ++r) {
+ double acc = 0.;
+ for (int c = 0; c < N; ++c)
+ acc += P[r * N + c] * v[c];
+ out[r] = acc;
+ }
+}
+
+static int
+static_forces_tikhonov(struct winch_flex *wf, const struct coord *pos,
+ double *forces)
+{
+ int N = wf->num_anchors;
+ int M = has_attachments(wf) ? 6 : 3;
+ double lambda = has_attachments(wf) ? LAMBDA_MOMENTS : LAMBDA;
+ double A[WINCH_MAX_ROWS * WINCH_MAX_ANCHORS];
+ if (!(has_attachments(wf) ? build_wrench_matrix(wf, pos, A)
+ : build_direction_matrix(wf, pos, A)))
+ return 0;
+
+ double Fext[WINCH_MAX_ROWS] = {0., 0., 0., 0., 0., 0.};
+ double T[WINCH_MAX_ANCHORS];
+ memset(T, 0, sizeof(T));
+ if (!wf->ignore_gravity) {
+ Fext[2] = wf->mover_weight * G_ACCEL;
+ // base min-norm solution (regularized pseudoinverse)
+ // Magic number LAMBDA (1e-3) is regulatization strength,
+ // damping the least squares problem.
+ // It gives Thikonov a ~milliforce
+ // leeway to make nicer (no blow up) but less exact solutions
+ solve_min_norm_T(A, M, N, Fext, lambda, T);
+ }
+
+ // Tmin is a soft target in Tikhonov; only zero and Tmax are hard limits.
+ if (!wf->ignore_pretension) {
+ double P[WINCH_MAX_ANCHORS * WINCH_MAX_ANCHORS];
+ build_null_projector(A, M, N, lambda, P);
+ const double tol = 1e-3;
+ // Magic step_damp number that makes gradient descent typically converge within tol fast
+ // Anything within [0.1, 1.5] works
+ const double step_damp = 0.75;
+ const int max_iters = 100;
+ for (int it = 0; it < max_iters; ++it) {
+ double gradient[WINCH_MAX_ANCHORS];
+ for (int i = 0; i < N; ++i) {
+ // Gradient from the target objective: 0.5 * (T - T_target)^2
+ double target_grad = 0.;
+ // If tension is beyond max, pull strongly back into acceptable range
+ if (T[i] > wf->max_force[i])
+ target_grad += T[i] - wf->max_force[i];
+ // If tenson is below min, pull strongly back into acceptable range
+ if (T[i] < wf->min_force[i])
+ target_grad += T[i] - wf->min_force[i];
+ // Always pull weakly towards the minvalue
+ target_grad += 0.1 * (T[i] - wf->min_force[i]);
+ gradient[i] = target_grad;
+ }
+ double d[WINCH_MAX_ANCHORS];
+ project_nullspace(P, N, gradient, d);
+ double norm_sq = 0.;
+ for (int i = 0; i < N; ++i)
+ norm_sq += d[i] * d[i];
+ if (norm_sq < tol * tol) {
+ break;
+ }
+ for (int i = 0; i < N; ++i)
+ T[i] -= step_damp * d[i];
+ }
+
+ }
+ // Ignoring pretension still respects physical tension limits.
+ for (int i = 0; i < N; ++i) {
+ if (wf->min_force[i] >= 0. && T[i] < 0.) T[i] = 0.;
+ if (T[i] > wf->max_force[i]) T[i] = wf->max_force[i];
+ }
+
+ for (int i = 0; i < N; ++i) {
+ forces[i] = T[i];
+ }
+ for (int i = N; i < WINCH_MAX_ANCHORS; ++i)
+ forces[i] = 0.;
+ return 1;
+}
+
+
+// ---- Cholesky solver for small SPD systems (k x k), row-major in/out -------
+static int
+chol_decompose_spd(double *G, int k)
+{
+ const double eps = 1e-12;
+ for (int i = 0; i < k; ++i) {
+ for (int j = 0; j <= i; ++j) {
+ double s = G[i * k + j];
+ for (int p = 0; p < j; ++p)
+ s -= G[i * k + p] * G[j * k + p];
+ if (i == j) {
+ if (s <= eps)
+ s = eps;
+ G[i * k + j] = sqrt(s);
+ } else {
+ G[i * k + j] = s / G[j * k + j];
+ }
+ }
+ for (int j = i + 1; j < k; ++j)
+ G[i * k + j] = 0.;
+ }
+ return 1;
+}
+
+static void
+chol_solve_spd(const double *L, int k, const double *b, double *x)
+{
+ double y[WINCH_MAX_ANCHORS] = { 0.0 };
+ // Solve L y = b
+ for (int i = 0; i < k; ++i) {
+ double s = b[i];
+ for (int p = 0; p < i; ++p)
+ s -= L[i * k + p] * y[p];
+ y[i] = s / L[i * k + i];
+ }
+ for (int i = 0; i < k; ++i)
+ x[i] = 0.;
+ // Solve L^T x = y
+ for (int i = k - 1; i >= 0; --i) {
+ double s = y[i];
+ for (int p = i + 1; p < k; ++p)
+ s -= L[p * k + i] * x[p];
+ x[i] = s / L[i * k + i];
+ }
+}
+
+// Smallest tensions within [L, U] that balance the force and optional moment
+// equations A T = F. Minimizes |A T - F|^2 + lambda |T|^2 for a small lambda
+// with an active-set method. Every solve is of the M x M system
+// A_f A_f^T + lambda I over the free tensions, which stays well conditioned
+// however small lambda is, and the bound multipliers T_i - a_i^T y are in
+// Newton, so tol is too.
+static void
+solve_box_min_norm(const double *A, int M, int N, const double *Fext,
+ double lambda, const double *Lbounds,
+ const double *Ubounds, int max_iters, double tol,
+ double *t)
+{
+ int is_free[WINCH_MAX_ANCHORS];
+ int cols[WINCH_MAX_ANCHORS] = { 0 };
+ double S[WINCH_MAX_ROWS * WINCH_MAX_ROWS];
+ double r[WINCH_MAX_ROWS], y[WINCH_MAX_ROWS];
+
+ // Start from the unbounded solution, clamped into the bounds
+ for (int i = 0; i < N; ++i)
+ cols[i] = i;
+ factor_gram(A, M, N, cols, N, lambda, S);
+ chol_solve_spd(S, M, Fext, y);
+ for (int i = 0; i < N; ++i) {
+ t[i] = 0.;
+ for (int row = 0; row < M; ++row)
+ t[i] += A[row * N + i] * y[row];
+ is_free[i] = t[i] > Lbounds[i] && t[i] < Ubounds[i];
+ if (t[i] <= Lbounds[i])
+ t[i] = Lbounds[i];
+ else if (t[i] >= Ubounds[i])
+ t[i] = Ubounds[i];
+ }
+
+ int released = -1;
+ for (int it = 0; it < max_iters; ++it) {
+ int k = 0;
+ for (int i = 0; i < N; ++i)
+ if (is_free[i])
+ cols[k++] = i;
+ for (int row = 0; row < M; ++row) {
+ r[row] = Fext[row];
+ for (int i = 0; i < N; ++i)
+ if (!is_free[i])
+ r[row] -= A[row * N + i] * t[i];
+ }
+ factor_gram(A, M, N, cols, k, lambda, S);
+ chol_solve_spd(S, M, r, y);
+
+ // Move the free tensions towards their optimum, stopping at the
+ // first bound that gets in the way
+ double alpha = 1.;
+ int blocking = -1;
+ double blocking_bound = 0.;
+ double step[WINCH_MAX_ANCHORS];
+ for (int p = 0; p < k; ++p) {
+ int i = cols[p];
+ double target = 0.;
+ for (int row = 0; row < M; ++row)
+ target += A[row * N + i] * y[row];
+ step[p] = target - t[i];
+ double bound = step[p] > 0. ? Ubounds[i] : Lbounds[i];
+ if (step[p] != 0. && (bound - t[i]) / step[p] < alpha) {
+ alpha = (bound - t[i]) / step[p];
+ blocking = i;
+ blocking_bound = bound;
+ }
+ }
+ if (alpha < 0.)
+ alpha = 0.;
+ for (int p = 0; p < k; ++p)
+ t[cols[p]] += alpha * step[p];
+ if (blocking >= 0) {
+ t[blocking] = blocking_bound;
+ is_free[blocking] = 0;
+ continue;
+ }
+
+ // The free tensions are optimal. Release the bound tension that
+ // most wants to move into its range, if any.
+ double worst = tol;
+ released = -1;
+ for (int i = 0; i < N; ++i) {
+ if (is_free[i] || Ubounds[i] <= Lbounds[i])
+ continue;
+ double mu = t[i];
+ for (int row = 0; row < M; ++row)
+ mu -= A[row * N + i] * y[row];
+ double want = t[i] <= Lbounds[i] ? -mu : mu;
+ if (want > worst) {
+ worst = want;
+ released = i;
+ }
+ }
+ if (released < 0)
+ break;
+ is_free[released] = 1;
+ }
+}
+
+static int
+static_forces_qp(struct winch_flex *wf, const struct coord *pos,
+ double *forces)
+{
+ int N = wf->num_anchors;
+
+ double A[WINCH_MAX_ROWS * WINCH_MAX_ANCHORS];
+ if (!(has_attachments(wf) ? build_wrench_matrix(wf, pos, A)
+ : build_direction_matrix(wf, pos, A)))
+ return 0;
+
+ double Fext[WINCH_MAX_ROWS] = {0., 0., 0., 0., 0., 0.};
+ if (!wf->ignore_gravity)
+ Fext[2] = wf->mover_weight * G_ACCEL;
+
+ double Lbounds[WINCH_MAX_ANCHORS] = { 0. };
+ double Ubounds[WINCH_MAX_ANCHORS] = { 0. };
+ for (int i = 0; i < N; ++i) {
+ double li = wf->ignore_pretension ? 0. : wf->min_force[i];
+ double ui = wf->max_force[i];
+ if (ui < li)
+ ui = li;
+ Lbounds[i] = li;
+ Ubounds[i] = ui;
+ }
+
+ // Solve convex QP
+ const int max_iters = 100;
+ const double tol = 1e-3;
+ double T[WINCH_MAX_ANCHORS];
+ solve_box_min_norm(A, has_attachments(wf) ? 6 : 3, N, Fext,
+ has_attachments(wf) ? LAMBDA_MOMENTS : LAMBDA,
+ Lbounds, Ubounds, max_iters, tol, T);
+
+ for (int i = 0; i < N; ++i)
+ forces[i] = T[i];
+ for (int i = N; i < WINCH_MAX_ANCHORS; ++i)
+ forces[i] = 0.;
+ return 1;
+}
+
+static int
+compute_static_forces(struct winch_flex *wf, const struct coord *pos,
+ double *forces, int algo)
+{
+ int ok = 0;
+ if (algo == WINCH_FORCE_ALGO_QP) {
+ ok = static_forces_qp(wf, pos, forces);
+ } else if (algo == WINCH_FORCE_ALGO_TIKHONOV) {
+ ok = static_forces_tikhonov(wf, pos, forces);
+ }
+ if (ok) {
+ return 1;
+ }
+ memset(forces, 0, sizeof(double) * wf->num_anchors);
+ return 0;
+}
+
+static void
+routed_lengths_and_payout_corrections(struct winch_flex *wf, double x, double y, double z,
+ double *distances, double *flex)
+{
+ int num = wf->num_anchors;
+ struct coord pos;
+ pos.x = x;
+ pos.y = y;
+ pos.z = z;
+ for (int i = 0; i < num; ++i) {
+ struct coord exit;
+ distances[i] = line_length(wf, i, &pos, &exit);
+ }
+ if (!wf->enabled) {
+ for (int i = 0; i < num; ++i)
+ flex[i] = 0.;
+ return;
+ }
+ double forces[WINCH_MAX_ANCHORS];
+ memset(forces, 0, sizeof(forces));
+ compute_static_forces(wf, &pos, forces, wf->flex_compensation_algorithm);
+ for (int i = 0; i < num; ++i) {
+ // Without a spring constant there is no stretch to compensate
+ if (!(wf->spring_constant > 0.)) {
+ flex[i] = 0.;
+ continue;
+ }
+ double spring_length = distances[i]*wf->mechanical_advantage[i] + wf->guy_wires[i];
+ if (spring_length < EPSILON)
+ spring_length = EPSILON;
+ double spring_k = wf->spring_constant / spring_length;
+ double ma = wf->mechanical_advantage[i];
+ if (ma <= 0.)
+ ma = 1.;
+ // Convert per-line stretch to effector distance; steps/mm includes MA.
+ flex[i] = wf->home_flex[i] - hp_span_extension(
+ forces[i], spring_k, ma, wf->lines_per_axis[i]);
+ // The drum stores rope at the strain and flattened radius it was
+ // wound with, so a motor-side millimetre carries less rest length.
+ // Assume the rope was wound at the current tension.
+ double tension = forces[i] / (ma * wf->lines_per_axis[i]);
+ double strain = wf->strained_spool_storage && wf->spring_constant > 0.
+ ? tension / wf->spring_constant : 0.;
+ double sink = wf->spool_radius_sq[i] > 0.
+ ? fmin(wf->spool_flattening * tension / wf->spool_radius_sq[i], .5)
+ : 0.;
+ double rest_payout = hp_relative_payout(distances[i], wf->distances_origin[i], flex[i]);
+ flex[i] += hp_storage_correction(rest_payout, strain, sink);
+ }
+}
+
+static inline double
+relative_payout_to_motor_position(struct winch_flex *wf, int idx, double line_pos)
+{
+ if (!wf || idx < 0 || idx >= wf->num_anchors)
+ return line_pos;
+ if (wf->use_constant_spool_model[idx])
+ return line_pos;
+ double inv_spmm = wf->inv_steps_per_mm[idx];
+ double k2 = wf->k2[idx];
+ if (inv_spmm <= 0. || fabs(k2) <= 1e-16)
+ return line_pos;
+ double radicand = wf->spool_radius_sq[idx] + line_pos * k2;
+ if (radicand < 0.)
+ return -wf->k0[idx] * wf->spool_radius[idx] * inv_spmm;
+ double motor_steps = line_pos * (wf->k0[idx] * k2)
+ / (sqrt(radicand) + wf->spool_radius[idx]);
+ return motor_steps * inv_spmm;
+}
+
+static inline double
+motor_position_to_relative_payout(struct winch_flex *wf, int idx, double motor_pos)
+{
+ if (!wf || idx < 0 || idx >= wf->num_anchors)
+ return motor_pos;
+ if (wf->use_constant_spool_model[idx])
+ return motor_pos;
+ double spmm = wf->steps_per_mm[idx];
+ double k2 = wf->k2[idx];
+ double k0 = wf->k0[idx];
+ if (spmm <= 0. || fabs(k0) <= 1e-16 || fabs(k2) <= 1e-16)
+ return motor_pos;
+ double motor_steps = motor_pos * spmm;
+ double delta_radius = motor_steps / k0;
+ return delta_radius * (2. * wf->spool_radius[idx] + delta_radius) / k2;
+}
+
+// ---- Forward transform (motor positions -> Cartesian) ----
+static inline double
+vec_norm3(const double v[3])
+{
+ return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
+}
+
+static double
+residuals_and_derivatives(struct winch_flex *wf, const double *line_pos, int N,
+ const struct coord *pos, double *residuals,
+ double *jac, double *hess)
+{
+ const double impact_step = 1e-3;
+ double base_flex[WINCH_MAX_ANCHORS];
+ double impact_plus[3][WINCH_MAX_ANCHORS];
+ double impact_minus[3][WINCH_MAX_ANCHORS];
+ memset(base_flex, 0, sizeof(base_flex));
+ memset(impact_plus, 0, sizeof(impact_plus));
+ memset(impact_minus, 0, sizeof(impact_minus));
+
+ if (wf && wf->enabled) {
+ double distances[WINCH_MAX_ANCHORS];
+ routed_lengths_and_payout_corrections(wf, pos->x, pos->y, pos->z, distances, base_flex);
+ for (int axis = 0; axis < 3; ++axis) {
+ struct coord shifted = *pos;
+ if (axis == 0)
+ shifted.x += impact_step;
+ else if (axis == 1)
+ shifted.y += impact_step;
+ else
+ shifted.z += impact_step;
+ routed_lengths_and_payout_corrections(wf, shifted.x, shifted.y, shifted.z,
+ distances, impact_plus[axis]);
+ if (axis == 0)
+ shifted.x = pos->x - impact_step;
+ else if (axis == 1)
+ shifted.y = pos->y - impact_step;
+ else
+ shifted.z = pos->z - impact_step;
+ routed_lengths_and_payout_corrections(wf, shifted.x, shifted.y, shifted.z,
+ distances, impact_minus[axis]);
+ }
+ }
+
+ double cost = 0.;
+ for (int i = 0; i < N; ++i) {
+ // Lengths grow along the free span, from where the line leaves its anchor
+ struct coord exit;
+ double length = line_length(wf, i, pos, &exit);
+ double dx = pos->x - exit.x;
+ double dy = pos->y - exit.y;
+ double dz = pos->z - exit.z;
+ double dist = hypot3(dx, dy, dz);
+ if (dist < EPSILON)
+ dist = EPSILON;
+ double inv_len = 1. / dist;
+ double inv_len3 = inv_len * inv_len * inv_len;
+
+ double flex = base_flex[i];
+ double found_line_pos = hp_relative_payout(length, wf->distances_origin[i], flex);
+ double res = found_line_pos - line_pos[i];
+ if (residuals)
+ residuals[i] = res;
+
+ double impact_deriv_x = (impact_plus[0][i] - impact_minus[0][i])
+ / (2. * impact_step);
+ double impact_deriv_y = (impact_plus[1][i] - impact_minus[1][i])
+ / (2. * impact_step);
+ double impact_deriv_z = (impact_plus[2][i] - impact_minus[2][i])
+ / (2. * impact_step);
+
+ if (jac) {
+ jac[i * 3 + 0] = dx * inv_len + impact_deriv_x;
+ jac[i * 3 + 1] = dy * inv_len + impact_deriv_y;
+ jac[i * 3 + 2] = dz * inv_len + impact_deriv_z;
+ }
+
+ if (hess) {
+ double *hrow = hess + i * 9;
+ double d[3] = {dx, dy, dz}, n[3] = {0., 0., 0.}, turn = 0.;
+ // The exit turns with a swivel pulley's fork (see hp_swivel_turn)
+ if (wf->pulley_radius[i] > 0.) {
+ const struct coord *a = &wf->anchors[i];
+ double entry[3] = {a->x, a->y, a->z};
+ double axis[3] = {wf->swivel_axis[i].x, wf->swivel_axis[i].y,
+ wf->swivel_axis[i].z};
+ double p[3] = {pos->x, pos->y, pos->z};
+ double e[3] = {exit.x, exit.y, exit.z};
+ turn = hp_swivel_turn(entry, axis, wf->pulley_radius[i], p, e, n)
+ * inv_len;
+ }
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c)
+ hrow[r * 3 + c] = (r == c ? inv_len : 0.)
+ - d[r] * d[c] * inv_len3 - turn * n[r] * n[c];
+ }
+
+ cost += 0.5 * res * res;
+ }
+ return cost;
+}
+
+static void
+accumulate_normals(const double *jac, const double *residuals, int N,
+ double JTJ[3][3], double grad[3])
+{
+ grad[0] = grad[1] = grad[2] = 0.;
+ JTJ[0][0] = JTJ[0][1] = JTJ[0][2] = 0.;
+ JTJ[1][0] = JTJ[1][1] = JTJ[1][2] = 0.;
+ JTJ[2][0] = JTJ[2][1] = JTJ[2][2] = 0.;
+ for (int i = 0; i < N; ++i) {
+ double jx = jac[i * 3 + 0];
+ double jy = jac[i * 3 + 1];
+ double jz = jac[i * 3 + 2];
+ double r = residuals[i];
+ grad[0] += jx * r;
+ grad[1] += jy * r;
+ grad[2] += jz * r;
+ JTJ[0][0] += jx * jx;
+ JTJ[0][1] += jx * jy;
+ JTJ[0][2] += jx * jz;
+ JTJ[1][0] += jy * jx;
+ JTJ[1][1] += jy * jy;
+ JTJ[1][2] += jy * jz;
+ JTJ[2][0] += jz * jx;
+ JTJ[2][1] += jz * jy;
+ JTJ[2][2] += jz * jz;
+ }
+}
+
+static int
+solve_normal_system(double JTJ[3][3], const double rhs[3], double delta[3])
+{
+ double JTJ_inv[3][3];
+ if (!invert3x3((const double (*)[3])JTJ, JTJ_inv))
+ return 0;
+ delta[0] = JTJ_inv[0][0] * rhs[0] + JTJ_inv[0][1] * rhs[1] + JTJ_inv[0][2] * rhs[2];
+ delta[1] = JTJ_inv[1][0] * rhs[0] + JTJ_inv[1][1] * rhs[1] + JTJ_inv[1][2] * rhs[2];
+ delta[2] = JTJ_inv[2][0] * rhs[0] + JTJ_inv[2][1] * rhs[1] + JTJ_inv[2][2] * rhs[2];
+ return 1;
+}
+
+static int
+solve_hybrid_halley(struct winch_flex *wf, const double *line_pos, int N,
+ struct coord *pos, double eta, double tol,
+ int halley_iters, int max_iters,
+ double *cost_out, int *iters_out)
+{
+ int iter_count = 0;
+ int converged = 0;
+ double cost = 0.;
+ double residuals[WINCH_MAX_ANCHORS];
+ double jac[WINCH_MAX_ANCHORS * 3];
+ double hess[WINCH_MAX_ANCHORS * 9];
+ int hi_limit = halley_iters < max_iters ? halley_iters : max_iters;
+
+ double anchors[WINCH_MAX_ANCHORS][3], ranges[WINCH_MAX_ANCHORS];
+ for (int i=0;ianchors[i].x; anchors[i][1]=wf->anchors[i].y; anchors[i][2]=wf->anchors[i].z;
+ // Seed swivel pulleys as pinholes at their entry points
+ ranges[i]=hypot3(anchors[i][0],anchors[i][1],anchors[i][2])+line_pos[i];
+ }
+ double candidates[3][3], normal[3]; int planar=0;
+ int candidate_count=hp_range_candidates(anchors,ranges,N,candidates,normal,&planar);
+ double initial[3]={pos->x,pos->y,pos->z};
+ cost=hp_forward_allowed(anchors,N,wf->anchor_mode,normal,planar,initial)
+ ? residuals_and_derivatives(wf,line_pos,N,pos,residuals,jac,NULL) : INFINITY;
+ for (int i=0;ianchor_mode,normal,planar,candidates[i])) continue;
+ struct coord trial={candidates[i][0],candidates[i][1],candidates[i][2]};
+ double trial_cost=residuals_and_derivatives(wf,line_pos,N,&trial,residuals,jac,NULL);
+ if (trial_costx += delta[0];
+ pos->y += delta[1];
+ pos->z += delta[2];
+ double position[3]={pos->x,pos->y,pos->z};
+ hp_reflect_above(anchors[0],normal,planar,position);
+ pos->x=position[0];pos->y=position[1];pos->z=position[2];
+ iter_count = iter + 1;
+ if (vec_norm3(delta) < tol) {
+ converged = 1;
+ break;
+ }
+ }
+
+ for (int iter = halley_iters; iter < max_iters && !converged; ++iter) {
+ cost = residuals_and_derivatives(wf, line_pos, N, pos,
+ residuals, jac, NULL);
+ double JTJ[3][3], grad[3];
+ accumulate_normals(jac, residuals, N, JTJ, grad);
+ JTJ[0][0] += eta;
+ JTJ[1][1] += eta;
+ JTJ[2][2] += eta;
+ double rhs[3] = { -grad[0], -grad[1], -grad[2] };
+ double delta[3];
+ if (!solve_normal_system(JTJ, rhs, delta))
+ break;
+ pos->x += delta[0];
+ pos->y += delta[1];
+ pos->z += delta[2];
+ double position[3]={pos->x,pos->y,pos->z};
+ hp_reflect_above(anchors[0],normal,planar,position);
+ pos->x=position[0];pos->y=position[1];pos->z=position[2];
+ iter_count = iter + 1;
+ if (vec_norm3(delta) < tol) {
+ converged = 1;
+ break;
+ }
+ }
+
+ double residuals_final[WINCH_MAX_ANCHORS];
+ double jac_tmp[WINCH_MAX_ANCHORS * 3];
+ cost = residuals_and_derivatives(wf, line_pos, N, pos,
+ residuals_final, jac_tmp, NULL);
+ if (iters_out)
+ *iters_out = iter_count;
+ if (cost_out)
+ *cost_out = cost;
+ double final_position[3]={pos->x,pos->y,pos->z};
+ if (!hp_forward_allowed(anchors,N,wf->anchor_mode,normal,planar,final_position)) converged=0;
+ return converged;
+}
+
+int __visible
+winch_forward_solve(struct winch_flex *wf, const double *motor_pos,
+ const double *initial_guess, double eta, double tol,
+ int halley_iters, int max_iters,
+ double *out_pos, double *out_cost, int *out_iters)
+{
+ if (!wf || !motor_pos || !out_pos)
+ return 0;
+ int N = wf->num_anchors;
+ if (N < 3 || N > WINCH_MAX_ANCHORS)
+ return 0;
+ if (halley_iters < 0)
+ halley_iters = 0;
+ if (max_iters < 0)
+ max_iters = 0;
+ double line_pos[WINCH_MAX_ANCHORS];
+ for (int i = 0; i < N; ++i)
+ line_pos[i] = motor_position_to_relative_payout(wf, i, motor_pos[i]);
+
+ struct coord pos;
+ pos.x = initial_guess ? initial_guess[0] : 0.;
+ pos.y = initial_guess ? initial_guess[1] : 0.;
+ pos.z = initial_guess ? initial_guess[2] : 0.;
+
+ double cost = 0.;
+ int iters = 0;
+ int ok = solve_hybrid_halley(wf, line_pos, N, &pos, eta, tol,
+ halley_iters, max_iters, &cost, &iters);
+ out_pos[0] = pos.x;
+ out_pos[1] = pos.y;
+ out_pos[2] = pos.z;
+ if (out_cost)
+ *out_cost = cost;
+ if (out_iters)
+ *out_iters = iters;
+ if (!ok || cost > 10.)
+ return 0;
+ return 1;
+}
+
+static double
+calc_position_common(struct winch_stepper *ws, struct move *m, double move_time)
+{
+ struct coord pos = move_get_coord(m, move_time), exit;
+ struct winch_flex *wf = ws->wf;
+ int i = ws->index;
+ double routed_length, correction = 0.;
+ if (wf->enabled) {
+ double distances[WINCH_MAX_ANCHORS], flex[WINCH_MAX_ANCHORS];
+ routed_lengths_and_payout_corrections(wf, pos.x, pos.y, pos.z, distances, flex);
+ routed_length = distances[i];
+ correction = flex[i];
+ } else {
+ routed_length = line_length(wf, i, &pos, &exit);
+ }
+ double payout = hp_relative_payout(routed_length, wf->distances_origin[i], correction);
+ return relative_payout_to_motor_position(wf, i, payout);
+}
+
+static double
+winch_stepper_calc_position(struct stepper_kinematics *sk, struct move *m,
+ double move_time)
+{
+ struct winch_stepper *ws = container_of(sk, struct winch_stepper, sk);
+ return calc_position_common(ws, m, move_time);
+}
+
+struct winch_flex * __visible
+winch_flex_alloc(void)
+{
+ struct winch_flex *wf = malloc(sizeof(*wf));
+ if (!wf)
+ return NULL;
+ memset(wf, 0, sizeof(*wf));
+ return wf;
+}
+
+void __visible
+winch_flex_free(struct winch_flex *wf)
+{
+ free(wf);
+}
+
+static void
+recalc_origin(struct winch_flex *wf)
+{
+ int num = wf->num_anchors;
+ if (num <= 0)
+ return;
+
+ struct coord origin = {0., 0., 0.}, exit;
+ for (int i = 0; i < num; ++i) {
+ wf->distances_origin[i] = line_length(wf, i, &origin, &exit);
+ double ma = wf->mechanical_advantage[i] > 0 ? wf->mechanical_advantage[i] : 1.;
+ double spring_length = wf->distances_origin[i] * ma + wf->guy_wires[i];
+ double spring_k = wf->spring_constant / (spring_length > EPSILON ? spring_length : EPSILON);
+ wf->home_flex[i] = spring_k > 0.
+ ? hp_span_extension(wf->home_tension[i], spring_k, ma, wf->lines_per_axis[i]) : 0.;
+ }
+}
+
+void __visible
+winch_flex_set_swivels(struct winch_flex *wf, const double *radii,
+ const double *axes, const double *home_tension)
+{
+ if (!wf)
+ return;
+ for (int i = 0; i < wf->num_anchors; ++i) {
+ double ax = axes[i * 3], ay = axes[i * 3 + 1], az = axes[i * 3 + 2];
+ double n = hypot3(ax, ay, az);
+ wf->pulley_radius[i] = radii[i];
+ wf->swivel_axis[i].x = n > 0. ? ax / n : 0.;
+ wf->swivel_axis[i].y = n > 0. ? ay / n : 0.;
+ wf->swivel_axis[i].z = n > 0. ? az / n : 0.;
+ wf->home_tension[i] = home_tension[i];
+ }
+ recalc_origin(wf);
+}
+
+static void
+set_default_spool_params(struct winch_flex *wf, int idx)
+{
+ wf->spool_radius[idx] = 0.;
+ wf->spool_radius_sq[idx] = 0.;
+ wf->k0[idx] = 0.;
+ wf->k2[idx] = 0.;
+ wf->steps_per_mm[idx] = 1.;
+ wf->inv_steps_per_mm[idx] = 1.;
+ wf->use_constant_spool_model[idx] = 1;
+}
+
+void __visible
+winch_flex_set_spool_params(struct winch_flex *wf, int index,
+ double rotation_distance,
+ double steps_per_rotation)
+{
+ if (!wf || index < 0 || index >= wf->num_anchors)
+ return;
+ double ma = wf->mechanical_advantage[index];
+ if (ma <= 0.)
+ ma = 1.;
+ double steps_per_mm = rotation_distance > 0.
+ ? steps_per_rotation / rotation_distance : 0.;
+ wf->steps_per_mm[index] = steps_per_mm;
+ wf->inv_steps_per_mm[index] = steps_per_mm > 0. ? 1. / steps_per_mm : 0.;
+
+ const double two_pi = 2.0 * M_PI;
+ double r0 = rotation_distance > 0. ? (rotation_distance * ma) / two_pi : 0.;
+ wf->spool_radius[index] = r0;
+ wf->spool_radius_sq[index] = r0 * r0;
+
+ double k2 = -wf->buildup_factor * ma;
+ wf->k2[index] = k2;
+ wf->k0[index] = 0.;
+ wf->use_constant_spool_model[index] = 1;
+ if (fabs(k2) <= 1e-12 || steps_per_mm <= 0.)
+ return;
+ double steps_per_unit_times_r = steps_per_mm * r0;
+ wf->k0[index] = 2.0 * steps_per_unit_times_r / k2;
+ wf->use_constant_spool_model[index] = 0;
+}
+
+void __visible
+winch_flex_configure(struct winch_flex *wf,
+ int num_anchors,
+ const double *anchors,
+ const double *attachments,
+ double buildup_factor,
+ double mover_weight,
+ double spring_constant,
+ const double *min_force,
+ const double *max_force,
+ const double *guy_wires,
+ int flex_compensation_algorithm,
+ int ignore_gravity,
+ int ignore_pretension,
+ const int *mechanical_advantage,
+ const int *lines_per_axis,
+ double spool_flattening,
+ int strained_spool_storage)
+{
+ if (!wf)
+ return;
+ if (num_anchors < 0)
+ num_anchors = 0;
+ if (num_anchors > WINCH_MAX_ANCHORS)
+ num_anchors = WINCH_MAX_ANCHORS;
+ wf->num_anchors = num_anchors;
+ wf->buildup_factor = buildup_factor;
+ wf->spool_flattening = spool_flattening;
+ wf->strained_spool_storage = strained_spool_storage;
+ wf->mover_weight = mover_weight;
+ wf->spring_constant = spring_constant;
+ wf->flex_compensation_algorithm = flex_compensation_algorithm;
+ wf->ignore_gravity = ignore_gravity;
+ wf->ignore_pretension = ignore_pretension;
+
+ for (int i = 0; i < num_anchors; ++i) {
+ wf->anchors[i].x = anchors[i * 3];
+ wf->anchors[i].y = anchors[i * 3 + 1];
+ wf->anchors[i].z = anchors[i * 3 + 2];
+ wf->attachments[i].x = attachments[i * 3];
+ wf->attachments[i].y = attachments[i * 3 + 1];
+ wf->attachments[i].z = attachments[i * 3 + 2];
+ wf->min_force[i] = min_force ? min_force[i] : 0.;
+ wf->max_force[i] = max_force ? max_force[i] : 120.0;
+
+ if (guy_wires)
+ wf->guy_wires[i] = guy_wires[i];
+ else
+ wf->guy_wires[i] = 0.;
+
+ if (mechanical_advantage)
+ wf->mechanical_advantage[i] = mechanical_advantage[i];
+ else
+ wf->mechanical_advantage[i] = 1;
+ wf->lines_per_axis[i] = lines_per_axis ? lines_per_axis[i] : 1;
+ set_default_spool_params(wf, i);
+ }
+ for (int i = num_anchors; i < WINCH_MAX_ANCHORS; ++i) {
+ wf->anchors[i].x = wf->anchors[i].y = wf->anchors[i].z = 0.;
+ wf->attachments[i].x = wf->attachments[i].y = 0.;
+ wf->attachments[i].z = 0.;
+ wf->min_force[i] = 0.;
+ wf->max_force[i] = 120.0;
+ wf->guy_wires[i] = 0.;
+ wf->mechanical_advantage[i] = 1;
+ wf->lines_per_axis[i] = 1;
+ set_default_spool_params(wf, i);
+ }
+ if (wf->flex_compensation_algorithm < WINCH_FORCE_ALGO_TIKHONOV
+ || wf->flex_compensation_algorithm > WINCH_FORCE_ALGO_QP) {
+ wf->flex_compensation_algorithm = WINCH_FORCE_ALGO_QP;
+ }
+ double radius_sq = 0.;
+ for (int i = 0; i < num_anchors; ++i)
+ radius_sq += wf->attachments[i].x * wf->attachments[i].x
+ + wf->attachments[i].y * wf->attachments[i].y
+ + wf->attachments[i].z * wf->attachments[i].z;
+ wf->inv_attachment_radius = radius_sq > EPSILON
+ ? sqrt(num_anchors / radius_sq) : 0.;
+ recalc_origin(wf);
+}
+
+void __visible
+winch_flex_calc_arrays(struct winch_flex *wf, double x, double y, double z,
+ double *distances_out, double *flex_out)
+{
+ if (!wf || wf->num_anchors <= 0)
+ return;
+ routed_lengths_and_payout_corrections(wf, x, y, z, distances_out, flex_out);
+}
+
+int __visible
+winch_flex_set_anchor_mode(struct winch_flex *wf, int mode)
+{
+ if (!wf || mode<0 || mode>3 || (mode==HP_ANCHORS_CUBE_CORNER && wf->num_anchors!=8)) return 0;
+ wf->anchor_mode=mode;
+ return 1;
+}
+
+int __visible
+winch_flex_is_reachable(struct winch_flex *wf, double x, double y, double z)
+{
+ if (!wf) return 0;
+ double anchors[WINCH_MAX_ANCHORS][3], position[3]={x,y,z};
+ for (int i=0;inum_anchors;++i) {
+ anchors[i][0]=wf->anchors[i].x; anchors[i][1]=wf->anchors[i].y; anchors[i][2]=wf->anchors[i].z;
+ }
+ return hp_reachable(anchors,wf->num_anchors,wf->anchor_mode,position);
+}
+
+void __visible
+winch_flex_set_enabled(struct winch_flex *wf, int enabled)
+{
+ if (!wf)
+ return;
+ wf->enabled = enabled ? 1 : 0;
+}
+
+double __visible
+winch_flex_motor_to_line_pos(struct winch_flex *wf, int index,
+ double motor_pos)
+{
+ if (!wf || index < 0 || index >= wf->num_anchors)
+ return motor_pos;
+ return motor_position_to_relative_payout(wf, index, motor_pos);
+}
+
struct stepper_kinematics * __visible
-winch_stepper_alloc(double anchor_x, double anchor_y, double anchor_z)
-{
- struct winch_stepper *hs = malloc(sizeof(*hs));
- memset(hs, 0, sizeof(*hs));
- hs->anchor.x = anchor_x;
- hs->anchor.y = anchor_y;
- hs->anchor.z = anchor_z;
- hs->sk.calc_position_cb = winch_stepper_calc_position;
- hs->sk.active_flags = AF_X | AF_Y | AF_Z;
- return &hs->sk;
+winch_stepper_alloc(struct winch_flex *wf, int index)
+{
+ if (!wf || index < 0 || index >= wf->num_anchors)
+ return NULL;
+ struct winch_stepper *ws = malloc(sizeof(*ws));
+ if (!ws)
+ return NULL;
+ memset(ws, 0, sizeof(*ws));
+ ws->wf = wf;
+ ws->index = index;
+ ws->sk.calc_position_cb = winch_stepper_calc_position;
+ ws->sk.active_flags = AF_X | AF_Y | AF_Z;
+ return &ws->sk;
}
diff --git a/klippy/chelper/line_transforms.h b/klippy/chelper/line_transforms.h
new file mode 100644
index 000000000000..3ebd1c671560
--- /dev/null
+++ b/klippy/chelper/line_transforms.h
@@ -0,0 +1,31 @@
+#pragma once
+
+// One cable direction at a time. Lengths are in mm at the effector,
+// forces are in N. Positive relative payout moves away from the anchor.
+typedef double hp_line_scalar;
+
+static inline hp_line_scalar
+hp_relative_payout(hp_line_scalar routed_length, hp_line_scalar home_length,
+ hp_line_scalar correction)
+{
+ return (routed_length - home_length) + correction;
+}
+
+// The direction force is shared by all parallel lines and reeved spans.
+// Convert rope extension back into a displacement of the effector.
+static inline hp_line_scalar
+hp_span_extension(hp_line_scalar direction_force, hp_line_scalar spring_rate,
+ hp_line_scalar reeving, hp_line_scalar parallel_lines)
+{
+ return direction_force / (spring_rate * reeving * reeving * parallel_lines);
+}
+
+// Additional motor-side payout when wound rope is strained and the loaded
+// drum radius is smaller by the given fraction of its unloaded radius.
+static inline hp_line_scalar
+hp_storage_correction(hp_line_scalar rest_payout, hp_line_scalar winding_strain,
+ hp_line_scalar radius_loss_fraction)
+{
+ return rest_payout * (winding_strain + radius_loss_fraction)
+ / (1 - radius_loss_fraction);
+}
diff --git a/klippy/chelper/serialqueue.c b/klippy/chelper/serialqueue.c
index c232172010d8..fd6ac0bc6559 100644
--- a/klippy/chelper/serialqueue.c
+++ b/klippy/chelper/serialqueue.c
@@ -700,6 +700,27 @@ background_thread(void *data)
list_init(&dummy);
receive_append_wake(&sq->receiver, &dummy);
+ if (sq->serial_fd_type == SQT_DEBUGFILE) {
+ // A file has no clock to wait for: write every queued message,
+ // advancing through the send schedule instead of sleeping.
+ double eventtime = get_monotonic();
+ for (;;) {
+ pthread_mutex_lock(&sq->lock);
+ int queued = sq->ready_bytes;
+ pthread_mutex_unlock(&sq->lock);
+ pthread_mutex_lock(&sq->transmit_requests.lock);
+ queued |= sq->transmit_requests.upcoming_bytes;
+ pthread_mutex_unlock(&sq->transmit_requests.lock);
+ if (!queued)
+ break;
+ double waketime = command_event(sq, eventtime);
+ if (waketime == PR_NEVER)
+ break;
+ if (waketime > eventtime)
+ eventtime = waketime;
+ }
+ }
+
return NULL;
}
diff --git a/klippy/chelper/swivel_pulley.h b/klippy/chelper/swivel_pulley.h
new file mode 100644
index 000000000000..509435beb832
--- /dev/null
+++ b/klippy/chelper/swivel_pulley.h
@@ -0,0 +1,61 @@
+// Shared by the development solvers, RepRapFirmware and Klipper.
+// A swivel pulley's fork turns about a fixed axis through the point where the
+// line enters it. The line arrives travelling along the axis, wraps the wheel
+// and leaves from a tangent point towards the mover. Zero radius is a pinhole.
+#ifndef HANGPRINTER_SWIVEL_PULLEY_H
+#define HANGPRINTER_SWIVEL_PULLEY_H
+#include
+
+// entry: where the line enters the pulley, axis: unit direction of travel of
+// the incoming line, p: where the line ends. Returns the line length from entry
+// to p (wrap plus free span) and writes the point where the line leaves the wheel.
+static inline double hp_swivel_length(const double entry[3], const double axis[3], double radius,
+ const double p[3], double exit[3]) {
+ double v[3]={p[0]-entry[0],p[1]-entry[1],p[2]-entry[2]};
+ double z=v[0]*axis[0]+v[1]*axis[1]+v[2]*axis[2];
+ double e[3]={v[0]-z*axis[0],v[1]-z*axis[1],v[2]-z*axis[2]};
+ double rho=sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);
+ if (!(radius>0.)) {
+ for (int j=0;j<3;++j) exit[j]=entry[j];
+ return sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
+ }
+ if (rho<1e-9) {
+ // On the axis every fork angle gives the same length; pick any wheel plane.
+ int k=fabs(axis[0])<.6 ? 0 : (fabs(axis[1])<.6 ? 1 : 2);
+ for (int j=0;j<3;++j) e[j]=(j==k)-axis[k]*axis[j];
+ double n=sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);
+ for (int j=0;j<3;++j) e[j]/=n;
+ } else {
+ for (int j=0;j<3;++j) e[j]/=rho;
+ }
+ // In the wheel plane, with the wheel centre at entry + radius*e
+ double c=rho-radius, d=sqrt(c*c+z*z);
+ double ratio=d>radius ? radius/d : 1.;
+ double theta=atan2(z,c)+acos(ratio);
+ // Inside the wheel (d <= radius) there is no tangent; the span collapses to zero.
+ double span=d>radius ? sqrt(d*d-radius*radius) : 0.;
+ for (int j=0;j<3;++j) exit[j]=entry[j]+radius*(e[j]*(1.+cos(theta))+axis[j]*sin(theta));
+ return span+radius*(3.14159265358979323846-theta);
+}
+
+// The exit point turns with the fork about the axis, so across the wheel plane
+// the length bends less than a fixed exit would make it: its Hessian is
+// (I - u u^T - k n n^T) / span, with u the free span direction and n the wheel
+// plane normal written here. Returns k, the exit's distance from the axis over
+// p's distance (0 for pinholes).
+static inline double hp_swivel_turn(const double entry[3], const double axis[3], double radius,
+ const double p[3], const double exit[3], double normal[3]) {
+ double v[3]={p[0]-entry[0],p[1]-entry[1],p[2]-entry[2]};
+ double w[3]={exit[0]-entry[0],exit[1]-entry[1],exit[2]-entry[2]};
+ double zv=v[0]*axis[0]+v[1]*axis[1]+v[2]*axis[2], zw=w[0]*axis[0]+w[1]*axis[1]+w[2]*axis[2];
+ for (int j=0;j<3;++j) { v[j]-=zv*axis[j]; w[j]-=zw*axis[j]; }
+ double rv=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]), rw=sqrt(w[0]*w[0]+w[1]*w[1]+w[2]*w[2]);
+ for (int j=0;j<3;++j) normal[j]=0.;
+ if (!(radius>0.) || rv<1e-9) return 0.;
+ normal[0]=(axis[1]*v[2]-axis[2]*v[1])/rv;
+ normal[1]=(axis[2]*v[0]-axis[0]*v[2])/rv;
+ normal[2]=(axis[0]*v[1]-axis[1]*v[0])/rv;
+ return rw/rv;
+}
+
+#endif
diff --git a/klippy/extras/hangprinter_m569.py b/klippy/extras/hangprinter_m569.py
new file mode 100644
index 000000000000..8b927d6a72f7
--- /dev/null
+++ b/klippy/extras/hangprinter_m569.py
@@ -0,0 +1,249 @@
+# Minimal Hangprinter compatibility helpers for RepRapFirmware-style M569 gcodes.
+import math
+import shlex
+
+
+MIN_FORCE_MODE_THRESHOLD_N = 0.001
+
+
+def _parse_motor_address(raw_value):
+ if raw_value is None:
+ return None
+ text = str(raw_value).strip()
+ if not text:
+ return None
+ parts = text.split('.', 1)
+ can_address = int(parts[0])
+ driver_index = 0
+ if len(parts) > 1 and parts[1]:
+ driver_index = int(parts[1])
+ return {
+ 'can_address': can_address,
+ 'driver': driver_index,
+ }
+
+
+def _motor_address_key(motor_address):
+ if motor_address is None:
+ return None
+ return '%d.%d' % (
+ motor_address['can_address'],
+ motor_address.get('driver', 0),
+ )
+
+
+def _parse_driver_list(raw_value):
+ descriptors = []
+ for item in str(raw_value).split(':'):
+ text = item.strip()
+ if not text:
+ continue
+ descriptors.append(text)
+ return descriptors
+
+
+def _parse_float_list(raw_value):
+ values = []
+ for item in str(raw_value).split(':'):
+ text = item.strip()
+ if not text:
+ continue
+ values.append(float(text))
+ return values
+
+
+def _get_param_text(gcmd, name):
+ value = gcmd.get(name, None)
+ if value is not None:
+ return str(value)
+
+ raw_getter = getattr(gcmd, 'get_raw_command_parameters', None)
+ if not callable(raw_getter):
+ return None
+
+ rawparams = raw_getter()
+ if not rawparams:
+ return None
+
+ prefix = name.upper()
+ for token in shlex.split(rawparams, posix=True):
+ upper = token.upper()
+ if upper.startswith(prefix + '='):
+ return token[len(prefix) + 1:]
+ if upper.startswith(prefix):
+ return token[len(prefix):]
+ return None
+
+
+class HangprinterM569:
+ def __init__(self, config):
+ self.printer = config.get_printer()
+ self.gcode = self.printer.lookup_object('gcode')
+ self.driver_states = {}
+ self.gcode.register_command('M569.3', self.cmd_M569_3,
+ desc=self.cmd_M569_3_help)
+ self.gcode.register_command('M569.4', self.cmd_M569_4,
+ desc=self.cmd_M569_4_help)
+
+ cmd_M569_3_help = "Read motor encoder positions (placeholder for terminal-side simulation bridge)"
+ cmd_M569_4_help = "Set motor torque mode from requested line force (placeholder driver backend)"
+
+ def _get_driver_lookup(self):
+ toolhead = self.printer.lookup_object('toolhead', None)
+ if toolhead is None:
+ return {
+ 'by_name': {},
+ 'by_address': {},
+ 'has_configured_addresses': False,
+ }
+ kin = toolhead.get_kinematics()
+ steppers = list(kin.get_steppers())
+ motor_descriptors = list(getattr(kin, 'm569_driver_descriptors', []))
+ flex_helper = getattr(kin, 'flex_helper', None)
+ mechanical_advantage = list(getattr(flex_helper, 'mechanical_advantage', []))
+ driver_lookup = {
+ 'by_name': {},
+ 'by_address': {},
+ 'has_configured_addresses': False,
+ }
+ for index, stepper in enumerate(steppers):
+ descriptor = motor_descriptors[index] if index < len(motor_descriptors) else {}
+ stepper_name = descriptor.get('stepper_name') or stepper.get_name()
+ motor_address = descriptor.get('motor_address')
+ driver_key = _motor_address_key(motor_address) or stepper_name
+ rotation_distance_mm, _steps_per_rotation = stepper.get_rotation_distance()
+ invert_dir, _orig_invert_dir = stepper.get_dir_inverted()
+ mech_adv = 1
+ if index < len(mechanical_advantage) and mechanical_advantage[index]:
+ mech_adv = mechanical_advantage[index]
+ driver_entry = {
+ 'stepper_name': stepper_name,
+ 'motor_address': motor_address,
+ 'driver_key': driver_key,
+ 'has_motor_address': motor_address is not None,
+ 'mechanical_advantage': mech_adv,
+ 'rotation_distance_mm': rotation_distance_mm,
+ 'invert_dir': bool(invert_dir),
+ }
+ driver_lookup['by_name'][stepper_name] = driver_entry
+ if motor_address is not None:
+ driver_lookup['by_address'][_motor_address_key(motor_address)] = driver_entry
+ driver_lookup['has_configured_addresses'] = True
+ return driver_lookup
+
+ def _resolve_driver_token(self, token, driver_lookup):
+ text = str(token).strip()
+ if not text:
+ return {'error': f"{text} did not match any stepper name or m569_address."}
+
+ by_name = driver_lookup.get('by_name', {})
+ by_address = driver_lookup.get('by_address', {})
+
+ name_match = by_name.get(text)
+ if name_match is not None:
+ if driver_lookup.get('has_configured_addresses') and not name_match.get('has_motor_address'):
+ return {'error': 'm569_address not configured for %s' % (name_match['stepper_name'],)}
+ return {'descriptor': name_match}
+
+ address_match = None
+ try:
+ address_match = by_address.get(_motor_address_key(_parse_motor_address(text)))
+ except (TypeError, ValueError):
+ address_match = None
+ if address_match is not None:
+ return {'descriptor': address_match}
+
+ return {'error': f"{text} did not match any stepper name or m569_address."}
+
+ def _compute_torque_from_force(self, driver_config, force_newtons):
+ position_mode = abs(force_newtons) < MIN_FORCE_MODE_THRESHOLD_N
+ if position_mode:
+ return 0., True
+ mech_adv = driver_config['mechanical_advantage'] or 1
+ line_tension_n = force_newtons / mech_adv
+ # Klipper's winch stepper rotation_distance is line mm per motor
+ # rotation, so it already folds spool radius and gearing into one
+ # effective radius.
+ effective_radius_m = (
+ abs(driver_config['rotation_distance_mm']) / (2.0 * math.pi)
+ ) * 0.001
+ torque_nm = abs(line_tension_n * effective_radius_m)
+ if not driver_config['invert_dir']:
+ torque_nm = -torque_nm
+ return torque_nm, False
+
+ def _set_placeholder_driver_state(self, driver_key, force_newtons,
+ torque_nm, position_mode):
+ self.driver_states[driver_key] = {
+ 'force_newtons': force_newtons,
+ 'torque_nm': 0. if position_mode else torque_nm,
+ 'position_mode': bool(position_mode),
+ }
+
+ def cmd_M569_3(self, gcmd):
+ p_value = _get_param_text(gcmd, 'P')
+ if p_value is None:
+ gcmd.respond_raw("Error: M569: missing parameter 'P'")
+ return
+ try:
+ drivers = _parse_driver_list(p_value)
+ except (TypeError, ValueError):
+ gcmd.respond_raw("Error: M569.3 unable to parse parameters")
+ return
+ if not drivers:
+ gcmd.respond_raw("Error: M569: missing parameter 'P'")
+ return
+ driver_lookup = self._get_driver_lookup()
+ for descriptor in drivers:
+ resolution = self._resolve_driver_token(descriptor, driver_lookup)
+ if 'error' in resolution:
+ gcmd.respond_raw(resolution['error'])
+ return
+ # The terminal bridge overrides this placeholder reply with simulated
+ # encoder angles when hp-sim is attached over gcode_ws.
+ gcmd.respond_raw("Error: M569.3: Message not received")
+
+ def cmd_M569_4(self, gcmd):
+ p_value = _get_param_text(gcmd, 'P')
+ if p_value is None:
+ gcmd.respond_raw("Error: M569: missing parameter 'P'")
+ return
+ t_value = _get_param_text(gcmd, 'T')
+ if t_value is None:
+ gcmd.respond_raw("Error: M569.4 missing parameter 'T'")
+ return
+ try:
+ drivers = _parse_driver_list(p_value)
+ forces = _parse_float_list(t_value)
+ except (TypeError, ValueError):
+ gcmd.respond_raw("Error: M569.4 unable to parse parameters")
+ return
+ if not drivers:
+ gcmd.respond_raw("Error: M569: missing parameter 'P'")
+ return
+ if len(forces) == 1 and len(drivers) > 1:
+ forces = forces * len(drivers)
+ elif len(forces) != len(drivers):
+ gcmd.respond_raw("M569.4 requires one T value per P")
+ return
+ driver_lookup = self._get_driver_lookup()
+ response_parts = []
+ for descriptor, force_newtons in zip(drivers, forces):
+ resolution = self._resolve_driver_token(descriptor, driver_lookup)
+ if 'error' in resolution:
+ gcmd.respond_raw(resolution['error'])
+ return
+ driver_config = resolution['descriptor']
+ torque_nm, position_mode = self._compute_torque_from_force(
+ driver_config, force_newtons)
+ self._set_placeholder_driver_state(
+ driver_config['driver_key'], force_newtons, torque_nm, position_mode)
+ if position_mode:
+ response_parts.append("pos_mode, ")
+ else:
+ response_parts.append("%.6f Nm, " % (torque_nm,))
+ gcmd.respond_raw("".join(response_parts))
+
+
+def load_config(config):
+ return HangprinterM569(config)
diff --git a/klippy/extras/motion_queuing.py b/klippy/extras/motion_queuing.py
index 07a6d63ed85c..7e34f9ce7b4d 100644
--- a/klippy/extras/motion_queuing.py
+++ b/klippy/extras/motion_queuing.py
@@ -3,13 +3,28 @@
# Copyright (C) 2025 Kevin O'Connor
#
# This file may be distributed under the terms of the GNU GPLv3 license.
-import logging
+import logging, os
import chelper
BGFLUSH_LOW_TIME = 0.200
BGFLUSH_HIGH_TIME = 0.400
-BGFLUSH_SG_LOW_TIME = 0.450
-BGFLUSH_SG_HIGH_TIME = 0.700
+
+def _get_env_float(name, default):
+ value = os.environ.get(name)
+ if value in (None, ""):
+ return default
+ try:
+ parsed = float(value)
+ except (TypeError, ValueError):
+ logging.warning("Ignoring invalid %s=%r", name, value)
+ return default
+ if parsed <= 0.:
+ logging.warning("Ignoring non-positive %s=%r", name, value)
+ return default
+ return parsed
+
+BGFLUSH_SG_LOW_TIME = _get_env_float("KLIPPY_MOTION_QUEUE_SG_LOW_TIME", 0.450)
+BGFLUSH_SG_HIGH_TIME = _get_env_float("KLIPPY_MOTION_QUEUE_SG_HIGH_TIME", 0.700)
BGFLUSH_EXTRA_TIME = 0.250
MOVE_HISTORY_EXPIRE = 30.
diff --git a/klippy/gcode.py b/klippy/gcode.py
index f18bde12dca9..3cf77e976c96 100644
--- a/klippy/gcode.py
+++ b/klippy/gcode.py
@@ -358,6 +358,10 @@ def request_restart(self, result):
self.printer.send_event("gcode:request_restart", print_time)
toolhead.dwell(0.500)
toolhead.wait_moves()
+ # Batch output cannot wait for the background flush timer, which
+ # may not have run yet. Generate every remaining step first.
+ if not toolhead.can_pause:
+ toolhead.flush_step_generation()
self.printer.request_exit(result)
cmd_RESTART_help = "Reload config file and restart host software"
def cmd_RESTART(self, gcmd):
diff --git a/klippy/kinematics/winch.py b/klippy/kinematics/winch.py
index 77f3cc734509..9265b88d8cde 100644
--- a/klippy/kinematics/winch.py
+++ b/klippy/kinematics/winch.py
@@ -3,13 +3,200 @@
# Copyright (C) 2018-2021 Kevin O'Connor
#
# This file may be distributed under the terms of the GNU GPLv3 license.
-import stepper, mathutil
+import math
+import stepper, mathutil, chelper
+
+
+class WinchFlexHelper:
+ ANCHOR_MODES = {'none': 0, 'last_on_top': 1, 'all_on_top': 2, 'cube_corner': 3}
+ ANCHOR_MODE_NAMES = {v: k for k, v in ANCHOR_MODES.items()}
+ ALGORITHMS = {'tikhonov': 0, 'qp': 1}
+ ALGO_NAMES = {v: k for k, v in ALGORITHMS.items()}
+
+ def __init__(self, anchors, attachments, config, pulley_radii=None,
+ swivel_axes=None):
+ self._anchors = tuple(anchors)
+ self._attachments = tuple(attachments)
+ self.num = len(self._anchors)
+ self._pulley_radii = tuple(pulley_radii or (0.,) * self.num)
+ self._swivel_axes = tuple(swivel_axes or ((0., 0., 0.),) * self.num)
+ self.origin_distances = ()
+ self.ptr = None
+ self.enabled = False
+ self.flex_compensation_algorithm_name = 'qp'
+ self.flex_compensation_algorithm = self.ALGORITHMS[self.flex_compensation_algorithm_name]
+ self.ignore_gravity = False
+ self.ignore_pretension = False
+ self.ffi_main = self.ffi_lib = None
+ self._read_config(config)
+ if not self.num:
+ return
+ self.ffi_main, self.ffi_lib = chelper.get_ffi()
+ self.ptr = self.ffi_main.gc(
+ self.ffi_lib.winch_flex_alloc(), self.ffi_lib.winch_flex_free)
+ self._configure()
+ self.set_active(self.enabled)
+
+ def _read_config(self, config):
+ self.anchor_mode = config.getchoice('winch_anchor_mode', self.ANCHOR_MODES, default='none')
+ if self.anchor_mode == 3 and self.num != 8:
+ raise config.error("CubeCorner anchor mode requires exactly 8 anchors")
+ self.buildup_factor = config.getfloat('winch_buildup_factor', 0., minval=0.)
+ self.spool_flattening = config.getfloat(
+ 'winch_spool_flattening', 0., minval=0.)
+ self.strained_spool_storage = config.getboolean(
+ 'winch_strained_spool_storage', False)
+ if not math.isfinite(self.spool_flattening):
+ raise config.error("winch_spool_flattening must be finite")
+ if self.buildup_factor and (self.spool_flattening
+ or self.strained_spool_storage):
+ raise config.error(
+ "winch_buildup_factor cannot be combined with"
+ " winch_spool_flattening or winch_strained_spool_storage")
+ self.mover_weight = config.getfloat('winch_mover_weight', 0., minval=0.)
+ self.spring_constant = config.getfloat('winch_spring_constant', 0., minval=0.)
+ if (self.spool_flattening or self.strained_spool_storage) \
+ and not 0. < self.spring_constant < math.inf:
+ raise config.error(
+ "Spool flattening and strained storage need flex compensation"
+ " with a positive, finite winch_spring_constant")
+ if self.num:
+ default_min = tuple(0. for _ in range(self.num))
+ default_max = tuple(120. for _ in range(self.num))
+ default_guy_wires = tuple(0. for _ in range(self.num))
+ default_mechanical_advantage = tuple(1 for _ in range(self.num))
+ self.min_force = list(config.getfloatlist(
+ 'winch_min_force', default_min, count=self.num))
+ self.max_force = list(config.getfloatlist(
+ 'winch_max_force', default_max, count=self.num))
+ self.guy_wires = list(config.getfloatlist(
+ 'winch_guy_wire_lengths', default_guy_wires, count=self.num))
+ self.mechanical_advantage = list(config.getintlist(
+ 'winch_mechanical_advantage', default_mechanical_advantage, count=self.num))
+ self.lines_per_axis = list(config.getintlist(
+ 'winch_lines_per_axis', tuple(1 for _ in range(self.num)),
+ count=self.num))
+ # Direction-total tension when the motors were zeroed at the origin
+ self.home_tension = list(config.getfloatlist(
+ 'winch_home_tension', tuple(0. for _ in range(self.num)),
+ count=self.num))
+ else:
+ self.min_force = []
+ self.max_force = []
+ self.guy_wires = []
+ self.mechanical_advantage = []
+ self.lines_per_axis = []
+ self.home_tension = []
+ algo_choices = list(self.ALGORITHMS.keys())
+ self.flex_compensation_algorithm_name = config.getchoice(
+ 'flex_compensation_algorithm', algo_choices, default='qp')
+ self.flex_compensation_algorithm = self.ALGORITHMS[self.flex_compensation_algorithm_name]
+ self.ignore_gravity = config.getboolean('ignore_gravity', False)
+ self.ignore_pretension = config.getboolean('ignore_pretension', False)
+
+ def _configure(self):
+ anchors_flat = [float(coord) for anchor in self._anchors for coord in anchor]
+ anchors_c = self.ffi_main.new("double[]", anchors_flat)
+ attachments_c = self.ffi_main.new("double[]", [
+ float(coord) for attachment in self._attachments
+ for coord in attachment])
+ min_c = self.ffi_main.new("double[]", self.min_force)
+ max_c = self.ffi_main.new("double[]", self.max_force)
+ guy_ptr = self.ffi_main.new("double[]", self.guy_wires)
+ self.ffi_lib.winch_flex_configure(
+ self.ptr, self.num, anchors_c, attachments_c,
+ self.buildup_factor, self.mover_weight,
+ self.spring_constant, min_c, max_c,
+ guy_ptr, self.flex_compensation_algorithm,
+ self.ignore_gravity, self.ignore_pretension, self.mechanical_advantage,
+ self.lines_per_axis, self.spool_flattening,
+ self.strained_spool_storage)
+ self.ffi_lib.winch_flex_set_swivels(
+ self.ptr, self.ffi_main.new("double[]", list(self._pulley_radii)),
+ self.ffi_main.new("double[]", [
+ float(c) for axis in self._swivel_axes for c in axis]),
+ self.ffi_main.new("double[]", self.home_tension))
+ self.origin_distances = tuple(self.calc_arrays((0., 0., 0.))[0])
+ self.set_anchor_mode(self.anchor_mode)
+
+ def set_anchor_mode(self, mode):
+ if mode not in self.ANCHOR_MODE_NAMES or (mode == 3 and self.num != 8):
+ raise ValueError("Anchor mode must be 0..3; CubeCorner requires exactly 8 anchors")
+ if not self.ffi_lib.winch_flex_set_anchor_mode(self.ptr, mode):
+ raise ValueError("Unable to configure winch anchor mode")
+ self.anchor_mode = mode
+
+ def is_reachable(self, position):
+ return bool(self.ffi_lib.winch_flex_is_reachable(self.ptr, *position[:3]))
+
+ def get_ptr(self):
+ if self.ptr is not None:
+ return self.ptr
+ if self.ffi_main is None:
+ self.ffi_main, _ = chelper.get_ffi()
+ return self.ffi_main.NULL
+
+ def is_active(self):
+ return bool(self.ptr) and bool(self.enabled)
+
+ def set_active(self, enable):
+ enable = bool(enable)
+ self.enabled = enable
+ if self.ptr and self.ffi_lib is not None:
+ self.ffi_lib.winch_flex_set_enabled(self.ptr, 1 if enable else 0)
+ return self.is_active()
+ def set_spool_params(self, index, rotation_distance, steps_per_rotation):
+ if not self.ptr or self.ffi_lib is None:
+ return
+ self.ffi_lib.winch_flex_set_spool_params(
+ self.ptr, index, rotation_distance, steps_per_rotation)
+ def motor_to_line_pos(self, index, motor_pos):
+ if not self.ptr or self.ffi_lib is None:
+ return motor_pos
+ return self.ffi_lib.winch_flex_motor_to_line_pos(
+ self.ptr, index, motor_pos)
+
+ def config_valid(self):
+ return True
+
+ def get_algorithm_name(self):
+ return self.flex_compensation_algorithm_name
+
+ def calc_arrays(self, pos):
+ if not self.ptr or not self.num:
+ return [], []
+ distances = self.ffi_main.new("double[]", self.num)
+ flex = self.ffi_main.new("double[]", self.num)
+ self.ffi_lib.winch_flex_calc_arrays(self.ptr, pos[0], pos[1], pos[2],
+ distances, flex)
+ return ([distances[i] for i in range(self.num)],
+ [flex[i] for i in range(self.num)])
+
+
+def _parse_m569_address(raw_value):
+ if raw_value is None:
+ return None
+ text = str(raw_value).strip()
+ if not text:
+ return None
+ parts = text.split('.', 1)
+ can_address = int(parts[0])
+ driver = 0
+ if len(parts) > 1 and parts[1]:
+ driver = int(parts[1])
+ return {'can_address': can_address, 'driver': driver}
+
class WinchKinematics:
def __init__(self, toolhead, config):
+ self.printer = config.get_printer()
+ self.toolhead = toolhead
# Setup steppers at each anchor
self.steppers = []
self.anchors = []
+ self.attachments = []
+ self.m569_driver_descriptors = []
+ pulley_radii, swivel_axes = [], []
for i in range(26):
name = 'stepper_' + chr(ord('a') + i)
if i >= 3 and not config.has_section(name):
@@ -17,24 +204,89 @@ def __init__(self, toolhead, config):
stepper_config = config.getsection(name)
s = stepper.PrinterStepper(stepper_config)
self.steppers.append(s)
- a = tuple([stepper_config.getfloat('anchor_' + n) for n in 'xyz'])
+ self.m569_driver_descriptors.append({
+ 'stepper_name': name,
+ 'motor_address': _parse_m569_address(
+ stepper_config.get('m569_address', None)),
+ })
+ a = tuple(stepper_config.getfloat('anchor_' + n) for n in 'xyz')
self.anchors.append(a)
- s.setup_itersolve('winch_stepper_alloc', *a)
+ self.attachments.append(tuple(
+ stepper_config.getfloat('attachment_' + n, 0.)
+ for n in 'xyz'))
+ # A swivel pulley anchor is where the line enters the pulley
+ radius = stepper_config.getfloat('pulley_radius', 0., minval=0.)
+ axis = tuple(stepper_config.getfloat('swivel_axis_' + n, 0.)
+ for n in 'xyz')
+ if radius > 0. and not any(axis):
+ raise stepper_config.error(
+ "Swivel pulley needs a nonzero swivel_axis")
+ pulley_radii.append(radius)
+ swivel_axes.append(axis)
+ self.flex_helper = WinchFlexHelper(
+ self.anchors, self.attachments, config, pulley_radii, swivel_axes)
+ self.force_move = self.printer.lookup_object('force_move')
+ self.stepper_enable = self.printer.lookup_object('stepper_enable')
+ self.pretension_speed = config.getfloat(
+ 'flex_pretension_speed', 5., minval=0.001)
+ self.pretension_accel = config.getfloat(
+ 'flex_pretension_accel', 0., minval=0.)
+ self.pretension_min_delta = config.getfloat(
+ 'flex_pretension_min_delta', 0.0005, minval=0.)
+ gcode = self.printer.lookup_object('gcode')
+ gcode.register_command(
+ 'M666', self.cmd_M666,
+ desc="Toggle winch flex compensation. Use M666 F0/F1.")
+ flex_ptr = self.flex_helper.get_ptr()
+ if not flex_ptr:
+ raise config.error("Failed to initialise winch flex helper")
+ for idx, s in enumerate(self.steppers):
+ rdist, steps_per_rot = s.get_rotation_distance()
+ self.flex_helper.set_spool_params(idx, rdist, steps_per_rot)
+ s.setup_itersolve('winch_stepper_alloc', flex_ptr, idx)
s.set_trapq(toolhead.get_trapq())
- # Setup boundary checks
+ # Anchor extents for status; workspace checks use the configured mode.
acoords = list(zip(*self.anchors))
self.axes_min = toolhead.Coord([min(a) for a in acoords])
self.axes_max = toolhead.Coord([max(a) for a in acoords])
self.set_position([0., 0., 0.], "")
+ # Halley/LM hybrid parameters for the forward transform (3T only)
+ self._halley_eta = 1e-3
+ self._halley_tol = 1e-3
+ self._halley_max_iters = 30
+ self._halley_hybrid_iters = 3
def get_steppers(self):
return list(self.steppers)
def calc_position(self, stepper_positions):
- # Use only first three steppers to calculate cartesian position
- pos = [stepper_positions[rail.get_name()] for rail in self.steppers[:3]]
- return mathutil.trilateration(self.anchors[:3], [sp*sp for sp in pos])
+ flex_ptr = self.flex_helper.get_ptr()
+ ffi_main, ffi_lib = self.flex_helper.ffi_main, self.flex_helper.ffi_lib
+ if not flex_ptr or ffi_main is None or ffi_lib is None:
+ return [None, None, None]
+ try:
+ motor_pos = [stepper_positions[s.get_name()] for s in self.steppers]
+ except KeyError:
+ return [None, None, None]
+ motor_c = ffi_main.new("double[]", motor_pos)
+ guess = self._last_forward if self._last_forward is not None else [0., 0., 0.]
+ guess_c = ffi_main.new("double[3]", guess)
+ out_pos = ffi_main.new("double[3]")
+ out_cost = ffi_main.new("double[1]")
+ out_iters = ffi_main.new("int[1]")
+ ok = ffi_lib.winch_forward_solve(
+ flex_ptr, motor_c, guess_c,
+ self._halley_eta, self._halley_tol,
+ self._halley_hybrid_iters, self._halley_max_iters,
+ out_pos, out_cost, out_iters)
+ if not ok:
+ return [None, None, None]
+ result = [out_pos[0], out_pos[1], out_pos[2]]
+ self._last_forward = result
+ return result
def set_position(self, newpos, homing_axes):
for s in self.steppers:
s.set_position(newpos)
+ if len(newpos) >= 3:
+ self._last_forward = list(newpos[:3])
def clear_homing_state(self, clear_axes):
# XXX - homing not implemented
pass
@@ -43,8 +295,8 @@ def home(self, homing_state):
homing_state.set_axes([0, 1, 2])
homing_state.set_homed_position([0., 0., 0.])
def check_move(self, move):
- # XXX - boundary checks and speed limits not implemented
- pass
+ if not self.flex_helper.is_reachable(move.end_pos):
+ raise move.move_error("Move outside configured winch workspace")
def get_status(self, eventtime):
# XXX - homed_checks and rail limits not implemented
return {
@@ -53,5 +305,69 @@ def get_status(self, eventtime):
'axis_maximum': self.axes_max,
}
+ def _apply_flex_transition(self, current_pos, previous_motor_positions):
+ moves = []
+ for stepper, previous in zip(self.steppers, previous_motor_positions):
+ target = stepper.calc_position_from_coord(current_pos)
+ delta = target - previous
+ if abs(delta) <= self.pretension_min_delta:
+ continue
+ moves.append((stepper, delta))
+ if not moves:
+ return []
+ stepper_names = [s.get_name() for s, _ in moves]
+ self.stepper_enable.set_motors_enable(stepper_names, True)
+ speed = max(self.pretension_speed, 0.001)
+ accel = self.pretension_accel
+ for stp, delta in moves:
+ self.force_move.manual_move(stp, delta, speed, accel)
+ return [(stp.get_name(), delta) for stp, delta in moves]
+
+ def cmd_M666(self, gcmd):
+ mode = gcmd.get_int('A', None, minval=0, maxval=3)
+ if mode is not None:
+ if mode == 3 and self.flex_helper.num != 8:
+ raise gcmd.error("CubeCorner anchor mode requires exactly 8 anchors")
+ self.toolhead.wait_moves()
+ self.flex_helper.set_anchor_mode(mode)
+ param = gcmd.get_int('F', None)
+ if param is None:
+ state = "enabled" if self.flex_helper.is_active() else "disabled"
+ algo = self.flex_helper.get_algorithm_name()
+ gcmd.respond_info(
+ "Winch flex compensation is %s (algo=%s, anchor_mode=%s)"
+ % (state, algo, self.flex_helper.ANCHOR_MODE_NAMES[self.flex_helper.anchor_mode]))
+ return
+ requested = bool(param)
+ current_state = self.flex_helper.is_active()
+ if requested == current_state:
+ gcmd.respond_info(
+ f"Winch flex compensation already {'enabled' if current_state else 'disabled'}.")
+ return
+ self.toolhead.wait_moves()
+ current_pos = list(self.toolhead.get_position())
+ previous_motor_positions = [s.get_commanded_position() for s in self.steppers]
+ actual = (self.flex_helper.config_valid()
+ and self.flex_helper.set_active(requested))
+ if requested and not actual:
+ gcmd.respond_info(
+ "Unable to enable flex compensation; check winch configuration parameters.")
+ return
+ extra_msg = ""
+ if actual != current_state:
+ try:
+ adjustments = self._apply_flex_transition(current_pos, previous_motor_positions)
+ except Exception as exc:
+ self.flex_helper.set_active(current_state)
+ self.set_position(current_pos, "")
+ raise gcmd.error(f"Failed to apply flex transition: {exc}")
+ self.set_position(current_pos, "")
+ if adjustments:
+ deltas = ", ".join(
+ f"{name}:{delta:+.6f}" for name, delta in adjustments)
+ extra_msg = f" Applied pretension deltas ({deltas})."
+ state = "enabled" if actual else "disabled"
+ gcmd.respond_info(f"Winch flex compensation {state}.{extra_msg}")
+
def load_kinematics(toolhead, config):
return WinchKinematics(toolhead, config)
diff --git a/test/__init__.py b/test/__init__.py
new file mode 100644
index 000000000000..9ffab18f3802
--- /dev/null
+++ b/test/__init__.py
@@ -0,0 +1 @@
+# Enable Python package imports for test modules
diff --git a/test/klippy/__init__.py b/test/klippy/__init__.py
new file mode 100644
index 000000000000..30367eb9d219
--- /dev/null
+++ b/test/klippy/__init__.py
@@ -0,0 +1 @@
+# Package marker for Klippy unit tests
diff --git a/test/klippy/test_serialqueue.py b/test/klippy/test_serialqueue.py
new file mode 100644
index 000000000000..9dcc8a35bc76
--- /dev/null
+++ b/test/klippy/test_serialqueue.py
@@ -0,0 +1,41 @@
+import os
+import sys
+import tempfile
+import unittest
+
+KLIPPY_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__)))), 'klippy')
+if KLIPPY_ROOT not in sys.path:
+ sys.path.insert(0, KLIPPY_ROOT)
+
+import chelper # noqa: E402
+
+ffi, lib = chelper.get_ffi()
+
+
+class BatchOutputTests(unittest.TestCase):
+ def test_exit_writes_messages_scheduled_in_the_future(self):
+ # Batch output (klippy -o) exits as soon as the last step is queued,
+ # long before the clock reaches the queued messages' send times.
+ freq = 1000000.
+ payloads = [bytes([0x20 + i, 0x55, i]) for i in range(40)]
+ with tempfile.TemporaryFile() as out:
+ sq = lib.serialqueue_alloc(out.fileno(), b'f', 0,
+ ffi.new('char[16]', b'batch_test'))
+ lib.serialqueue_set_clock_est(sq, freq, lib.get_monotonic(), 0)
+ cq = lib.serialqueue_alloc_commandqueue()
+ for i, payload in enumerate(payloads):
+ clock = int((i + 1) * 5. * freq) # 5 to 200 seconds ahead
+ lib.serialqueue_send(sq, cq, payload, len(payload),
+ clock, clock, 0)
+ lib.serialqueue_exit(sq)
+ lib.serialqueue_free(sq)
+ lib.serialqueue_free_commandqueue(cq)
+ out.seek(0)
+ data = out.read()
+ for payload in payloads:
+ self.assertIn(payload, data)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/test/klippy/test_winch.py b/test/klippy/test_winch.py
new file mode 100644
index 000000000000..bdc86cd624e3
--- /dev/null
+++ b/test/klippy/test_winch.py
@@ -0,0 +1,537 @@
+import os
+import sys
+import math
+import unittest
+from unittest.mock import Mock
+import configparser
+
+HERE = os.path.abspath(__file__)
+TEST_DIR = os.path.dirname(HERE)
+ROOT = os.path.dirname(TEST_DIR)
+REPO_ROOT = os.path.dirname(ROOT)
+KLIPPY_ROOT = os.path.join(REPO_ROOT, 'klippy')
+if KLIPPY_ROOT not in sys.path:
+ sys.path.insert(0, KLIPPY_ROOT)
+
+import configfile # noqa: E402
+import chelper # noqa: E402
+from stepper import MCU_stepper # noqa: E402
+from kinematics.winch import WinchFlexHelper, WinchKinematics # noqa: E402
+
+
+ffi, lib = chelper.get_ffi()
+
+
+def list_str(values):
+ return ', '.join(f"{v:.6f}" for v in values)
+
+
+def int_list_str(values):
+ return ', '.join(str(int(v)) for v in values)
+
+
+class DummyPrinter:
+ def lookup_object(self, name, default=None):
+ if default is not None:
+ return default
+ raise configfile.error("Unknown object '%s'" % (name,))
+
+
+FOUR_ANCHORS_DEFAULT = (
+ (16.4, -1610.98, -131.53),
+ (1314.22, 1268.14, -121.28),
+ (-1415.73, 707.61, -121.82),
+ (0.0, 0.0, 2299.83),
+)
+
+FOUR_ANCHORS_PROBLEM = (
+ (-1000.0, 1000.0, -121.28),
+ (500.0, -500.0, -131.53),
+ (-1415.73, 707.61, -121.82),
+ (0.0, 0.0, 2299.83),
+)
+
+FIVE_ANCHORS_DEFAULT = (
+ (16.4, -1610.98, -131.53),
+ (1314.22, 128.14, -121.28),
+ (-15.73, 1415.61, -121.82),
+ (-1211.62, 18.14, -111.18),
+ (10.0, -10.0, 2299.83),
+)
+
+
+class WinchFlexHelperTests(unittest.TestCase):
+ def build_helper(self, anchors, mover_weight=2.0, spring=20000.0,
+ target=20.0, min_force=None, max_force=None,
+ guy_wires=None, buildup_factor=0.0,
+ mechanical_advantage=None, lines_per_axis=None,
+ attachments=None, algorithm='qp', ignore_pretension=False, anchor_mode='none',
+ spool_flattening=0.0, strained_spool_storage=False):
+ num = len(anchors)
+ if attachments is None:
+ attachments = [(0.0, 0.0, 0.0)] * num
+ if min_force is None:
+ min_force = [0.0] * num
+ if max_force is None:
+ max_force = [120.0] * num
+ if mechanical_advantage is None:
+ mechanical_advantage = [1] * num
+ cfg = configparser.ConfigParser()
+ options = {
+ 'winch_anchor_mode': anchor_mode,
+ 'winch_mover_weight': f"{mover_weight}",
+ 'winch_spring_constant': f"{spring}",
+ 'winch_target_force': f"{target}",
+ 'winch_min_force': list_str(min_force),
+ 'winch_max_force': list_str(max_force),
+ 'winch_buildup_factor': f"{buildup_factor}",
+ 'winch_mechanical_advantage': int_list_str(mechanical_advantage),
+ 'flex_compensation_algorithm': algorithm,
+ 'ignore_pretension': str(ignore_pretension),
+ 'winch_spool_flattening': f"{spool_flattening}",
+ 'winch_strained_spool_storage': str(strained_spool_storage),
+ }
+ if guy_wires is not None:
+ options['winch_guy_wire_lengths'] = list_str(guy_wires)
+ if lines_per_axis is not None:
+ options['winch_lines_per_axis'] = int_list_str(lines_per_axis)
+ cfg['printer'] = options
+ wrapper = configfile.ConfigWrapper(DummyPrinter(), cfg, {}, 'printer')
+ return WinchFlexHelper(tuple(anchors), tuple(attachments), wrapper)
+
+ def test_tikhonov_without_pretension_still_obeys_physical_force_limits(self):
+ anchors = [(0., -1900., -280.), (1900., 0., -280.),
+ (0., 1900., -280.), (-1900., 0., -280.), (0., 0., 1900.)]
+ for mass in (.081, 10.):
+ helper = self.build_helper(anchors, mover_weight=mass, min_force=[3.]*5,
+ max_force=[5.]*5, algorithm='tikhonov', ignore_pretension=True)
+ helper.set_active(True)
+ distances, flex = helper.calc_arrays((1800., 300., 1800.))
+ forces = [-f*20000./d for f,d in zip(flex, distances)]
+ self.assertTrue(all(-1e-9 <= force <= 5.+1e-9 for force in forces), forces)
+
+ def test_tikhonov_minimum_is_a_soft_target(self):
+ anchors = [(0., -1900., -280.), (1900., 0., -280.),
+ (0., 1900., -280.), (-1900., 0., -280.), (0., 0., 1900.)]
+ helper = self.build_helper(anchors, mover_weight=.081, min_force=[3.]*5,
+ max_force=[170.]*5, algorithm='tikhonov')
+ helper.set_active(True)
+ distances, flex = helper.calc_arrays((0., 0., 0.))
+ forces = [-f*20000./d for f,d in zip(flex, distances)]
+ self.assertGreater(max(3.-f for f in forces), .2)
+ self.assertLess(max(3.-f for f in forces), .3)
+
+ def spool_lengths(self, helper, pos):
+ distances, flex = helper.calc_arrays(pos)
+ lengths = [d + f for d, f in zip(distances, flex)]
+ return lengths, distances, flex
+
+ def expected_motor_to_line_pos(self, motor_pos, rotation_distance,
+ steps_per_rotation, buildup_factor,
+ mechanical_advantage=1):
+ radius = rotation_distance * float(mechanical_advantage) / (2.0 * math.pi)
+ steps_per_mm = steps_per_rotation / rotation_distance
+ k2 = -float(buildup_factor) * float(mechanical_advantage)
+ if abs(k2) <= 1.0e-12 or steps_per_mm <= 0.0:
+ return motor_pos
+ k0 = 2.0 * steps_per_mm * radius / k2
+ motor_steps = motor_pos * steps_per_mm
+ term = motor_steps / k0 + radius
+ return ((term * term) - (radius * radius)) / k2
+
+ def test_hp5_force_balance_and_flex_forward_round_trip(self):
+ anchors = [(0., -1900., -280.), (1900., 0., -280.),
+ (0., 1900., -280.), (-1900., 0., -280.), (0., 0., 1900.)]
+ strands = [2, 2, 2, 2, 4]
+ for ma in ([1]*5, [2, 2, 2, 2, 4]):
+ guy = [429.1]*4 + [352.3]
+ helper = self.build_helper(anchors, mover_weight=.081,
+ mechanical_advantage=ma, lines_per_axis=strands, guy_wires=guy,
+ min_force=[3. if ma[0] == 1 else 10.]*5)
+ helper.set_active(True)
+ steppers = [ffi.gc(lib.winch_stepper_alloc(helper.ptr, i), lib.free) for i in range(5)]
+ for pos in ((0., 0., 0.), (300., -200., 50.), (-400., 350., 400.)):
+ distances, flex = helper.calc_arrays(pos)
+ forces = [-f * 20000. * u*u*n / (d*u+y)
+ for f, d, u, n, y in zip(flex, distances, ma, strands, guy)]
+ residual, _ = self.wrench_residual(anchors, [(0.,0.,0.)]*5,
+ pos, forces, distances, .081*9.81)
+ # This firmware minimizes ridge-regularized force error rather
+ # than enforcing exact equilibrium. Check its KKT conditions.
+ minimum = 3. if ma[0] == 1 else 10.
+ for anchor, distance, force in zip(anchors, distances, forces):
+ gradient = sum((anchor[j]-pos[j])/distance * residual[j] for j in range(3)) + 1e-3*force
+ if force > minimum + 1e-5:
+ self.assertLess(abs(gradient), .003)
+ else:
+ self.assertGreaterEqual(gradient, -.003)
+ self.assertTrue(all(force > 0 for force in forces))
+ motor = ffi.new('double[]', [lib.itersolve_calc_position_from_coord(stp, *pos) for stp in steppers])
+ out, cost, iters = ffi.new('double[3]'), ffi.new('double[1]'), ffi.new('int[1]')
+ ok = lib.winch_forward_solve(helper.ptr, motor, ffi.new('double[3]', [0.,0.,0.]),
+ .001, .001, 3, 30, out, cost, iters)
+ self.assertTrue(ok)
+ for actual, wanted in zip(out, pos):
+ self.assertAlmostEqual(actual, wanted, delta=.01)
+
+ def test_forward_uses_gravity_and_near_planar_range_information(self):
+ for height in (1900., .01, 0.):
+ anchors = [(0.,-1900.,0.), (1900.,0.,0.), (0.,1900.,0.),
+ (-1900.,0.,0.), (0.,0.,height)]
+ helper = self.build_helper(anchors, buildup_factor=0.)
+ steppers = [ffi.gc(lib.winch_stepper_alloc(helper.ptr, i), lib.free) for i in range(5)]
+ pos = (10., 20., 100.)
+ motor = ffi.new('double[]', [lib.itersolve_calc_position_from_coord(stp, *pos) for stp in steppers])
+ out, cost, iters = ffi.new('double[3]'), ffi.new('double[1]'), ffi.new('int[1]')
+ ok = lib.winch_forward_solve(helper.ptr, motor, ffi.new('double[3]', [0.,0.,0.]),
+ .001, .001, 3, 30, out, cost, iters)
+ self.assertTrue(ok)
+ wanted_pos = pos if height else (10.,20.,-100.)
+ for actual, wanted in zip(out, wanted_pos):
+ self.assertAlmostEqual(actual, wanted, delta=.01)
+
+ def test_cube_corner_mode_and_move_checks(self):
+ anchors = [(1000.,-1000.,1900.),(1000.,1000.,1900.),(-1000.,1000.,1900.),(-1000.,-1000.,1900.),
+ (1000.,-1000.,-280.),(1000.,1000.,-280.),(-1000.,1000.,-280.),(-1000.,-1000.,-280.)]
+ with self.assertRaises(configfile.error):
+ self.build_helper(anchors[:4], anchor_mode='cube_corner')
+ helper = self.build_helper(anchors, anchor_mode='cube_corner')
+ kin = WinchKinematics.__new__(WinchKinematics)
+ kin.flex_helper = helper
+ class Move:
+ def __init__(self, position): self.end_pos = position
+ def move_error(self, message): return ValueError(message)
+ for position in ((0.,0.,0.), (1000.,1000.,1900.), (0.,0.,-1500.)):
+ kin.check_move(Move(position))
+ for position in ((1001.,0.,0.), (0.,0.,2000.), (0.,1100.,-1500.)):
+ with self.assertRaises(ValueError): kin.check_move(Move(position))
+ helper.set_anchor_mode(0)
+ kin.check_move(Move((10000.,10000.,10000.)))
+ class Toolhead:
+ def wait_moves(self): pass
+ class Command:
+ def get_int(self, key, default=None, **kwargs): return 3 if key=='A' else default
+ def respond_info(self, message): self.response=message
+ kin.toolhead=Toolhead()
+ command=Command()
+ kin.cmd_M666(command)
+ self.assertEqual(helper.anchor_mode, 3)
+ self.assertIn('cube_corner', command.response)
+ with self.assertRaises(ValueError): helper.set_anchor_mode(4)
+
+ def test_last_top_lower_prism_and_all_top_no_height_limit(self):
+ helper = self.build_helper(FOUR_ANCHORS_DEFAULT, anchor_mode='last_on_top')
+ self.assertTrue(helper.is_reachable((0.,0.,-1000.)))
+ self.assertFalse(helper.is_reachable((0.,0.,3000.)))
+ anchors = [(1000.,-1000.,1900.),(1000.,1000.,1900.),(-1000.,1000.,1900.),(-1000.,-1000.,1900.)]
+ helper = self.build_helper(anchors, anchor_mode='all_on_top')
+ self.assertTrue(helper.is_reachable((0.,0.,3000.)))
+ for pos in ((1100.,0.,0.),(-1100.,0.,0.),(0.,1100.,0.),(0.,-1100.,0.)):
+ self.assertFalse(helper.is_reachable(pos))
+
+ def test_disabled_flex_matches_geometry(self):
+ helper = self.build_helper(FOUR_ANCHORS_DEFAULT,
+ mover_weight=0.0,
+ spring=0.0,
+ target=0.0)
+ self.assertFalse(helper.enabled)
+ ptr = helper.get_ptr()
+ self.assertTrue(ptr)
+ stepper = ffi.gc(lib.winch_stepper_alloc(ptr, 0), lib.free)
+ dist = lib.itersolve_calc_position_from_coord(stepper, 0.0, 0.0, 0.0)
+ expected = 0.0
+ self.assertAlmostEqual(dist, expected, places=6)
+ for pos in ((0.0, 0.0, 0.0), (100.0, -50.0, 10.0), (-200.0, 150.0, 75.0)):
+ lengths, distances, flex = self.spool_lengths(helper, pos)
+ for d, f, l in zip(distances, flex, lengths):
+ self.assertAlmostEqual(f, 0.0, places=9)
+ self.assertAlmostEqual(l, d, places=9)
+
+ def test_parallel_lines_share_flex(self):
+ single = self.build_helper(FOUR_ANCHORS_DEFAULT, mechanical_advantage=[2, 2, 2, 4],
+ min_force=[10.0] * 4)
+ shared = self.build_helper(FOUR_ANCHORS_DEFAULT, mechanical_advantage=[2, 2, 2, 4],
+ min_force=[10.0] * 4,
+ lines_per_axis=[2, 2, 2, 3])
+ single.set_active(True)
+ shared.set_active(True)
+ for pos in ((0.0, 0.0, 0.0), (300.0, -200.0, 50.0)):
+ _, _, flex_single = self.spool_lengths(single, pos)
+ _, _, flex_shared = self.spool_lengths(shared, pos)
+ for f1, fn, n in zip(flex_single, flex_shared, (2, 2, 2, 3)):
+ self.assertNotAlmostEqual(f1, 0.0, places=3)
+ self.assertAlmostEqual(fn, f1 / n, places=9)
+
+ def test_flex_reels_the_elastic_stretch_of_each_line(self):
+ force = 20.0
+ spring = 20000.0
+ mechanical_advantage = (1, 2, 2, 4)
+ lines_per_axis = (1, 2, 2, 3)
+ guy_wires = (100.0, 200.0, 300.0, 400.0)
+ helper = self.build_helper(
+ FOUR_ANCHORS_DEFAULT, spring=spring,
+ min_force=[force] * 4, max_force=[force] * 4,
+ mechanical_advantage=mechanical_advantage,
+ lines_per_axis=lines_per_axis, guy_wires=guy_wires)
+ helper.set_active(True)
+ for pos in ((0.0, 0.0, 0.0), (300.0, -200.0, 50.0)):
+ distances, flex = helper.calc_arrays(pos)
+ for distance, offset, ma, n, guy in zip(
+ distances, flex, mechanical_advantage,
+ lines_per_axis, guy_wires):
+ reeled_line = -offset * ma
+ strain = reeled_line / (distance * ma + guy)
+ self.assertAlmostEqual(strain * spring, force / (ma * n),
+ places=9)
+
+ def test_spool_storage_pays_out_strained_flattened_line(self):
+ force, spring, radius = 20.0, 20000.0, 30.0
+ ma, n, guy = (2, 2, 2, 4), (2, 2, 2, 3), (528.3, 528.3, 528.3, 398.9)
+ kwargs = dict(spring=spring, min_force=[force] * 4, max_force=[force] * 4,
+ mechanical_advantage=ma, lines_per_axis=n, guy_wires=guy)
+ plain = self.build_helper(FOUR_ANCHORS_DEFAULT, **kwargs)
+ stored = self.build_helper(FOUR_ANCHORS_DEFAULT, spool_flattening=.015,
+ strained_spool_storage=True, **kwargs)
+ for helper in (plain, stored):
+ helper.set_active(True)
+ for i, u in enumerate(ma):
+ helper.set_spool_params(i, 2. * math.pi * radius / u, 3200.)
+ for pos in ((0.0, 0.0, 0.0), (300.0, -200.0, 50.0), (-500., 400., 600.)):
+ distances, flex = plain.calc_arrays(pos)
+ _, stored_flex = stored.calc_arrays(pos)
+ for i, (d, f, g) in enumerate(zip(stored_flex, flex, FOUR_ANCHORS_DEFAULT)):
+ tension = force / (ma[i] * n[i])
+ sink = .015 * tension / radius ** 2
+ payout = (1. + tension / spring) / (1. - sink)
+ line = distances[i] - math.sqrt(sum(c * c for c in g)) + f
+ self.assertAlmostEqual(line + d - f, line * payout, places=9)
+ steppers = [ffi.gc(lib.winch_stepper_alloc(stored.ptr, i), lib.free) for i in range(4)]
+ for pos in ((300.0, -200.0, 50.0), (-500., 400., 600.)):
+ motor = ffi.new('double[]', [lib.itersolve_calc_position_from_coord(stp, *pos) for stp in steppers])
+ out, cost, iters = ffi.new('double[3]'), ffi.new('double[1]'), ffi.new('int[1]')
+ self.assertTrue(lib.winch_forward_solve(stored.ptr, motor, ffi.new('double[3]', [0., 0., 0.]),
+ .001, .001, 3, 30, out, cost, iters))
+ for actual, wanted in zip(out, pos):
+ self.assertAlmostEqual(actual, wanted, delta=.01)
+ for options in (dict(buildup_factor=.007, spool_flattening=.015),
+ dict(buildup_factor=.007, strained_spool_storage=True),
+ dict(spool_flattening=float('nan')),
+ dict(spring=0., strained_spool_storage=True),
+ dict(spring=float('inf'), spool_flattening=.015)):
+ with self.assertRaises(configfile.error):
+ self.build_helper(FOUR_ANCHORS_DEFAULT, **options)
+
+ def line_forces(self, helper, pos, spring, guy_wire):
+ distances, flex = helper.calc_arrays(pos)
+ return [-f * spring / (d + guy_wire)
+ for d, f in zip(distances, flex)], distances
+
+ def wrench_residual(self, anchors, attachments, pos, forces, distances,
+ weight):
+ force = [0.0, 0.0, -weight]
+ moment = [0.0, 0.0, 0.0]
+ for anchor, arm, tension, dist in zip(anchors, attachments, forces,
+ distances):
+ pull = [tension * (anchor[i] - pos[i]) / dist for i in range(3)]
+ for i in range(3):
+ force[i] += pull[i]
+ moment[0] += arm[1] * pull[2] - arm[2] * pull[1]
+ moment[1] += arm[2] * pull[0] - arm[0] * pull[2]
+ moment[2] += arm[0] * pull[1] - arm[1] * pull[0]
+ return force, moment
+
+ def test_attachments_balance_moments_on_the_mover(self):
+ # Eight lines from the corners of a 400 mm cube
+ corners = [(x, y, z) for z in (200.0, -200.0)
+ for x, y in ((200.0, -200.0), (200.0, 200.0),
+ (-200.0, 200.0), (-200.0, -200.0))]
+ anchors = [(1284.9 * x / 200.0, 1284.9 * y / 200.0,
+ 1900.0 if z > 0.0 else -280.0) for x, y, z in corners]
+ mass, spring, guy_wire = 0.216, 20000.0, 117.2
+ weight = mass * 9.81
+ options = dict(mover_weight=mass, spring=spring,
+ min_force=[3.0] * 8, max_force=[170.0] * 8,
+ guy_wires=[guy_wire] * 8)
+ point = self.build_helper(anchors, **options)
+ rigid = self.build_helper(anchors, attachments=corners, **options)
+ for helper in (point, rigid):
+ helper.set_active(True)
+ previous = None
+ for step in range(61):
+ pos = (10.0 * step, 6.0 * step, 0.0)
+ forces, distances = self.line_forces(rigid, pos, spring, guy_wire)
+ force, moment = self.wrench_residual(
+ anchors, corners, pos, forces, distances, weight)
+ for value in force:
+ self.assertAlmostEqual(value, 0.0, delta=0.05)
+ for value in moment:
+ # N*mm
+ self.assertAlmostEqual(value, 0.0, delta=20.0)
+ for tension in forces:
+ self.assertGreaterEqual(tension, 3.0 - 1e-6)
+ if previous is not None:
+ for now, before in zip(forces, previous):
+ self.assertLess(abs(now - before), 2.0)
+ previous = forces
+ # The point model leaves a moment for the lines to resolve by
+ # tilting the mover.
+ pos = (500.0, 300.0, 0.0)
+ forces, distances = self.line_forces(point, pos, spring, guy_wire)
+ _, moment = self.wrench_residual(
+ anchors, corners, pos, forces, distances, weight)
+ self.assertGreater(max(abs(value) for value in moment), 200.0)
+
+ def test_four_anchor_small_perturbation(self):
+ helper = self.build_helper(FOUR_ANCHORS_DEFAULT)
+ origin_lengths, _, _ = self.spool_lengths(helper, (0.0, 0.0, 0.0))
+
+ def rel(lengths):
+ return [l - o for l, o in zip(lengths, origin_lengths)]
+
+ left = rel(self.spool_lengths(helper, (16.3, 0.0, 0.0))[0])
+ nominal = rel(self.spool_lengths(helper, (16.4, 0.0, 0.0))[0])
+ right = rel(self.spool_lengths(helper, (16.5, 0.0, 0.0))[0])
+
+ for i in range(4):
+ self.assertLess(abs(left[i] - nominal[i]), 0.2)
+ self.assertLess(abs(right[i] - nominal[i]), 0.2)
+ self.assertLess(abs(left[i] - right[i]), 0.2)
+ for i in range(3):
+ self.assertGreaterEqual(abs(left[i] - nominal[i]), 0.0)
+ self.assertGreaterEqual(abs(right[i] - nominal[i]), 0.0)
+ self.assertGreaterEqual(abs(left[i] - right[i]), 0.0)
+
+ def test_buildup_model_matches_closed_form_with_gearing(self):
+ buildup = 0.6366197723675814
+ rotation_distance = 246.20
+ steps_per_rotation = 3200.0 * 12.75
+ helper = self.build_helper(((0.0, 0.0, 0.0),),
+ mover_weight=0.0,
+ spring=0.0,
+ target=0.0,
+ buildup_factor=buildup,
+ mechanical_advantage=[1])
+ helper.set_spool_params(0, rotation_distance, steps_per_rotation)
+ motor_pos = 18.5
+ actual = helper.motor_to_line_pos(0, motor_pos)
+ expected = self.expected_motor_to_line_pos(
+ motor_pos, rotation_distance, steps_per_rotation, buildup, 1)
+ self.assertAlmostEqual(actual, expected, places=12)
+
+ def test_buildup_model_scales_with_mechanical_advantage(self):
+ buildup = 0.6366197723675814
+ rotation_distance = 123.10
+ steps_per_rotation = 3200.0 * 12.75
+ helper = self.build_helper(((0.0, 0.0, 0.0),),
+ mover_weight=0.0,
+ spring=0.0,
+ target=0.0,
+ buildup_factor=buildup,
+ mechanical_advantage=[2])
+ helper.set_spool_params(0, rotation_distance, steps_per_rotation)
+ motor_pos = 18.5
+ actual = helper.motor_to_line_pos(0, motor_pos)
+ expected = self.expected_motor_to_line_pos(
+ motor_pos, rotation_distance, steps_per_rotation, buildup, 2)
+ self.assertAlmostEqual(actual, expected, places=12)
+
+ def test_small_buildup_preserves_submillimetre_motor_motion(self):
+ helper = self.build_helper(((0., 0., 0.),), mover_weight=0.,
+ target=0., spring=0., buildup_factor=1e-10)
+ helper.set_spool_params(0, 250., 3200.)
+ for motor in (-0.001, 0.001):
+ self.assertAlmostEqual(helper.motor_to_line_pos(0, motor), motor,
+ delta=1e-14)
+
+ def test_m666_round_trip_on_a_changing_radius_drum(self):
+ radius, rotation_steps, buildup = 40., 3200, .6
+ step_mm = 2 * math.pi * radius / rotation_steps
+ pose = (400., -300., 200.)
+ force, ea = 40., 20000.
+ kin = WinchKinematics.__new__(WinchKinematics)
+ kin.flex_helper = self.build_helper(
+ FOUR_ANCHORS_DEFAULT, spring=ea, buildup_factor=buildup,
+ guy_wires=[200.] * 4, min_force=[force] * 4, max_force=[force] * 4)
+ kin.toolhead, kin.stepper_enable, kin.force_move = Mock(), Mock(), Mock()
+ kin.toolhead.get_position.return_value = pose
+ kin.pretension_speed, kin.pretension_accel = 3., 1.
+ kin.pretension_min_delta = .0005
+ kin.steppers = []
+ for i in range(4):
+ kin.flex_helper.set_spool_params(i, 2 * math.pi * radius, rotation_steps)
+ st = MCU_stepper.__new__(MCU_stepper)
+ st._name = 'stepper_' + chr(ord('a') + i)
+ st._step_dist, st._mcu_position_offset = step_mm, 0.
+ st._stepper_kinematics = ffi.gc(lib.winch_stepper_alloc(kin.flex_helper.ptr, i), lib.free)
+ kin.steppers.append(st)
+ kin.set_position(pose, '')
+ initial = [s.get_commanded_position() for s in kin.steppers]
+ physical = initial.copy()
+
+ def motor_mm(payout):
+ return 2 * radius * payout / (radius + math.sqrt(radius**2 - buildup * payout))
+
+ for mode in (1, 0):
+ before = [s.get_commanded_position() for s in kin.steppers]
+ gcmd = Mock()
+ gcmd.get_int.side_effect = lambda key, *args, **kwargs: mode if key == 'F' else None
+ kin.force_move.manual_move.reset_mock()
+ kin.cmd_M666(gcmd)
+ calls = kin.force_move.manual_move.call_args_list
+ self.assertEqual(len(calls), 4)
+ for i, (st, anchor, call) in enumerate(zip(kin.steppers, FOUR_ANCHORS_DEFAULT, calls)):
+ routed = math.dist(pose, anchor)
+ payout = routed - math.dist((0., 0., 0.), anchor)
+ extension = force * (routed + 200.) / ea
+ target = motor_mm(payout - mode * extension)
+ driver, delta, speed, accel = call.args
+ self.assertIs(driver, st)
+ self.assertAlmostEqual(delta, target - before[i], places=8)
+ self.assertAlmostEqual(st.get_commanded_position(), target, places=8)
+ physical[i] += round(delta / step_mm) * step_mm
+ self.assertAlmostEqual(physical[i], target, delta=step_mm / 2)
+ for actual, start in zip(physical, initial):
+ self.assertAlmostEqual(actual, start, delta=step_mm)
+
+ def test_four_anchor_near_singularity(self):
+ helper = self.build_helper(FOUR_ANCHORS_PROBLEM)
+ origin_lengths, _, _ = self.spool_lengths(helper, (0.0, 0.0, 0.0))
+
+ def rel(lengths):
+ return [l - o for l, o in zip(lengths, origin_lengths)]
+
+ left = rel(self.spool_lengths(helper, (-0.1, 0.0, 0.0))[0])
+ nominal = [0.0] * len(origin_lengths)
+ right = rel(self.spool_lengths(helper, (0.1, 0.0, 0.0))[0])
+
+ for i in range(4):
+ self.assertLess(abs(left[i] - nominal[i]), 10.0)
+ self.assertLess(abs(right[i] - nominal[i]), 10.0)
+ self.assertLess(abs(left[i] - right[i]), 10.0)
+ for i in range(3):
+ self.assertGreater(abs(left[i] - nominal[i]), 0.0001)
+ self.assertGreater(abs(right[i] - nominal[i]), 0.0001)
+ self.assertGreater(abs(left[i] - right[i]), 0.0001)
+
+ def test_five_anchor_mass_zero(self):
+ helper = self.build_helper(FIVE_ANCHORS_DEFAULT,
+ mover_weight=0.0,
+ spring=0.0,
+ target=0.0)
+ self.assertFalse(helper.enabled)
+ for pos in ((0.0, 0.0, 0.0), (100.0, -50.0, 10.0)):
+ lengths, distances, flex = self.spool_lengths(helper, pos)
+ for d, f, l in zip(distances, flex, lengths):
+ self.assertAlmostEqual(f, 0.0, places=9)
+ self.assertAlmostEqual(l, d, places=9)
+
+ def test_five_anchor_origin(self):
+ helper = self.build_helper(FIVE_ANCHORS_DEFAULT)
+ lengths, distances, flex = self.spool_lengths(helper, (0.0, 0.0, 0.0))
+ for d, f, l in zip(distances, flex, lengths):
+ self.assertAlmostEqual(f, 0.0, places=9)
+ self.assertAlmostEqual(l, d, places=9)
+
+
+if __name__ == '__main__':
+ unittest.main()