Skip to content

Robot Calibration Cell: All Prompts

These are the prompts of the robot calibration cell case study, in the order the cell was built. Each hands one job to an AI coding assistant (Claude, ChatGPT, Gemini or another). Values in square brackets are ours; put your own there.

How to use them:

  • Give one prompt per session, in a project directory of its own, with the input files it names. Prompts 4 and 11 continue in the directory that prompt 3 built.
  • Every prompt ends with a check. Run it yourself. An assistant can turn a transform the wrong way or weaken a test as easily as a person can.
  • Nothing a prompt produces goes on a robot before the path has passed a separate clearance check, a person has looked at it in the viewer, and the first run is slow. See Camera path.
  • Each prompt was run by a fresh AI session that had none of our code, and what it built was checked with tools proven on the real cell. The page linked under each heading says what came back.

From Gates. Output: a table of limits, written before any result exists.

I am setting up a robot cell that calibrates stereo cameras with a built-in IMU, one camera after
another. Before any calibration work, write the acceptance gates the results will be judged by. I
want this first because every later step (the robot path, the solver, the report) is tuned against
these gates, and a gate invented after seeing the results is not a gate.
About the camera: [two global-shutter sensors of 1920 x 1200 pixels and one IMU soldered to one PCB;
one wide-angle lens per sensor, about 190 degrees; design baseline 60 mm, optical axes parallel; 60
frames and 600 IMU samples per second on one clock].
About the cell: [a robot arm holds the camera and stops at about 100 poses in front of a fixed
AprilGrid target, one still per stop, then swings it continuously for the camera-to-IMU part; one
recording per camera; target throughput one camera every few minutes].
Fixed by me, do not change:
- [Mean reprojection error per lens at most 0.5 px: the mean of the per-corner distance in pixels
(not RMS), on images held out of the fit, with no statistical rejection after the fit. The same
limit must also hold in the outer band of the lens (80 to 95 degrees off axis), so a good centre
cannot hide bad edges.]
- [Stereo translation within 1 mm of the PCB design: the length of the difference between the
measured and the design translation vectors.]
- [Stereo rotation: warn above 2 degrees from design, do not fail.]
Propose the remaining gates as one table: gate, what is measured, limit, fail or warn, what input it
needs, why it exists. Cover: the recording itself (dropped frames, IMU samples per frame,
timestamps, frame rate), corner coverage of the image including the edges, error on images that were
held out of the fit, error by angle from the axis, a check against known geometry (the target's real
size), camera to IMU (rotation, position, time offset, residuals), repeatability between two runs of
the same camera, and cycle time.
Rules for the table:
- Where a limit cannot be justified before the first cameras are measured, write "set from the first
units" and say what measurement will set it. Do not invent a number: a guessed limit either fails
good cameras or passes bad ones, and nobody remembers it was a guess.
- Compare two calibrations in pixels across the image (project the same rays through both), never
parameter by parameter: lens parameters trade off against each other, so two good fits can have
different numbers.
- Say for each gate what a failure rejects: the RECORDING (record again), the CAMERA (it does not
ship as it is), or the CELL (something in the station is wrong and no camera should be judged
until it is fixed). Say whether it stops (fail) or only asks a person to look (warn), and keep the
two apart.
- Bin sizes, the share of images held out and the size of the first lot are procedure, not limits:
choose them, and list them as choices I should confirm.
- Mark the gates that must exist on day one (at most twelve). The rest can wait for the first units.
- Add a short list of the inputs I must supply before the gates can run (for example the design
positions of the sensors and the IMU).
Finish with the three gates you are least sure of and what would settle each.

From Camera definition. Output: tables with a source for every value, and a check of the lens figures against each other.

Write the camera definition for calibrating a stereo camera with a built-in IMU. It is the single
place every later step reads the camera's facts from (the simulator, the path planner, the solver's
start values), so every value needs its source, and a value nobody has measured must say so.
Inputs: the maker's datasheet (pasted below) and what I know myself: [design baseline 60 mm lens to
lens, optical axes parallel, colour sensor].
Produce one table per part, each row = item, value, source:
1. Sensors and streams: sensor, shutter type, resolution per lens, pixel size, how the two images
arrive (for example side by side in one frame), frame rates, stream formats and which of them is
lossless.
2. IMU: chip, sample rate, how the samples reach the computer, full-scale ranges as the chip allows
and as configured (if not stated: unknown).
3. Lens: focal length, f-number, field of view as stated.
4. Design geometry: baseline, axis directions, where the IMU sits relative to the left lens.
5. Settings that must be locked before recording (exposure, gain, frame rate, any in-camera
processing) and why each one matters to calibration.
Look up the sensor's pixel size and the IMU's ranges and noise on the chip makers' own pages and
link them. If a page will not load, say so and mark the value "not read"; do not fill it from
memory.
Then check the lens numbers against each other, because datasheets often quote a focal length and
field-of-view figures that cannot both be true on this sensor:
- convert the focal length to pixels with the pixel size;
- under the equidistant projection (r = f * theta) and the equisolid projection (r = 2 f sin(theta /
2)), compute the horizontal, vertical and diagonal field of view that this focal length gives on
this sensor;
- going the other way, compute the focal length each stated field-of-view figure implies;
- check the three field-of-view figures against each other as well: two of them may agree with each
other while the third is the lens's own limit rather than this sensor's;
- show all of it as tables. If the focal length and the field-of-view figures disagree by more than
5 %, say so plainly, treat the lens as unknown, and give the range of focal lengths in pixels a
solver should search: from the smallest to the largest value any of the figures implies, rounded
outward to 5 px.
Recommend a lens model for the calibration, with the reason, and name one alternative.
End with a list of everything still unknown that a later step needs, and which step needs it. Do not
fill a gap with a typical value.
Datasheet:
[paste]

