First commit

This commit is contained in:
sandst_a committed 2026-10-23 08:51:30 +02:00
commit 1166eb808c
20 files changed
+1340

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
build/
.venv/
__pycache__/
*.pyc
+43
View File
@@ -0,0 +1,43 @@
CXX ?= c++
CXXFLAGS ?= -O2 -std=c++17 -Wall -Wextra -pedantic
ECMC_ROOT ?= ../ecmc
ECMCCFG_ROOT ?= ../ecmccfg
PYTHON ?= python3
UNAME := $(shell uname -s)
ifeq ($(UNAME),Darwin)
SHARED := -dynamiclib
EXT := dylib
else
SHARED := -shared
EXT := so
endif
.PHONY: all test logic pvs clean
all: build/libhexapod.$(EXT) build/test_kinematics
build:
mkdir -p build
build/libhexapod.$(EXT): src/c_api.cpp src/kinematics.hpp | build
$(CXX) $(CXXFLAGS) -fPIC $(SHARED) -o $@ src/c_api.cpp
build/test_kinematics: tests/test_kinematics.cpp src/kinematics.hpp | build
$(CXX) $(CXXFLAGS) -Isrc -o $@ tests/test_kinematics.cpp
test: all
./build/test_kinematics
$(PYTHON) python/viewer.py --self-test
logic: build/libhexapod_logic.$(EXT) pvs
build/libhexapod_logic.$(EXT): src/logic.cpp src/kinematics.hpp | build
$(CXX) $(CXXFLAGS) -fPIC $(SHARED) -I$(ECMC_ROOT)/devEcmcSup/logic -o $@ src/logic.cpp
pvs:
$(PYTHON) $(ECMCCFG_ROOT)/examples/PSI/plugins/cpp_logic/utils/ecmcCppLogicSourceSubstGen.py --source src/logic.cpp --logic-name hexapod --output cfg/libhexapod_logic.so_cpp_logic.subs
clean:
rm -rf build
.PHONY: test-logic
test-logic: build/test_logic
./build/test_logic
build/test_logic: tests/test_logic.cpp src/logic.cpp src/kinematics.hpp | build
$(CXX) $(CXXFLAGS) -I$(ECMC_ROOT)/devEcmcSup/logic -o $@ tests/test_logic.cpp
.PHONY: bench
bench: build/kinematics_bench
./build/kinematics_bench
build/kinematics_bench: bench/kinematics_bench.cpp src/kinematics.hpp | build
$(CXX) $(CXXFLAGS) -Isrc -o $@ bench/kinematics_bench.cpp
+491
View File
@@ -0,0 +1,491 @@
# ecmc hexapod — first simulation prototype
Twelve axes, with inverse **and** forward kinematics implemented in C++:
| Axes | Meaning | Trajectory source | Encoder source |
|---|---|---|---|
| 1–6 | X, Y, Z, Rx, Ry, Rz | Internal ecmc trajectories | External, from forward kinematics |
| 7–12 | Six leg strokes relative to home | External, from inverse kinematics | External, ideal simulated legs |
The two axis ranges are configurable through `COORD_FIRST` and `LEG_FIRST`.
`cfg/axis_coordinate.yaml` defines the coordinate axes and `cfg/axis_leg.yaml`
defines the simulated legs. `cfg/axes.cmd` loads each shared template six times
using `loadYamlAxis.cmd` with `AX_ID`, `AX_NAME` and `AX_UNIT` macros, following
the PSI examples. IDs and names are assigned in `cfg/axes.cmd`; units are mm
except Rx/Ry/Rz, which use deg. `AX_UNIT` defaults to mm. No motor hardware is linked.
## Quick start: offline 3D view
```sh
cd /Users/sandst_a/sources/ecmc_hexapod
make test
python3 -m venv .venv
.venv/bin/pip install -r python/requirements.txt
.venv/bin/python python/viewer.py
```
Set the six sliders and click **Move (3 seconds)**. The orange outline shows
commanded pose; the blue platform is reconstructed by forward kinematics from
simulated leg feedback. Offline movement uses one quintic interpolation parameter
for all six coordinates, with zero endpoint velocity and acceleration. Retargeting
mid-move starts a new profile and does not preserve velocity continuity.
The offline leg model has simple first-order lag per display frame, not calibrated
dynamics. Rotate the view with the mouse.
Both Python and the IOC adapter use `src/kinematics.hpp`; Python calls the compiled
C interface, so there is no second implementation of the kinematic equations.
The command-line tests need only C++17 and Python, not matplotlib or EPICS.
```sh
make test
make test-logic ECMC_ROOT=../ecmc
# Headless visualization check:
.venv/bin/python python/viewer.py --snapshot build/preview.png
```
## Defining the geometry
The current model represents two flat plates with three pairs of joints on each
plate. It is parameterized by radii, pair angles and nominal height. Geometry is
measured between **joint pivot centres**, not plate edges, actuator housings or
mounting bolt positions.
Use a right-handed base frame: origin at the centre of the base joint circle,
base joints in the XY plane, +Z toward the platform. The platform frame has its
origin at the centre of its joint circle and its own joints in its local XY plane.
At home, the frames have parallel axes and the platform centre is at `(0,0,H)`.
The 60-degree offset between joint patterns is built into the attachment layout;
it is not a 60-degree home yaw.
### Parameters and where to set them
`cfg/geometry.json` is the viewer's seven-element array, in this exact order:
```json
[200, 120, 250, 10, 10, 180, 400]
```
| Index | C++ parameter | IOC load macro | Meaning | Default |
|---|---|---|---|---|
| 0 | `baseRadius` | `BASE_RADIUS` | Base centre to base joint centre | 200 mm |
| 1 | `platformRadius` | `PLATFORM_RADIUS` | Platform centre to platform joint centre | 120 mm |
| 2 | `height` | `HEIGHT` | Separation of joint planes at home | 250 mm |
| 3 | `baseHalfAngle` | `BASE_HALF_ANGLE` | Half the angular separation of a base pair | 10 deg |
| 4 | `platformHalfAngle` | `PLATFORM_HALF_ANGLE` | Half the angular separation of a platform pair | 10 deg |
| 5 | `minLength` | `MIN_LENGTH` | Minimum total joint-centre-to-joint-centre leg length | 180 mm |
| 6 | `maxLength` | `MAX_LENGTH` | Maximum total joint-centre-to-joint-centre leg length | 400 mm |
The last two values are **total lengths**, not axis displacement limits or actuator
stroke. A joint assembly contributes to this total even if it does not telescope.
All six legs currently share these limits.
For a measured distance `d` between the centres of two joints in a pair on a
circle of radius `r`, the half-angle is `asin(d/(2*r))`, converted to degrees.
It is half the included angle, not the full angle or half the chord length.
Set the IOC geometry in the `MACROS` argument of the existing C++ load line in
`cfg/load.cmd`, for example:
```text
${SCRIPTEXEC} ${ecmccfg_DIR}loadCppLogic.cmd, "DIR=./build/,FILE=libhexapod_logic.so,ASYN_PORT=HEX,REPORT=1,MACROS='COORD_FIRST=1,LEG_FIRST=7,SIMULATION=1,BASE_RADIUS=200,PLATFORM_RADIUS=120,HEIGHT=250,BASE_HALF_ANGLE=10,PLATFORM_HALF_ANGLE=10,MIN_LENGTH=180,MAX_LENGTH=400'"
```
Keep this macro configuration and `cfg/geometry.json` identical. The IOC does not
read the JSON, and the viewer does not fetch geometry from the IOC. Restart the
viewer and reload/restart the IOC after geometry changes. The axis YAML files
configure the axes; they do not define the mechanical geometry.
### Attachment numbering and leg connections
For zero-based leg index `i`, let `sector = 120 * floor(i/2)` degrees, base
half-angle `a` and platform half-angle `b`. Attachment angles are:
```text
even i odd i
base angle sector - a sector + a
platform angle sector - 60 + b sector + 60 - b
```
Using the default half-angles gives this explicit wiring table:
| Leg | ecmc leg axis | Base angle | Platform-local angle |
|---|---|---|---|
| 1 | 7 | -10 deg | -50 deg |
| 2 | 8 | 10 deg | 50 deg |
| 3 | 9 | 110 deg | 70 deg |
| 4 | 10 | 130 deg | 170 deg |
| 5 | 11 | 230 deg | 190 deg |
| 6 | 12 | 250 deg | 290 deg |
Angles increase counterclockwise when viewed from +Z toward the base. Leg i joins
base point i to platform point i; preserve that association. Each base pair fans
out to two neighbouring platform pairs. Upper close pairs are legs (2,3), (4,5),
and (6,1), not (1,2), (3,4), (5,6). This is what avoids the original crossed-pair
layout. Do not independently sort or swap the upper attachment points.
For base angle `beta_i` and platform angle `gamma_i`:
```text
b_i = [Rb*cos(beta_i), Rb*sin(beta_i), 0] # base frame
p_i = [Rp*cos(gamma_i), Rp*sin(gamma_i), 0] # platform frame
```
Trigonometric functions use radians internally. `Model::base` and `Model::top`
in `src/kinematics.hpp` contain these six point pairs.
### Choosing and checking a geometry
1. Measure both radii and pair spacings at the pivot centres; calculate the half-angles.
2. Choose a home height that leaves useful actuator travel in both directions.
3. Enter actual minimum/maximum assembled leg lengths, including joints.
4. Verify all-zero pose gives the expected six total lengths and zero leg-axis strokes.
5. Exercise the intended poses and paths in the viewer, checking stroke, joint
articulation and clearance. Endpoint feasibility alone does not validate a path.
The default symmetric home length is approximately **283.0721935 mm** for every
leg. With the example 180–400 mm total-length limits, each leg's home-relative
stroke range is approximately -103.0722 to +116.9278 mm. These are derived
individual leg bounds, not a rectangular Cartesian workspace.
The parameter validation checks finite positive radii/height, half-angles between
0 and 60 degrees and ordered positive length limits. It does not establish that
the mechanism is well-conditioned. For example, a sum of half-angles equal to
60 degrees aligns each leg's base/platform azimuth at home and loses first-order
yaw sensitivity. Avoid degenerate layouts and check conditioning over the intended
workspace before using hardware.
Arbitrary measured XYZ attachment coordinates, unequal joint heights, per-leg
length limits and calibrated encoder zero offsets are **not currently loadable**
through JSON or macros. The mathematical equations below support arbitrary
`b_i` and `p_i`, but using them requires extending the shared geometry loader and
IOC/viewer configuration together. Do not approximate a substantially asymmetric
mechanism by changing radii alone.
## Kinematics mathematics
### Pose and rotation convention
The six coordinate axes represent
```text
q = [X, Y, Z, Rx, Ry, Rz]
t = [X, Y, H + Z]
```
Translations are in mm, exported angles in degrees. Z=0 is the nominal home
height, not the base plane. A positive Z raises the platform. Define
`alpha = Rx*pi/180`, `beta = Ry*pi/180`, `gamma = Rz*pi/180` and use active,
right-handed rotations acting on column vectors:
```text
Rx(alpha) = [ 1 0 0 ]
[ 0 cos(alpha) -sin(alpha)]
[ 0 sin(alpha) cos(alpha)]
Ry(beta) = [ cos(beta) 0 sin(beta)]
[ 0 1 0 ]
[-sin(beta) 0 cos(beta)]
Rz(gamma) = [cos(gamma) -sin(gamma) 0]
[sin(gamma) cos(gamma) 0]
[ 0 0 1]
R = Rz(gamma) * Ry(beta) * Rx(alpha)
```
Thus Rx acts first on a local attachment vector, then Ry, then Rz. Changing the
order changes the resulting orientation. The platform rotates about its frame
origin; translation then puts that origin at `t`.
### Inverse kinematics: pose to six leg strokes
Transform each upper attachment into the base frame, subtract its lower
attachment and take the Euclidean length:
```text
u_i(q) = t + R*p_i # upper joint in base coordinates
v_i(q) = u_i(q) - b_i # leg vector
L_i(q) = sqrt(v_ix^2 + v_iy^2 + v_iz^2)
```
This is a direct calculation, with no iterative solve. The six axis commands are
strokes measured from the individual nominal home lengths:
```text
L0_i = L_i([0,0,0,0,0,0])
s_i_command = L_i(q_command) - L0_i
```
At the all-zero pose all six stroke commands are zero. For this symmetric
geometry, with `delta = (60-a-b)*pi/180`, home lengths can also be checked
independently using the cosine rule:
```text
L0 = sqrt(H^2 + Rb^2 + Rp^2 - 2*Rb*Rp*cos(delta))
```
The adapter checks every commanded total length against `minLength` and
`maxLength` before publishing leg setpoints. A valid length does not by itself
prove joint-angle or collision feasibility.
### Forward kinematics: six measured strokes to pose
First convert the six encoder strokes back into measured total lengths:
```text
L_i_measured = s_i_encoder + L0_i
```
We need a pose satisfying all six equations `L_i(q) = L_i_measured` at once.
The implementation minimizes the sum of squared residuals:
```text
r_i(q) = L_i_measured - L_i(q)
C(q) = sum_i r_i(q)^2
```
It starts from the previous valid pose (home at startup). To give angular and
linear steps comparable magnitudes, define the diagonal scale matrix:
```text
D = diag(1, 1, 1, 1/(Rp*pi/180), 1/(Rp*pi/180), 1/(Rp*pi/180))
q_trial = q + D*delta_u
```
A unit angular component of `delta_u` corresponds approximately to 1 mm of
platform-edge movement. The solver estimates the Jacobian with central differences
using `h = 0.001` in these scaled coordinates:
```text
J_ij ≈ [L_i(q + h*D*e_j) - L_i(q - h*D*e_j)] / (2*h)
```
Here `e_j` is a unit vector along coordinate j. Each iteration solves the damped
normal equations for a six-component correction:
```text
(J^T*J + lambda*I)*delta_u = J^T*r
```
The code uses Gaussian elimination with partial pivoting, rather than explicitly
inverting a matrix. It limits the largest scaled step component to 20, evaluates
the trial pose and accepts it only when `C` decreases. Damping starts at `1e-5`;
it is multiplied by 0.3 after an accepted step or by 10 after a rejected step,
within bounds 1e-12 to 1e12.
Convergence means `max(abs(r_i)) < 1e-7 mm`. At most 30 correction attempts are
made; the final residual is also checked after the last attempt. A rejected step
still consumes an iteration. This tolerance is a numerical residual threshold,
not a claim of achievable mechanical accuracy. Near a singularity, a small length
residual can correspond to a large pose uncertainty.
On success, the six recovered coordinates feed the coordinate axes' external
encoders. On failure, the current adapter latches fault 2 and retains the last
valid feedback. It does not silently use the requested pose as measured feedback.
FK is a **local** solve: multiple assembly configurations can have the same six
lengths. The seed selects the nearby branch, not necessarily the intended physical
branch after a large jump or unknown startup position. The Euler representation
also becomes singular near Ry=±90 degrees; this is separate from mechanical
singularities. There is no Jacobian-conditioning, joint-angle or collision monitor
in the current prototype.
## ecmc integration
Build on the Linux IOC host against headers matching that IOC's ecmc build:
```sh
make logic ECMC_ROOT=../ecmc ECMCCFG_ROOT=../ecmccfg
make test-logic ECMC_ROOT=../ecmc
```
This produces `build/libhexapod_logic.so` and the generated EPICS substitutions.
On macOS the build produces `.dylib` files for development tests; these cannot be
loaded in a Linux IOC.
From an existing ecmccfg IOC startup, with this project as its working directory,
include the following **after ecmccfg initialization and before runtime startup**:
```text
${SCRIPTEXEC} ./cfg/load.cmd
```
The include instantiates twelve axes from the two YAML templates through
`cfg/axes.cmd`, then loads
the C++ logic and custom status PVs. It is an integration fragment, not a complete site-specific IOC launcher.
Each YAML file explicitly sets `epics.motorRecord.enable: false` and
`axis.autoEnable.atStartup: false`, preserving the previous simulation setup.
The YAML loader also creates the standard axis diagnostic/control PVs using the
names X, Y, Z, Rx, Ry, Rz and L1–L6 (mm for translations/legs, deg for rotations).
The include does not configure a motor controller port or enable axes. Use the
existing IOC's normal axis/motor-record setup for commanding axes 1–6. Do not command leg axes 7–12 independently while the transform is active.
Axis IDs 1–12 must be free. No axis PLC may overwrite these external setpoints or
encoder feeds.
In the inspected ecmc source, axes execute before C++ logic. The adapter reads
coordinate trajectory positions and leg encoder positions from that cycle, then
writes values consumed by the next axis cycle. This introduces pipeline latency;
coordinate feedback also includes the inverse/plant/forward round trip.
The ideal leg plant copies the computed stroke to the external leg encoder.
The forward solver reads the **axis encoder values**, not the commanded pose, and
writes its resulting six coordinates to the external coordinate encoders.
A disabled virtual leg does not model a stopped physical actuator: the ideal plant
is just a mathematical simulation, independent of drive-enable state.
The adapter does not yet provide a coordinated six-coordinate move command.
Internal coordinate trajectories can be used for individual-axis experiments.
For a specified Cartesian path, a later common-time trajectory generator must
feed all six coordinate axes; independent point-to-point moves are not equivalent.
The quintic profile in the offline viewer is not an IOC trajectory generator.
## EPICS viewer
For a running IOC, install the IOC viewer requirements and use the IOC record
prefix, including the trailing colon:
```sh
.venv/bin/pip install -r python/requirements-ioc.txt
.venv/bin/python python/viewer.py --prefix HEX:
```
Use the prefix configured by `loadCppLogic.cmd` (`DB_PREFIX`, default `${IOC}:`).
Pyepics needs an EPICS Channel Access library (`libca`) and network access to the
IOC. If CA discovery does not reach the IOC subnet, configure
`EPICS_CA_ADDR_LIST` / `EPICS_CA_AUTO_ADDR_LIST` for your network before starting.
IOC mode is read-only, with the offline motion controls disabled. It subscribes
to these six PVs through pyepics monitors:
| PV suffix | Display use |
|---|---|
| `hex-pose-set` | Orange commanded platform and coordinate setpoints |
| `hex-pose-actual` | Blue actual platform using the IOC's forward-kinematic result |
| `hex-leg-set` | Six leg stroke setpoints |
| `hex-leg-actual` | Six leg stroke readbacks |
| `hex-fault` | IOC fault status |
| `hex-fk-residual` | IOC forward-solver residual in mm |
Both coordinate and leg values are shown as setpoint/readback pairs. Pose order
is X, Y, Z, Rx, Ry, Rz (mm/degrees). Leg arrays are strokes relative to individual
home lengths, in mm. The IOC computes the actual pose; live mode does not replace
it with a separate Python FK solution or simulate leg feedback. C++ geometry is
still used to draw the attachment positions, so the geometry JSON must match the
IOC configuration.
CA callbacks update a thread-safe cache. Display refreshes never issue blocking
PV reads. Missing connections, invalid values and pending initial samples are
reported; the last drawing is retained with red status until valid data returns.
Unchanging monitored values remain valid: this is not an IOC heartbeat monitor.
The separate records are not an atomic snapshot of one real-time cycle.
Without `--prefix`, the standalone offline demo remains available. `--snapshot`
is for offline rendering only. The monitor-cache tests run without pyepics or an
IOC: `python3 tests/test_epics_source.py`.
## Fault handling and current boundary
`hex-fault` is latched: 0 OK; 1 invalid pose or commanded stroke outside limits;
2 forward solution failed; 3 host write failed; 4 one of twelve axes reports error.
On fault the adapter stops publishing new output values and retains the last
accepted outputs. Fix the cause and restart/reload the simulation. This is not a
controlled group stop: coordinate trajectories can continue, and a failed host
write can leave some channels updated. Motor operation needs a separate coherent
stop/interlock implementation and physical calibration.
The current adapter explicitly requires `SIMULATION=1`. Replacing leg axes with
physical axes requires removing the ideal encoder feed, selecting real encoder
sources, adding enable/group-stop logic and validating trajectory limits,
calibration, branch handling and timing. The kinematic core can be reused unchanged.
Velocity/acceleration limits in joint space are not implemented by the transform.
## Can IK and FK run at 1 kHz?
**Yes, the measured computational cost makes 1 kHz plausible for this C++
implementation.** A 1 kHz cycle is 1,000 microseconds, shared with all other ecmc,
EtherCAT, motion and user-logic work. The actual real-time IOC must still be
measured under its intended load; a standalone benchmark is not a deadline proof.
IK is a fixed-size calculation for six lengths. FK is more expensive because it
iterates. Previous-pose seeding usually keeps consecutive tracking solves close
to the solution. The solver uses fixed-size stack arrays, no heap allocation,
no I/O and a fixed iteration cap. Those properties suit a cyclic task, although
bounded iteration count alone does not establish worst-case execution time.
### Reproducible numerical-core benchmark
Run on the target IOC CPU, with the same optimization flags as the logic module:
```sh
make bench
# To rebuild explicitly with selected compiler flags:
make -B bench CXXFLAGS='-O2 -std=c++17 -Wall -Wextra -pedantic'
```
`bench/kinematics_bench.cpp` measures **one IK plus one FK** per sample. Each case
has 1,000 warm-up calls and 20,000 measured calls. Input poses are sampled along
a smooth near-home trajectory with a 1 ms parameter increment; the benchmark
executes as fast as possible, without sleeping or scheduling actual 1 ms periods.
It consumes results to prevent removal of unused calculations and includes the
per-sample clock overhead. Allocation and sorting of statistics occur outside the
timed section.
Local results on 2026-10-22, macOS/Darwin arm64, Apple Clang 21.0.0, `-O2`:
| IK + FK case | Mean | Median | p99 | Observed maximum | FK iterations | Failed solves |
|---|---:|---:|---:|---:|---|---:|
| Tracking, previous pose seed | 1.406 us | 1.416 us | 1.500 us | 17.959 us | 2 | 0 / 20,000 |
| Same trajectory, fresh home seed each time | 1.936 us | 1.917 us | 2.042 us | 48.833 us | 3 | 0 / 20,000 |
| Impossible length input, full iteration cap | 21.132 us | 21.000 us | 25.333 us | 106.959 us | 30 | 20,000 / 20,000 |
The last case deliberately replaces leg 1's total length with 1,000 mm. It tests
the nonconvergent path; it is not an acceptable working pose. All calls reached
the iteration cap in this run. The benchmark repeatedly invokes the solver;
the real adapter would latch a fault on its first failed solve.
These measurements exclude host-service calls, axis execution, binding copies,
EPICS publication, EtherCAT and the rest of the IOC. They were taken on the
development Mac, without real-time scheduling or CPU isolation; the exact CPU
model was not recorded. The observed maximum is a finite-sample result, **not**
a certified upper bound, and cannot be transferred directly to a different CPU.
At the measured mean, normal tracking used about 0.14% of a 1 ms period and the
30-iteration case about 2.1%; the largest observed duration used about 10.7%.
### Validating on the IOC
1. Run the core benchmark on the actual IOC host, then measure the complete C++
callback and the complete ecmc cycle at 1 kHz with the intended twelve axes.
2. Exercise startup, normal tracking, maximum intended velocity, boundary poses,
noisy encoder input and deliberately failing FK. Count overruns and record
iteration counts and high-percentile/maximum durations over a sustained run.
3. Include the real EtherCAT and other PLC/C++ logic load. Leave margin for the
remaining cycle work and scheduling variation; do not budget the whole 1 ms
for kinematics. Keep file I/O, printing and visualization outside the RT path.
4. Keep FK iteration count bounded and define a coherent group response to
nonconvergence before commissioning physical motion. The current latched-output
simulation fault handling is not yet that hardware response.
The current finite-difference Jacobian evaluates all six lengths twice per
coordinate (12 evaluations), in addition to the current and trial pose. A full
30-attempt solve can therefore perform 421 six-length evaluations, including the
last residual check. If target measurements require more margin, an analytic
Jacobian and computing rotation/trigonometry once per pose are natural optimization
steps. Changing iteration limits or tolerances needs convergence testing over the
actual workspace; the current 1e-7 mm tolerance is much tighter than many encoder
measurement resolutions.
The Python viewer is independent of the 1 kHz loop and refreshes at approximately
20 Hz. EPICS monitor publication can be decimated separately. Neither GUI refresh
nor Channel Access delivery needs to run at 1 kHz for the kinematics to do so.
## Verification
- 1,000 deterministic random pose → IK → FK round trips near home.
- 1,000 samples of a continuous trajectory using the previous FK result as seed.
- Independent analytic home-length and rotation-convention checks.
- Invalid geometry, non-finite input, negative length, iteration-limit and stroke checks.
- C++ adapter tests with mocked ecmc host services: IK to leg axes, FK to coordinate
encoders, and latched geometry/FK/axis/host faults.
- Python/C ABI round trip and headless 3D rendering.
A live IOC and real-time execution timing have **not** been tested yet.
+43
View File
@@ -0,0 +1,43 @@
#include "kinematics.hpp"
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace hexapod;
using Clock = std::chrono::steady_clock;
volatile double sink = 0;
int main() {
Model m;
constexpr int samples=20000, warmup=1000;
for(int mode=0;mode<3;++mode) {
Six seed{};
std::vector<double> times; times.reserve(samples);
int failures=0,maxIterations=0; double iterationSum=0;
for(int n=-warmup;n<samples;++n) {
const double t=(n+warmup)*.001;
Six q{10*std::sin(t),8*std::cos(t),5*std::sin(t),3*std::sin(t),2*std::cos(t),4*std::sin(t)};
const auto begin=Clock::now();
const auto command=m.inverse(q); // One IK plus one FK per timed call.
auto measured=command;
if(mode==2) measured[0]=1000; // Impossible: exercise nonconvergent path.
const auto result=forward(m,measured,mode==0 ? seed : Six{});
const auto end=Clock::now();
sink=command[0]+result.pose[0]+result.residual;
if(mode==0 && result.converged) seed=result.pose;
if(n>=0) {
times.push_back(std::chrono::duration<double,std::micro>(end-begin).count());
failures+=!result.converged;
maxIterations=std::max(maxIterations,result.iterations);
iterationSum+=result.iterations;
}
}
std::sort(times.begin(),times.end());
double sum=0; for(double t:times) sum+=t;
std::cout<<std::fixed<<std::setprecision(3)
<<(mode==0 ? "tracking" : mode==1 ? "home seed" : "nonconvergent")
<<": mean_us="<<sum/samples<<" median_us="<<times[samples/2]
<<" p99_us="<<times[samples*99/100]<<" max_us="<<times.back()
<<" mean_iterations="<<iterationSum/samples<<" max_iterations="<<maxIterations
<<" failures="<<failures<<"/"<<samples<<"\n";
}
}
+14
View File
@@ -0,0 +1,14 @@
# Twelve virtual axes from two shared YAML templates.
# Coordinate axes use internal trajectories; legs use external IK setpoints.
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_coordinate.yaml,AX_ID=1,AX_NAME=X,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_coordinate.yaml,AX_ID=2,AX_NAME=Y,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_coordinate.yaml,AX_ID=3,AX_NAME=Z,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_coordinate.yaml,AX_ID=4,AX_NAME=Rx,AX_UNIT=deg"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_coordinate.yaml,AX_ID=5,AX_NAME=Ry,AX_UNIT=deg"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_coordinate.yaml,AX_ID=6,AX_NAME=Rz,AX_UNIT=deg"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_leg.yaml,AX_ID=7,AX_NAME=L1,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_leg.yaml,AX_ID=8,AX_NAME=L2,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_leg.yaml,AX_ID=9,AX_NAME=L3,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_leg.yaml,AX_ID=10,AX_NAME=L4,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_leg.yaml,AX_ID=11,AX_NAME=L5,AX_UNIT=mm"
${SCRIPTEXEC} ${ecmccfg_DIR}loadYamlAxis.cmd, "FILE=./cfg/axis_leg.yaml,AX_ID=12,AX_NAME=L6,AX_UNIT=mm"
+51
View File
@@ -0,0 +1,51 @@
# Macros: AX_ID, AX_NAME, AX_UNIT (default mm).
# Coordinate axis: external encoder from forward kinematics.
axis:
id: ${AX_ID}
type: virtual
autoEnable:
atStartup: false
epics:
name: ${AX_NAME}
precision: 4
unit: ${AX_UNIT=mm}
motorRecord:
enable: false
description: "Hexapod ${AX_NAME}"
encoder:
type: 0
source: 1
numerator: 1
denominator: 1
bits: 32
position: ec0.s-1.ONE
trajectory:
source: 0
axis:
velocity: 5
acceleration: 10
deceleration: 10
input:
limit:
forward: ec0.s-1.ONE.0
backward: ec0.s-1.ONE.0
home: ec0.s-1.ZERO.0
softlimits:
enable: false
monitoring:
lag:
enable: false
tolerance: 0.1
time: 100
velocity:
enable: false
max: 0
time:
trajectory: 100
drive: 100
+52
View File
@@ -0,0 +1,52 @@
# Macros: AX_ID, AX_NAME, AX_UNIT (default mm).
# Simulated leg: external trajectory from IK and ideal encoder feedback.
# Leg positions are strokes relative to nominal home lengths.
axis:
id: ${AX_ID}
type: virtual
autoEnable:
atStartup: false
epics:
name: ${AX_NAME}
precision: 4
unit: ${AX_UNIT=mm}
motorRecord:
enable: false
description: "Hexapod ${AX_NAME}"
encoder:
type: 0
source: 1
numerator: 1
denominator: 1
bits: 32
position: ec0.s-1.ONE
trajectory:
source: 1
axis:
velocity: 5
acceleration: 10
deceleration: 10
input:
limit:
forward: ec0.s-1.ONE.0
backward: ec0.s-1.ONE.0
home: ec0.s-1.ZERO.0
softlimits:
enable: false
monitoring:
lag:
enable: false
tolerance: 0.1
time: 100
velocity:
enable: false
max: 0
time:
trajectory: 100
drive: 100
+1
View File
@@ -0,0 +1 @@
[200, 120, 250, 10, 10, 180, 400]
+22
View File
@@ -0,0 +1,22 @@
# Auto-generated C++ logic substitutions
# Logic: hexapod
file ecmcCppLogicWaveformIn.template {
pattern { REC, PARAM, DESC, NELM, FTVL, DTYP }
{ "hex-pose-set", "hex.pose_set", "hex.pose_set", "6", "DOUBLE", "asynFloat64ArrayIn" }
{ "hex-pose-actual", "hex.pose_actual", "hex.pose_actual", "6", "DOUBLE", "asynFloat64ArrayIn" }
{ "hex-leg-set", "hex.leg_set", "hex.leg_set", "6", "DOUBLE", "asynFloat64ArrayIn" }
{ "hex-leg-actual", "hex.leg_actual", "hex.leg_actual", "6", "DOUBLE", "asynFloat64ArrayIn" }
}
file ecmcCppLogicLongIn.template {
pattern { REC, PARAM, DESC }
{ "hex-fault", "hex.fault", "hex.fault" }
{ "hex-fk-iterations", "hex.fk_iterations", "hex.fk_iterations" }
{ "hex-simulation", "hex.simulation", "hex.simulation" }
}
file ecmcCppLogicAi.template {
pattern { REC, PARAM, DESC, PREC }
{ "hex-fk-residual", "hex.fk_residual", "hex.fk_residual", "3" }
}
+6
View File
@@ -0,0 +1,6 @@
# Include from the hexapod project working directory after ecmccfg initialization,
# before IOC/runtime startup. Requires a Linux build of `make logic`.
# cfg/axes.cmd loads the two shared axis YAML templates via loadYamlAxis.cmd.
# Axis IDs 1..12 must be free. No physical EtherCAT hardware is linked.
${SCRIPTEXEC} ./cfg/axes.cmd
${SCRIPTEXEC} ${ecmccfg_DIR}loadCppLogic.cmd, "DIR=./build/,FILE=libhexapod_logic.so,ASYN_PORT=HEX,REPORT=1,MACROS='COORD_FIRST=1,LEG_FIRST=7,SIMULATION=1'"
+78
View File
@@ -0,0 +1,78 @@
"""Read-only CA monitor cache; GUI reads never issue blocking network requests."""
import math
from threading import Lock
class IocSource:
SUFFIXES = {
'pose_set': 'hex-pose-set',
'pose_actual': 'hex-pose-actual',
'leg_set': 'hex-leg-set',
'leg_actual': 'hex-leg-actual',
'fault': 'hex-fault',
'residual': 'hex-fk-residual',
}
ARRAYS = {'pose_set', 'pose_actual', 'leg_set', 'leg_actual'}
def __init__(self, prefix, pv_factory=None):
if pv_factory is None:
from epics import PV
pv_factory = PV
self._lock = Lock()
self._values = {}
self._connected = {}
self._errors = {}
self.pvs = {}
for key, suffix in self.SUFFIXES.items():
self.pvs[key] = pv_factory(
prefix + suffix, auto_monitor=True,
callback=lambda value=None, _key=key, **kw: self._update(_key, value),
connection_callback=lambda conn=False, _key=key, **kw: self._connection(_key, conn))
def _connection(self, key, connected):
with self._lock:
self._connected[key] = connected
if not connected:
self._values.pop(key, None)
self._errors.pop(key, None)
def _update(self, key, value):
try:
if key in self.ARRAYS:
value = tuple(float(v) for v in value)
if len(value) != 6 or not all(math.isfinite(v) for v in value):
raise ValueError('expected six finite values')
else:
value = float(value)
if not math.isfinite(value):
raise ValueError('expected finite scalar')
if key == 'fault':
if not value.is_integer():
raise ValueError('expected integer fault code')
value = int(value)
except (TypeError, ValueError, OverflowError) as exc:
with self._lock:
self._values.pop(key, None)
self._errors[key] = str(exc)
return
with self._lock:
self._values[key] = value
self._errors.pop(key, None)
def snapshot(self):
# Consistent local cache copy; separate CA records are not a single IOC cycle.
with self._lock:
missing = [self.SUFFIXES[k] for k in self.SUFFIXES if not self._connected.get(k)]
if missing:
raise RuntimeError('EPICS disconnected:\n' + '\n'.join(missing))
if self._errors:
key = next(iter(self._errors))
raise RuntimeError(f'{self.SUFFIXES[key]}:\n{self._errors[key]}')
pending = [self.SUFFIXES[k] for k in self.SUFFIXES if k not in self._values]
if pending:
raise RuntimeError('Waiting for PV data:\n' + '\n'.join(pending))
return dict(self._values)
def close(self):
for pv in self.pvs.values():
pv.disconnect()
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pyepics>=3.5
+3
View File
@@ -0,0 +1,3 @@
matplotlib>=3.7
# Optional for --prefix:
# pyepics>=3.5
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""Offline hexapod demo or read-only EPICS view; both use the C++ model."""
import argparse
import ctypes as ct
import json
import math
from pathlib import Path
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_GEOMETRY = [200, 120, 250, 10, 10, 180, 400]
class Model:
def __init__(self, geometry=DEFAULT_GEOMETRY):
if len(geometry) != 7 or not all(math.isfinite(x) for x in geometry):
raise ValueError('Geometry must contain seven finite numbers')
candidates = [ROOT / 'build' / ('libhexapod.' + ext) for ext in ('so', 'dylib')]
path = next((p for p in candidates if p.exists()), None)
if path is None:
raise RuntimeError('Build the C++ library first: make')
self.lib = ct.CDLL(str(path))
pointer = ct.POINTER(ct.c_double)
self.lib.hex_inverse.argtypes = [pointer] * 4
self.lib.hex_inverse.restype = ct.c_int
self.lib.hex_forward.argtypes = [pointer] * 5
self.lib.hex_forward.restype = ct.c_int
self.geometry = (ct.c_double * 7)(*geometry)
self.home = self.inverse([0] * 6)[0]
@staticmethod
def six(values):
if len(values) != 6 or not all(math.isfinite(x) for x in values):
raise ValueError('Expected six finite values')
return (ct.c_double * 6)(*values)
def inverse(self, pose):
lengths, points = (ct.c_double * 6)(), (ct.c_double * 36)()
status = self.lib.hex_inverse(self.geometry, self.six(pose), lengths, points)
if status < 0:
raise ValueError('Invalid geometry or pose')
pts = [list(points[i:i+3]) for i in range(0, 36, 3)]
return list(lengths), pts[:6], pts[6:], status == 0
def forward(self, lengths, seed):
pose, residual = (ct.c_double * 6)(), ct.c_double()
status = self.lib.hex_forward(self.geometry, self.six(lengths), self.six(seed), pose, ct.byref(residual))
return list(pose), residual.value, status == 0
def self_test(model):
pose = [5, -8, 12, 3, -4, 6]
lengths, _, _, valid = model.inverse(pose)
actual, residual, converged = model.forward(lengths, [0]*6)
if not valid or not converged or max(abs(a-b) for a, b in zip(actual, pose)) > 1e-5:
raise RuntimeError('C API roundtrip failed')
print(f'PASS: Python/C++ IK/FK roundtrip, residual={residual:.3g} mm')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prefix', help='Read-only EPICS mode, e.g. HEX: (requires pyepics)')
parser.add_argument('--geometry', type=Path, default=ROOT/'cfg'/'geometry.json')
parser.add_argument('--self-test', action='store_true')
parser.add_argument('--snapshot', type=Path, help='Render one offline frame to PNG')
args = parser.parse_args()
if args.prefix and args.snapshot:
parser.error('--snapshot is offline only; omit --prefix')
model = Model(json.loads(args.geometry.read_text()))
if args.self_test:
self_test(model)
return
import matplotlib
if args.snapshot:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Slider, Button
pvs = None
if args.prefix:
from epics_source import IocSource
pvs = IocSource(args.prefix)
fig = plt.figure(figsize=(11, 8))
ax = fig.add_axes([0.04, 0.31, .72, .66], projection='3d')
status = fig.text(.75, .78, '', family='monospace', fontsize=9, va='top')
fig.suptitle('ecmc hexapod — 6 coordinate axes + 6 leg axes')
sliders = []
for i, label in enumerate(('X [mm]', 'Y [mm]', 'Z [mm]', 'Rx [deg]', 'Ry [deg]', 'Rz [deg]')):
slider_ax = fig.add_axes([.15, .245-i*.035, .5, .02])
limit = 30 if i < 3 else 10
sliders.append(Slider(slider_ax, label, -limit, limit, valinit=0))
if pvs:
sliders[-1].set_active(False)
state = dict(pose=[0.]*6, seed=[0.]*6, start=[0.]*6, target=[0.]*6,
started=time.monotonic(), legs=list(model.home))
def move(_):
state.update(start=list(state['pose']), target=[s.val for s in sliders], started=time.monotonic())
button = Button(fig.add_axes([.73, .13, .2, .05]), 'Move (3 seconds)')
button.on_clicked(move)
if pvs:
button.set_active(False)
button.label.set_text('IOC monitor (read-only)')
if args.snapshot:
state['pose'] = [8, -5, 12, 4, -3, 5]
state['start'] = list(state['pose'])
state['target'] = list(state['pose'])
for slider, value in zip(sliders, state['pose']):
slider.set_val(value)
def update(_):
try:
fault = 0
if pvs:
live = pvs.snapshot()
fault = live['fault']
state['pose'] = list(live['pose_set'])
state['seed'] = list(live['pose_actual'])
state['legs'] = [h+s for h,s in zip(model.home, live['leg_actual'])]
leg_set = live['leg_set']
leg_actual = live['leg_actual']
residual = live['residual']
ok = fault == 0
for slider, value in zip(sliders, state['pose']):
slider.set_val(value)
else:
t = min(1., (time.monotonic()-state['started'])/3.)
s = t*t*t*(10+t*(-15+6*t))
state['pose'] = [a+s*(b-a) for a,b in zip(state['start'],state['target'])]
requested, _, _, allowed = model.inverse(state['pose'])
if allowed:
# Visual demo's simple first-order leg response; not an ecmc plant model.
state['legs'] = [a+.2*(b-a) for a,b in zip(state['legs'], requested)]
lengths, base, requested, allowed = model.inverse(state['pose'])
if not pvs:
recovered, residual, ok = model.forward(state['legs'], state['seed'])
if ok:
state['seed'] = recovered
leg_set = [l-h for l,h in zip(lengths, model.home)]
leg_actual = [l-h for l,h in zip(state['legs'], model.home)]
_, _, actual, _ = model.inverse(state['seed'])
ax.clear()
def outline(points, color, style):
order = sorted(range(6), key=lambda i: math.atan2(points[i][1], points[i][0]))
ring = [points[i] for i in order] + [points[order[0]]]
ax.plot(*zip(*ring), color=color, linestyle=style)
outline(base, '0.3', '-')
outline(requested, 'tab:orange', '--')
outline(actual, 'tab:blue', '-')
for i in range(6):
ax.plot(*zip(base[i], requested[i]), color='tab:orange', linestyle='--', alpha=.6)
ax.plot(*zip(base[i], actual[i]), color='tab:blue', linewidth=2)
ax.text(*base[i], str(i+1))
radius = model.geometry[0]*1.3
ax.set(xlim=(-radius,radius), ylim=(-radius,radius), zlim=(0,model.geometry[2]*1.7),
xlabel='X [mm]', ylabel='Y [mm]', zlabel='Z base frame [mm]')
ax.set_box_aspect((2*radius,2*radius,model.geometry[2]*1.7))
message = ('IOC / EPICS read-only' if pvs else 'Offline demo')
message += '\nBlue: actual pose\nOrange: setpoint pose\n'
message += f'\nStroke: {"OK" if allowed else "OUTSIDE"}\nFK residual: {residual:.2g} mm\nIOC fault: {fault}\n'
message += '\nLeg stroke [mm]\n Set Actual\n'
message += '\n'.join(f'L{i+1} {a:8.3f} {b:8.3f}' for i,(a,b) in enumerate(zip(leg_set,leg_actual)))
message += '\n\nPose [mm / deg]\n Set Actual\n'
message += '\n'.join(f'{n:2} {a:8.3f} {b:8.3f}' for n,a,b in zip(('X','Y','Z','Rx','Ry','Rz'),state['pose'],state['seed']))
if not ok and not pvs:
message += '\nFK FAILED: last valid pose'
status.set_text(message)
status.set_color('black' if allowed and ok and not fault else 'red')
except (RuntimeError, ValueError, TypeError) as exc:
status.set_text(str(exc)); status.set_color('red')
return ()
if args.snapshot:
state['legs'] = model.inverse(state['pose'])[0]
update(0)
fig.savefig(args.snapshot, dpi=140)
else:
animation = FuncAnimation(fig, update, interval=50, cache_frame_data=False)
try:
plt.show()
finally:
if pvs:
pvs.close()
if __name__ == '__main__':
main()
+22
View File
@@ -0,0 +1,22 @@
#include "kinematics.hpp"
// Stateless C API shared by Python and tests. Geometry: Rb,Rp,H,base half-angle,
// platform half-angle,min length,max length. All pointers must have indicated size.
static hexapod::Model model(const double* g) {
return hexapod::Model({g[0],g[1],g[2],g[3],g[4],g[5],g[6]});
}
extern "C" {
int hex_inverse(const double* g,const double* pose,double* lengths,double* points) {
auto m=model(g); hexapod::Six q{}; std::copy(pose,pose+6,q.begin());
if(!m.g.valid() || !hexapod::finite(q)) return -1;
auto l=m.inverse(q); std::copy(l.begin(),l.end(),lengths);
for(int i=0;i<6;++i) { auto p=m.world(i,q); for(int j=0;j<3;++j) { points[i*3+j]=m.base[i][j]; points[18+i*3+j]=p[j]; } }
return m.withinStroke(l) ? 0 : 1;
}
int hex_forward(const double* g,const double* lengths,const double* seed,double* pose,double* residual) {
auto m=model(g); hexapod::Six l{},s{};
std::copy(lengths,lengths+6,l.begin()); std::copy(seed,seed+6,s.begin());
auto result=hexapod::forward(m,l,s);
std::copy(result.pose.begin(),result.pose.end(),pose); *residual=result.residual;
return result.converged ? 0 : 1;
}
}
+120
View File
@@ -0,0 +1,120 @@
#pragma once
#include <array>
#include <algorithm>
#include <cmath>
#include <limits>
namespace hexapod {
using Six = std::array<double, 6>;
using Vec = std::array<double, 3>;
constexpr double rad = 3.14159265358979323846 / 180.0;
// Pose: mm, mm, mm relative to home height, degrees Rx/Ry/Rz.
// Active rotation Rz(Rz)*Ry(Ry)*Rx(Rx), fixed base frame.
struct Geometry {
double baseRadius = 200, platformRadius = 120, height = 250;
double baseHalfAngle = 10, platformHalfAngle = 10;
double minLength = 180, maxLength = 400;
bool valid() const {
return std::isfinite(baseRadius) && baseRadius > 0 &&
std::isfinite(platformRadius) && platformRadius > 0 &&
std::isfinite(height) && height > 0 &&
std::isfinite(baseHalfAngle) && baseHalfAngle > 0 && baseHalfAngle < 60 &&
std::isfinite(platformHalfAngle) && platformHalfAngle > 0 && platformHalfAngle < 60 &&
std::isfinite(minLength) && std::isfinite(maxLength) && minLength > 0 && maxLength > minLength;
}
};
inline bool finite(const Six& q) { for (double v:q) if (!std::isfinite(v)) return false; return true; }
inline Vec rotate(Vec p, const Six& q) {
const double a=q[3]*rad,b=q[4]*rad,c=q[5]*rad;
Vec x{p[0],std::cos(a)*p[1]-std::sin(a)*p[2],std::sin(a)*p[1]+std::cos(a)*p[2]};
Vec y{std::cos(b)*x[0]+std::sin(b)*x[2],x[1],-std::sin(b)*x[0]+std::cos(b)*x[2]};
return {std::cos(c)*y[0]-std::sin(c)*y[1],std::sin(c)*y[0]+std::cos(c)*y[1],y[2]};
}
struct Model {
Geometry g;
std::array<Vec,6> base{}, top{};
explicit Model(Geometry geometry = {}) : g(geometry) {
// Each base pair fans out to the two neighbouring platform pairs.
// Platform pairs are shifted 60 degrees; preserve cyclic leg order.
// Each leg keeps its array index on both plates. Do not sort these points.
for(int i=0;i<6;++i) {
double sector=(i/2)*120.0;
double a=(sector+(i%2 ? g.baseHalfAngle : -g.baseHalfAngle))*rad;
double b=(sector+(i%2 ? 60-g.platformHalfAngle : -60+g.platformHalfAngle))*rad;
base[i]={g.baseRadius*std::cos(a),g.baseRadius*std::sin(a),0};
top[i]={g.platformRadius*std::cos(b),g.platformRadius*std::sin(b),0};
}
}
Vec world(int i,const Six& q) const {
Vec v=rotate(top[i],q);
for(int j=0;j<3;++j) v[j]+=q[j];
v[2]+=g.height; return v;
}
Six inverse(const Six& q) const {
Six out{};
for(int i=0;i<6;++i) {
Vec p=world(i,q); double d=0;
for(int j=0;j<3;++j) d+=(p[j]-base[i][j])*(p[j]-base[i][j]);
out[i]=std::sqrt(d);
}
return out;
}
bool withinStroke(const Six& l) const {
if(!finite(l)) return false;
for(double v:l) if(v<g.minLength || v>g.maxLength) return false;
return true;
}
};
struct ForwardResult { Six pose{}; double residual=std::numeric_limits<double>::infinity(); int iterations=0; bool converged=false; };
inline bool solve(double a[6][6],double b[6],Six& x) {
for(int k=0;k<6;++k) {
int p=k; for(int i=k+1;i<6;++i) if(std::abs(a[i][k])>std::abs(a[p][k])) p=i;
if(std::abs(a[p][k])<1e-14) return false;
for(int j=k;j<6;++j) std::swap(a[k][j],a[p][j]); std::swap(b[k],b[p]);
for(int i=k+1;i<6;++i) {
double f=a[i][k]/a[k][k];
for(int j=k;j<6;++j) a[i][j]-=f*a[k][j]; b[i]-=f*b[k];
}
}
for(int i=5;i>=0;--i) { double v=b[i]; for(int j=i+1;j<6;++j) v-=a[i][j]*x[j]; x[i]=v/a[i][i]; }
return finite(x);
}
// Bounded damped Gauss-Newton. Local solution only: seed selects assembly branch.
// Scaling angular unknowns to an equivalent platform-edge displacement improves conditioning.
inline ForwardResult forward(const Model& m,const Six& lengths,const Six& seed,int maxIterations=30,double tolerance=1e-7) {
ForwardResult out; out.pose=seed;
if(!m.g.valid() || !finite(seed) || !finite(lengths)) return out;
for(double l:lengths) if(l<=0) return out;
double scale[6]={1,1,1,1/(m.g.platformRadius*rad),1/(m.g.platformRadius*rad),1/(m.g.platformRadius*rad)};
double lambda=1e-5;
for(int n=0;n<=maxIterations;++n) {
Six predicted=m.inverse(out.pose),res{}; double cost=0; out.residual=0; out.iterations=n;
for(int i=0;i<6;++i) { res[i]=lengths[i]-predicted[i]; cost+=res[i]*res[i]; out.residual=std::max(out.residual,std::abs(res[i])); }
if(!finite(predicted)) return out;
if(out.residual<tolerance) { out.converged=true; return out; }
if(n==maxIterations) break;
double jac[6][6]{};
for(int j=0;j<6;++j) {
Six plus=out.pose,minus=out.pose; const double h=1e-3;
plus[j]+=h*scale[j]; minus[j]-=h*scale[j];
Six lp=m.inverse(plus),lm=m.inverse(minus);
for(int i=0;i<6;++i) jac[i][j]=(lp[i]-lm[i])/(2*h);
}
double a[6][6]{},b[6]{};
for(int j=0;j<6;++j) {
for(int i=0;i<6;++i) b[j]+=jac[i][j]*res[i];
for(int k=0;k<6;++k) for(int i=0;i<6;++i) a[j][k]+=jac[i][j]*jac[i][k];
a[j][j]+=lambda;
}
Six step{}; if(!solve(a,b,step)) return out;
double largest=0; for(double v:step) largest=std::max(largest,std::abs(v));
double factor=largest>20 ? 20/largest : 1;
Six trial=out.pose; for(int j=0;j<6;++j) trial[j]+=factor*step[j]*scale[j];
Six lp=m.inverse(trial); double trialCost=0;
for(int i=0;i<6;++i) trialCost+=(lengths[i]-lp[i])*(lengths[i]-lp[i]);
if(std::isfinite(trialCost) && trialCost<cost) { out.pose=trial; lambda=std::max(1e-12,lambda*0.3); }
else lambda=std::min(1e12,lambda*10);
}
return out;
}
} // namespace hexapod
+76
View File
@@ -0,0 +1,76 @@
#include "ecmcCppLogic.hpp"
#include "kinematics.hpp"
#include <stdexcept>
struct HexapodLogic : ecmcCpp::LogicBase {
hexapod::Model model;
std::array<double, 6> pose_set{};
std::array<double, 6> pose_actual{};
std::array<double, 6> leg_set{};
std::array<double, 6> leg_actual{};
std::array<double, 6> geometry_home{};
// 1 invalid/stroke, 2 FK, 3 host write, 4 axis error
int32_t fault{0};
int32_t fk_iterations{0};
double fk_residual{0};
int32_t simulation{1};
int coordFirst=1, legFirst=7;
HexapodLogic() {
const auto macros=ecmcCpp::getMacrosString();
coordFirst=ecmcCpp::getMacroValueInt(macros,"COORD_FIRST",1);
legFirst=ecmcCpp::getMacroValueInt(macros,"LEG_FIRST",7);
simulation=ecmcCpp::getMacroValueInt(macros,"SIMULATION",1);
// This initial adapter deliberately supports simulated legs only.
if(simulation!=1) throw std::runtime_error("Physical leg adapter not commissioned; SIMULATION must be 1");
if(coordFirst<1 || legFirst<1 || std::abs(coordFirst-legFirst)<6)
throw std::runtime_error("Axis ranges must be positive and non-overlapping");
hexapod::Geometry g;
g.baseRadius=ecmcCpp::getMacroValueDouble(macros,"BASE_RADIUS",g.baseRadius);
g.platformRadius=ecmcCpp::getMacroValueDouble(macros,"PLATFORM_RADIUS",g.platformRadius);
g.height=ecmcCpp::getMacroValueDouble(macros,"HEIGHT",g.height);
g.baseHalfAngle=ecmcCpp::getMacroValueDouble(macros,"BASE_HALF_ANGLE",g.baseHalfAngle);
g.platformHalfAngle=ecmcCpp::getMacroValueDouble(macros,"PLATFORM_HALF_ANGLE",g.platformHalfAngle);
g.minLength=ecmcCpp::getMacroValueDouble(macros,"MIN_LENGTH",g.minLength);
g.maxLength=ecmcCpp::getMacroValueDouble(macros,"MAX_LENGTH",g.maxLength);
if(!g.valid()) throw std::runtime_error("Invalid hexapod geometry");
model=hexapod::Model(g); geometry_home=model.inverse({});
if(!model.withinStroke(geometry_home)) throw std::runtime_error("Home is outside leg stroke");
for(int i=0;i<6;++i) {
ecmc.input("ax"+std::to_string(coordFirst+i)+".traj.setpos",pose_set[i]);
ecmc.input("ax"+std::to_string(legFirst+i)+".enc.actpos",leg_actual[i]);
}
epics.readOnlyArray("hex.pose_set",pose_set)
.readOnlyArray("hex.pose_actual",pose_actual)
.readOnlyArray("hex.leg_set",leg_set)
.readOnlyArray("hex.leg_actual",leg_actual)
.readOnly("hex.fault",fault)
.readOnly("hex.fk_iterations",fk_iterations)
.readOnly("hex.fk_residual",fk_residual)
.readOnly("hex.simulation",simulation);
}
void run() override {
if(fault) return; // latched; reload/restart simulation after fixing cause
for(int i=0;i<6;++i) if(ecmcCpp::axisHasError(coordFirst+i) || ecmcCpp::axisHasError(legFirst+i)) { fault=4; return; }
if(!hexapod::finite(pose_set)) { fault=1; return; }
auto lengths=model.inverse(pose_set);
if(!model.withinStroke(lengths)) { fault=1; return; }
// Leg axis zero = its individual length at nominal home (not total length).
hexapod::Six actualLengths{};
for(int i=0;i<6;++i) actualLengths[i]=leg_actual[i]+geometry_home[i];
auto fk=hexapod::forward(model,actualLengths,pose_actual);
fk_iterations=fk.iterations; fk_residual=fk.residual;
if(!fk.converged) { fault=2; return; }
pose_actual=fk.pose;
for(int i=0;i<6;++i) leg_set[i]=lengths[i]-geometry_home[i];
for(int i=0;i<6;++i) {
// Unit-gain plant: publish previous command as next encoder sample.
// Sources are configured before enabling axes in cfg/axes.cmd.
int rc=ecmcCpp::axisSetExternalSetpointPos(legFirst+i,leg_set[i]);
rc|=ecmcCpp::axisSetExternalEncoderPos(legFirst+i,leg_set[i]);
rc|=ecmcCpp::axisSetExternalEncoderPos(coordFirst+i,pose_actual[i]);
if(rc) { fault=3; return; }
}
}
};
ECMC_CPP_LOGIC_REGISTER_DEFAULT(HexapodLogic)
+50
View File
@@ -0,0 +1,50 @@
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'python'))
from epics_source import IocSource
class FakePV:
def __init__(self, name, auto_monitor, callback, connection_callback):
self.name, self.callback, self.connection = name, callback, connection_callback
assert auto_monitor
def send(self, value): self.callback(value=value)
def connect(self): self.connection(conn=True)
def disconnect(self): self.connection(conn=False)
class SourceTest(unittest.TestCase):
def setUp(self):
self.source = IocSource('HEX:', FakePV)
def ready(self):
for key, pv in self.source.pvs.items():
pv.connect()
pv.send([1, 2, 3, 4, 5, 6] if key in IocSource.ARRAYS else 0)
def test_mapping_and_updates(self):
self.ready()
self.assertEqual(self.source.pvs['pose_actual'].name, 'HEX:hex-pose-actual')
self.assertEqual(self.source.pvs['leg_set'].name, 'HEX:hex-leg-set')
old = self.source.snapshot()
self.source.pvs['pose_actual'].send([6]*6)
self.assertEqual(self.source.snapshot()['pose_actual'], (6,)*6)
self.assertEqual(old['pose_actual'], (1,2,3,4,5,6))
def test_disconnect_and_reconnect_waits_for_data(self):
self.ready()
pv = self.source.pvs['leg_actual']
pv.disconnect()
with self.assertRaisesRegex(RuntimeError, 'disconnected'): self.source.snapshot()
pv.connect()
with self.assertRaisesRegex(RuntimeError, 'Waiting'): self.source.snapshot()
pv.send([0]*6)
self.assertEqual(self.source.snapshot()['leg_actual'], (0,)*6)
def test_bad_array_and_recovery(self):
self.ready()
for bad in ([1]*5, [float('nan')]*6, None):
self.source.pvs['pose_set'].send(bad)
with self.assertRaisesRegex(RuntimeError, 'hex-pose-set'): self.source.snapshot()
self.source.pvs['pose_set'].send([0]*6)
self.source.pvs['fault'].send(2)
self.assertEqual(self.source.snapshot()['fault'], 2)
if __name__ == '__main__': unittest.main()
+50
View File
@@ -0,0 +1,50 @@
#include "kinematics.hpp"
#include <iostream>
#include <random>
#include <stdexcept>
using namespace hexapod;
void check(bool value,const char* message) { if(!value) throw std::runtime_error(message); }
int main() {
Model m; Six home{}; auto lengths=m.inverse(home);
check(m.withinStroke(lengths),"home stroke");
for(int i=0;i<6;++i) {
double delta=40*rad;
double expected=std::sqrt(250*250+200*200+120*120-2*200*120*std::cos(delta));
check(std::abs(lengths[i]-expected)<1e-10,"analytic home length");
}
// Attachment order around the platform must match the base order; a
// reversal within a pair reproduces the original crossed-leg regression.
double winding=0;
for(int i=0;i<6;++i) {
const auto& a=m.top[i]; const auto& b=m.top[(i+1)%6];
double turn=std::atan2(a[0]*b[1]-a[1]*b[0],a[0]*b[0]+a[1]*b[1]);
check(turn>0,"platform attachment order must not reverse");
winding+=turn;
check(std::abs(lengths[i]-lengths[0])<1e-10,"symmetric home lengths");
}
check(std::abs(winding-360*rad)<1e-10,"platform winding");
auto p=rotate({1,0,0},{0,0,0,0,0,90}); check(std::abs(p[0])<1e-12 && std::abs(p[1]-1)<1e-12,"rotation convention");
std::mt19937 rng(1234); std::uniform_real_distribution<double> u(-1,1);
double worst=0; int maxIterations=0;
for(int n=0;n<1000;++n) {
Six q{}; for(int j=0;j<6;++j) q[j]=u(rng)*(j<3?20:8);
auto l=m.inverse(q); auto f=forward(m,l,home);
check(f.converged,"roundtrip convergence");
for(int j=0;j<6;++j) { worst=std::max(worst,std::abs(f.pose[j]-q[j])); check(std::abs(f.pose[j]-q[j])<1e-5,"roundtrip pose"); }
maxIterations=std::max(maxIterations,f.iterations);
}
Six invalid=home; invalid[0]=std::numeric_limits<double>::quiet_NaN();
check(!forward(m,invalid,home).converged,"NaN rejection");
check(!forward(m,lengths,invalid).converged,"NaN seed rejection");
auto impossible=lengths; impossible[0]=-1; check(!forward(m,impossible,home).converged,"negative length rejection");
check(!forward(m,m.inverse({10,5,2,3,1,1}),home,0).converged,"iteration limit");
check(!m.withinStroke(m.inverse({0,0,500,0,0,0})),"stroke rejection");
Geometry bad; bad.platformRadius=0; check(!forward(Model(bad),lengths,home).converged,"invalid geometry");
// Follow a smooth trajectory using the previous solution as seed.
Six seed{};
for(int n=0;n<1000;++n) {
double t=n*.01; Six q{10*std::sin(t),8*std::cos(t),5*std::sin(t),3*std::sin(t),2*std::cos(t),4*std::sin(t)};
auto f=forward(m,m.inverse(q),seed); check(f.converged,"tracking"); seed=f.pose;
}
std::cout<<"PASS: 1000 random IK/FK roundtrips, trajectory and invalid inputs. Worst pose error "<<worst<<", max iterations "<<maxIterations<<"\n";
}
+28
View File
@@ -0,0 +1,28 @@
#include "../src/logic.cpp"
#include <iostream>
#include <stdexcept>
#include <array>
std::array<double,13> setpoint{},encoder{};
int badAxis=0,writeFailure=0;
int32_t error(int32_t axis) { return axis==badAxis; }
int32_t putSet(int32_t axis,double value) { setpoint.at(axis)=value; return writeFailure; }
int32_t putEnc(int32_t axis,double value) { encoder.at(axis)=value; return writeFailure; }
void check(bool value,const char* message) { if(!value) throw std::runtime_error(message); }
int main() {
ecmcCppLogicHostServices host{};
host.get_axis_error=error; host.set_axis_ext_set_pos=putSet; host.set_axis_ext_act_pos=putEnc;
ecmcCpp::setHostServices(&host);
HexapodLogic logic;
logic.run(); check(logic.fault==0,"home cycle");
logic.pose_set={5,-4,8,2,-3,4}; logic.run(); check(logic.fault==0,"IK cycle");
for(int i=0;i<6;++i) logic.leg_actual[i]=encoder[i+7];
logic.run(); check(logic.fault==0,"FK cycle");
for(int i=0;i<6;++i) check(std::abs(encoder[i+1]-logic.pose_set[i])<1e-5,"coordinate encoder FK");
auto held=setpoint; logic.pose_set[2]=1000; logic.run();
check(logic.fault==1 && setpoint==held,"stroke fails before writes");
logic.pose_set={}; logic.run(); check(logic.fault==1 && setpoint==held,"fault latched");
HexapodLogic fkFail; fkFail.leg_actual[0]=-1000; fkFail.run(); check(fkFail.fault==2,"FK error");
HexapodLogic axisFail; badAxis=8; axisFail.run(); check(axisFail.fault==4,"axis error"); badAxis=0;
HexapodLogic hostFail; writeFailure=1; hostFail.run(); check(hostFail.fault==3,"host error");
std::cout<<"PASS: 12-axis adapter, encoder feedback, latched stroke/FK/axis/host faults\n";
}