Metadata-Version: 2.5
Name: designoptpy-xray
Version: 0.1.0
Summary: Interactive Qt and Matplotlib application for DesignOptPy X-Ray sessions
Author: Eduardo Rodrigues Della Noce
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: NOTICE
Requires-Python: <3.15,>=3.12
Requires-Dist: designoptpy-core[io]<0.2,>=0.1.0
Requires-Dist: designoptpy-sso<0.2,>=0.1.0
Requires-Dist: matplotlib<4,>=3.11
Requires-Dist: numpy<3,>=1.26
Requires-Dist: pyside6-essentials<7,>=6.10
Description-Content-Type: text/markdown

# designoptpy-xray

This application displays and edits Box X-Ray projections in an interactive window.
A projection shows two selected design variables and sampled requirement results.
The window uses Qt for its controls and Matplotlib for its projections.

Division of work:

- The `designoptpy.sso.xray` engine configures the domain, computes projections, stores session state, and reads Excel workbooks.
- The application provides the window, controls, and background model calculations.
- The controller coordinates window actions with engine state.
- Widgets are controls such as sliders, buttons, and text fields.

## Install

From `designoptpy`, run `uv sync --locked --package designoptpy-xray --no-dev`.
This installs the application, workbook support, and the Solution Space Optimization (SSO) engine.
Before these projects are published to an index, install all three local projects together with pip:
`./packages/designoptpy-core`, `./packages/designoptpy-sso`, and `./apps/designoptpy-xray`.
The `designoptpy` distribution also includes this application.
Before installing by package name from an index, verify the account that published the package and inspect its published files.

The window needs `PySide6-Essentials`, the Qt library for Python, which is available under the GNU Lesser General Public License (LGPL) version 3.
On a minimal Linux system, Qt also needs the system library `libEGL`, even for a hidden window.
On Linux without a display, the application selects Qt's `offscreen` platform, which draws into memory.