From Cell model and viewer. Output: kinematics, the cell in one frame, collision distances, a viewer.

Build a model of a robot calibration cell and a 3D viewer for it. A camera is bolted to the robot's
flange; the robot shows it a fixed calibration board from many directions. Everything later
(planning the poses, checking them for collisions, writing the robot program) is computed on this
model, and I will approve robot motions by looking at them in the viewer before they run on the real
arm. So the model must be exact where it can be, and honest where it is a guess.
Work in this directory. Python 3 with numpy for the model and pyyaml to read files (no ROS, no
simulator packages), and one self-contained HTML file for the viewer, with the scene data and, if
you can download it, three.js embedded in the file so it opens by double-click with no network.
Inputs: `inputs.yaml` (the robot's DH table, joint limits and speeds, what the robot stands on, the
board, the camera and how it is mounted, the lens) and `robot_body.json` (the arm's real outer shape
as a few boxes and cylinders per link, simplified from the maker's CAD so that every part of the
real arm is inside them).
Build:
1. `cell/robot.py`: forward kinematics from the DH table (a frame per link), and inverse kinematics
for a flange pose that returns every solution inside the joint limits (this arm has a
spherical-wrist offset layout; if a closed form is not available use a numeric solve from several
seeds and remove duplicates).
2. `cell/cell.py`: the cell in one world frame: robot base, floor, the stand under the robot, the
board with its tag corners in 3D, and the camera rig on the flange with both lenses.
3. `cell/camera.py`: project a 3D point into each lens with the lens model in the inputs; say
whether a board corner is visible (inside the image, inside the lens's angle limit, seen from the
front of the board); and say whether a tag is decodable (all four corners visible, the angle
between the board's normal and the line of sight under the limit in the inputs' `detection` table,
linear between its rows, and its shortest side at least `min_tag_px`).
4. `cell/collision.py`: distances, in millimetres, between (a) the camera body and, separately, a
box for its cable and plug, and (b) every link of the robot, the board, the stand and the floor,
for one pose and along a move between two poses (the robot moves in a straight line in joint
space: sample about every degree of joint travel). For the robot use the shapes in
`robot_body.json`, moved with their links. Do NOT use capsules along the kinematic skeleton: the
motor housings at the shoulder and elbow of a real arm stick out far beyond it, and when we tested
a skeleton model against poses that had really collided it rated them no closer than poses that
had run a hundred times. The camera against the robot's own links is the check that matters most:
a view of the board from far away folds the wrist back toward the arm, and a tool that clears
every obstacle in the room can still hit the robot that carries it. Leave out of the headline
number the link the camera is bolted to and the wrist link next to it (their distance to the
camera cannot change), and list them separately. Report as well the smallest distance from the
arm's own links (forearm, wrist, elbow) to the board, the stand and the floor: an arm that reaches
around the target can touch it with its elbow.
5. `viewer.html` built by `python3 -m cell.build_viewer [waypoints.json]`: the robot drawn from the
shapes in `robot_body.json`, the board with its tags, the stand, the camera and its cable box with
each lens's field of view, orbit controls, a slider per joint, and, when a waypoint file is given
(a JSON list of poses, each a list of 6 joint angles in degrees in the model's convention), a
slider that steps through the poses and shows for each one what each lens sees of the board (a
small panel per lens with the projected tag corners), the smallest camera-to-robot and
cable-box-to-robot distances at the pose and along the move to the next pose, with the closest
pair of parts named, in red under [20] mm and amber under [50] mm.
6. `tests/`: checks that run with plain `python3 tests/<file>.py` and print their numbers (pytest
may not be installed).
Checks you must run and report, with numbers:
- forward kinematics at all-zero joints and at the home pose: print the flange position; state the
reach it implies and compare it with the datasheet reach in the inputs;
- inverse then forward kinematics on 200 random reachable poses: worst position error under 0.01 mm;
- the collision function returns a distance near zero for a pose you construct with the camera
touching the upper arm or shoulder, and its value at home; print for each robot link the smallest
distance to the camera over 2,000 random poses inside the joint limits, so I can see which links
the camera can reach;
- the viewer file opens without JavaScript errors (load it headless if a browser is available; say
so if you could not).
Things I do not know yet, which you must not guess silently: whether the real robot's joint
directions match the DH convention (keep one sign and one offset per joint in a config file, default
+1 and 0, clearly marked unverified), and the exact size of the cable and its support (keep it a
named box with a generous default).
Report back: the files written, the numbers from the checks, anything in the inputs that looked
inconsistent, and three poses with a small camera-to-robot distance that I should approach slowly on
the real arm with a ruler, to check the model against the machine before trusting it.

From Camera path. Output: the poses, a coverage and clearance report, a separate check.

Plan the camera path for the calibration cell in this directory: the list of robot poses at which
the camera stops and takes a picture of the board. The model of the cell is already here (`cell/`:
kinematics, the board, the lenses, the collision distances for a pose and along a move) with a
viewer. Read it first and use it; do not write a second kinematics or a second collision model.
Why the path matters: the calibration can only be as good as the pictures. The lens is a fisheye, so
its edge is where the model is hardest to pin down and where a careless path leaves no data.
What a good path has:
1. Coverage of the IMAGE, per lens: divide each lens's image into a grid ([16 x 10] cells) and aim
for at least [25] board corners in every cell that the lens can physically fill, corners and edges
included. Count coverage by angle from the axis too (5 degree rings out to the lens limit).
2. Close-ups and tilt: most poses close to the board ([0.2 to 0.6 m] from the lens to the board's
centre, more of them near the short end) and the board tilted [15 to 60] degrees to the view (the
angle between the board's normal and the line from its centre to the camera), not head-on. Poses
that exist to fill the edge of the image may tilt further: the edge is reached by pointing the
camera away from the board, and coverage of the edge comes before the tilt rule. Close, tilted
views are what separate focal length from distance; a path of distant head-on views fits well and
is wrong.
3. Both lenses on the board together in at least [20] poses, for the stereo geometry.
4. A realistic idea of what will be detected: a tag seen at a grazing angle is not detected. Use the
limit in `inputs.yaml` (largest angle between the board's normal and the line of sight at which
tags still decode, lower toward the lens edge), and a minimum tag size in pixels. Plan to what
will be detected, not to what is geometrically in view.
5. No more poses than needed: stop adding poses when a new one adds almost nothing, and never exceed
[114] poses. If you stop at the limit, say what the last pose still added.
Safety, checked for every pose AND along every move between poses (sample each move about every
degree of joint travel; the robot moves in straight lines in joint space):
- the camera body at least [100] mm from the robot's base, turret, upper arm and elbow and [60] mm
from the forearm (the camera is bolted just beyond it); the cable box at least [50] mm and [20] mm
from the same; both at least [150] mm from the board, the stand, the floor and what the robot
stands on. Once a path has run on the real arm, replace these numbers by that path's own smallest
distances: nothing new may come closer than something that has already run;
- every joint inside its limits with [5] degrees to spare, joint 6 inside +-[170] degrees (the
camera cable), and joint 5 more than [5] degrees from zero (the wrist singularity);
- reject a pose rather than shave a margin. A pose that would be useful but is too close is not
useful. Check the margins per link (the limits differ by link), and the arm's own links against
the board, the stand and each other.
Order the poses to make the run short (nearest-neighbour then 2-opt on joint-space move time is
enough), choosing between inverse-kinematics solutions so the wrist does not flip between
neighbours. The path starts and ends at the home pose in `inputs.yaml`.
Write:
- `plan/plan_camera_path.py` (runs from the directory root, a fixed random seed, finishes in a few
minutes);
- `out/camera_waypoints.json`: a list of poses, each a list of 6 joint angles in degrees in the
model's convention, in run order, without home;
- `out/camera_path_report.md`: number of poses; per lens the count of grid cells with at least 10
and at least 25 planned corners out of those reachable, and the emptiest cells; corners per 5
degree ring; poses with both lenses on the board; the closest approach of camera and cable box to
the robot, the board and the stand, with the pose or move where it happens; estimated run time at
[60] % of the datasheet joint speeds with an acceleration of [400] degrees per second squared (a
move is a trapezoid in speed, limited by the slowest joint) and [0.3] s stopped per pose;
- rebuild `viewer.html` with the path.
Then check your own work: run the collision function over the written file (poses and moves) in a
separate script, `tests/check_path.py`, that fails if any margin is broken, and print its result.
Say plainly which targets were not met and why.

From Robot programs. Output: a tool that writes importable programs, learned from the pendant’s own export.

Write a tool that turns a list of joint-angle waypoints into a program my robot's pendant can
import, by learning the file format from a backup the pendant itself exported. The robot is an
industrial arm whose programs are normally taught by hand on the pendant; I want to generate them,
because a calibration path has more than a hundred poses and will be re-planned many times.
In this directory:
- `export/`: a backup exported from the pendant, as the original archive and unzipped, containing a
main program and two small functions I taught by hand: a few joint moves and pauses.
`export_notes.md` says what I taught, in the order I taught it, with the numbers I typed (the file
may hold the measured value, a few thousandths away). The pendant's speed is a percentage, 1 to
100.
- `waypoints/`: one JSON file per program to generate, `{"name": ..., "speed_pct": ..., "dwell_s":
..., "poses": [[6 joint angles in degrees], ...]}`. The poses are in my MODEL's angles; convert
them with `joint_map.yaml`. Move to each pose at `speed_pct`, pause `dwell_s` after each pose (not
at home), and use speed [20] for the moves to and from home.
- `joint_map.yaml`: for each joint the sign and offset that turn my model's angle into the pendant's
angle (pendant = sign * model + offset).
How to work:
1. Work out the format from the export alone. Find where my taught moves and pauses are, which
fields carry the joint angles, speed and pause time, how a function is declared and called from
the main program, and what marks the end of a program. Look hard at any numbering field: if its
values are not in line order it may record the order in which lines were created on the pendant,
not their position. Never renumber a line that is already in the export; give new lines numbers
that are not in use, state the rule you chose, and say that it is a guess until the pendant has
accepted it. Write what you found in `FORMAT.md`, and mark every field whose meaning you are
guessing.
2. Prove you understand it before generating anything new: regenerate the exported files from your
own data structures and compare with the originals byte for byte. Any difference is a
misunderstanding; resolve it or list it.
3. Change as little as possible. Start from the export as a template, replace only the function
table and the calls in the main program, and copy every field you do not understand exactly as it
was. A controller that meets a file it half-understands may load it and move somewhere else. My
taught functions are examples: overwrite them, put the generated programs in slots 0, 1, ... in
command-line order, and leave unused slots exactly as the export has them. Function names: at most
[10] characters from A-Z, 0-9 and _.
4. Keep the main program's own moves (the approach from and return to the loading position that I
taught). Add one call line per generated function, with exactly one call active and the others
present but disabled, and say in the output which one is active: with two active the robot runs
both, one after the other.
5. Every generated program begins and ends at the home pose in `joint_map.yaml`.
6. Also generate a joint-direction check named [JOINT_CHK], in the slot after the paths: from home
it moves one joint at a time by [+10] degrees in MODEL angles and back, at [5] % speed, with a [3]
s pause after the move out and after the move back, ending at home, every move at that speed, so a
person can stand at the robot and confirm that each joint turns the way the model says before any
real path runs. `--enable` accepts it like any other program, and it is what I will enable for the
first import of anything this tool writes.
7. Write the package the way the pendant expects it back (same file names, same archive layout,
file-name encoding, compression and naming pattern as the original archive, named with the current
time), into an emptied `out/`, with a `programs.json` beside it: `{"main": [[6 pendant angles],
...], "programs": {"NAME": [[6 pendant angles], ...]}}`, every joint target in order including the
home moves. A station can later compare the robot's joint log with this file to see which program
ran.
Write `robot_program.py` (a library and a command line: `python3 robot_program.py pack
waypoints/*.json --enable NAME`), `FORMAT.md`, and tests: the byte-for-byte round trip, joint limits
respected (limits in `joint_map.yaml`), exactly one active call.
Report: what you are sure of in the format, what you are guessing, and what I should check on the
pendant after the first import (for example: the program list shows the names, the active call is
the one I asked for, the joint check at low speed moves each joint the way the model says). If one
export cannot settle a question, tell me which second export would (for example: the same program
after I insert one line in the middle).

From Robot programs. Output: a check on the joint log.

Write a check for a robot calibration station: after a run, decide from the robot's joint log which
program the robot actually ran, and whether it ran exactly once.
Why: the station tells the robot to start, but the program that runs is whichever one is enabled on
the robot's pendant. On our cell an old package was still loaded with two programs enabled; the
robot ran both, and the station reported a clean run of a third. Nothing failed until someone looked
at the joint log.
Inputs in this directory:
- `programs.json`: `{"main": [[6 joint angles], ...], "programs": {"NAME": [[6 joint angles], ...],
...}}`: for every program the joint targets it visits, in order, in degrees. `main` holds the
moves the robot makes around the program: from the loading position through the first half of
`main`, then the enabled program (or programs, one after another, when more than one is enabled),
then the second half of `main` back to the loading position. Each program is a stop-and-go part, a
return to its first pose with a pause, then continuous loops; a target repeated twice in a row is
a pause, not an error. The programs share most of their targets: [PATH_C is PATH_A with 45 extra
targets; PATH_A and PATH_B differ in 7 slightly moved poses].
- `logs/*.csv`: one joint log per run, sampled about once per second with occasional gaps; the check
must work as well on logs sampled four times per second. Columns: unix time, robot mode (7 =
running a program; other values = idle or manual), alarm code (0 = none), moving flag, then the
six joint angles separated by spaces, to 0.01 degree.
- `home.json`: the loading position, where every run starts and ends.
Facts about the robot: it moves from target to target in a straight line in joint space. In the
continuous part it does not stop at a target and rounds the corner (it leaves the incoming line
before the target and joins the outgoing one after it), so a sample near a target can be a few
degrees inside the corner; in the stop-and-go part it stops exactly. At one sample a second most
targets are never seen exactly in the log. The robot repeats a path to within [0.1] degree, and no
joint moves faster than [600] degrees per second.
Write `check_run.py` with `check_run(log_path, expected_program) -> dict(ok, ran, why, evidence)`:
- `ok` is True when the expected program ran, once, and the robot returned to the loading position;
False only when you are certain it did not (another program ran, or more than one, or none of the
known ones, or the run ended in an alarm or away from the loading position); None when the log
cannot decide (for example two programs that the log cannot tell apart). A wrong False throws a
good recording away, so prefer None to a guess, and say what counts as proof (for example: a
sample in the stop-and-go part more than [1] degree off every point of a program's path).
- `ran`: your best identification, `why`: one sentence a technician can act on, `evidence`: the
numbers behind it.
Also a command line: `python3 check_run.py LOG EXPECTED`.
Then run it on every log in `logs/` against every program name and print a table. I will compare it
with what really ran. Tell me which pairs of programs your method cannot separate at this sample
rate, and what sample rate would.

From Recording and stills. Output: one sharp frame per robot stop.

Write the step that picks the still frames out of a calibration recording. The robot moves the
camera from pose to pose and stops briefly at each; the recording is one continuous video with the
camera's own IMU samples time-stamped on the same clock as the frames. I need exactly one sharp
frame per stop.
Why by the IMU and not by the pictures: in a compressed video two frames of a static scene are
bit-identical and slow motion looks still, so frame differences pick blurred frames and miss stops.
The gyroscope knows when the camera is not turning.
Inputs in this directory:
- `imu.csv`: time in seconds, gyro x, y, z in raw sensor counts, accelerometer x, y, z in raw
counts, about 600 samples per second. The scale is [8.192 counts per degree per second]. The gyro
has a constant bias that you must estimate from the data.
- `frames.csv`: frame index and time in seconds, 60 frames per second.
- The recording may contain two parts: first the stop-and-go camera path, then, after a hold of at
least 3 seconds at the home pose, a second part where the camera is moved continuously (it is used
for something else). Only the first part gives stills.
Write `pick_stills.py`:
- estimate the gyro bias from the steadiest moments of the WHOLE recording, not from the first
seconds: the robot may already be moving when the recording starts. Cut the recording into blocks
of about [0.2] s, keep the quietest tenth by their spread, and take the median of their MEANS (a
median of raw samples can only land on a whole sensor count);
- a stop is a stretch where the rotation rate (the length of the bias-corrected gyro vector,
smoothed over about [20] ms) stays under [1.0] degree per second for at least [0.15] s; join two
stretches separated by less than [30] ms; pick the frame nearest the middle of the stretch, never
the first or last frame of it (the arm is still settling at the start); a stretch cut off by the
start or end of the recording is not a stop;
- find the long hold that separates the two parts, if there is one. The hold itself gets no still.
Report the first frame after the hold as the start of the second part, and pick nothing after it;
- output `stills.json`: the picked frame indices and times, the bias, the number of stops, the split
point; and print a summary.
Then check yourself on `truth.json` (the true stop intervals of this recording): every true stop
must have exactly one pick inside it, with no picks outside any stop. Print the counts. If the first
seconds of the recording are in motion, show that your bias estimate is unaffected.

From The solve. Output: corners re-located in a local undistorted view, or dropped.

Write the corner refinement step of a fisheye calibration pipeline and run it on the images here. A
tag detector has already found the corners of the calibration target's tags in each image, but only
roughly: near the edge of a fisheye a tag is small, stretched and curved, and the detector's corners
are off by a pixel or more there. The calibration is only as good as these corners, so each one is
to be re-located precisely, or thrown away.
In this directory:
- `images/`: grey-scale stills of an AprilGrid target (Kalibr layout: every tag corner touches a
small black square, so each corner is the crossing point of two edges, like the inner corner of a
checkerboard).
- `corners_rough.json`: per image the rough corners: `corner_id`, `uv` in pixels, and `P`, the same
corner on the target in metres (target frame, Z = 0).
- `lens_approx.yaml`: an approximate model of the lens (an earlier calibration, good to a pixel or
two), with its projection formula named. [Double sphere: for a point (x, y, z), d1 = |(x, y, z)|,
zeta = xi d1 + z, d2 = sqrt(x^2 + y^2 + zeta^2), u = fx x / (alpha d2 + (1 - alpha) zeta) + cx,
the same for v.]
Method (the idea is published in the TartanCalib paper: refine where the distortion has been taken
out locally):
1. Per image, fit the target's pose from the rough corners through the approximate lens model,
robustly, so a few gross errors do not steer it. That gives a predicted position for every corner.
2. For each corner, build a small virtual pinhole view that looks straight along the ray of that
corner, [31 x 31] pixels with a focal length chosen so that the patch has about the same pixel
scale as the image has there (do not magnify: interpolation invents no information). Resample the
image into that view through the lens model. In this view the crossing is two straight edges.
3. Refine the crossing point to sub-pixel precision in the patch (OpenCV's cornerSubPix with a
search window of about [7] pixels half-width, or a saddle-point fit), starting from the rough
corner; if that fails, start again from the predicted position.
4. Verify, and drop the corner unless ALL hold: the refinement converged; it lies within [3] pixels
of the predicted position; the patch really shows a crossing (opposite quadrants alike,
neighbouring quadrants different, enough contrast); the refinement window (not necessarily the
whole patch) lies inside the image and inside the lens's image circle (find the circle from the
black surround if it is not given). A corner that fails is dropped, never passed on unrefined: on
our data, keeping failed corners at their rough positions was worse than either dropping them or
not refining at all.
5. Map the refined point back to image pixels through the same lens model. The model is only used to
make the local view and to undo it, so its own small errors cancel to first order.
Write `refine_corners.py` and `corners_refined.json`: per image `corner_id`, refined `uv`, `P`, for
the kept corners only; plus `refine_report.md`: corners in, kept, dropped by reason, and the share
dropped by angle from the lens axis in 10 degree bands. A refinement that drops far more at the edge
than in the centre is not refining the edge, it is deleting it: say so if you see it.
A check you can run without knowing the true positions: fit the target pose per image again from the
refined corners and report the mean distance between refined and predicted corners, by the same
angle bands, before and after. It should fall everywhere, most at the edge.
Then refine a second time from start positions moved by a random [0.7] pixels and report how far the
results move: that is the repeatability of the refinement itself. Whatever distance to the predicted
corners remains beyond it is the lens model's error, not the corners'.
Tell me which images or regions you would not trust, and which of your drop rules never fired on
this data (an untested rule).

From The solve. Output: an independent solver with held-out error by angle and a bootstrap error bar.

Write a stereo camera calibration solver in Python (numpy and scipy only) and run it on the data in
this directory. It will be the second, independent solver next to an established tool: two solvers
that agree on the same corners is the evidence that a calibration is right, and when they disagree
the data is the first suspect.
Data: `corners.json` = `{"cam0": [{"file", "uv": [[u, v], ...], "P": [[X, Y, Z], ...]}, ...],
"cam1": [...]}`. Each entry is one still image of one lens: `uv` are detected target corners in
pixels, `P` the same corners on the calibration board in metres (the board's own frame, Z = 0 on a
flat board). The same `file` name in cam0 and cam1 is the same instant, so the board has one pose
for both. Images are [1920 x 1200]. cam0 is the left lens. The lenses are fisheyes of roughly [130
to 190] degrees.
Model, per lens: Kannala-Brandt with four radial terms plus two decentering (tangential) terms:
theta = angle of the ray from the axis; d = theta (1 + k1 theta^2 + k2 theta^4 + k3 theta^6 + k4
theta^8); (mx, my) = d (x, y) / sqrt(x^2 + y^2); r2 = mx^2 + my^2; mx' = mx + 2 p1 mx my + p2 (r2 +
2 mx^2); my' = my + p1 (r2 + 2 my^2) + 2 p2 mx my; u = fx mx' + cx, v = fy my' + cy.
The decentering terms are not optional: on our lenses, models without them moved the second lens
more than a millimetre to absorb a slightly off-centre lens, and the baseline came out wrong while
the pixel error looked fine.
Unknowns: 10 intrinsics per lens, the pose of cam1 relative to cam0, and one board pose per still.
Requirements:
1. Start values without help from me: focal length from a coarse search (the value that makes the
per-image pose fits best), principal point at the image centre, distortion zero, a board pose per
image from a pose fit, the stereo transform from the images both lenses share.
2. Joint optimisation of everything (Levenberg-Marquardt; exploit the block structure or sparse
Jacobian so it finishes in about a minute), with a robust loss so a few bad corners do not steer
it.
3. Hold out every fifth still (sorted by file name: the 5th, 10th, ...) completely from the fit.
After the fit, solve only the board pose of each held-out still, one pose shared by both lenses,
with the lenses and the stereo transform frozen, and report the error on those with no rejection
of corners. This number, not the fit residual, is the result.
4. Report: held-out mean and median error per lens in pixels; the same split by angle from the axis
in 10 degree bands, with corner counts; baseline in millimetres and the rotation between the
lenses in degrees; the intrinsics; how many corners each lens had and how they are spread over a
16 x 10 grid of the image (so thin coverage is visible).
5. An uncertainty for the baseline from a bootstrap over stills (resample the stills, refit, at
least 20 times; a warm start is fine). Do not report the difference between two halves of the same
run as the uncertainty: halves that share their poses agree far better than the truth allows.
6. Write `camchain.yaml` (intrinsics per lens, the 4 x 4 transform that takes a point from cam0's
frame to cam1's, units stated) and `report.md`.
Sanity checks to run and print: the mean residual vector per region of the image (a smooth pattern
means the model or the board is wrong, not the corners); and, for each board corner, its mean
residual across all images carried back onto the board's plane in millimetres (a smooth pattern
across the board means the board is not flat or not the size stated; in pixel space this hides).
Say how far from the axis the corners reach: beyond that angle the model is an extrapolation,
whatever the lens's nominal field of view.
Tell me the numbers, anything in the data that looks wrong, and what you would not trust.

From Camera to IMU. Output: rotation, time offset and the IMU’s position, with honest error bars.

Write the camera-to-IMU step of a calibration pipeline and run it on the data here. The stereo
calibration is already done; this step finds how the IMU is turned relative to the left lens, the
time offset between the IMU's clock stamps and the frames', and where the IMU sits.
Data in this directory:
- `poses.json`: for each video frame that saw the calibration board, the frame time in seconds and
the pose of the board in the left lens's frame (rotation vector and translation in metres), from
the finished camera calibration. About 60 frames per second; some frames are missing (board not
detected).
- `imu.csv`: time in seconds, gyro x, y, z and accelerometer x, y, z in raw counts, about 600 per
second. Scales: [8.192 counts per degree per second, 1024 counts per g].
- The recording starts with a few seconds standing still, then the camera is swung about all axes in
front of the board.
Method, in this order, because each part needs the one before:
1. Rotation and time offset from the gyroscope alone. The camera's angular velocity between
consecutive frames (from the board poses) must equal the gyro's mean over the same interval,
turned by a fixed rotation. For each candidate time offset in a range of [+-60 ms], average the
gyro over the shifted intervals, fit the rotation in closed form (Kabsch / SVD on the two sets of
vectors), and keep the offset with the smallest residual; refine the offset to [0.05 ms]. Estimate
the gyro bias from the still start. Skip intervals that span a missing frame.
2. Position of the IMU (lever arm), gravity and accelerometer bias from the accelerometer. Fit a
smoothing spline to the camera POSITIONS and differentiate it twice for the camera's acceleration.
Take the angular rate and angular acceleration from the GYROSCOPE (bias removed, turned into the
camera frame with the rotation from step 1, lightly smoothed), not from differentiated board
poses: differentiating orientation twice makes the answer swing by centimetres with the smoothing.
Then solve the linear least-squares problem in which the measured specific force equals the
camera's acceleration minus gravity, plus the terms from rotation about the lever arm, plus a
bias. Report the value at a knot spacing of [0.10] s, repeat for spacings from [0.07 to 0.15] s
and say how much the lever arm moves: that movement, together with the spread between thirds in
step 3, is its error bar. The length of the gravity vector must come out near 9.81 m/s^2: print
it, it is a free check of the accelerometer scale.
3. Honest error bars: repeat step 1 and 2 on three separate thirds of the swinging part of the
recording (the gyro bias from the still start serves all three) and report the spread. State which
results you would trust, and to how many millimetres or milliseconds.
Things that will mislead you if ignored:
- report the rotation as R with v_imu = R v_camera (a direction in the left lens's frame turned into
the IMU's frame), the offset as t_imu = t_camera + offset, and the IMU's position in the left
lens's frame; write these three conventions into the result file in words;
- the time offset depends on the exposure time of the camera (the frame's stamp sits somewhere
inside the exposure), so it is a property of the camera AND its settings: store the exposure of
this recording, [1.5 ms], with it;
- motion blur and a shaking robot base hurt the lever arm long before they hurt the rotation; if the
accelerometer residual is large compared with the signal, say the lever arm is not determined
rather than print three digits.
Write `imu_calib.py`, `imu_result.json` (rotation matrix, offset in ms, lever arm in mm, gravity
norm, biases, residuals, per-third values) and print a summary. Then compare with `truth.json` if it
is present and print the errors.

From Camera to IMU. Output: the robot motion for the camera-to-IMU recording.

Plan the robot motion for the camera-to-IMU calibration in the cell modelled in this directory
(`cell/` has the kinematics, the board, the lenses and the collision distances; read and use it;
`inputs.yaml` has the home pose, the joint speeds and the detection limits). In this recording the
camera does not stop: the robot swings it in front of the board so the gyroscope and accelerometer
see motion about every axis while the board stays in view.
What the motion must achieve, and the physics that sets its shape:
- Rotation about all three axes and acceleration along all three, at the same time rather than one
axis after another: it is shorter and the axes do not hide in each other.
- Motion blur is the price of the motion. Blur in pixels is about (angular speed in rad/s) x
(exposure in s) x (focal length in px); with exposure [1.5 ms] and focal length [618 px], 60
degrees per second is about 1 px. Sharp frames (under half a pixel) would need a swing so slow
that the accelerometer sees almost nothing, so this recording accepts some blur: aim for an RMS
angular speed of [60 to 90] degrees per second on each axis, and report the RMS and 95th
percentile of blur that gives. Tags still decode at that blur; the rotation and the time offset
tolerate it; the IMU's position is what pays, and more light (a shorter exposure) is the only
thing that buys it back.
- The IMU's position is found from angular ACCELERATION, the blur comes from angular SPEED. For a
swing of amplitude A at frequency f, speed grows with f A and acceleration with f^2 A, so at equal
blur a faster, smaller swing tells more. But a robot controller smooths closely spaced points: on
our arm a path of many small steps came out at a fifth of the planned amplitude. So use few,
large, well separated targets: one full pose per half swing, about [+-15 degrees and +-60 mm]
around an anchor pose, and let the controller blend.
- The board must stay detectable through the swing: at least [8] whole tags decodable in the better
of the two lenses at every target. The swing of [+-15 degrees and +-60 mm] is per camera axis, all
axes at once and not in step with each other.
- Use [3] anchor poses at different distances and tilts, about [40] targets each at [50] % of the
datasheet joint speeds (write the speed into the path file per anchor), a pause of [1.5 s] at each
anchor, and start with a hold of [4 s] at home (the software finds this hold to know where the
swinging part begins).
- Keep away from the wrist singularity (joint 5 more than [15] degrees from zero): near it small
camera motions need huge joint speeds.
Safety, for every target and every move between targets, sampled about every degree, using the
collision functions in `cell/` (per link where the limits differ), and including the arm's own links
against each other and against the board and stand: the camera body at least [100] mm from the
robot's base, turret, upper arm and elbow and [60] mm from the forearm; the cable box at least [50]
mm and [20] mm from the same; both at least [150] mm from the board, the stand, the floor and what
the robot stands on; joints inside limits with [5] degrees to spare. If a camera path has already
run on the real arm, use its smallest distances instead.
Write `plan/plan_imu_path.py`, `out/imu_path.json` (`{"anchors": [{"q0": [6 joint angles, degrees,
model convention], "points": [[6 angles], ...]}, ...]}`: the robot goes home, holds, then for each
anchor goes to q0, pauses, visits the points in order, returns to q0; home at the end), and
`out/imu_path_report.md`: per anchor the RMS and peak angular speed and linear acceleration of the
camera on each axis (state the motion profile you assume between targets; a controller that blends
corners moves smoothly through them), predicted blur RMS and 95th percentile, the fewest tags
visible at any target, closest approaches, and total time. Rebuild the viewer with this path. Run a
separate `tests/check_imu_path.py` that fails on any broken margin and print its result.
One more thing to put in the report: run the first test of this path on the real arm at half speed
and watch the base. If the robot's stand shakes, the board poses and the IMU disagree for a reason
no solver can fix.

From Production station. Output: the station’s supervisor, a simulator and fault-injection tests.

Design and write the supervisor of a production calibration station, with a simulated robot and
camera so it can be tested without hardware. A technician mounts a camera on the robot, presses one
button, and the station records a video while the robot runs its program, then processes the
recording and shows the result. The technician is not a programmer and may not share a language with
the engineers; the engineers are not in the room.
Everything in the list below is a failure we had on a real cell. The station must catch each one by
itself, because a rule that depends on someone watching will be broken the first time nobody is.
Before the robot starts, refuse with a plain reason when:
1. no camera is streaming, or the recording file is not growing. Recording starts first, is checked
for [2] seconds, and only then is the robot started; a refused start deletes that file. (A camera
can drop off USB while the program still believes it is recording: the robot then runs a whole
path with nothing recorded);
2. the frame rate measured from the recording is under [58] frames per second when [60] is expected
(some cameras have a 30 / 60 switch);
3. the exposure is not the locked value, [1.5 ms] by hand (a re-plugged camera comes back on
automatic exposure: set it again after every plug-in);
4. the camera's serial number could not be read from the camera itself, and nobody typed one (do not
use a USB descriptor that is the same on every unit);
5. the camera model is unknown: the model decides which robot program is right. A table maps
serial-number patterns to models; a serial that matches none makes the technician pick from a
list, and the pick must not be carried over silently from the previous camera;
6. the robot is not in automatic mode, has an alarm, is moving, or is not at the loading position (a
program stopped half-way resumes half-way);
7. the robot link is stale: after a controller restart an open connection can fail every request
while the screen keeps the last good values. A value is fresh only if the request that fetched it
succeeded within the last [3] seconds; a failed or late request clears the values, shows an error
and reopens the link;
8. the program for this model has never completed a verified run on this station and the robot's
speed is above [30] %: a first run is slow by construction, whoever presses the button. Verified
means item 10 answered ok; remember it per program name together with a checksum of the program's
targets, so a changed program is new again. The station refuses; it does not change the robot's
speed itself.
During and after the run:
9. an alarm, a lost camera, or the robot stopping away from the loading position ends the run as an
error and keeps the recording. On a lost camera the station does not stop the robot: the program
brings it back to the loading position by itself;
10. after the run, check from the joint log that the expected program ran, once (give this as an
interface, `check_run(log, expected) -> ok / not ok / cannot tell`, with a simple implementation).
Not ok is an error and nothing is solved; cannot tell goes on to processing but does not count as a
verified run;
11. processing is queued: the technician can mount the next camera while the last one is solved;
12. the result on screen is PASS or CHECK in calm colours with one line of reason; CHECK means "look
again", not "scrap". PASS or CHECK comes from a function `gates(report) -> (result, reason)` that I
will supply; use a stand-in;
13. after a result, keep one take's results per camera (the best: most of the image covered first,
then lowest error). Videos: a take is about 1 GB; when a camera has a take that passed, delete all
of that camera's videos; while it has none, keep only the video of its latest take so it can be
reprocessed;
14. write a folder per serial number meant for the customer, for every camera that has a calibration
whether PASS or CHECK: the calibration in one file, a page that defines every number (lens model
formula, frames, units), a one-page certificate with the measured numbers. No internal reports, no
verdict words. (The cameras are stereo; take the content of the calibration file as given by the
solver.);
15. never block the screen on a device that does not answer: every device call has a timeout and
runs off the user-interface thread.
Write it as: `station/supervisor.py` (a state machine with explicit states and the checks above, no
GUI), `station/sim.py` (a simulated robot and camera that can be told to misbehave: drop the camera,
report 30 frames per second, raise an alarm mid-run, return stale data, run the wrong program, stop
half-way), and `tests/test_station.py` with one test per numbered item that injects the fault and
asserts what the station does and what it tells the technician. Messages for the technician go
through one function so they can be shown in two languages, [English and Chinese]. Use `unittest` if
pytest is not installed.
Run the tests and print the result. Then list any item you could not test and why.

The sources behind each prompt are listed on its page.