The application can be released separately from the engine.
The [designoptpy-sso README](../../packages/designoptpy-sso/README.md#box-x-ray-engine) explains the engine.
It covers domain configuration, the workbook schema, sessions, result freshness, exports, and resource limits.

## Create a small interactive study

This example evaluates the squared distance from the origin for two design variables.
An upper limit of 0.5 accepts points inside the corresponding disk.

```python
import numpy as np

from designoptpy.sso.xray import DesignVariable, QuantityOfInterest, XRayDomain
from designoptpy.xray import create_xray_gui


def measures(samples):
    return np.sum(samples**2, axis=1)[:, None]


domain = XRayDomain(
    measures,
    (
        DesignVariable("x", -1.0, 1.0, -0.5, 0.5),
        DesignVariable("y", -1.0, 1.0, -0.5, 0.5),
    ),
    (QuantityOfInterest("squared_radius", upper=0.5),),
    number_samples_per_plot=100,
)
controller = create_xray_gui(domain, rng=4)
```

Each row of `samples` is one design. The returned column is a raw measure.
The domain converts its limit violation into a normalized deficit.
A deficit at or below zero satisfies the requirement. A positive deficit violates it.
Projected variables span the design space.
Other variables, when present, are sampled inside the solution box.
Samples provide evidence. They do not prove that every unsampled design satisfies the requirements.
Call `controller.close()` after programmatic use.

## Inspect stored design rows

Pass an `XRaySampleData` record through `XRayDomain.sample_data` to use existing measurements.
The record holds design samples, performance measures, and optional physical feasibility measures.
It replaces the evaluator.
Column names bind the stored arrays to variable and quantity records.
Changing the column order therefore keeps each stored column attached to its name.

What the window shows in this mode:

- It shows **Data points: N** instead of a sample-count setting.
- Each panel shows the rows whose other coordinates lie inside the solution box.
  Panels can contain different numbers of rows.
- The panel title states the number of shown rows and the total, such as **615 of 5,000 points**, including **0 of 5,000 points** for an empty panel.
- The window says "point" instead of "sample", for example **Selected point** and **Inspect a point**.
- Selected rows use **Stored response**, and the legend uses **Rejected row**.
- A positive infinite measure marks an explicit rejection. NaN remains an input error.

**Update Plot** selects and labels the stored rows again under the current limits.
It draws no new samples and calls no model.
In both modes, field edits, requirement toggles, and moved bounds remain historical until **Update Plot**.

**Optimize** trims a box on stored evidence.
It adds no growth step and makes no new model evaluation.
The outcome states how many valid and other rows remain.
Remaining nonvalid rows or a stopped trimming search produce a warning.
Regions without rows remain untested. The box does not prove validity between rows.

An optional **Stored Samples** workbook sheet opens the same mode without `--evaluator`.
The engine README describes its columns and data-construction helpers.

## Command line

Installation provides the `designoptpy-xray` console command, equivalent to `python -m designoptpy.xray`.
The command reads a Box X-Ray workbook, loads the optional evaluator selected by `--evaluator`, and opens the window.
Omit `--evaluator` when the workbook contains stored samples.
The evaluator reference has the form `MODULE:ATTRIBUTE`.
It must be importable in the running environment.
`MODULE` identifies the Python module. `ATTRIBUTE` names its evaluator function or object.

```shell
designoptpy-xray XRayInputCarCrash.xlsx --evaluator my_models:car_crash_evaluator
```

The option `--seed` makes projection sampling reproducible.
Without it, the application creates an unseeded random generator, as the library does.

## Evaluation and background jobs

### Start-up and completion

- By default, `create_xray_gui(..., show=True)` submits the initial work to a background worker.
- With `show=False`, it computes the initial projections synchronously. They are complete before the function returns.
- The argument `synchronous_initial` overrides this choice.
- `initial_evaluation=False` skips the initial projections: the window starts without samples, and no job starts.
  Use it when the next call replaces them, for example `controller.optimize()` in a script.
  The skipped evaluation still draws its child seed (see [Random numbers](#random-numbers)),
  so a seeded optimization and the projections after it are the same with and without the skip.
  `ready` stays False until a later evaluation.
- `controller.ready`, `active_job`, and `last_error` report completion and failure.
- A running Qt event loop polls jobs automatically.
- Asynchronous calculations continue after the function returns.
  A worker thread runs model code independently within the same Python process.
- Without a running event loop, call `controller.poll_jobs()` to read worker messages and apply complete results.
- Projection progress counts completed design-variable pairs.
  An optimization is one work unit and completes only when the computation returns.
  Its progress fraction does not report intermediate iterations or evaluated rows.
  A save from the window counts written files; see [Saving from the window](#saving-from-the-window).

### Random numbers

`rng` is a NumPy `Generator`, an integer seed, or `None`.
The controller converts it once with `numpy.random.default_rng`.
Every model computation, synchronous or in the background, draws one child seed from this random number generator (RNG).
The computation then uses a new generator from that seed.
This isolates its draws from later controller work.
A seed initializes a generator. The generator state records the current position in the sequence of random draws.
Both paths derive their generator in the same way, so one seed gives the same samples with and without a display.

### Isolation, deadline, and cancellation

- Each job evaluates a copied session on one background worker.
  The live session changes only when the controller commits the result.
- Projection jobs check cancellation between variable pairs and evaluation batches.
- An optimization job checks cancellation before each evaluator batch of the optimizer and after the optimizer returns.
  A request during the trimming or the final steps of one iteration takes effect at the next batch or at the end.
  A cancelled optimization ends without a result.
- `XRayResourceLimits.maximum_wall_time_seconds` of the domain sets the job deadline.
  The default is 3,600 s.
- After the deadline, the same checks stop a projection job, and the controller reports a timeout.
  An optimization stops at its next evaluator batch and reports the timeout.
  A result that arrives after the deadline is discarded.
- No check can interrupt model code that is running, so a model call that never returns keeps the job active.
- `controller.close()` waits for the worker at most until the job deadline.
  A save job has no deadline, so `close()` waits until its files are written.
  A window close event does not wait.
- A model call that is still running can delay Python process exit, because Python cannot stop a thread from outside.
- A session accepts a new controller only after the worker of its earlier controller has returned from its model work.
  This also holds after the window closed. A save job of the earlier controller does not block, because it calls no model.
  Until then, `create_xray_gui` with the same session raises `RuntimeError` and changes nothing.
  The model therefore never runs in two threads at once.

### One computation at a time

Model work runs one computation at a time.
While a background job runs, the controls that change model inputs are disabled.
These public methods raise `RuntimeError` and change nothing:

- `set_solution_box`, `set_design_space`, `set_qoi_limits`, `set_qoi_active`, and `set_parameter`;
- `refresh()` with evaluation;
- `optimize()`.

The job evaluates a copy of the earlier inputs with the same model object.
A second evaluation would call that model from two threads.

### Errors and status

- Synchronous engine methods return their result or raise the model error.
- Controller `refresh()`, `optimize()`, and `save_safely()` store a recoverable failure in `last_error` instead.
- Every outcome appears in the status area.
  Errors have an `Error:` prefix, an error icon, a red border, and dark red text.
  Warnings have a `Warning:` prefix, a warning icon, an orange border, and dark orange text.
  The first sentence of an error or a warning is bold. Ordinary outcomes use black text and a gray border.
  The status area grows from two to four lines when a message needs the space.
- A model optimization that stops without convergence is a warning, for example at the iteration limit.
  The status states the reason in plain words, the iteration count, the duration, and the box volume as a fraction of the design-space volume, before and after.
  A following plot outcome stays in normal text on its own line.
- The application opens no outcome dialogs, including when the window is hidden.
- After a failed evaluation, the window keeps showing the earlier projections.
  The session also keeps them.
- `ready` ignores `last_error`.
  It reports whether the retained projections are current and drawn completely.
- After synchronous controller work without a display, check `controller.last_error`, then `controller.ready`, before you use projections.

### Render stamp and saving

- A render stamp records which projection result the figure shows.
  Every redraw invalidates the stamp first.
  The redraw sets it only when every retained projection has its own axes and the canvas finished drawing.
- The redraw draws the canvas at once, not at the next idle event.
  Matplotlib parses texts such as legend labels only while it draws.
- The axes come from `desired_pairs` at construction.
  After a pair edit, the figure cannot show the new projections.
  Create a new controller for changed pairs.
- `save()` raises write and validation errors.
  It also raises `ValueError` when the figure does not show the retained projection result, for example after a rendering failure.
  The saved images and the numeric files therefore always describe the same samples.

### Saving from the window

`save()` does all its work before it returns, so a script without an event loop can use it.
The **Save** button and the S key run the same steps in two parts:

1. On the window's thread, the controller checks the evidence and renders the figure at the export resolution.
   Matplotlib must draw on this thread.
2. A background job then encodes the Portable Network Graphics (PNG) images and writes the CSV table and the NPZ archive.
   The window stays responsive. The controls stay locked as during other jobs, and the progress row counts the written files.

The job reads only the rendered pixels, the image names and crop boxes, a copy of the session with a snapshot of the domain,
and one capture of the declared inputs, taken at the click.
It checks freshness and writes the session record against this capture.
A model or sampler without `clone_configuration` stays shared with the snapshot, but the job does not read its configuration again.
An edit during the write therefore cannot change or reject the saved evidence.
The staged folder is renamed into the destination only after every file is written.
The status then reports `Saved to ...`.
A write error reaches `last_error` and the status, as `save_safely()` reports it.
**Cancel** cannot stop a save: the job publishes its folder in its last step, and a later request could not undo the files.
The total work is the same as for `save()`. For the car-crash example (10 projections of 1,000 samples at 300 dpi),
the window thread is busy for about half of the save.

The `--evaluator` target imports and executes Python with the permissions of the current process.
Use only a trusted workbook and evaluator module.

## The window

The window has three regions.
A splitter separates the configuration tabs on the left from the projections on the right. Drag it to give the projections more width.
The tab panel starts at the narrowest width that still shows full-precision values.
**« Hide Tabs (T)** at the right end of the tab bar hides it, and **» Show Tabs (T)** in the projection header shows it again.
A window whose projection panel would be narrower than 600 pixels starts with the tabs hidden, until you show or hide them yourself.
The lower row shows the outcome of the last operation and the commands.

Each tab page has a fixed header with a title, a short explanation, and, where fields form columns, the column headings.
The panels below the header scroll, so the headings stay in view.

| Tab | Content |
| --- | --- |
| Variables | One panel per design variable: its name, unit, and description, a **Design space** row and a **Solution box** row with a lower and an upper field each, and a range slider. Design-space fields have a gray background, because they change less often. **Show descriptions** and **Show sliders** hide the descriptions or the sliders independently. |
| Parameters | One row per constant parameter. The tab appears only for a function evaluator, which is the only evaluator that receives the parameters. |
| Quantities | One panel per quantity of interest (QoI), a model output that describes or classifies a design: **Apply limits**, the lower and upper limits, and a **Violation** row with the **Color…** button and, below it, the marker shape of the class and the violation text. `-Inf` or `Inf` means no limit on that side. |
| Inspect (I) | The selected sample: the projection where it was selected, its class, its model response and physical feasibility, all design values, and all QoI values with their limit states. |
| Export | The save folder with **Browse…**, and the optimization result with **Discard Optimization Result**. A path longer than its field shows a leading "…" and its last folders. |

Tab tooltips hold the full names. Names and units render TeX-style subscripts and superscripts, as the axis labels do.

The projection panel holds, from top to bottom:

- A header with display choices, which change no model input:
  **Show explanations**, the layout (**Auto (scrolls)**, **All at once**, **1 per row** to **N per row**, and **Matrix view**), the marker size (**Auto**, **Tiny**, **Small**, **Normal**, **Large**),
  **Show** (**Samples** or **Class shares**), and, after a thin divider, **View:** with the projection selector and ◀ and ▶.
  Choosing one pair opens a single-projection view with one large plot that fills the panel width. **Show All Projections** returns to the grid.
  The canvas of this view holds one tile, so its pixels and each full draw cover one projection, whatever the number of projections.
  ◀, ▶, and the mouse wheel therefore draw the next projection instead of scrolling to it. A save still writes every projection.
  On a narrow panel, the choices from **Layout** to ▶ move to a second header line.
- A guidance line that states what the plots show and what a click does on the current tab.
  Every tab states that samples are evidence and not a proof that every design in the box is good.
  **Show explanations** hides this text and the explanations at the top of every tab; one short line of the main actions then stays.
  A window shorter than 800 pixels starts without explanations.
- A colored notice: green when the plot shows the current inputs, amber after an input change, blue while a job runs, and gray without samples.
  **Revert Box** and **Show All Projections** sit inside the notice at its right end. The notice keeps the height of its longest text, so the plots do not move.
- A legend strip with the same marker icons as the tabs. Its groups wrap into balanced rows. It lists only the classes that some projection shows.
- The grid of square projections. **Auto (scrolls)** chooses the column count from the panel size and scrolls when a tile would get too small to read.
  **All at once** shows every projection without scrolling. When every projection fits at a readable size, the two choose the same grid.
  A fixed count, such as **3 per row**, places exactly that many projections per row.
  All these layouts use at most `maximum_number_of_plots_per_row` columns (the workbook uses the same name),
  so N is the smaller of this maximum and the number of projections. A session with many projections therefore does not get a long list of narrow layouts.
- **Matrix view** shows every ordered pair of design variables as a scatterplot matrix. Row i holds variable i on the vertical axis,
  column j holds variable j on the horizontal axis. The grid therefore has one row and one column per variable, whatever the configured
  maximum, and the projections of one row or one column share an axis at the same scale. Only the leftmost projection of a row repeats the
  vertical axis name. A saved matrix shows the horizontal axis names in its bottom row only; the window grid scrolls, so it keeps them on
  every tile.
  The lower triangle shows the samples; the upper triangle shows the class shares of the same pairs in cells, as **Show: Class shares** does, so no tile repeats another with the axes swapped.
  Each diagonal tile shows the class share along its variable: for each interval of the variable, the share of valid (good) samples, of each
  violated requirement, of physically infeasible, and of rejected samples, as stacked areas from 0 to 100 %, with the box bounds as black lines.
  The tile counts the samples of its column whose other plotted variable lies inside the box, so every counted sample has all other variables
  inside the box. It shows where along the variable each requirement starts to fail, and so which bound it limits. An interval with fewer than
  five samples shows no share.
  When the view opens, a background job evaluates the pairs that the shown projections lack. With `reuse_transposed_pair_samples`
  (on by default; the workbook uses the same name), a pair (b, a) shows the samples of the pair (a, b) with the axes swapped, so each unordered pair is evaluated once.
  When the shown projections hold every pair or its transpose, the view opens without new samples.
  Another layout returns to the earlier projections: the same samples while they are current, or else the matrix samples of the same pairs.
  Outdated samples stay outdated and the notice says so; a view change evaluates only pairs that no retained result holds.
  While a job runs, the change between the two views waits. A save exports what is shown: the matrix figure, with the legend in a column at its right, and every shown pair in the table and the archive.
  `initial_view` (`normal`, the default, or `matrix`; the workbook uses the same name) selects the first view, so a session that starts in the matrix view evaluates its pairs once.
  While a job runs, a pale layer dims the plots; the notice states that they show the previous result.

The lower row holds these controls:

- The status area shows the outcome of the last operation, and during a job its progress. The application opens no outcome dialogs.
- **Samples per projection** sets the samples of each projection. An empty field selects the automatic count. With stored data, **Data points: N** replaces it.
- **Update Options** (model sources only) chooses how Update Plot computes.
  **Reuse unchanged projections after a bound edit** (default off) copies each projection whose sampling box did not change, instead of drawing and evaluating it again.
  A projection samples its two variables over the design space, so a box edit of a shown variable leaves it unchanged.
  Turn it on only when the model responses do not depend on the bounds. Copied projections keep their earlier samples, so a seeded update differs from a full update.
  **Evaluate all projections in shared batches** (default off) evaluates the samples of all projections in batches that span projections, so a model with a notable cost per call gets fewer calls.
  Turn it on only when the result of a sample does not depend on the other samples of its batch.
- **Relabel** (model sources only) labels the shown samples again after a limit edit or an Apply limits toggle, without a model run.
  The samples and the model evaluation counts stay those of the last update. A limit edit needs a model that returns raw measures. Any other edit needs Update Plot.
- **Update Plot (U)** evaluates the current inputs. **Optimize (O)** optimizes the box. **Cancel (Esc)** requests that a running job stops.
- **Save (S)** writes the exports in a background job; see [Saving from the window](#saving-from-the-window). It is disabled, with the reason in its tooltip, while a save cannot succeed: during a job, while the plot does not show the current inputs, or while a stored optimization result is out of date.
  The S key then writes the reason to the status as a warning.

After a plot update, the status states how many shown samples inside the solution box are valid, summed over all projections.
This count is sampled evidence. It is not a proof that every design in the box is valid.

Each projection holds two box outlines:

- The solid black box is the solution box of the shown samples (points, for stored rows): the box at the last plot update. The shown samples describe this box.
- The dashed box is the current solution box. Drag one of its edges to move that bound. The full-length line of a bound shows while you drag it.

The two outlines separate when you move a bound. This shows that the samples do not describe the current box.
The black outline is wider, so it shows in the gaps of the dashes, and the two outlines read as one dashed line when the boxes match.
A moved side of the dashed box has a white halo, so it stays visible over dense samples.
A saved figure always shows current evidence, so its two boxes match; it draws the solid box alone.

The title of each projection counts the samples inside the solid box and how many of them are good, with the whole-percent share, for example **Solid box: 57 of 256 good (22 %)** (valid, when the problem has physical feasibility requirements).
A partial share never reads 0 or 100 %; it reads <1 % or >99 %. A title shrinks to fit a narrow tile.
The other variables of every sample already lie inside the box, so these samples estimate the share of good designs in the box. They are evidence, not a proof.
Stored-row titles count the shown rows instead: every stored projection holds the same rows inside the box, so a line below the window legend and the note of a saved figure state that count once.
The note of a saved figure also states that samples are evidence, not proof, and in how many projections samples that are not good remain inside a box that comes from a box optimization.

**Show: Class shares** replaces the markers with shares. Each projection is divided into cells, 5 to 24 per axis, so that a cell holds about 100 samples and the sampling noise of a share stays below the width of a shade level; the box holds up to 6 cells per axis: the finest of 6 to 2 for which a cell of every projection keeps about 50 samples, one value for the whole figure, so the tiles compare cell for cell (a coarser grid has more support and less spatial detail), and the note states the mean count per cell. The legend lists all share levels, so the scale reads the same in every figure.
The bounds of the box of the shown samples are cell edges, so a cell lies either inside or outside the box.
Each cell has one of six shades of green by the share of its good samples: 100 % (the full good color), 75 to under 100 %, 50 to under 75 %, 25 to under 50 %, above 0 and under 25 %, or 0 % (white).
In every cell that is not all good, a hatch shows the most frequent failure (pale, at a low contrast, where at least half are good, so the green shade stays the main signal): each requirement has its own hatch in its color, and physical infeasibility has small circles, the area version of the open ring.
A sample that is physically infeasible and also bad counts as infeasible, and the legend says so. A failure counts as the most frequent only when its count a leads the next count b by at least 2√(a + b), about two standard deviations of their difference; otherwise the cell shows one small gray cross (6 pt, at most half the cell) at its center ("Unclear: two failures nearly tied"), so a near tie that a new sample could flip draws no false pattern. A cell with one failure kind shows that failure.
A cell with fewer than five samples is plain gray, so it differs from a cell with no good sample. The note states the mean number of samples per cell.
In a narrow tile, the projection titles shorten their "Solid box:" prefix to "Solid:" before they shrink below 8.5 pt ("Solid: 1,452 of 7,483 good (19 %)"); in the narrowest tiles, such as the matrix window, they show the share alone ("Solid: 19 % good").
The legend lists only the shades and the failures that the projections show.
Use it for dense data, where markers cover one another and their shapes cannot be read. It shows no single sample; **Samples** shows those. A save exports the shown display.
A gray band outside the white design space shows where no sample can lie, so a bound at the edge of the design space stays visible.
Large values use prefixes, such as `250k` and `1M`, on the axes and on the sliders, which share their tick positions.
Each violated requirement has its own filled marker shape (an upward triangle, a square, a downward triangle, a diamond, a cross, then a plus) as well as its own color, so the classes stay distinct without color.
Filled shapes keep their outline at small sizes, where the strokes of a thin cross would merge into a dot. A triangle and a square come first, because their corners stay visible at a few pixels.
Good-design dots and requirement shapes have a thin edge in a darker shade of their own color.
The classes have about the same marker area, so no class looks more frequent only because its marker is larger.
A projection with many samples draws its classes in up to 16 interleaved layers, so in a crowded region each class shows about in proportion to its sample count.
Inside one layer, the valid samples lie lowest, so a region that holds bad designs never looks good.
When the box of the shown samples holds only a few samples that are not good (at most 10, or 5 % of its samples), they lie above all good samples and above the box outlines, at 2.5 times the normal marker area whatever the marker size, with a thicker edge, so a single bad sample in a nearly clean box stays visible, also on a box edge.
More such samples stay in the interleaved layers, so a mixed box keeps its proportions and shows no false edge at its outline.
The one common bad class of `marker_colors_criterion=None` is a diamond.
The **Auto** marker size compares the summed area of the normal markers of a projection with its plot area (the coverage).
Above 35 %, it shrinks the markers until they cover 35 % of the plot area again, down to 0.45 times the normal area while shapes can be read, or down to the tiny size when the coverage is above 2.5, so a small window tile and a large export tile show about the same density; tiny markers with thin edges show the share of each class as a fine texture.
Below 8 %, for example on the large tile of the single-projection view, it draws large markers; otherwise normal markers.
The rule uses the tile size and the number of samples. Auto applies the factor of the densest projection to every projection, so one class has one marker size in the whole figure. It changes only the display: every sample stays drawn.
A long axis, as in the single-projection view, uses up to 10 round tick intervals.

### Editing values

- A field applies its value when you press Enter or leave the field.
- Fields show the shortest decimal text that converts back to exactly the same number, so a field never rounds a value.
  A field without the focus whose text is too long shows a shortened text with "…": its sign, its leading digits, and always its exponent, for example `1.234567890123…e-05`.
  Its tooltip then adds the full value, and the focused field shows all digits.
- A box bound outside its allowed interval moves to the nearest end of that interval. The status reports `Input adjusted` as a warning.
- A design-space bound that excludes part of the box also moves the box bound.
- Rejected text returns to the accepted value. The status reports `Invalid input` as an error, names the field, and states the value that the field keeps.
  A solid red border and an error symbol mark the field until the next accepted edit or plot update.
  While the mark stays, every later status message ends with a line that names the field and the value that it keeps.
- An accepted edit appears in the status, for example `Changed F₁ solution-box upper bound. Save needs a plot update first.`
- A bound field that differs from the bounds of the shown samples has an amber background and a dashed border.
  A **↶** button at the end of its row label restores both bounds of that row.
  The field's context menu offers **Revert to Value at Last Plot Update** for that one bound. **Revert Box** reverts every bound at once.
- A pointer that rests on a control shows its explanation.
- Raw-measure callables and response methods permit quantity-limit edits.
  An `evaluate` method supplies normalized deficits and controls its own conversion limits, so the limit fields are then disabled.

A range slider also works with the keyboard.
Tab moves the focus from the lower handle to the upper handle.
The arrow keys move the focused handle by one hundredth of the track, Page Up and Page Down by one tenth, and Home and End to a limit.

Dragging a box edge and moving a slider handle redraw only the box lines of the projections that show the moved variable, so these actions stay fast with many samples.
The pointer shape shows when a press would grab a line. A press within 8 pixels grabs a line, even when its highlight is thinner.

Main keyboard shortcuts:

| Key | Action |
| --- | --- |
| U | Update Plot |
| O | Optimize |
| S | Save |
| Escape | Cancel |
| T | Hide or show the tabs |
| I | Open the Inspect tab |
| Ctrl+arrow keys | On Inspect, select the nearest sample in that direction; without a selection, select the sample nearest to the box center |

A text field that has the focus receives letter keys first, so typing never starts a command.
After the focus moves by the keyboard, the focused control has a 2-pixel blue ring; a mouse click hides it.
A focused slider handle and a focused tab get their own ring. While a job runs, the focus waits on **Cancel**, and afterwards it returns.

### Inspect a sample

Open the **Inspect** tab, then click a projection to inspect the nearest sample.
On the other tabs, a press on a projection can only start a bound drag, so one press has one meaning.
A black ring marks the selected design in every projection. Saved images omit it.
**Clear Selection** removes it. The arrow buttons and Ctrl+arrow keys select the nearest sample in one direction, so a sample can be selected without a mouse.

The tab shows:

- the projection where the sample was selected, and its class with the marker of that class;
- all design values, with units, aligned on the decimal point;
- all quantity values, with units for raw measures, and for each applied quantity whether the value meets its limits;
- the **Model response** of the selected design, separate from its **Physical feasibility**, each with a short explanation.

Rules for the displayed values:

- Raw measures use their configured units.
  Normalized deficits are dimensionless, because their conversion removes physical units. Their values therefore carry the prefix `Deficit (dimensionless):`.
- Model response is `available` or `rejected`.
  It is `unavailable` when rejection evidence is absent.
  A positive infinite deficit means that the model rejected the design.
- Physical feasibility is `feasible` when every physical deficit is at or below zero. Otherwise it is `infeasible`.
  It is `not required` when no physical deficit column exists.
  It is `unavailable` for a model rejection or missing evidence.

Nearest-sample selection:

- It uses cached quantities and does not evaluate the model again.
- It divides coordinate differences by the shown axis span of each variable before it measures distance.
  A variable with larger units therefore cannot dominate the choice.
  The axes keep the design space of their last draw, so a design-space edit changes this measure only after the next draw.
- It requires no active model job, and no input edit other than a bound since the last plot update.
  A moved bound keeps selection available: the bounds decide only where samples are drawn, so each shown sample still holds the model values of its design.
  An edit of a parameter, a limit, or a requirement can change those values, so selection waits for **Update Plot**.
- Replacing projections clears the previous selected design and its quantities.
- `runtime.selected_values` exposes complete selected designs.
  `runtime.selected_quantities` exposes their raw and effective quantity arrays.
  The returned design and the design of each observer are independent copies.

### Freshness of results

- Before a replacement, an input edit makes the retained projections historical.
  An edit other than a bound also makes the selection historical, because it can change the values of the selected design.
- `runtime.result_configuration_status("projection")` reports the input freshness of the projections.
- A persistent notice above the projections states whether inputs changed since the last plot update.
  After a change, it directs the user to **Update Plot**. The check compares input values,
  so an edit followed by its reverse, for example with ↶ or **Revert Box**, makes the plot current again.
  An unchanged opaque model carries a warning that hidden model changes cannot be checked.
  The notice stays separate from the outcome of the last operation.

### Editing, updating, and discarding

- Field edits, moved sliders, dragged bounds, and requirement toggles do not evaluate the model.
  They leave the retained evidence historical.
  Press **Update Plot** to compute projections from the edited inputs.
- In model mode, the window keeps an edit of the samples per plot, or of the pairs, that exceeds the 2,000,000 total-sample rule.
  **Update Plot** then rejects the work before any sample is drawn.
  The status area and `last_error` show the error.
  Reduce the pairs or the samples per plot, and evaluate again.
- Changes to the save path and to violation colors require no model evaluation.
- A window keeps the model or stored-data source mode that it opened with.
  Open a new controller to change the source mode.
  A rejected mode change leaves input edits unapplied.
- After optimization, editing, and refresh, **Discard Optimization Result** removes obsolete optimization evidence.
  It keeps the edited box and the current projections.
  Its tooltip explains this before use. The button is disabled while no result exists.
  The method `discard_optimization()` reports `Nothing discarded` as a warning when no result exists.
- Projection table exports require current projections.
  Combined archives also require any retained optimization result to be current.

## Figures and exports

The window draws each projection with `designoptpy.sso.plotting.plot_projection`, so it shows the sample categories of the library plots.
Axis labels use 12 points from the first draw, unless `axis_labels_options` overrides the size.

The sample categories, with their default marks, are:

- physically infeasible samples: open rings in a darker red, larger than the requirement shapes;
- samples that violate a requirement: a filled shape per requirement, in its quantity color;
- model-rejected samples: dark gray open squares;
- valid samples: green filled circles.

Green means good and red means bad, as in every DesignOptPy figure.
A sample that is physically infeasible and also violates a requirement shows its requirement shape inside the ring.

A valid design is good and physically feasible.
A good design meets every performance requirement.
The legend of the valid category reads "Good design" when the problem has no physical feasibility requirement.
The domain plot options style the categories. Model-rejected samples use `plot_options_bad`.
The requirement colors come from the violation indices that the session computed with `marker_colors_criterion`.
A redraw therefore never recolors samples.
With `marker_colors_criterion=None`, every bad sample has one common color.

`XRayController.save` creates a timestamped folder containing:

- `projections.png`, the combined projection figure. A save adds the legend as the first tile, or beside the projections when they fit in one row, so the image explains its marks. In the matrix view, the legend takes a column at the right. A legend entry shows the ring around a requirement shape when a sample is physically infeasible and also bad. A save needs current evidence, so the two box outlines lie on each other; the image draws the solid box alone, and the legend shows it once as the solution box of the shown samples (or points). The last legend entry states the result: the count of stored rows inside the box in every variable; for a box from an optimization, how many samples inside it are not good and in how many projections; otherwise the count of good samples inside the box pooled over the projections (each such sample is a uniform sample of the box; a transposed pair that reuses the samples of its pair counts once). A gray note in a band below the projections states what each projection samples and which violated requirement a bad sample shows.
- One Portable Network Graphics (PNG) image per projection axes, at 300 dots per inch (dpi) by default.
- `results.csv`, a comma-separated values (CSV) table with one row per sample.
  Its classification is `Valid`, `Bad`, `PhysicallyInfeasible`, or `Rejected`.
  A heading that starts with a formula character, such as `=`, `+`, `-`, or `@`, receives an apostrophe prefix.
  Spreadsheet programs then show it as text and do not run it as a formula.
- `data.npz`, a NumPy archive with bounds, projection samples, labels, deficits, and any retained box-optimization result.
  A stored-data session writes its observations and their labels once, and each panel as its source row indices.

Use `designoptpy.sso.xray.XRaySession.export_npz` and `export_results_table` for numeric exports without the graphical user interface (GUI).
A full repository checkout includes `designoptpy/examples/application_examples/xray_session.py` with workbook and export examples.
The application distribution does not include those scripts or workbooks.

### Controller structure

- The controller keeps the `window`, the `figure`, the projection `axes`, and the `legend_axes`.
  The window shows the legend in its own strip. The `legend_axes` hold the same legend for a save, which shows them as a tile.
  `window` and `figure` raise `RuntimeError` after `close()`. The other handles are then empty or `None`.
- `XRayWindow` holds the Qt controls and reports each edit through a signal. It contains no model logic.
- The controller validates each edit, installs accepted records, and chooses whether to submit new model work.
- An export-folder context owns staged files.
  It renames them into the destination when every writer finished, and it removes failures.
- The controller retains figure rendering and the selection of scientific output files.
  It creates and closes the window. This responsibility is resource ownership.

### Render policy and limits

- Pass `XRayRenderPolicy` as `render_policy` to `create_xray_gui` to set the tile size of a hidden window.
  It also sets the window and export resolutions in dots per inch (dpi).
  A shown window sets its canvas size from the available space.
- The policy validates each canvas size and resolution before drawing or saving.
  `save` checks every export image before it writes the first file.
- `last_render_plan` records the bytes of one raster buffer of the window canvas.
  A raster buffer stores image pixels before display or export.
- No panel, raster, memory, or byte limit applies.
- Model projection requests admit at most 2,000,000 total samples. Stored-data requests have no row cap.
- A canvas or export that does not fit in memory raises the Matplotlib error or `MemoryError`.

## Window design and input limits

- The window has configuration tabs, projections, and a status row.
  It uses Qt controls, including the legend strip, and one Matplotlib canvas for the projections.
  It offers the Inspect class and limit states, the single-projection view, the layout and marker-size choices, Revert Box, and field marks.
- The application evaluates on a background worker, so the window stays responsive. **Cancel** and the keyboard shortcuts control the worker.
- Fields show the shortest text that reads back as the exact stored number.
- The slider and a dragged line update the box and its fields while they move.
- The bound hit test uses the `patch_relative_width` option of the domain, with a minimum of 8 pixels, so a thin line stays usable on small axes.
  `patch_options` supplies Matplotlib `Patch` keywords for the bound highlight patches.
- A save writes PNG images, a CSV table, and an NPZ archive.
- The workbook reader limits untrusted input files.
  The limits are `XRayResourceLimits.maximum_sheets` (16), `maximum_theme_bytes` (1 MiB), and the shared `designoptpy.core.InputLimits`.
  The reader applies them before it reads worksheet data.
  They validate the input for the OpenPyXL, python-calamine, and `defusedxml` parsing for security. They are not resource caps on the work.
  An `.ods` workbook passes the OpenDocument preflight of `designoptpy.core.io`, which checks every sheet before python-calamine parses it.
- To accept a larger workbook or a longer job, pass a larger `XRayResourceLimits` or `InputLimits` value directly.
  No confirmation text or trusted destination is required.

The [engine resource limits](../../packages/designoptpy-sso/README.md#resource-limits-and-trust) list every limit and its default.

## Engine results and recorded evidence

The controller computes results through the engine functions `compute_projections` and `compute_optimization`.
It applies them with `commit_result`.
`commit_result` rejects a result from another domain, revision, or declared model input.
A direct domain edit during a job makes its result obsolete.
The controller then discards that result and reports it in the status.
Changing the bound domain clears old samples, so they cannot be used with a different domain.

Before combining results, projection batches validate every raw measure and deficit array.
Each array must agree across batches in its column count and element type.
Each row belongs to one design sample.
This required column-and-type layout is the output schema.

Session NPZ exports preserve these items:

- raw measures and deficits;
- normalization and range metadata;
- a versioned JavaScript Object Notation (JSON) record.

The record separates resolved operation inputs, completion details, effective work plans, and initial random number generator (RNG) states from domain defaults.
The recorded inputs and producing configuration describe how results arose. This is provenance.
Provenance cannot verify hidden state inside caller-supplied model functions.
