designoptpy-sso
This package provides DesignOptPy Solution Space Optimization (SSO), product-family design, and Box X-Ray computation.
SSO searches for acceptable design regions using random samples, growth, and trimming.
Product-family design groups variants that can share a verified component design.
Box X-Ray displays two selected variables and sampled requirement results.
This package has its own installation and version. Import it through designoptpy.sso.
- After publication, install it with
python -m pip install designoptpy-sso. - In the source workspace, run
uv sync --package designoptpy-sso. - For the complete package family, including X-Ray and optional workbook and palette support, install
designoptpy.
See the workspace documentation for development and release procedures.
Evaluators and mappings return the result forms of the core result contract.
DesignEvaluator is the core protocol. Import it, DesignEvaluation, RequirementSpace, and the other shared result records from designoptpy.core, and Box from designoptpy.core.geometry.
designoptpy.sso does not repeat these core names, so each object has one import path.
Importing designoptpy.sso imports every listed name directly. This is an eager import, and it does not import Matplotlib.
It also loads no SciPy module: a function that needs SciPy, such as a linear program, a hull, a distance, or a local solve, imports it on its first call.
SciPy is a required dependency, so this changes only when its import cost is paid.
Python imports a package before its submodules, so an import of any designoptpy.sso submodule, such as designoptpy.sso.xray, also runs this eager import.
Import plots from designoptpy.sso.plotting and designoptpy.sso.batch_plotting, and the Box X-Ray engine from designoptpy.sso.xray.
GeometryWorkPolicy is defined in designoptpy.sso.geometry_policy; the package root also lists it.
Method: grow and trim a box of acceptable designs
optimize_box(evaluator, initial_box, design_space, *, options=None, rng=None) returns a BoxOptimizationResult.
options=None selects BoxSsoOptions().
Its candidate_box is a box of designs that the sampled evidence labels acceptable.
The initial box can be one feasible design. The design_space box bounds all growth.
Random numbers:
- The
rngkeyword is the only source of randomness: a NumPyGenerator, an integer seed, orNone.numpy.random.default_rngconverts it once. - The options hold no random state.
- The result records
initial_rng_state, the generator state before the first draw, so a run can be replayed. - The other SSO entry points with an
rngparameter accept the same three forms. Examples areoptimize_components, the batch runners, the random product-family searches (random_compatible_groupsand the metaheuristic), and the X-Ray session methods. - The samplers and strategy callbacks that a run calls with its own generator require a Generator:
sample_all_feasible,sample_individual_feasible,sample_set_hit_and_run,uniform_grouping_sampler, and the protocol callbacks.
Each iteration performs these steps:
- In the exploration phase, the iteration grows the candidate box. Each face of variable
jmoves outward byg * (U_j - L_j). Heregis the growth rate and[L_j, U_j]is the design-space interval. The iteration clips the result to the design space. - It draws
number_samplesdesigns uniformly inside the candidate box and evaluates their requirement deficits. - It labels each row acceptable and useful under the selected requirement space (see below).
- It trims the box: faces move until the rejected rows are outside, while viable rows stay protected.
- In exploration, it updates the growth rate once per batch. A rolled-back batch reduces the rate. An accepted batch adapts it from the observed purity and the growth in geometric volume.
The consolidation phase repeats steps 2 to 4 without growth, so trimming can make the sampled box pure. By default, each phase runs a fixed number of iterations (see Convergence and stopping).
Measures used in trimming:
- Purity is the fraction of evaluated rows that are acceptable:
p = n_acceptable / n. - The default box measure is
mu(B) = f_useful * prod_j (u_j - l_j), wheref_useful = n_useful / n. - Trimming selects the candidate box with the largest measure.
- A new face lies between the nearest viable coordinate
vand the removed coordinater, atv + s * (r - v). The slacksistrimming_slack, default 0.5.
Theory: growth moves the boundary toward unexplored designs, and trimming removes the sampled evidence of violation. Alternating them approximates the largest acceptable box near the seed. The search uses only finite samples. It cannot prove that every design inside the returned box is acceptable.
Worked example
The requirement is x1**2 + x2**2 <= 1.
The largest centered square inside the unit disk has half-width 1/sqrt(2), about 0.707, and area 2.
import numpy as np
from designoptpy.core.geometry import Box
from designoptpy.sso import BoxSsoOptions, MappingEvaluator, optimize_box
evaluator = MappingEvaluator(
lambda designs: np.sum(designs**2, axis=1, keepdims=True),
performance_upper=1.0,
)
result = optimize_box(
evaluator,
np.zeros(2),
Box(np.array([-1.5, -1.5]), np.array([1.5, 1.5])),
options=BoxSsoOptions(number_samples=100),
rng=np.random.default_rng(7),
)
box = result.candidate_box
check = np.random.default_rng(99).uniform(box.lower, box.upper, size=(10_000, 2))
print(
result.termination_reason.value, round(result.final_measure, 2)
) # consolidation-complete 2.09
print(np.mean(np.sum(check**2, axis=1) <= 1.0)) # 0.999
The returned area is close to the analytic value 2.
It is slightly larger, because 100 samples per iteration rarely fall in the thin violating corners.
consolidation-complete states that the last consolidation batch was fully acceptable; it is a sampled certificate, not a proof.
The independent check estimates that 99.9% of the box satisfies the requirement.
Always validate a returned region with separate samples before relying on it.
estimate_solution_space_purity performs this check and adds a 95 percent Wilson interval (see Independent purity estimate).
Tutorial 02 runs a similar search with retained samples.
Component solution spaces
optimize_components(evaluator, initial_design, design_space, component_layout, *, options=None, rng=None) returns one region per component.
options=None selects ComponentSsoOptions().
A component is a group of design variables that one team or part owns.
The full design is acceptable only if it lies in every component region; the set of such designs is the Cartesian product of the regions.
ComponentLayout maps each component's local coordinates to zero-based full-design indices.
Component lists must be disjoint and must cover every variable.
from functools import partial
from designoptpy.sso import ComponentSsoOptions
from designoptpy.sso.regions import (
ComponentLayout,
CornerRemovalRegion,
PlanarRegion,
PlanarTrimmingOptions,
)
layout = ComponentLayout(([0, 1], [2]), dimension=3)
options = ComponentSsoOptions(
candidate_factories=(
partial(PlanarRegion, trimming_options=PlanarTrimmingOptions(trimming_slack=0.25)),
CornerRemovalRegion,
),
)
Pass layout and options to optimize_components.
The initial design can be a full-design point, a box, or one candidate region per component.
candidate_factories takes one factory for all components or a tuple with one factory per component.
Each factory receives the component's domain Box. The returned region then runs initialize_from_box(initial_box).
Without factories, each component uses PlanarRegion. Prebuilt regions keep their own shape and configuration.
Each region owns its trimming options; bind them with functools.partial, as above.
Tutorial 09 runs a complete component search.
The example component_ball_volume_fraction.py computes the fraction of a ball that a product of equal component balls keeps, by dimension and component count.
Evaluators and requirement spaces
Each optimizer consumes the DesignEvaluator protocol: an object with evaluate(samples) that returns deficits.
A deficit at or below zero satisfies a requirement. A positive deficit violates it.
These adapters implement the protocol:
MappingEvaluatorconverts the raw measures of a core mapping into deficits with inclusive limits. Its default limits are(-inf, 0].MeasureDeficitOptionssets normalization and weights for each group. Automatic normalization factors come from the limits only, so a design gets the same deficit in every batch and X-Ray chunk. The record has no observed-normalization switch. When the limits give no useful scale, pass explicitnormalization_factorvalues, for example frommeasure_normalization_factoron a reference batch. Construction converts a zero-row batch of each group with its limits, factors, and weights, so an invalid setting raisesValueErrorbefore any mapping work.FastForwardEvaluatorapplies the same check.FastForwardEvaluatorreplaces the mapping with fitted surrogate models. It composesdesignoptpy.core.SurrogateMappingwithMappingEvaluator. Without a model, it repeats a configured default deficit row.performance_trusted_rangeandphysical_trusted_rangeare explicit(2, n)design boxes[lower; upper],Noneby default. A design outside a box never reaches that model, so a model that fails outside its range cannot stop the batch. Such a row gets+infin every deficit column of its group, and*_prediction_range_validin the metadata marks the in-range rows. TheSurrogateMappingdocumentation gives the recipe for the box of the training designs that satisfy the limits. The box screens prediction range; it does not certify accuracy. A range needs the model of its group, because a default deficit has no prediction to restrict: a range without its model raisesValueError("performance_trusted_range requires a performance model")orValueError("physical_trusted_range requires a physical model")at construction.MultiFidelityEvaluatorevaluates a fast model and sends selected rows to an expensive model.CompensationEvaluatoroptimizes compensating variables for each fixed design.
A requirement space is a named Boolean rule for acceptable and useful labels. Let G mean good performance: every performance deficit is at or below zero. Let F mean physical feasibility: every physical deficit is at or below zero. A group with zero columns is satisfied.
| Requirement space | Acceptable | Useful |
|---|---|---|
| Omega0 | G | True |
| Omega1 | G and F | True |
| Omega2 (default) | G | F |
| Omega3 | G or not F | F |
Acceptance controls purity and which rows cause trimming. Usefulness controls the useful fraction in the box measure.
A lean box without a row has no useful fraction, so BoxSsoOptions.measure receives None, and the default measure is unweighted. No rows give no information, and a zero would state an empty box.
Omega1 can reject a performance-good but physically infeasible row.
Under Omega2, such a row counts toward purity but is not useful.
Omega3 labels a physically infeasible row acceptable, so its performance cannot force trimming; the row stays not useful.
Choose the rule that matches the scientific meaning of the requirements.
CommonSsoOptions.performance_scoring takes a core DeficitScoringPolicy. It ranks rows by performance; the same policy works in label_evaluation and score_threshold_decision.
Scorer weights and options change the ranking of rows. Labels still come from the deficit signs, even if a custom score changes its sign.
The physical feasibility label needs no score: a row is physically feasible when every physical deficit is at or below zero (designoptpy.core.deficit_labels).
So the run options, label_evaluation, and the projection functions take no physical scoring policy. score_threshold_decision keeps its physical scoring, because it compares physical scores with thresholds.
Multifidelity selection and calibration decisions
MultiFidelityEvaluator evaluates every row with the low-fidelity model, then replaces the selected rows with high-fidelity results.
Both models must return the same number of columns in each requirement group.
A row is selected when the decision selects it or when any of its low-fidelity deficits is +inf.
+inf is the rejection signal of an evaluator: the row has no usable estimate, for example outside the trusted range of a FastForwardEvaluator.
Such a row gives no evidence about the system, so the high-fidelity model decides it.
This rule can add high-fidelity model rows beyond the rows that the decision selects.
MultiFidelityEvaluationMetadata.is_uncertain marks every row that high fidelity evaluated.
An empty batch calls the low-fidelity model with zero rows and calls neither the decision nor the high-fidelity model.
Unused high-fidelity metadata remains None.
The evaluator always calls the decision as decision(samples, low_evaluation).
A decision can therefore use the design values as well as the low-fidelity deficits.
score_threshold_decision(samples, evaluation, ...) uses only the scores and ignores the sample values.
Bind its options with functools.partial(score_threshold_decision, performance_threshold=0.15).
Pass calibration statuses to score_threshold_decision through performance_calibration_status and physical_calibration_status.
An unavailable threshold without a status disables that group.
NoErrorsObserved uses the conservative policy by default and selects every row for high-fidelity evaluation.
An empirical no-error policy requires a separately chosen explicit score interval.
InsufficientEvidence also selects every row. ObservedErrors requires its calibrated interval.
No observed error does not establish accuracy for untested designs.
Compensation
CompensationEvaluator splits the design with a Boolean a_space_mask.
A-space variables are fixed choices that the caller supplies. B-space variables are optimized for each A-space row.
The example compensation_evaluation_order.py draws the order in which the evaluator visits the A-space designs and the evaluated design that gives the next one its warm start.
Start order:
- For each A row, the evaluator builds B starts in this order: nearby cached designs, the current sample, the given start, the additional starts, then the B-space center.
- The generic bound center is the last fallback, after every start that carries problem knowledge.
- By default, the evaluator stops at the first start that satisfies performance and physical requirements, so the start order can decide the returned design.
- Otherwise, it runs at most
maximum_optimizationssolver starts and stops at the first satisfying result. - The default solver,
scipy_compensation_optimizer, is a local search. A returned violation means the search found no satisfying compensation. It does not prove that none exists. In this role, DesignOptRs uses a native algorithm: sequential quadratic programming (SequentialCompensationOptimizer).
Warm starts and reuse:
precomputed_optimal_samplesupplies nearby B coordinates as warm starts.- The evaluator evaluates each reused B design again at the current A row. Proximity does not prove satisfaction.
- Within one A row, identical B designs reuse their saved evaluation. This reuse is memoization.
noisy_repeats=Truerequests fresh evaluations of repeated starts.- Within one solve,
scipy_compensation_optimizerreuses the evaluation of every point that it already evaluated. The reuse assumes a deterministic model;noisy_repeats=Trueturns it off. scipy_compensation_optimizer(maximum_evaluations=N)caps the calls ofevaluate_b_spacein one solve, throughoptimizer_optionsof the evaluator. An exhausted allowance stops SciPy and returns the best evaluated design (feasible first); it does not prove that no compensation exists.start_batch_row_metadata, a per-row metadata adapter(batch_metadata, row) -> row_metadata, evaluates all starts of one A row in one base-evaluator call whendo_not_optimize_if_initial_is_valid=False. The defaultNonekeeps one call per start. The adapter requires a row-independent base evaluator. Then the selected designs andnumber_of_evaluationsstay the same, and only the number of base-evaluator calls drops.
Bounds and A-space settings:
- Full-design bounds also constrain the A coordinates, and the evaluator rejects outside A rows before model work.
- Full-design
b_space_initial_designandcomponent_indexare split by the same mask. a_space_lower_bound,a_space_upper_bound,a_space_initial_design, anda_space_component_indexthen configure a component SSO run in A space.- Empty batches keep the declared
requirement_widths=(performance_width, physical_width)or the widths of an earlier call. An unknown width raisesValueErrorthat namesrequirement_widths.
Nearby-witness search:
maximum_a_space_path_startscaps the path starting rows at 256 by default.- With
a_space_normalize_dimensions=True, the default, the visit order and the nearby-witness ranking both use unit coordinates. A variable in large units therefore cannot dominate "nearby". - The witness ranking uses one box per call: the declared A-space bounds when full-design bounds exist, otherwise the range of the batch rows and the initial cached rows. A fixed dimension of that box, with equal bounds, gives every row the same coordinate, so it adds no distance.
- A missing
VorVIofa_space_distance_metricis estimated from the searched set: the normalized batch rows for the visit order, and the stored witnesses for each witness ranking. A singular, nonfinite, or ill-conditioned estimate raisesValueError. In that case, supplyVorVI, or choose an explicit metric, such as"euclidean".
Cached designs:
maximum_cached_designscaps the rows of the persisted nearest-start store. The cap applies once, whenappend_new_closest=Truepersists the store after a call.- Before the cap, repeatable mode removes repeated rows from the persisted store and keeps the first of equal rows. During a call, the store keeps every accepted row.
- The default
Nonekeeps every row. A finite cap reduces memory and distance work, at a possible cost in later search quality.
Custom optimizer:
CompensationEvaluatoralways callsoptimizer(evaluate_b_space, initial_design, lower_bound, upper_bound, scoring=..., noisy_repeats=..., **optimizer_options).- A custom optimizer must accept the two keywords
scoringandnoisy_repeats.optimizer_optionscannot contain them. - The evaluator evaluates every returned design again through
evaluate_b_space, so a returned deficit always comes from the base evaluator. - A repeatable design that the optimizer already evaluated through
evaluate_b_spacereuses that evaluation without new model work.
Evaluation cost diagnostics
Logical SSO budgets count requested designs. A composite evaluator can evaluate several model rows for one requested design.
CompensationEvaluationMetadata.number_of_evaluations records the base-evaluator rows used for each A-space design.
termination records why each search ended: valid_start, valid_refinement, refinement_limit, or starts_exhausted. A bounded miss does not prove that compensation is impossible.
attempted_starts, attempted_refinements, skipped_starts, and skipped_refinements record the work of each A-space row.
MultiFidelityEvaluationMetadata.is_uncertain identifies the rows evaluated by the high-fidelity model.
save_evaluation_metadata=True retains this metadata in each SSO iteration's evaluation_metadata field.
These records support later cost analysis without a shared ledger or an underlying-model row cap.
The total and phase evaluated-design budgets still limit the rows requested by SSO.
Nested evaluators retain their own cost evidence in their evaluation metadata.
Candidate geometry
The designoptpy.sso.regions regions are BoundingBoxRegion, ConvexHullRegion, CornerRemovalRegion, PlanarRegion, and AnalyticalRegion.
The CandidateRegion protocol provides bounds, sampling_box, membership_box, plot_envelope, measure, definition, classify, and expanded.
definition is the retained evidence: samples and their membership labels.
plot_envelope is the box that the candidate-space plotters cover (see Projections and plots).
membership_box is a box outside which classify accepts no point, or None when the region gives no such box.
Product-family searches intersect it with the declared domains bounds to prove that regions share no admissible design; component optimization does not read it.
A product's solution space lies inside its declared design space, so a shared design must lie in every member's bounds, also when classify accepts points outside them.
The proposal box sampling_box cannot give that proof, because a region can accept points outside it.
| Region | membership_box |
Reason |
|---|---|---|
BoundingBoxRegion |
fitted box, else bounds |
Classification is the exact inclusive box test. |
PlanarRegion, CornerRemovalRegion |
the envelope (sampling_bounds, else the inside-evidence box) |
The default classify(include_bounding_box=True) requires it. The tighter planar sampling_box is not used, because the plane tolerance can accept points outside it. |
ConvexHullRegion, fitted |
bounds |
The facet tolerance can accept points far outside the vertex box. |
ConvexHullRegion, unfitted |
sampling_box |
Classification is the inclusive test of the pending box. |
AnalyticalRegion |
sampling_box, or None with consider_sampling_box=False |
Without the box test, the score alone decides, also outside bounds. |
For a fitted hull, the facet tolerance acts near a sharp vertex over a long distance.
The triangle (0, 0), (1, 0.01), (1, -0.01) with classification_tolerance=1e-3 accepts (-0.05, 0), 50 times the tolerance outside its vertex box.
Component SSO also requires the TrimmableCandidateRegion methods initialize_from_box, propose_trimming, and apply_trimming.
propose_trimming(samples, remove_index, is_keep) returns a Boolean removal mask with one row per sample and one column per proposal.
Each column has an opaque description. Unless the region has exact proposal masks, the optimizer applies each proposal to a trial copy with apply_trimming(samples, is_inside, descriptions, trial=True) and ranks the copies.
It then applies the selected proposal again with trial=False.
A region with exact proposal masks is ranked from its masks, and the accepted cuts of the selected pass are applied in one update with trial=False.
A trial copy can skip work that changes membership at most within the region's own tolerance:
- Planar regions skip their detailed redundancy check.
- Built-in box regions keep the fitted box but skip the evidence record and its face-support rows, so a box trial copy has
definition=None. Box subclasses return the full result. - Hull and corner regions ignore
trial.
A custom region implements these methods to choose its own geometry. Component SSO checks these capabilities before any evaluator work.
A region initialized from a box is that box until evidence arrives, for every built-in representation.
- Its membership is the box.
- Its
measureis the exact box measure (zero for a flat box, such as a point seed). - Growth moves the box faces by
growth_ratetimes the domain widths, as a box region grows. BoundingBoxRegion.initialize_from_boxgenerates box geometry and evidence immediately.- Planar and corner regions store the box as their envelope
sampling_bounds, without evidence rows. - A convex hull stays pending without a fit. Its first update or trimming fits the new evidence merged with the
2**dbox corners as prior inside evidence, so labels that agree with the box never shrink it. That first fit reportsGeometryUnavailableErrorwithwork-limitstatus above 100,000 corners (more than 16 variables). - A region without an initial box, such as
PlanarRegion(bounds), classifies within its domain, and its measure remains unavailable asNone. Growth returns such a region unchanged, because the whole domain cannot grow.
A planar or corner region is the domain, an envelope box, and its cuts.
- The envelope is the explicit
sampling_bounds, or forgeneratedwithoutenvelopethe tight box of the in-domain rows that pass every cut. generatedwith neither an envelope nor such a row raisesValueError: negative evidence alone does not define a region, and the domain is not a substitute.update_candidate_spacekeeps the envelope of the region (itsmembership_box), so new rows can never enlarge the region. A planar update recomputes the tightenedsampling_boxfrom this envelope and the cuts, so membership never depends on the linear-program rounding ofsampling_box.- A pending region keeps its box as the envelope. A region without an initial box, such as
PlanarRegion(bounds), is generated from the new evidence instead. - Every evidence row gets the label of the default membership, so a row outside the envelope is labeled outside.
Evidence handling:
generatedreplaces geometry and retained evidence.update_candidate_spacekeeps only the coordinate extrema of the existing evidence, for all and for inside rows. It adds the new samples and the anchors of the cuts that remain after pruning (and, for corner regions, after anchor alignment).- Corner growth keeps the same in-domain extrema, the rows outside the domain, and both moved copies of every in-domain row. This rule keeps the evidence bounded.
- Measure estimates draw
measure_estimation_factorsamples per evidence row, so their cost stays bounded too.
Growth:
- Expansion grows the envelope by
grow_boxwithin the design domain, including an envelope initialized from a point. - Each evidence row in the domain moves away from the inside centroid (corner regions also add a copy moved toward it). The step stops at the first domain face along its ray, so the moved row stays on that ray.
- Rows outside the domain are negative observations and stay unchanged.
- Planar
plane-directiongrowth moves each anchor along the unit normal of its plane in unit-domain coordinates,w * widths. Every plane therefore moves outward by exactlygrowth_ratein domain fractions for any cut normalization.
Component optimization accepts planar, corner, bounding-box, and convex-hull candidate regions.
Analytical regions support controlled test examples using a caller-supplied score function. They do not support expansion, update, or trimming operations.
The score function must return real numbers.
A NaN, complex, or nonnumeric score raises ValueError, because it means a failed evaluation, not an outside design.
The values -inf and +inf remain valid inside and outside signals.
If consider_sampling_box=False, the analytical score alone determines membership, including outside the declared bounds.
Such a region has no membership box.
A read-only outer domain bounds all supported candidate growth.
Retained labels and geometry determine membership within that domain.
sampling_box_slack, default 0, sets the proposal box of bounding-box and hull regions. It does not change fitted membership.
Zero uses the tight box around inside evidence. One uses the relaxed evidence box, which need not reach the full domain.
Without evidence, one uses the outer bounds. A different proposal box can change sampling work and later trimming evidence.
Bounding-box and hull regions keep every evidence row by default, so their evidence grows with every update.
keep_only_defining_evidence=True makes each full update keep only the rows that define the fit:
the inside coordinate extrema and face-support rows of a box, and the vertices of a hull.
The cost of an update then stops growing with the iteration count; in a 30-update example with 200 rows per update, a box update fell from 2.5 ms to 0.8 ms and a hull update from 32 ms to 5 ms.
The option trades solution quality for speed: a later mixed-label update can no longer keep an earlier interior row, so a box can shrink and hull facets can move,
and the relaxed box of a positive sampling_box_slack sees fewer outside rows. It is off by default.
A CornerCut with direction True removes points strictly above its anchor in that coordinate; False removes points strictly below.
A point is removed only when every coordinate condition holds. A point equal to an anchor coordinate stays.
This set is an open orthant: one direction from the anchor on every axis.
The example candidate_region_growth_and_update.py fits planar and convex-hull regions to labeled annulus samples, grows and updates them, and trims corner-removal components before and after growth.
Membership and ranking scores
classify returns a membership mask and one ranking score per row. The mask decides membership. The score only ranks.
The example candidate_space_geometry.py draws the score contours of hull, planar, and corner regions, and the example partial_commonality_score.py those of the cumulative score of several product variants.
BoundingBoxRegion, ConvexHullRegion, CornerRemovalRegion, and PlanarRegion also have contains, which returns the mask of classify without any score.
The samplers, the Monte Carlo measure, and the evidence labels read the mask through contains for these four classes.
Subclasses and custom regions keep classify, because a subclass can change it.
The label path raises only the errors of the label arithmetic: a row far outside a box is labeled outside instead of raising the score-range error of Box.classify.
The cut and facet tests run only on the rows inside the selected box.
A planar query tests its cuts in chunks, in stored order, and stops testing a row after the first chunk that removes it.
When a chunk holds a projection that is not finite, the query retests that chunk one cut at a time, so each row stops at its first removing cut.
So a cut projection that is not finite raises GeometryUnavailableError only for a row inside the selected box and a cut up to the first removing cut of that row.
Planar and corner scores:
- Planar and corner scores take the largest cut deficit, then the maximum with a box score.
- With
include_bounding_box=True, the default, that box is the envelope:sampling_bounds, else the tight box of the in-domain inside rows. WithFalse, it is the outer bounds, also for a pending region. - Planar membership does not use the cut-tightened
sampling_box, because that box depends on the configuredtolerance. Example: with envelope[0, 1], the cutx >= 0.5, andtolerance=0,classify([[0.45]], distance_to_plane_tolerance=0.1)accepts the point, althoughsampling_boxis[0.5, 1]. - With
compute_variant_score=True, inside rows use the negative geometric mean of the cut margins. Outside rows then use the Euclidean norm of positive cut deficits. This mode changes ranking, not membership. - Planar and hull regions also accept
variant_score_policy, adesignoptpy.core.DeficitScoringPolicywith weights and named or custom scorers for this mode.Nonekeeps the default scorers.
Hull scores:
- A hull score is the largest facet deficit: the facet residual minus its tolerance, the explicit
classification_toleranceor the inferred local roundoff. - With
compute_variant_score=True, a hull scores its facet deficits with the variant policy instead. - An accepted row therefore has a nonpositive hull score, and a rejected row a positive one.
- A facet projection is a physical distance only when its stored normal has unit length. Normals of a hull fitted in normalized coordinates need not have unit physical length.
Planar membership uses one rounding tolerance for each query row and each plane:
- A cut has an anchor
aon its plane and a directionw = inward_normal / normalization. - The deficit of a point
xis(a - x) @ w - K*eps*(|a - x| @ |w|), whereepsis the float64 machine epsilon andK = max(10, d + 2)fordcoordinates. - A point is inside the cut when the deficit is zero or negative.
- The second term covers the rounding error of that pair's differences, products, and sum: at most
gamma_(d+1) * |a - x| @ |w|, withgamma_n = n*u/(1 - n*u)andu = eps/2.(d + 2)*epsexceeds this bound for every coordinate count, and the floor 10 keeps the earlier labels ford <= 8. Changing physical units or adding a distant query row therefore cannot relax another row's plane test. - The projection and the allowance add their coordinate terms in coordinate order, so a deficit depends only on its own row and cut. A label is the same whether the row is classified alone, in a subset, or in the full batch. Exact proposal masks need this property.
- The anchor itself has deficit zero, so it stays inside its own cut. The threshold form
a @ w - x @ wrounds two separate dot products and can exclude the anchor. - An explicit
distance_to_plane_tolerancereplaces the second term and uses projected plane coordinates.
PlanarRegion.convex_hull reconstructs vertices in unit-box coordinates.
- Its
toleranceapplies to normalized planes. Box boundaries use a separate machine-precision tolerance. fixed_variablescontains one value per coordinate. NaN marks free coordinates. Returned vertices contain only those free coordinates.- Before enumerating intersections, reconstruction removes cuts satisfied throughout the proposal box. This proof prevents irrelevant cuts from exhausting the intersection allowance.
Hull evidence:
convex_hull_evidencereturns vertices, facets, measure,complete, andstatustogether.- A completed empty region has empty arrays and zero measure.
- Unavailable geometry has
Nonearrays and measure, withwork-limitorarithmetic-unavailablestatus. - Direct
convex_hullqueries raiseGeometryUnavailableErrorfor these limits. - Argument validation errors remain errors in both methods.
Fitted hulls:
- Fitted hulls store physical facet equations, even when
normalize_variables=Truefits in unit-domain coordinates. - The fit divides each unit-domain coefficient by its domain width and multiplies the unit volume by the domain measure. It does not rescale the result, because a rescaled equation would change an explicit absolute facet tolerance.
- Qhull computes the facets in floating-point arithmetic.
The facets must agree with the hull points within the rounding allowance of the core
ConvexPolytopecheck, in the fit coordinates and in the stored physical coordinates. - For nearly degenerate inside evidence, the rounding error can exceed this allowance. A normalized fit adds the rounding of its coordinate transformation. The same allowance decides default membership, so the fit does not relax it.
ConvexHullRegion.fitthen raisesGeometryUnavailableErrorwithhull-consistencystatus: the evidence is valid, but its hull is unavailable. Component trimming records such a refit as an unavailable proposal.
Corner pruning:
- Corner pruning first removes same-direction cuts that another cut contains (exact anchor dominance).
- The detailed corner proof then checks cell interiors and boundary faces in an anchor partition. Membership is constant within each partition piece, so one representative suffices for each piece, and the proof is exact.
- It removes, in input order, each cut whose removed representatives another retained cut also removes.
- If the partition exceeds
redundancy_maximum_cellsrepresentatives (default 100000), a local proof uses overlapping retained cuts.redundancy_neighbor_count, default 24, bounds that subset. Zero disables the local proof. - The proofs and the exact face search of the corner sampling box need only labels, so they compare coordinates (
x > aorx < a) instead of forming directed differences. They group the cuts by direction pattern and test the cuts only on the rows that no earlier cut removed. The labels equal the scored labels ofclassifybit for bit. Small row sets test several cuts in one comparison; large row sets test one cut at a time. Membership work grows with rows times cuts, and both grow during consolidation, so skipping removed rows saves the most on grids where most rows lie in removed orthants. - Failure to prove coverage keeps the cut. A proof that removes a cut preserves the current region.
- The complete partition proof classifies the whole product grid at once, without batches.
It compares each axis vector with the anchor coordinate of each cut and combines the axis results, so it forms no coordinate matrix.
It holds one Boolean per representative and cut, for at most
redundancy_maximum_cellsrepresentatives. The local neighbor proof classifies its representatives in batches of 1024 and stops at the first batch with an uncovered point. The exact face search of the corner sampling box classifies its grid points in batches of 16384. These batch sizes change only time and memory.
Planar pruning:
- Planar pruning first keeps the strictest of the cuts whose unit normals in unit-domain coordinates are bitwise equal, in its own input position. It does not group nearly parallel cuts, because a narrow strip between them can be necessary. This is the only cheap rule: a cut that retains or excludes the whole domain stays until the detailed check or growth removes it. Such a cut does not change membership.
- Detailed pruning under the default
redundancy_rule="exact"then keeps a cut unless the other cuts imply it with at leastredundancy_margin, default 1e-6 domain fractions. A non-redundancy witness is a point of the bounds that satisfies every other cut and projects below this cut's threshold plus the margin. - Keeping a cut is always safe, so every tolerance lies on the keep side and exact pruning never changes the represented set.
- Under the exact rule, a bounded linear program finds such a witness or shows that none exists.
redundancy_rule="witness"(opt-in, not exact) solves no linear program in the detailed check. It tests the cuts one at a time, in cut order, against the cuts that are still kept. A cut keeps a stored witness that still holds. Otherwise the check projects the witness rows orthogonally onto the plane of the cut, in unit-domain coordinates, and clips them to the domain. The first projected row that holds is the witness. An older cut without a witness is removed without proof; the cuts of the current update always stay.prune_planar_cuts_by_witness(cuts, bounds, evidence, is_new, redundancy_margin=..., witnesses=...)applies the rule to explicit rows. Tradeoff: a failed witness search does not prove redundancy. The rows can miss a face that a cut bounds, so the rule can remove a cut that still bounds the region. The region then grows beyond its former cuts and accepts designs that the cut excluded, and these designs can be bad. Membership, measure, later trimming, and run statuses can then change. A witness-rule removal also discards the stored coordinate-bound optima ofsampling_box. Proposal masks stay exact for the current members, because a current member satisfies every older cut. The effect on run time and region quality was not measured in this package. Measured in an earlier implementation of a similar rule: a five-product family study took 0.92 to 0.94 times the time of the exact rule with 0.56 to 0.64 times the planes, its fraction of good designs fell by 0.12 percentage points on average and by up to 0.43 points for one product, and two searches stopped at the iteration limit; a truss study took 1.00 to 1.05 times the time.witness_sourceselects the witness rows and has an effect only withredundancy_rule="witness"."evidence"(default) uses every stored definition row before the update, then the update rows, then the anchors of the cuts that remain after the equal-normal rule."anchors"uses only those anchors, the new ones included. Each anchor lies on its own plane. The anchors cost less work, but for a cut tested against the same other cuts they find no witness that the full rows miss, so they usually remove more cuts without proof and give a larger region. This is a tendency, not a guarantee for each cut, because a removal makes the tests of later cuts easier.prune_planar_cutsreturns the witnesses, and a planar region keeps them. A later check solves linear programs only for new cuts and for cuts whose witness no longer holds.- Growth moves each witness with the anchor of its cut (
move_witnesses_on_growth=True, the default). Under plane-direction growth a moved witness keeps its distance to its own plane and gains slack to the others, so the first detailed check after growth solves programs mainly for the new cuts and the cuts whose moved point fails.move_witnesses_on_growth=Falsediscards the witnesses, so that check proves every cut again. New cuts start without a witness. extended_update_proof_reuse=Truereuses more stored proof points at updates: an update offers the anchor of each new cut as its witness, and a chain of updates keeps the coordinate-bound optima of the last solvedsampling_box. The default keeps the reference path at updates.- Every reused point is tested again before use, so the retained cuts and the sampling box are the same in exact arithmetic. Rounding can keep a cut that lies within rounding of redundancy, and a reused bound keeps the value of its earlier solve, so seeded runs can differ.
redundancy_proof="screened"(default) decides most of these tests with two block-diagonal programs. A screen first bounds every untested cut over the domain and the cuts that a witness keeps; a bound of at least the threshold plus twice the margin removes the cut in any test order. Without a witnessed cut the screen bounds are the closed-form box minima, so the screen calls no solver. One joint program then bounds each remaining test. Its point keeps a cut, and its bound can remove one. After a removal, the bound of each later test of the program is recomputed from its multipliers of the remaining cuts. Each test that no bound decides solves its own program. Weak duality turns the solver multipliers into lower bounds that solver error can weaken but not make wrong.redundancy_proof="per-cut"solves one program for each test, in input order. The two proofs keep the same cuts unless a solver misses a minimum by more than the margin, or a program of the per-cut proof fails on a test that a proven bound decides. In a component search of the drone family example (10+10 iterations, 300 samples), the screened proof needed about 0.6 times as many solver calls, with identical regions.- The equal-normal grouping looks up each unit normal in a dictionary of the retained normals, so the cheap rule costs one pass over the cuts.
Redundancy-check schedule:
- Planar and corner regions run the detailed check only in an update that adds cuts, because only new cuts can make earlier cuts redundant there.
- An update without cuts, such as the evidence refresh before trimming, and a growth step with
check_redundant_trimming_growthapply only the cheap rule. The cheap rule is equal normals for planar cuts and anchor dominance for corner cuts. - Each update that adds cuts to a region with at least two cuts counts toward
check_redundancy_cadence(default 5 for planar and 10 for corner regions). - Under the default exact planar rule and for corner cuts, pruning never changes membership at that moment.
The opt-in planar
redundancy_rule="witness"can remove cuts that still bound the region (see "Planar pruning"). A covered cut that stays until the next proof still moves at later growth and still adds its anchor to the evidence, so the cadence can change later iterations. - Finite evidence alone cannot certify either kind of geometric redundancy.
- Corner
detach_toleranceis a separate optional anchor-alignment operation. Positive values can change geometry. The default zero disables alignment. The tolerance scales the inside-evidence spans of the region that an update or growth starts from.
Corner membership and growth use membership_box, the envelope before corner removal.
sampling_box is a tighter box that contains the retained region. Sampling and measure estimates use it.
An exact face search finds each bound when its slice fits sampling_box_maximum_points, default 100000.
A stopped face keeps a wider safe bound. This changes seeded sample paths without changing membership.
Planar and corner regions accept shape_definition: "none", "extremes", or "extremes-and-anchors", matched under the choice-name rule of designoptpy.core.choices.
It selects the boundary rows supplied as shape evidence without model evaluations.
Planar regions default to "none"; corner regions default to "extremes-and-anchors".
Shape evidence can preserve a larger region and costs context-sampling work. Its benefit depends on the problem.
Changing this option changes the search path and can change solution quality.
Sampling inside regions
Rejection sampling draws proposals and keeps only points inside the required regions.
sample_all_feasible and sample_individual_feasible use it.
The example product_sampling_comparison.py samples a product of three analytic component regions with both samplers and compares their proposal and membership-test counts with the expected counts.
Proposal limits:
sample_all_feasiblerequests only the remaining rows and unused proposal allowance, at most the optionalmaximum_refill_batch_sizedesigns per batch (defaultNone, no cap). A smaller cap needs more batches at low acceptance and draws fewer unused designs at high acceptance. With the built-in uniform sampler it changes the batch count and the generator end state, not the returned designs.- Each
sample_individual_feasiblebatch holdsnumber_samplesproposals, limited by the optionalmaximum_refill_batch_sizeand the unused allowance. This tolerates acceptance near1/1000with the default 1000 batches, instead of nearln(number_samples)/1000. The tradeoff is more membership tests per filled sample at high acceptance. adaptive_batch_size=True(defaultFalse) insample_individual_feasibleandsample_all_feasibleuses one rule for later batches: the proposals expected to fill the remaining need at the acceptance fraction observed so far, at most the first batch, which holdsmin(number_samples, maximum_refill_batch_size)proposals (number_sampleswithout a cap). The individual sampler then tests fewer unused proposals at high acceptance; in an example at 90 percent acceptance, 1134 instead of 2000. The joint sampler, whose default batches hold only the designs still needed, then needs fewer batches at low acceptance; in an example at 0.8 percent joint acceptance, 115 instead of 694. Seeded draws,attempted_count,batches, and the point of a sampling limit change, so the option is off by default.- Accepted rows and padding are a prefix of the proposal stream: rows after the last needed accepted row are tested and not used. The padding count does not depend on the batch size.
- For both samplers,
controls.maximum_evaluationslimits all generated proposals in the operation.controlsis aSamplingControlsrecord. See Custom callbacks. - One proposal unit is one component-region membership test.
- A complete design of
sample_all_feasibleis tested against allkcomponent regions, sonsuch proposals reportattempted_count = k * n. sample_individual_feasibletests each local row against one region, and the count includes fresh rows used to fill padding.- Independent component sampling also accepts
maximum_evaluations_per_component. - If completing optional padding would exceed a limit, retain less padding.
Limit errors:
- A rejection sampler that reaches
maximum_evaluations,maximum_evaluations_per_component, ormaximum_batchesbefore it fills the sample raisesSamplingLimitErrorfromdesignoptpy.sso.regions. - This
RuntimeErrorkeeps the completed work:attempted_count,batches,accepted_count,requested_count, the exhaustedlimit, and the stoppedcomponentof independent sampling. - Cancellation raises a plain
RuntimeError.
sample_set_hit_and_run walks random chords inside each component region.
A chord is the segment of a random line that lies inside the region. This walk is a Markov chain.
- It runs
10 * number_sampleschains per component by default, each with up tosteps_per_sample=3transitions. - Failed attempts end a chain at its current point, which can repeat an unchanged seed.
- The default chord locator shortens an outside ray with eight bisection steps. It assumes one connected membership interval along the ray, as in a convex region.
- The default selection then greedily maximizes the nearest distance to seeds and earlier selections, in range-normalized Euclidean distance.
- The direction sampler receives a centered
[-1, 1]box in each coordinate. - Finite walks and greedy selection do not produce independent uniform samples. More chains or transitions add work and can change coverage. They do not certify it.
- The sampler rejects a
controls.maximum_evaluationscap, because its walk budgets limit its work. - By default, the chains of a component advance one after the other, and each attempt makes its own one-row calls.
batch_chains=Trueadvances all chains of a component together in rounds. One round draws a direction for every pending chain, locates all chords with one membership call per bisection round, and tests all proposals in one call. Each chain keeps its transition and retry rule, so the sampling distribution is the same. Only the exact built-in box, hull, corner, and planar regions receive these grouped membership calls. Every other region, also a subclass, can label a row by the other rows of a call, so it still receives one row per membership call. The generator is read in another order, so the same seed gives other samples, and a custom direction sampler receives one call with many rows. The option requires the default chord locator. In a measurement with 200 chains of three steps, a planar region with 20 cuts in three coordinates took 23 ms instead of 2.1 s. The default isFalse.
Trimming and candidate selection
Each region owns its proposal options and interprets its selected proposal descriptions.
The example trimming_proposals.py draws every planar and corner proposal of planar_trimming_candidates and corner_removal_candidates for one rejected sample, with its anchor, its cut geometry, and the rows that it removes.
The examples trimming_method_schematics.py and trimming_slack.py draw the cut kinds in one to three dimensions and the boundaries of a planar and a corner cut at several slacks.
PlanarTrimmingOptionssets reference designs,trimming_slack, normalization, keep-only slack protection, tolerance, andmaximum_candidates.CornerTrimmingOptionssetscorners_to_test("all"or"away"), slack, normalization, keep-only protection,use_vectorized_operations, andmaximum_candidates.maximum_candidates(defaultNone, no cap) refuses a proposal call whose enumeration exceeds the cap, before any enumeration or distance work. Corner proposals count2**dimensionorientations for"all"and one for"away"; a cap of 1024 permits the complete search through ten coordinates. Planar proposals, also those of bounding-box and hull regions, count the selected reference rows plus one for the keep centroid, before equal normals merge. A call without a keep row returns zero proposals before the check. Zero is a valid cap and refuses every other call. A refused call raisesGeometryUnavailableErrorwith statuswork-limit, which component trimming records as an incomplete search, not as a search without useful cuts.planar_trimming_candidatesandcorner_removal_candidatestake the same keyword.- With
trimming_slack=1, the new boundary can stay at the rejected target, so a proposal need not remove it. - Keep-row protection can also limit displacement. Inspect the removal mask before you treat a trim as an exclusion.
- The planar proposal
toleranceonly selects the rows that may limit the displacement. The raw distance to the nearest such row places the anchor. - The removal masks replay the planar membership test with the region's own
tolerance(membership_toleranceofplanar_trimming_candidates). - A keep mask without a true entry returns zero proposals from
planar_trimming_candidatesandcorner_removal_candidates. No cut can be constructed, and zero proposals state that without an error.
Vectorized corner operations:
CornerTrimmingOptions.use_vectorized_operationsand the directcorner_removal_candidateshelper default toFalse. They then loop over the coordinates and keep a running maximum of the sample-by-corner distances. No temporary array has a coordinate axis, which reduces the workspace.Trueuses sample-by-corner-by-coordinate temporary arrays.- Both modes give the same masks and cuts and retain sample-by-corner distances and removal masks.
How regions apply proposals:
- Box and hull regions use planar proposal masks, then refit the merged inside evidence. They do not store the proposed plane equations as additional cuts.
- Planar and corner regions add selected cuts and recompute membership from the combined geometry.
- These geometric decisions define membership between sampled rows.
The trimming order sets the sequence in which rejected rows are removed.
trimming_order defaults to TrimmingOrderMode.SCORE_ASCENDING_THEN_DESCENDING.
It tries an ascending and a descending score order, each from an independent stable sort.
Default component cut ranking:
- It first preserves full-product designs that are both acceptable and useful.
- It then prioritizes excluded-design removal, followed by component-local removal and retention counts.
- A design belongs to the full product only when it belongs to every component region. These joint counts explain why a locally attractive cut may lose to another component's proposal.
choose_component_trim_result selects the best complete pass with default criteria, compared in order:
- most viable rows inside the product;
- fewest excluded rows inside;
- most nonexcluded rows inside.
An excluded row is a row listed in any removal order, so passes with different orders are compared on the same rows.
trim_components uses it when optimal_choice is None. Batch optimal_choice_options configure it, so both routes select the same pass.
designoptpy.sso exports choose_component_trim_result, balanced_component_choice, and preserve_viable_cut_cost.
It also exports the protocols CutCostStrategy, ComponentChoiceStrategy, and OptimalComponentChoiceStrategy that a custom strategy implements.
The viable-volume criterion:
selection_criteriaalso acceptVolumeInsideViableand custom cost functions.VolumeInsideViableranks a sample estimate of the viable volume that the full product keeps. The estimate is the volume of the bounding box of the retained viable rows, times the fraction of trimming rows inside that box that are retained viable rows.- A region with one viable row has a box of zero width, so its estimate is zero. The criterion ranks viable evidence, not the region measure.
CutDiagnostics.viable_volumeandComponentTrimResult.viable_volumehold the value. A cut diagnostic computes it only when a ranking reads it.- Every complete pass takes part in the pass choice, also a pass whose product contains no sampled row.
Between two passes that keep no viable row, the pass that leaves fewer excluded rows inside wins. The retained-evidence check then reports a returned region without evidence as
no-valid-sample.
Ties and invalid scores:
- An exact ranking tie keeps the first tied choice: the first proposal in the region's proposal order, the first component in layout order, and the incumbent pass.
- Equal rankings mean equal observed sample consequences, so this first-tie rule needs no geometric reconstruction.
trimming_orderersets the removal order of the trimming search only.leanness_orderersets the order of the iteration and final leanness passes. A custom trimming order therefore does not change leanness.leanness_order(defaultscore-ascending) selects the built-in leanness order:score-ascending,score-descending, orrandom. A customleanness_ordererreceives it asmode. Leanness runs one order, soscore-ascending-then-descendingraisesValueError.randomdraws its permutation from the run generator, so the later draws of the run change.- A box batch without a rejected row makes no trimmer call and reports zero passes.
- The proposal and pass orders are deterministic for given inputs, so the choice is repeatable.
- Box trimming maximizes its configured finite measure, then prefers fewer retained requested exclusions and more viable rows. A remaining box tie keeps the box that the search found first.
- Ascending and descending score orders preserve input order when scores are equal.
- Positive-infinity requirement-rejection scores sort after finite scores ascending and before them descending.
- Negative-infinity scores sort before finite scores ascending and after them descending.
- NaN ordinary ranking scores remain invalid.
Planar regions, and corner regions with detach_tolerance=0, have exact proposal masks (exact_proposal_masks).
- Applying such a proposal removes from the current members exactly the rows of its mask, and the proposals do not depend on the cuts already applied.
- Component trimming therefore ranks these proposals on their masks. A pass only records its accepted cuts.
- The accepted cuts of the selected pass are applied once per region with
trial=False. One trim adds one to the redundancy count, and no redundancy program runs for a discarded pass. - A planar mask uses the same plane test as membership. The applied region keeps the envelope of the current region, so the masks equal the applied membership exactly.
- An update that differs from the masks raises
ValueError, because the region breaks the contract ofexact_proposal_masks. - An unavailable update states no membership. Its region stays unchanged, and the search is incomplete, as for a dropped proposal.
- A retained cut diagnostic measures its cut on a temporary copy. A custom pass chooser reads temporary copies too. The copies are not stored, they do not count toward the redundancy cadence, and an unavailable copy gives
NaNdiagnostic measures.
Trial copies for box and hull regions:
- Box and hull regions refit their geometry to the kept rows, so component trimming applies each of their proposals to a separate trial copy before it ranks the proposal.
- Built-in box and hull regions report the exact trial membership with
trial_membershipinstead, so their proposals are ranked without a trial copy. For a built-in hull, the search builds that trial copy once, reads its labels, and keeps it with the best offers. When such an offer is selected, its copy is the update, so the selected cut costs no second fit. - A full hull trial costs two fits: one fit of the kept rows restricts the prior inside evidence, and one fit of the merged rows gives the membership.
- By default (
fast_trial_membership=False), every hull trial runs both fits. A trial fit that fails therefore always drops its proposal and makes the search incomplete, also when another component wins. A rank-deficient trial is the exception (see below). - A repeated trial of the same region and labels reuses its stored membership, in every pass mode. Anchored passes repeat many trials of earlier passes, and two proposals of one pass can retain the same labels. The first trial established both the membership and the availability, so the reuse changes no result.
Rank-deficient hull trials:
- A hull fit in
dcoordinates needs more thandinside rows whose differences have numerical rankd.ConvexHullRegion.apply_trimmingtests the new inside rows of a mixed-label update and the merged inside evidence before it fits. When a test fails, it raisesRankDeficientEvidenceError(indesignoptpy.sso.regions.base), a subclass ofTrimmingGeometryUnavailableError. - Such rows span a lower-dimensional set: a point, a segment, or a flat polygon. The set has zero measure. The geometry is well defined, but a hull region cannot represent it, so the proposal can never be the best one.
- Component trimming and leanness therefore reject such a trial. They skip the proposal, count it, and record no unavailable geometry. The search stays complete when every other trial is available.
- Counts:
ComponentTrimResult.rank_deficient_trials,ComponentIterationRecord.trimming_rank_deficient_trials,ComponentIterationRecord.leanness_rank_deficient_trials, andComponentFinalLeanness.rank_deficient_trials. The final leanness counts in its own record,ComponentOptimizationResult.final_leanness. A repeated trial counts again, as inshortcut_trials. - The rejection applies only to the trials that rank or test one proposal.
Evidence refresh, the update of a selected proposal, and direct
apply_trimmingcalls keep the unavailable-geometry path. - A fit failure on rows that pass the rank test stays unavailable: a Qhull or
hull-consistencyfailure, a facet coefficient outside the floating-point range, or an unavailable measure.
Fast hull trial membership (ConvexHullRegion(..., fast_trial_membership=True)):
- The option lets component trimming and component leanness ask
shortcut_trial_membershipfirst. It tries two shortcuts, then the full trial. Leanness asks only this method: a region without the option keeps its leanness trials and results. - The guarded shortcut fits the rows labeled inside once. It returns the labels when every other row lies beyond a support plane of that hull by more than a rounding band.
It skips both trial fits. It applies in at most three coordinates, with an automatic or zero
classification_toleranceand no variant score. - The single-fit shortcut applies when the supplied labels override every prior inside coordinate. It fits the final inside coordinates once and skips the restriction fit. Its membership is exact in coordinates. Without prior evidence (an uninitialized region or a flat pending box), the full trial is one fit already, so the shortcut does not apply.
- Gain:
component_hull_4d(component SSO of two 2-D hulls) runs about 3.3 times as fast (ratio of the median run times), with the same regions on the benchmark seeds. - Limit: the guarded shortcut assumes that a fit moves each facet outward by at most
1024*eps*E, withEthe domain diameter. Hull fitting does not certify this bound. - Limit: a fit that a shortcut skips records no failure. The preliminary fit of a trial can fail in Qhull while the single fit works. For a proposal that is not selected, a search can then report complete when the full trials would report it incomplete.
- Neither shortcut decides a rank-deficient trial. The guard implies both rank tests of the full trial. The single-fit shortcut applies both tests to the same rows as the full trial, repeated rows included, so the full trial then rejects the trial.
- Signal:
ComponentTrimResult.shortcut_trialsandComponentIterationRecord.trimming_shortcut_trialscount the trimming trials that a shortcut decided, andComponentIterationRecord.leanness_shortcut_trialsandComponentFinalLeanness.shortcut_trialscount the leanness trials. A complete search with a positive count relied on the shortcuts. - A selected proposal still receives the full update. Its failure is recorded, and a membership that differs from the shortcut raises
ValueError. - In leanness, a shortcut answer can make a proposal safe whose full update is unavailable. Leanness can then report complete where full trials would report it incomplete, and it can select other cuts, so later iterations can change.
- Use the option for well-scaled hulls in few dimensions with many trimming passes. Keep it off when the complete-search signal must be exact.
Cost of ranking:
- A cut's region measures (
CutDiagnostics.component_measureandtotal_measure) are computed only when a ranking reads them. - The default rankings use only sample counts, so mask ranking builds no trial region and computes no Monte Carlo measure.
- The row counts of all exact-mask proposals of one component and step come from one set of column reductions of their membership matrix.
- Anchored passes (
REDUCEDandFULL) store the exact-mask proposals of each state, because they repeat the states of earlier passes. Single passes store none: each removal order removes other rows first, so their states rarely repeat. - A ranking that reads a measure builds the trial copy of that proposal, with the accepted cuts of the pass.
- A planar trial copy skips the detailed redundancy check, so it can keep cuts that the check would remove as redundant by at least its margin. Such cuts exclude no point, so the trial copy has the same membership and ranks the proposal like a fully checked copy.
- A box trial copy has the box of the full refit, so its membership and measure are exact.
- Planar proposal bounds reuse stored optimal points. A stored point is tested only against the cuts added since its solve, because only a new cut can exclude it. A new cut needs a new linear program only when it removes a bound's point.
- The one update of a trim runs the detailed check that
check_redundancy_cadenceschedules. The defaultcheck_redundancy_cadence=5runs that check every fifth update that adds cuts, so every fifth trim of a region. The check reuses the stored witnesses, so it usually solves linear programs only for the new cut and the cuts whose witness it excludes. - This cheaper policy can change later geometry and solution quality, because retained redundant cuts still move during growth.
Set
check_redundancy_cadence=1for the earlier, more thorough policy. - Trimming time grows with the rejected rows, the proposals for each row, and the retained cuts.
Consolidation and leanness:
- Consolidation accepts a sufficiently pure candidate before trimming.
- Purity skips ordinary trimming, not leanness. With
LeannessPolicy.ALWAYS, a pure consolidation batch still runs iteration leanness. - Its rows remain evidence for final leanness and the retained-evidence check.
With
reuse_previous_samples=True, a component run also reuses them, together with the earlier reused rows. The reused rows therefore accumulate, and the trim cost of a consolidation iteration grows with its index.maximum_reused_sampleskeeps only the newest reused rows before each batch is appended (defaultNone, no cap). A cap gives each cut less evidence, so the regions, the record counts, and the final status can change. - Each pure batch therefore costs one leanness pass, and the region can shrink earlier in consolidation.
- Useful shape rows support intermediate construction.
- Leanness means removing geometry unsupported by kept evaluated samples. Final and per-iteration leanness remove this geometry while preserving jointly viable evaluated rows.
- Leanness first tests individual safe cuts, then their combined update. If the combination is unsafe, it can keep only the first safe cut.
- For a region with exact proposal masks, the masks decide the individual cuts, so leanness builds no trial region for them.
- By default, leanness updates a region once per removed row.
defer_leanness_updates=True(defaultFalse) updates a region with exact proposal masks once per pass with all its cuts. Every evaluated row keeps its membership, and leanness needs far fewer region updates. The redundancy proof then runs less often, so regions can keep more redundant cuts, and their measures and later iterations can differ. - Each combined update is checked: it must be available, and the starting members inside the updated region must be exactly the rows that the masks keep. The first failed check makes the pass repeat its exclusions with one update per row from the same starting regions, which can fall back to the first safe cut of a row. The repeated pass gives the result.
- Leanness counts its work.
leanness_combined_updatescounts the combined updates that ran, also one that failed its check.leanness_per_removal_updatescounts the updates of the combined safe cuts of a row and component, whatever their outcome.leanness_combined_update_fallbacksis 1 after a fallback, else 0. After a fallback, the update counts include the discarded pass, because its work ran. The regions and the trial counts come from the repeated pass. The counts areNonein a record whose iteration ran no leanness, andComponentOptimizationResultholds their run totals (Nonewhen no leanness ran). - The final leanness reports its work and evidence in
ComponentOptimizationResult.final_leanness(ComponentFinalLeanness), not in the last iteration record, so every record describes its own iteration.final_leannessisNonewhen the final leanness did not run. - With
save_trimming_diagnostics=True, leanness builds one region per retained cut to measure it.fast_leanness_diagnostics=True(defaultFalse) builds these regions of planar components as trial copies without the detailed redundancy proof. The search keeps the same regions, but a stored diagnostic measure can differ slightly. It builds the combined update, and the update of the first safe cut only when it falls back to that cut. A region without exact masks gets one full trial update per proposal. Both ways give the same regions: an exact mask is the membership of the applied cut (see above). In a component search of the drone family example (10+10 iterations, 300 samples), leanness took about 1/400 of its former time, with bit-identical regions and measures. - If an iteration rolls back, it retains evidence from the accepted candidate.
Box leanness:
- Box leanness skips a boundary move when a kept row shares the removal coordinate on the remaining side, or no kept row lies there.
- The new bound would then equal the removal coordinate. Inclusive bounds keep the removal row inside, so the move could only collapse the interval, for example to zero width.
- Fixed variables, grid samplers, and discrete designs produce such ties. Continuous uniform samples almost never do.
- The rule compares the closest kept coordinate with the nearest coordinate of any inside row on that side. After a move has excluded the removal row, a later move of the same row is skipped when that nearest row is kept, so that face can stay beyond the kept rows.
Component shape rows supply boundary evidence without new model evaluations.
ADVANCEDhandles each component separately and fills its complement from designs inside the current component regions. The uncapped built-in sampler draws all contexts in one call, with an independent context row for every shape row. Rows do not share a context. Unused components need no draw. Custom or capped samplers retain per-component calls. Pooling preserves each row's distribution but changes random draws and seeded search paths.SIMPLEcombines components' shape coordinates in shared rows. It separates inside and outside definitions and uses the largest component row count in each group. Missing local coordinates are sampled uniformly from the proposal box and need not lie inside their region.- ADVANCED can use more rows and sampling work. Different completed rows can change the trimmed geometry.
- The defaults remain ADVANCED in exploration and SIMPLE in consolidation.
shape_typeoverrides both phases. Otherwiseshape_type_explorationandshape_type_consolidationselect them separately. minimum_paddingandmaximum_paddingcount full-design padding rows. A schedule with minimum above maximum raises before sampling.
Trimming passes and anchors:
- A trimming pass processes one removal order, optionally protecting one viable sample called an anchor.
- An anchor group is the set of passes, one per order, that share one anchor choice. The first group has no anchor.
SINGLEtries the requested orders without anchors.FULLalso tries each initially inside viable anchor.- Box trimming does not rerun an anchored pass when the unanchored pass for the same order kept that anchor.
Such a pass gives the same box, so it counts as completed and every result is unchanged (see
trim_box). - Box trimming also reuses the boundary moves of a state that an earlier pass reached: the same box, inside samples, and removal sample. The anchor only restricts which moves are allowed, so the reused counts and volumes are exact. The cache stores nothing when at most one pass can run, or when one state is larger than 32 MiB. Otherwise it keeps at most 32 MiB of states and drops the least recently used state first. A dropped state is computed again, so the bound changes only the run time.
- Component trimming replays the unchanged prefix under the built-in cost and component selectors. It resumes at the first step that removes the anchor, or reuses the completed pass when the anchor survives. Custom selectors run complete passes because they can depend on their call history.
REDUCEDuses one rule for boxes and components: after each anchor group, the anchors that the group's best pass retains become covered.- The group's best pass uses the rule that selects the returned result: the box ranking, or the configured
optimal_choicefor components. - The current anchor is also marked processed, and the search continues with the first uncovered anchor until every anchor is covered.
- This meets the contract that every viable anchor occurs in at least one examined pass.
- The group's best pass uses the rule that selects the returned result: the box ranking, or the configured
- Fewer passes save work but can select different geometry.
- FULL covers requested orders and anchors. The cuts within each pass remain greedy.
- The defaults remain FULL for boxes and REDUCED for components.
A component anchor is a search heuristic, not a hard rule. When no component offers a cut that excludes the rejected row and keeps the anchor, the pass uses the best cut that removes the anchor. The primary job of trimming is to exclude observed unacceptable rows. A strict anchor could keep such a row inside and still win the pass choice. The anchor's coverage is then left to other passes.
Convergence and stopping
Both fixed_exploration_iterations and fixed_consolidation_iterations default to True.
They disable convergence stopping for their respective phases. Other stopping conditions and budgets still apply.
To enable the convergence criterion of a phase, set its fixed switch to False.
Exploration convergence
Exploration convergence requires a completed trim and exploration_purity, which defaults to 0.95.
A complete comparison must show normalized geometry change no greater than exploration_geometry_tolerance, which defaults to 0.01.
- Small geometry change alone does not establish convergence.
- Component comparisons need complete geometry evidence for every component. Unavailable evidence cannot establish convergence.
- A numeric seed cannot converge in its first accepted batch. It is not evidence for a solution space, and the first accepted regions have no earlier regions to compare. A supplied region sequence can converge at once.
ComponentSsoOptions.geometry_change, called asgeometry_change(previous, current)with the accepted region tuples before and after a batch, replaces the component comparison. It has the same return rule as the box option below.- Box SSO measures the change as the largest endpoint change in unit coordinates of the design space.
BoxSsoOptions.geometry_change, called asgeometry_change(previous, current)with the accepted boxes before and after a batch, replaces that metric. It must return a finite nonnegative real scalar. Otherwise box SSO raisesValueError. Bind extra settings with a closure orfunctools.partial. A custom metric can state convergence in problem terms, for example a relative volume change.BoxIterationRecord.geometry_changekeeps the value. It isNonewhen no comparison ran (consolidation, a rolled-back batch, orfixed_exploration_iterations=True).- Component runs compare the geometry only for an accepted exploration batch that can converge: convergence enabled, earlier accepted or supplied regions, a completed trim, and purity at least
exploration_purity.ComponentIterationRecord.geometry_evidenceis empty for the other batches. save_geometry_change=Truecomputes and records the comparison of every accepted exploration batch with earlier regions, also under fixed iterations. It is a diagnostic that shows how the region settles and helps to chooseexploration_geometry_tolerance. The extra comparisons change no decision. A component comparison can solve linear programs or build corner partitions, so the diagnostic can cost time. It defaults toFalse.
Consolidation convergence
- Consolidation accepts a suitable sample at
consolidation_purity, which defaults to 1.0. - This skips ordinary trimming even while fixed iteration counts continue. Iteration leanness still applies under
ALWAYS. - If
fixed_consolidation_iterations=False, that acceptance also permits early stopping. - Consolidation has no geometry-change criterion.
Iteration limits
Each phase iteration limit comes from one source.
- An explicit phase setting takes precedence over the generic setting.
- Explicit
maximum_exploration_iterationsandmaximum_consolidation_iterationsare used as given, also whenmaximum_iterationsdiffers from their sum. - Otherwise, the total
maximum_iterationsallocates each missing limit. Its defaultNonemeans a total of 40, so the default run gives twenty iterations to each phase. - With one explicit phase limit, the other phase receives
max(0, total - explicit limit). - A total that disagrees with explicit phase limits therefore does not raise.
phase_iterations()returns the executed limits. - Evaluation caps never set or change an iteration limit. They only stop a phase. A total and a cap can therefore be given together, for example at most 40 iterations and at most 1000 evaluated rows.
- With a total cap and no phase cap, exploration can spend the whole cap and leave no consolidation. Set
maximum_exploration_evaluationsto reserve consolidation work.
Geometry change measures
Convex geometry:
- For convex geometry, change uses symmetric L-infinity Hausdorff distance between the convex sets.
- This distance measures the largest normalized coordinate displacement needed to reach the other set in either direction. It includes cut changes and translations.
Corner geometry:
- Corner geometry compares canonical exposed-face arrays in normalized domain coordinates.
- If their array shapes or face-axis columns differ, the comparison reports change as one. Otherwise, it returns the largest difference between corresponding face coordinates. Matching empty arrays return zero.
- This representation surrogate does not explicitly test face connectivity or calculate Hausdorff distance. Matching row counts and axes do not establish matching face connections.
Rounding and boxes:
- Coordinates in every comparison representation, box endpoints included, are rounded to
GeometryWorkPolicy.precision_digitsdecimals, default 12 (0 to 15). - Equal sets therefore compare as zero in every representation. A box face that moves by less than about half a unit of the last digit compares as unchanged.
- A box compared with a hull or a planar region uses the convex distance, so equal sets in different representations also compare as zero.
- See the geometry_change source documentation for the full comparison contract.
- Box-to-box comparison uses analytical endpoint differences and requires no vertex enumeration.
A box is a
BoundingBoxRegion, aConvexHullRegionbefore its first fit, or aPlanarRegionwithout cuts. - Box-to-box containment in
geometry_is_subsetcompares the rounded endpoints without a tolerance. - A box compared with other convex geometry enters as its
2**kdistinct corners, forkpositive-width coordinates, withinmaximum_cells. - Unsupported analytical or custom comparisons raise an error.
Geometry descriptions:
describe_geometry(region, *, policy)indesignoptpy.sso.regionsreturns the normalized description that the comparisons use, as a read-onlyGeometryDescriptionwith the fieldskind,bounds,boundary,complete, andstatus. It uses the same steps asgeometry_changeandgeometry_is_subset, so a caller can inspect and keep exactly what they compare.kind="box":boundaryis the2 x dmatrix of the rounded normalized lower and upper endpoints, andboundsequals it.kind="convex":boundaryholds the sorted unique rounded vertices, andboundstheir columnwise minimum and maximum.kind="corner":boundaryholds the merged exposed-face rows (zero-based face axis, plane coordinate, then the lower and the upper limits of the other coordinates), andboundsthe limits of these faces.- An empty convex or corner set has a
boundarywithout rows andbounds=None. - Every unavailable-geometry error of the description path (
work-limit,arithmetic-unavailable,membership-tolerance, orhull-consistency) givescomplete=False,bounds=None,boundary=None, the attemptedkind, and thatstatus. Invalid inputs and analytical or custom regions still raise.
Work limits and unavailable comparisons:
GeometryWorkPolicylimits this work. Pass the policy asComponentSsoOptions.geometry_work.maximum_cells, default 100000, caps corner partition points and the box corners of a box-to-convex comparison.maximum_combinations, default 1000000, caps planar intersection candidates.PlanarRegion.convex_hullandconvex_hull_evidencehave the same defaultmaximum_candidates.maximum_linear_programslimits convex comparisons. It defaults toNone, which preserves the full comparison. It counts one planned program per vertex of each compared description.linear_program_tolerance, default 1e-9 normalized domain units, a real number in[1e-10, 1e-3], sets the feasibility and optimality tolerances of every convex-distance linear program ofgeometry_change,geometry_change_evidence, andgeometry_is_subset. It is also the convex containment allowance ofgeometry_is_subset: a proposed vertex is contained when its infinity-norm distance to the container is at most this value, because a solve at tolerancetcan report a boundary vertex at a distance of ordert. It does not change the metric, box-to-box or corner comparisons, or the planar redundancy proofs. The lower end is the smallest feasibility tolerance that the HiGHS solver accepts; above1e-3a containment claim would admit vertices a thousandth of a domain width outside.
- A convex comparison solves no program for a vertex that both descriptions share, because its distance is exactly zero.
Two equal descriptions, for example a region compared with itself, therefore change by exactly zero without a program.
The budget test runs first and counts these vertices, so the
work-limitstatus does not depend on the skip. - Stored fitted-hull vertices require no enumeration under these caps.
- Custom component regions supply the
GeometryComparablemethodsgeometry_change(other, *, policy)andis_geometry_subset_of(other, *, policy). - An explicit positive configured membership tolerance on fitted hulls or cut planar regions makes nominal-boundary comparison unavailable. Its status is
membership-tolerance. Default and explicit zero tolerance retain nominal geometry comparisons. The nominal boundary cannot certify the larger set accepted by a positive tolerance. - An unavailable exploration comparison cannot certify convergence.
The optimizer retains its candidate and records
geometry_evidencein component iteration records. It can continue sampling within the remaining iteration and evaluation allowances.
Evaluation budgets and retention
maximum_function_evaluationslimits evaluated sample rows across exploration and consolidation.maximum_exploration_evaluationsandmaximum_consolidation_evaluationsadd phase-specific limits.- A phase admits a scheduled batch only when the whole batch fits every remaining evaluation cap. Otherwise the phase stops, before growth and sampling. A truncated final batch could accept a grown region, or end consolidation, from very few rows, so whole batches keep every purity signal at its scheduled size.
- Up to one batch minus one row of a cap can stay unused. Padding and shape rows are not evaluated.
Each cap has its own status:
evaluation-limit: the run total reachedmaximum_function_evaluations, or that cap refused a batch in either phase.consolidation-evaluation-limit: in a run with a consolidation phase, the consolidation rows reachedmaximum_consolidation_evaluations, or that cap refused a batch.exploration-evaluation-limit: the exploration cap in a run without consolidation.
The exploration cap ends only exploration, so with a consolidation phase it does not name the run.
The row count alone cannot show a refusal, because whole-batch admission can leave rows of a cap unused.
A cap that refuses the first batch leaves the run without an evaluated batch, so the status is not-run, with the cap status second in termination_reasons.
Other limits:
maximum_trimming_passeslimits each trimming search.- Shape rows have no separate cap. Their count grows linearly with the boundary evidence rows of the current regions.
maximum_sampler_evaluationscaps the candidate-region proposals of each sampler call. It defaults toNone, no cap.- These controls do not limit every solver operation or total elapsed time.
- The optimizers have no memory or row caps beyond these budgets. Memory and run time follow the sample counts, iteration counts, and retention flags that you choose.
- Retention flags such as
save_evaluated_samples,save_candidate_regions_after_trim, andsave_trimming_diagnosticskeep one entry per iteration or applied cut. Each flag retains one record field.save_evaluationretains the complete evaluation, the only record of the raw deficits, and also fillsevaluation_metadata. Their memory grows with the iteration count and the sample size. They default toFalse.
Growth and adaptation
Zero growth and zero geometry tolerance are supported.
- A numeric initial design with a zero-width interval, such as a point seed, needs a positive
growth_ratewhen exploration has iterations. With zero growth, the seed stays flat, sooptimize_componentsraisesValueErrorbefore any sampling. - If purity endpoints would cause division by zero during growth adaptation, set
adaptive_growth=False. Growth adaptation uses ratios of observed and target purity or rejected volume. The endpoint restriction follows from those denominators.
With adaptive_growth=True, each exploration batch updates the rate once, right after its rollback decision, in this order:
- A rolled-back batch multiplies the rate by
min(0.5, minimum_growth_factor), or by 0.5 when that factor is zero. A rollback means that the batch did not support the grown region, so the next batch does not repeat the same rejected step, also at purity one. - An accepted batch keeps the rate in three cases:
- at purity one when
do_not_adapt_on_full_purity=True; - when the measured size increase is NaN (an unavailable size);
- when the grown size does not exceed the previous size. Without a positive increase, the acceptable fraction of the added volume is undefined.
- at purity one when
- Otherwise, the update clips purity to [0.001, 0.999], computes the acceptable added-volume fraction, calls the policy, clips the factor to [0.2, 1.5], and multiplies the rate.
- Every updated rate is clipped to [0, 0.2]. The initial
growth_rate, default 0.1, is clipped to the same bounds at run start, so every executed rate lies inside them.
The corresponding minimum and maximum options control each interval.
SsoIterationRecord.growth_rate_updatenames the outcome as aGrowthRateUpdate:not-adaptive,reduced-after-rollback,adapted,skipped-full-purity,skipped-unavailable-measure, orskipped-no-measured-increase.growth_rate_after_rollbackkeeps the reduced rate of a rolled-back batch.target_accepted_fractionsupplies the policy's target purity and defaults to 0.7.- During adaptive exploration, purity below
minimum_purity_reset=0.15keeps the prior geometry. - Changing these controls can change both work and the final sampled solution space.
- A rollback reduces the rate by the default factor 0.2, so runs with rollbacks grow cautiously and can need more iterations to reach a large region.
Default volume policy:
- The default volume policy estimates the acceptable fraction of the added volume as
max(Vg * p - Vp, 0) / (Vg - Vp). Here Vg is the grown volume, Vp is the prior volume, and p is clipped sampled purity. - The product
p * Vgestimates the acceptable part of the grown region only for geometric volumes and uniform samples. Box SSO therefore passes the normalized geometric volumes of the grown and accepted boxes, independent ofBoxSsoOptions.measure. Component SSO passes the products of the component measures. - The fraction lies in [0, 1] and does not depend on the volume unit. The model treats the prior volume as acceptable.
- The policy interpolates a growth exponent using that fraction, then converts accepted-to-rejected volume ratios into a rate factor.
- The public growth-policy functions explain the formula and the linear and conservative alternatives. Their fraction input lies in [0, 1].
All three have the
GrowthAdaptationStrategycall, so each can serve asgrowth_adaptation. The linear policy ignores the dimension and the added-volume fraction. - Batch tables,
sso_stochastic_options, and the X-Rayoptimization_optionscell select the three policies with the textlinear,volume, orvolume-conservative, the DesignOptRs names, matched under the choice-name rule ofdesignoptpy.core.choices.CommonSsoOptionsitself holds the function, and agrowth_adaptationthat is neither callable norNoneraisesTypeError. - A custom
growth_adaptationreceives clipped purity, target purity, dimension, and the estimated acceptable fraction of added volume. - Finite samples and this model do not guarantee search quality or unsampled feasibility.
The example growth_and_measure_alternatives.py runs box SSO on an ellipse with the volume, conservative volume, and linear policies and with box_measure_minimum_length, and compares their growth rates and returned boxes with the analytic inscribed boxes.
The example growth_rate_update_factors.py draws the factor of each policy over the purity, without the clips of the optimizer.
Results and unavailable data
termination_reason is an SsoTerminationReason.
A run can meet several reasons at once, so termination_reasons keeps every triggered reason in priority order, and termination_reason is the first one.
The priority is:
not-run: no batch was evaluated, so the run returns its seed without evidence.no-valid-sample: the returned region has no supporting evaluated evidence (see below).consolidation-complete: the last evaluated consolidation batch metconsolidation_purity, also with fixed consolidation iterations. This is a sampled purity certificate, not a convergence of the geometry.exploration-converged: exploration converged in a run without a consolidation phase.work-limitorgeometry-unavailable: a work budget or unavailable geometry stopped the run, or a trimming search was incomplete. A box run reports onlywork-limit, after its pass cap stopped a trimming search.evaluation-limit,consolidation-evaluation-limit, andexploration-evaluation-limit: the total cap and the phase caps (see Convergence and stopping).iteration-limit: no other reason applies.
If the final attempted convergence comparison is unavailable, component results also append geometry-incomplete to termination_reasons.
It replaces a lone iteration-limit as termination_reason. Stronger stop facts keep priority.
Fixed-iteration runs do not claim an incomplete comparison merely because no convergence comparison was requested.
A default run has no cap and fixed iterations.
It reports consolidation-complete when its last consolidation batch is pure and iteration-limit otherwise.
With fixed iterations, the status therefore describes only the last batch.
For a region whose true purity is p, a batch of n independent uniform samples is pure with the probability p**n.
For example, p = 0.995 and n = 100 give about 0.61, so the status of a fixed-iteration run can depend on the seed.
The no-valid-sample reason:
no-valid-samplemeans that the returned region has no supporting evaluated evidence. Either a consolidation batch had no row that is both acceptable and useful, or, after final leanness, the returned region keeps no acceptable and useful evaluated row of the latest accepted evidence.- Such a row is a witness. Box runs test the latest accepted batch inside the returned box. Component runs test the latest trimming evidence, without padding and shape rows, inside every returned region.
- A run that evaluated a batch and keeps no witness reports
no-valid-sampleabove convergence and every limit, because those statuses would overstate a region without evidence. has_useful_retained_evidenceon the result records the witness test. The test reuses rows in memory and needs no model evaluation. A witness is sampled evidence, not a proof of feasibility in the region.
Records and exports:
designoptpy.ssoexportsSsoTerminationReason, the iteration recordsBoxIterationRecordandComponentIterationRecord, and theirIterationTimings. It also exports the run recordsSsoOperationSummary,FinalizationTimings, andComponentFinalLeanness, and the measure policyMeasureOptions.- A component record also holds
TrimmingTimings: the seconds that its trimming search spent proposing, ranking, and applying cuts. BoxTrimResultreports the selected box and measure,passes_completed,search_complete, andresidual_exclusions. Unpacking it yields the box and measure.ComponentTrimResultreports the corresponding component search data. Itsstopped_at_pass_capis true when the pass cap refused a further requested pass. A pass-cap stop and unavailable geometry both givesearch_complete=False, so this field tells them apart.residual_exclusion_indiceson both trim results and on the iteration records lists the zero-based rows thatresidual_exclusionscounts, ascending. The rows index the trimming input: the batch rows of a box run, and the trimming rows of a component run in the order that the trimmer received them.all_requested_exclusions_removedisresidual_exclusions == 0, orNonewithout a count. An empty removal order requests nothing, so it gives true. Inclusive boundaries, a slack of one, or a rejected row that coincides with a viable row can leave an exclusion inside. In records, the rows describe the trimmed geometry before iteration leanness, as the count does.
Run records:
result.optionsis the request: the validated options of the call, unchanged.result.effective_optionsis what ran.CommonSsoOptions.effective_options()derives the effective record. It states the phase iteration limits and their total, the phase sample schedules, and, with adaptive growth, the clipped initial growth rate.number_samplesstates the common count when both phase schedules hold one constant count. Every other field keeps its value.- The effective record is a record, not a template: its explicit phase settings take precedence over a later edit of
maximum_iterationsornumber_samples. Edit the requested options to configure a new run. - The option
evaluator_snapshot(defaultNone) is called once asevaluator_snapshot(evaluator), before the first batch and also when no batch runs.result.evaluator_snapshotkeeps its value without a copy, orNonewithout the option. An error of the function propagates. result.operation_summary(SsoOperationSummary) keeps the evaluated rows and batches of each phase and independent run facts, also without retained history. The facts are the exhausted total and phase budgets, the exhausted phase iteration limits, the consolidation purity of the last batch, the convergence of each phase, an invalid last batch, and a trimming search that stopped at a work limit. A budget is exhausted when its rows reached it or when it refused a scheduled batch. A cap ofNoneis never exhausted, and a zero iteration limit is exhausted. The flags do not depend on the status priority, so a fact thattermination_reasonsomits can still appear here.result.elapsed_secondsis the wall-clock time of the whole run.result.finalization_timings(FinalizationTimings) times the final processing after the phase loops. Itstotalcovers the final leanness, the witness check, the stop classification, and the final measures; itsleannessis the final leanness alone, including its removal order.leannessisNonewhen final leanness did not run (policynever, or no accepted evidence). Iteration records hold iteration work only.
Incomplete trimming and unavailable geometry:
trimming_geometry_evidenceretains proposal or application failures that prevent a complete trimming search.- A rejected rank-deficient hull trial adds no evidence, because its zero-measure region is well defined (see "Rank-deficient hull trials" in Trimming and candidate selection). The record counts it in
trimming_rank_deficient_trialsorleanness_rank_deficient_trials. - A dropped proposal sets the search incomplete and blocks convergence. Iteration leanness still runs, because the regions and the evidence stay valid. Only a trim that kept its regions, because a trimmed region was unavailable, skips leanness.
- Evidence with any status except
work-limityieldsGEOMETRY_UNAVAILABLE. Exclusively budget-limited evidence yieldsWORK_LIMIT. - The unavailable cut could still improve the region, so
GEOMETRY_UNAVAILABLEcannot certify convergence. The optimizer retains its safe current regions and does not label an incomplete trimming search converged. - A component run stops before sampling when it cannot construct or measure a grown region.
It keeps the last accepted regions and reports
work-limitfor a budget status andgeometry-unavailableotherwise. - A component run also stops with
work-limitwhen a rejection sampler raisesSamplingLimitErrorwhile it draws candidate rows or completes shape rows. The run keeps the last accepted regions and the records of the completed iterations. The stopped iteration has no record. Its proposals still count inComponentOptimizationResult.sampler_proposals. - Configured final leanness (
ALWAYSorEND_ONLY) applies after every stop reason, in box and component SSO alike. - Iteration records retain these values when available. Caller-supplied functions may omit search-work data as
None. - The returned geometry determines residual exclusions, independently of missing diagnostics from a caller-supplied function.
Termination reasons and sampled purity describe observed work and stopping. They do not prove feasibility at unsampled designs.
number_good_designscounts performance-good rows.number_acceptable_designscounts rows acceptable under the selected requirement space.number_acceptable_and_useful_designscounts the intersection used to preserve viable evaluated designs.postprocess_boxandpostprocess_componentsconvert a result into per-iteration metric series.
Final measure and unavailable values:
final_measuremeasures the returned geometry after final leanness, independently of the sampled before-and-after history.- Unknown final geometry remains unavailable. A measure that is not finite gives
None. - A design-space measure that is not finite makes the normalized measures of
postprocess_boxandpostprocess_componentsNone. The completed run stays available. final_geometry_evidenceseparately reports each returned component's boundary reconstruction status. An unavailable boundary reconstruction can coexist with an available Monte Carlo measure estimate.- Neither a missing comparison nor a missing measure is replaced by numeric zero.
- Undefined normalization is
NaN. Consolidation growth isNonein iteration records andNaNin numeric metric series. - A change ratio of the metrics divides an iteration by its predecessor. It is
NaNwhere the predecessor is zero,NaN, or infinite, or where the quotient is not finite, so the first entry is alwaysNaN. No change ratio is infinite. - A stage that an iteration did not run has the time
NoneinIterationTimings, andNaNin its row of thetime_elapsed_*metric series. A recorded0.0is a measured duration. For example, consolidation does not grow, a rolled-back batch does not trim or test convergence, and a batch that meetsconsolidation_puritydoes not trim.IterationTimingslists the rules. The iteration total is always measured. Both box and component metrics holdtime_elapsed_trimming_orderandtime_elapsed_leanness. The timing views stack aNaNstage time as zero seconds, because the stage did not run, and leave out a stage that ran in no iteration. The box timing views draw the stagesadapt_growth_rate,grow,generate,evaluate,label,count,measure,trimming_order,trim,leanness, andconvergence; the component views addshapeandprepare. Iteration time that no recorded stage covers reads as "not attributed to a stage".
Measure estimates:
- Planar and corner
estimate_measuremethods return these values:- the measure value, sample count, evaluations, seed, and cache status;
- the estimated standard error;
- the inside count (
accepted_count); - Wilson score intervals of the inside fraction and of the measure (
fraction_interval,measure_interval) atconfidence_level, default 0.95.
- A corner region splits its envelope at every anchor coordinate. When these cells fit
measure_maximum_cells, default 100000, and their arithmetic is representable, the measure is the exact sum of the cells that no cut removes. The result then has the exact form below. Reported measures and growth inputs shift slightly from the Monte Carlo value, with no sampling error for small cell counts.measure_maximum_cells=0always selects the estimate. - Otherwise the methods sample the proposal box uniformly and scale its volume by the observed inside fraction. This is Monte Carlo estimation.
- Each read-only geometry stores its own reusable estimates. Reusing an estimate for the same sample-count and seed key is memoization.
- Changing the requested sample count or seed refines the estimate independently of the configured scalar
measureproperty. - Estimates use a local random generator and have no sample cap: the requested count is the work. They leave the optimizer's or caller's generator unchanged.
evaluation_batch_size(defaultNone, one batch) caps the rows drawn and classified per batch, which bounds temporary memory. The batches continue one row-major generator stream, and a row's membership does not depend on the other rows of its batch, so every batch size gives the same estimate, counts, and intervals, bit for bit.MeasureEstimate.evaluation_batch_sizeechoes the request on every return, also for an exact measure, undefined geometry, and a cache hit.- The standard error estimates sampling uncertainty. It does not prove feasibility. It is zero when no sample or every sample is inside, although such a sample cannot certify an empty or a full box.
- The Wilson interval keeps a positive width there: with
nsamples and no hit, its upper end isz**2 / (n + z**2). - A region without cuts, such as a pending region initialized from a box, is exactly its envelope box.
Its
measureproperty andestimate_measurereturn the exact box measure without sampling:evaluationsis 0,accepted_countisNone, and both intervals have zero width. - With cuts and without an exact measure, the property draws
measure_samplesrows when set, ormeasure_estimation_factorrows per evidence row without an upper cap. The property andestimate_measure()then give the same estimate.
Measure policy of component SSO:
ComponentSsoOptions.measure_options(MeasureOptions:number_samples,seed,confidence_level,refresh,evaluation_batch_size) sets how component SSO measures every region: the initial, grown, trimmed, lean, and final regions, and the measures inside the built-in trimmer. A region withestimate_measure(planar and corner regions) is measured with it. A box or hull region gives its exactmeasure.- Component
i(zero-based, in layout order) uses the seedmeasure_options.seed + i. Each estimate records its seed, soestimate_measurewith that seed and the same count reproduces it. measure_options.evaluation_batch_size(defaultNone, one batch) passes unchanged to every component estimate and follows the validation of theestimate_measurekeyword. It bounds the temporary memory of each estimate. Every batch size gives the same estimates, so the regions, measures, and statuses of the run do not change; eachMeasureEstimaterecords the request.- Theory: the product measure is the product of the component measures. Independent component estimates give an unbiased product, because
E[XY] = E[X] E[Y]for independentXandY. One shared seed would make the components transform the same uniform numbers, so the estimates would be correlated, andCov(X, Y)would bias the product. Each component restarts from its own seed for every estimate, so its estimates over the run use common random numbers: their differences, which drive growth and trimming, carry less sampling noise. - The default
MeasureOptions()reproduces themeasureproperty for component 0. A component after the first uses another seed than the property, so its run measure can differ fromregion.measurewithin the sampling error. - Limit: two runs whose seeds differ by less than the number of components share some component seeds. The seeds inside one run are distinct.
ComponentOptimizationResult.final_measure_estimateskeeps the finalMeasureEstimateof each component, orNonefor a region without an estimator.final_component_measureholds their values.- A custom trimmer receives the policy in
ComponentTrimmingControls.measure_options. A custom region subclass that overrides only themeasureproperty must also overrideestimate_measure, because component SSO measures through the method. The override must accept every keyword of the method, includingevaluation_batch_size. - A batch table has no text form for
measure_options; pass aMeasureOptionsin the fixed options. A field of the options record takes precedence over the<field>_optionskeyword rule, so the component field is not read as keywords of the boxmeasurefunction.
Independent purity estimate
estimate_solution_space_purity(evaluator, region, sampling_box, sample_count, *, component_layout=None, rng=None, maximum_batches=1000, adaptive_batch_size=False) checks a returned region with fresh samples that the optimizer did not see.
region is a Box, or one candidate region per component with the component_layout that maps them to design columns.
- Box: the function draws
sample_countuniform designs fromsampling_boxand keeps the draws inside the box. - Component regions: the function draws
sample_countdesigns inside the region, one component at a time. Each component draws batches ofsample_countproposals from its ownsampling_box(within the component columns ofsampling_box) and keeps the firstsample_countproposals inside its region. Every evaluated design therefore lies inside the region, so every method gets all its draws. A component that cannot be filled withinmaximum_batchesbatches leaves the purity unavailable (None) and the evaluator uncalled.adaptive_batch_size=Truesizes each component batch after the first from the need: the missing designs over the observed acceptance fraction, plus ten percent, at mostsample_count.maximum_batches * sample_countis then the proposal budget. The draws stay uniform, but a seeded result andproposal_countchange.
The function evaluates the in-region designs once and returns a SolutionSpacePurityEstimate.
A design is accepted when every performance and physical deficit is at most zero: it is a valid design. Positive infinity marks an unavailable response and rejects; negative infinity is an inactive limit and accepts.
A NaN deficit is malformed data in the DesignEvaluation contract and raises ValueError, as in the optimizers.
The estimate holds draw_count, in_region_count, accepted_count, the in-region design_samples, their acceptance labels, empirical_purity, purity_interval, and proposal_count (the membership tests of the sampling).
sample_count=0 returns None. Without an in-region design, the evaluator is not called, and empirical_purity and purity_interval are None.
Drawing from a box and keeping only the in-region draws is rejection sampling: it gives uniform draws in the covered part of the region.
Independent uniform draws of each component give a uniform draw of their Cartesian product, so the component designs are uniform in the region,
provided that each component sampling box contains its region, as the component samplers of SSO assume.
Drawing complete designs from the joint box instead keeps only the product of the per-component acceptance fractions, which falls quickly with more components and coordinates.
Purity is a volume fraction, so a thin bad boundary layer gets few draws.
The accepted count of n draws is binomial with the unknown purity, and purity_interval is its 95 percent Wilson score interval, clipped to [0, 1].
Unlike the normal approximation, the Wilson interval keeps a positive width when every draw passes: its lower end is then n / (n + z**2).
The estimate does not prove that every point of the region meets the requirements, and a small region inside a large sampling box receives few draws and a wide interval.
Pass a separate rng to keep the validation draws apart from the optimizer draws.
Progress logging
While a run works, it writes progress records to the designoptpy.sso.box or designoptpy.sso.component logger of the Python logging module.
These are logger names. Both are children of the designoptpy.sso logger, so one handler on designoptpy.sso receives both.
Each iteration writes its label counts at DEBUG after it labels its sample, and its purity and measure at INFO after it records the iteration.
An iteration that a limit stops before it is recorded writes no INFO record.
WARNING records report three conditions:
- an iteration keeps the prior geometry because its sample is unsuitable for trimming; with adaptive growth, the record also states the reduced growth rate;
- a run ends with
no-valid-sampleafter no iteration found an acceptable design; - in component runs only, a candidate or shape sampler raises
SamplingLimitError. The sampler-cap check before sampling stops a component run without a record.
A severity is the importance number of a record, such as logging.INFO (20).
logging_level is a severity threshold: the run writes a record only when its severity is at least this value.
The option accepts a standard integer severity (used as given), a standard level name such as "debug" or "warning" (matched under the choice-name rule of designoptpy.core.choices), "off", or None.
A Boolean raises TypeError, and an unknown name raises ValueError.
None and "off" disable every record, including warnings. The default is "info".
batch_sso_stochastic_analysis, iter_batch_sso_stochastic_analysis, and sso_stochastic_options treat a None option value as blank: it keeps the inherited or default value, as for every option there.
The generic run_batch and iter_batch pass fixed options to the runner unchanged and treat only a None case value as blank.
Use "off", not None, to disable records through these typed functions or a batch table.
The threshold only selects records; it does not change any search decision or result.
The library adds no log handlers, so the application decides what is displayed.
By default, Python displays only WARNING and higher records.
Call logging.basicConfig(level=logging.INFO) to display the progress records, as the box and component examples do in their __main__ blocks.
Custom callbacks
A function supplied for the workflow to call is a callback.
Every strategy protocol accepts a plain callable with the documented call, for example GrowthAdaptationStrategy, TrimmingOrderStrategy, and CandidateRegionFactory.
Use functools.partial to bind configuration to a strategy or region factory.
Each strategy kind has one fixed call. The orchestrator passes its caps in a frozen keyword-only controls record.
| Strategy | Call | controls record and fields |
SSO options that set the fields |
|---|---|---|---|
candidate_sampler |
sampler(regions, layout, number_samples, rng, *, controls) returns SamplingResult |
SamplingControls: maximum_evaluations, maximum_padding |
maximum_sampler_evaluations; maximum_padding, or 0 when use_padding=False |
shape_sampler |
shape_sampler(regions, layout, sampling_box, shape_type, rng, *, controls) returns SamplingResult without padding rows |
ShapeSamplingControls: candidate_sampler, candidate_controls |
candidate_sampler; maximum_sampler_evaluations with no padding |
component trimmer |
trimmer(samples, is_viable, order, regions, layout, *, cut_cost, component_choice, optimal_choice, passes, controls) |
ComponentTrimmingControls: maximum_passes, retain_diagnostics, measure_regions |
maximum_trimming_passes, save_trimming_diagnostics |
box trimmer |
trimmer(samples, is_viable, order, candidate_box, *, measure, slack, passes, controls) |
BoxTrimmingControls: maximum_passes |
maximum_trimming_passes |
A built-in strategy, a wrapped built-in such as a functools.partial or a lambda, and a custom strategy receive the same record.
The built-ins accept these caps only through controls. A custom strategy must honor every field.
With a pass cap, a trimmer must also report passes_completed and search_complete.
A component trimmer can also report stopped_at_pass_cap. Without it, component SSO counts an incomplete search that completed every allowed pass as stopped at the cap.
The orchestrator replaces a controls value bound with functools.partial, so set caps through the SSO options.
Batch callback options, such as candidate_sampler_options, cannot set controls, a cap, geometry_work, retain_diagnostics, or rng.
They raise ValueError that names the key and the SSO option or call argument to set.
Set the caps and save_trimming_diagnostics with their own batch-table columns, such as maximum_trimming_passes and maximum_sampler_evaluations, or with fixed_options.
geometry_work holds a GeometryWorkPolicy object, which no cell can express, so set it with fixed_options in Python.
Because the call does not depend on how a strategy is wrapped, the same configuration gives the same work limits.
Before each candidate-sampler call, component SSO stops with work-limit when number_samples * n_components exceeds maximum_evaluations.
Each component must accept number_samples local rows, and each accepted complete design passed one membership test per component.
Both rejection samplers therefore need at least that many proposals. The rule is the same for every sampler.
Shape completion applies the same pre-check to each component's complement rows and raises SamplingLimitError.
Component SSO catches this error from either sampling site, charges the attempted proposals, and stops with work-limit.
Every shape sampler reports its proposals and batches in its SamplingResult. Iteration records add them to sampler_proposals and sampler_batches.
A custom evaluated sampler must return the requested number of finite real rows inside the active candidate.
A custom function receives documented inputs and must return results with the documented shapes and values.
A custom trimmer must return a finite nonnegative measure and contained, supported geometry.
Convex containment checks use linear programming with the normalized tolerance GeometryWorkPolicy.linear_program_tolerance, default 1e-9, which is also their containment allowance.
Corner containment checks use an exact bounded cell-and-face partition.
A returned region that is the input region object itself is contained without a check, so an unchanged component needs no proof.
Containment checks between corner and convex results from custom functions are unsupported. Contained component subdomains are supported.
Default shape rows come from retained region definitions.
A caller-supplied shape sampler can also run on the first enabled iteration.
It must respect the active proposal bounds and shape-row limit.
Ordinary ranking scores must be finite. Positive infinity explicitly rejects a model result.
Negative infinity cannot serve as a special marker for an unavailable ranking score.
Retained design_score arrays preserve positive-infinity rejection scores.
None means those scores were not retained.
Batch studies
run_batch(cases, runner, ...) runs BatchCase option variants with a caller-supplied runner.
It calls runner(evaluator=..., rng=..., **options) once per case. Nonblank case options override fixed_options.
Every case receives a full copy of one starting generator, built from the batch argument rng, so all cases start from the same random state.
The copy, made with designoptpy.core.sampling.copy_generator, holds the bit state and the seed sequence, so samplers that spawn child generators, such as Latin-hypercube sampling, also start equal.
A generator without a seed sequence, such as Generator(Philox(key=42)), gives copies without one, so a spawning sampler fails in every case, as it fails for that generator.
Giving compared cases the same random stream is called common random numbers.
Matching starts control the initial sampling variation; different algorithms can still consume different later draws.
rng is a NumPy Generator, an integer seed, or None. An integer seed reproduces the starts across invocations, and a supplied Generator does not advance.
designoptpy.sso.batch.batch_sso_stochastic_analysis and iter_batch_sso_stochastic_analysis run box or component SSO studies.
A component_layout selects component SSO; otherwise the study runs box SSO.
They use the same rng argument and the same full copies, so every case starts from one state.
The SSO options hold no random state, so a case cannot set its own generator.
The iterator yields one case at a time, so you can keep only metrics for long studies.
Each yielded BatchSsoRun keeps the executed_options that the case ran with, also when the iterator retains only metrics.
workers (default 1) runs up to that many cases at once on threads, in all four batch functions. The default runs the cases one after the other on the calling thread.
With more workers, the records still arrive in input order, each case keeps its own generator copy, and the earliest failing case in input order raises after the running cases finish.
The SSO study functions then require evaluator_factory, so that each case has its own evaluator; a factory that returns one shared evaluator declares it safe for concurrent calls.
Threads share the Python global interpreter lock, so they save time only for a model that releases it, such as a compiled model or an external solver.
Eight box cases with a model that releases the lock for 20 ms per call took 3.4 s serially and 2.1 s with four workers; a cheap NumPy model gained nothing.
Progress messages of concurrent cases interleave, and wall-clock diagnostics grow under contention.
case_limits=BatchCaseLimits(sample_count=..., maximum_iterations=..., maximum_function_evaluations=...) reduces a whole study, for example for a tutorial or a quick check.
After every case option is valid, both study functions resolve each case and apply the limits to all cases together:
sample_countmultiplies every phase sample count of every case by one factor,min(1, sample_count / largest), rounds down, and keeps each count at least one. One factor keeps the declared ratios between the cases before rounding.maximum_iterationscaps each resolved phase iteration limit; the executed options state both phase limits explicitly.maximum_function_evaluationscaps the total evaluation cap of each case.
The limits take precedence over the fixed and case options, which cannot express a common ratio-preserving reduction.
Two warnings report the effect of the limits. Both are CaseLimitsWarning, a UserWarning subclass.
- The first warning names the cases whose executed settings changed.
- The second warning names the case pairs that the limits made execute equal settings. Their comparison cannot show the effect of their declared difference.
A reduced study is cheaper and can give lower-quality regions than the declared settings.
read_batch_cases(path, limits=..., delimiter=None) reads cases from a delimited-text table or a workbook. The file suffix, compared without letter case, selects the reader:
| Suffix | Reader | Delimiter when delimiter is None |
|---|---|---|
.csv |
delimited text | comma |
.tsv |
delimited text | tab |
.txt, .dat |
delimited text | detected from the header line |
.xlsx, .xlsm, .xltx, .xltm |
Office Open XML workbook, first worksheet | not applicable |
.ods |
OpenDocument spreadsheet, first sheet in document order | not applicable |
Any other suffix fails with a message that names the conversion of a .xls or .xlsb workbook to .xlsx.
.xltx and .xltm are Excel templates in the archive format of .xlsx and .xlsm. Reading .xlsm and .xltm runs no macros.
Workbook formats require the io extra.
An explicit delimiter, one ASCII character other than a double quote, a line break, or NUL, replaces the suffix rule for every delimited-text suffix; with a workbook suffix it fails.
Detection reads the header line, the text before the first line break, after a UTF-8 byte order mark. It counts tab, semicolon, comma, and vertical bar outside double-quoted text and takes the most frequent one; a tie selects the earlier one in that order.
A header without any of them fails. A space is never a delimiter, because a matrix literal such as [1 2] holds spaces; use a tab instead.
The header holds names only, so a comma inside a matrix literal of a data row cannot change the choice. DesignOptRs applies the same rule.
Delimited text then follows the CSV rules: a double quote quotes a field, a doubled quote is one quote, and rows are rectangular.
batch_sso_stochastic_analysis and iter_batch_sso_stochastic_analysis read a table path with the suffix rule. Call read_batch_cases first to pass an explicit delimiter.
The table needs the exact headers id and reference_id; other columns name options.
Headers must be unique and nonblank, and a workbook header must be a text cell. The id and reference_id cells are trimmed.
A numeric identifier cell of a workbook gives the shortest decimal text that reads back to the same number, without an exponent: 12 gives 12 and 1e-7 gives 0.0000001.
A Boolean identifier cell fails. A workbook cell that holds an Excel error value, such as #N/A, or a date fails in every column. DesignOptRs applies the same rules.
A blank or repeated id fails when the batch starts. A nonblank reference_id must name an id of the same table.
A workbook without a named sheet uses its first sheet, because a saved window state must not choose the study cases.
The row, column, cell, and text limits of InputLimits apply to that sheet, to the shared text of the workbook, and to the archive.
The reader does not check the other sheets, because it never loads them.
An SSO batch table names its options with the field names of the selected option record, BoxSsoOptions or ComponentSsoOptions.
<field>_options holds the keywords of a configured function, such as trimmer_options for trimmer.
A name that is a field of the options record is always that field: the component field measure_options holds a MeasureOptions, while measure_options in a box table holds the keywords of the box measure function.
Column names are exact: letter case, spaces, and punctuation count, and no name has an alias.
Enumerated cell values are choice names and follow the choice-name rule of designoptpy.core.choices.
A column that names no option of the selected record raises ValueError before any model work, also when its cells are blank.
For example, a box table rejects the component field use_padding.
Column order does not change the result.
Cases and fixed_options that Python code constructs use the same names.
The cells use the spreadsheet literal grammar of the core README. The batch runner then applies these cell rules:
- A blank cell inherits the fixed run option.
[]sets an optional field toNoneand replaces the fixed value.maximum_iterations[]selects the automatic allocation, andexploration_samples[]removes the phase schedule.[]fails for a field that has noNonesetting.- A finite whole number becomes an integer, so
40sets an iteration limit. - A matrix with one row or one column is a vector, so
[100 200]sets the schedule(100, 200). A one-row cell, such as{2,4}, is a flat vector too, so it sets the schedule(2, 4). Infmeans no limit only formaximum_function_evaluations,maximum_exploration_evaluations,maximum_consolidation_evaluations,maximum_trimming_passes,maximum_sampler_evaluations, andmaximum_reused_samples.Inffails for every other option.-InfandNaNfail for every option.- Enumerated text is exact:
requirement_spaceisOmega0toOmega3;apply_leannessisalways,end-only, ornever;trimming_passesissingle,reduced, orfull;trimming_orderisscore-ascending,score-descending,score-ascending-then-descending, orrandom;leanness_orderisscore-ascending,score-descending, orrandom; the shape types areadvancedorsimple;growth_adaptationislinear,volume, orvolume-conservative.growth_adaptation[]selects the default volume policy (None). - A Boolean is
trueorfalsein any ASCII letter case. A number is not a Boolean. - Each
save_*column is one Boolean retention flag, such assave_design_score.
A <field>_options cell is a name-value cell in one of two forms: one row of alternating names and values, {'mode','score-ascending'}, or rows of one name and one value, {'passes','full';'slack',0.1}.
A later repeated name replaces the earlier one.
The names are the exact keywords of the configured function, such as slack and passes for trim_box, or maximum_batches for sample_individual_feasible.
Inside candidate_sampler_options, two keys have the same rules as in DesignOptRs, checked when the options are built, before the first case runs.
maximum_batches (proposal batches per component, default 1000) must be a finite positive integer; Inf, [], 0, and fractions fail, because a rejection sampler without a batch cap need not end on an empty region. maximum_sampler_evaluations caps the total proposals instead.
maximum_refill_batch_size is a positive integer, or Inf or [] for no cap, so one batch holds the requested row count.
The configured candidate sampler checks its other keys at its first call.
A nested configured function takes its keywords from <keyword>_options inside the cell, such as cut_cost_options inside trimmer_options. The sampler options are named sampling_method_options, the native keyword of the samplers.
geometry_change_options needs a configured geometry_change, because the built-in comparison takes its limits from geometry_work.
A text cell cannot name a function, so a configured-function column, such as trimmer, works only through the Python API.
The exception is growth_adaptation, whose three policy names select the built-in functions.
read_batch_cases(..., limits=...) and the study functions' input_limits= take a core InputLimits object.
The core README describes these untrusted-input limits.
sso_stochastic_options("box" | "component", options), exported from designoptpy.sso, accepts the same names and applies the same value rules.
It returns a validated BoxSsoOptions or ComponentSsoOptions. Python code can also construct these classes directly.
This table runs one box case with a two-entry exploration schedule, an unlimited evaluation cap, and a bound order mode:
id,reference_id,number_samples,exploration_samples,maximum_function_evaluations,save_design_score,trimming_orderer_options
base,,100,[100 200],Inf,true,"{'mode','score-ascending'}"
designoptpy.sso.batch_plotting draws the runs of a batch side by side (see Projections and plots).
batch_box_metric_series and batch_component_metric_series return the compared measure, purity, and evaluation series of the selected cases without Matplotlib, with finite-value masks and an availability status per case.
Sensitivity plots group cases by their reference_id and require the reference case to be present.
A reference_id names a case only when it equals the case ID exactly, as the batch runner compares IDs; the reference roles of the comparison views use the same rule.
Only finite numeric option values are plotted.
All includes related cases even when several recorded options differ.
Individual includes the reference and cases changing the selected option while all other recorded option values and presence match.
An option that no case changes alone gets no figure, because the related runs alone cannot separate its effect from the effects of the other options.
Both compare the last sampled pre-trim measure, last sampled purity, and total evaluated-design count.
All can mix several option effects; Individual controls only the other recorded options.
Interpretation still depends on matching unrecorded problem inputs.
These are comparisons of executed runs, not exact response curves or guarantees about returned geometry.
The option values come from the options that each run used, when they are known, and otherwise from the batch cases.
Pass the executed_options of the BatchSsoRun records to plot_batch_box_metrics or plot_batch_component_metrics (one record per case, aligned with the full batch).
Without them, the plots use result.options when every result is an optimization result; in a batch run, these are the executed options after the case limits.
An option name that is a field of the options record is then read from the record: maximum_iterations is the sum of the phase iteration limits that run, the phase limits and sample schedules are the resolved ones, number_samples is the common phase schedule when both phases share one, and a one-entry schedule (c,) reads c.
A name that is not a field, such as a <field>_options keyword name, keeps its declared value.
The axis label says which values it shows: option <name> (executed) or option <name> (declared), and a caption line explains the source.
Executed values attribute an effect only to settings that ran. For example, cases that declare 40 and 20 iterations under BatchCaseLimits(maximum_iterations=3) both run 3 + 3 iterations, so their executed totals are both 6, and no figure shows an iteration effect that the limits removed.
The executed growth_rate is the requested rate: the run clips it at its start, and the plot shows the clipped start from the recorded first exploration growth rate, with the label option growth_rate (<source>, before clipping).
sensitivity_selections(cases, executed_options=...), exported from designoptpy.sso, returns the selected runs of every figure without Matplotlib: per reference case and option, the zero-based positions and option values of the related and the individual runs, and the OptionValueSource (executed or declared).
Replicate statistics
One batch with one seed shows one difference between two cases.
Independent replicates, the same batch repeated with other seeds, show whether that difference exceeds the variation between seeds.
descriptive_statistics(values) summarizes the outcomes of one case over the replicates.
paired_difference_statistics(pairs) summarizes the per-replicate differences case - reference of (case, reference) pairs.
Both are exported from designoptpy.sso and return a DescriptiveStatistics record. DesignOptRs has the same functions, fields, and error messages.
| Field | Meaning |
|---|---|
count |
available finite observations |
missing |
unavailable observations (None) |
mean |
arithmetic mean; None without an observation |
sample_variance |
unbiased sample variance with the divisor count - 1; None below two observations |
standard_error |
sqrt(sample_variance) / sqrt(count), the uncertainty of the mean; None below two observations |
minimum, maximum |
range of the available observations; None without an observation |
None and NaN mean different things:
Noneis an unavailable outcome, for example a run without a history. It adds one tomissingand never counts as zero.- NaN or an infinity is a malformed outcome. It raises
ValueError(statistical observations must be finite or unavailable, orpaired observations must be finite or unavailablefor a pair member). A Boolean or a value that is not a real number raisesTypeError. - A pair with an unavailable member gives an unavailable difference.
The sample standard deviation is sqrt(sample_variance).
One observation cannot show variation, so the variance and the standard error are None, not zero.
The functions update the mean and the central sum of squares once per observation (Welford's recurrence), centered at the first observation, so a small spread around a large offset keeps its digits.
A scaled central sum avoids intermediate overflow; observations whose moments exceed the float64 range raise ValueError.
Pairing keeps the covariance reduction of common random numbers: the variance of a difference is var(a) + var(b) - 2 cov(a, b), smaller than the sum when the paired outcomes are positively correlated.
from designoptpy.sso import descriptive_statistics, paired_difference_statistics
descriptive_statistics([220.6, 239.6, None]) # count 2, missing 1, mean 230.1
paired_difference_statistics([(246.0, 220.6), (214.4, 239.6)]) # differences 25.4 and -25.2
The batch functions do not create independent repeated-run seeds automatically.
Tutorial 10 of the examples shows the pattern: one seed per replicate, seed + i, and these statistics over the replicates.
Product families
A product family is a set of variants that can share some component designs.
An assignment gives each variant a group label. The variants of one group share one component design.
A shared design must lie in the solution space of every member.
Each accepted group therefore needs a witness: one design verified inside every member region.
For boxes, the shared space is the exact box intersection, so no search is necessary.
group_boxes reports that exact intersection for every greedy group. The greedy endpoints alone can understate the shared box, so they are not reported as its bounds.
For general regions, find_common_design searches for a witness.
It intersects the declared bounds and the membership boxes of the regions (common_bounds), verifies known designs and retained inside samples, and then runs one score search inside that box.
A product's solution space lies inside its declared design space, and every accepted design lies in its region's membership box, so an empty intersection proves that no admissible witness exists.
A region whose membership_box is None still contributes its declared bounds, so the search box is always finite.
Family functions accept any RegionQuery: an object with a Box bounds, a membership_box, and classify, which returns a RegionClassification.
Every family classification checks a declared membership_box. A region that accepts a row outside it raises ValueError, because a false certificate can cause a false emptiness claim.
A solver proposal that is not finite records invalid-design, and the verified start stays.
The built-in regions qualify, and so can a small adapter without sampling or trimming.
The number of assignments of n variants is the Bell number bell_number(n), for example 115,975 for ten variants.
The example product_family_design.py optimizes three interval variants and states the analytic optimum.
Six lessons in the same folder check further steps against exact references:
product_family_clique_policies.pycompares the clique policies (see "Controlled policy comparison" below).product_family_component_sharing.pyvalidates the commonality patterns of circular solution spaces and optimizes their assignments.product_family_shared_intervals.pygroups one-dimensional intervals and decides every subset by its intersection.product_family_box_optimization.pyoptimizes a two-component box family and compares each verified cost with its analytic minimum.product_family_restricted_assignments.pychecksrestricted_assignment_schemesagainst an exhaustive filter of all partitions.product_family_commonality_frontier.pyshowsincrease_binary_cardinalityand the superset pruning ofvalidate_component_commonality.
The example partial_commonality_score.py draws the membership-signed cumulative score of component_cumulative_score for one, two, and three circular variants.
The research study product_family_ellipses.py in examples/research_studies compares the clique heuristic, exhaustive enumeration, and the genetic algorithm on four products with rotated ellipse solution spaces.
It also shows a solver constraint back-off that lets boundary optima pass the exact membership check.
designoptpy.sso.family has one module per concept. Import every name from the package.
| Module | Content |
|---|---|
assignments |
Count, enumerate, restrict, canonicalize, and pack assignments |
common_design |
find_common_design, CommonDesignOptions, the membership-signed component_cumulative_score, and the bound intersection common_bounds |
grouping |
clique_compatible_groups, random_compatible_groups, and validate_component_commonality |
component_optimization |
Exhaustive and metaheuristic optimization of component assignments and their shared designs |
assignment_genetic |
genetic_assignment_metaheuristic, the integer genetic algorithm over assignments |
boxes |
Interval and box commonality, greedy grouping, and optimize_box_product_family_exhaustive |
search_adapters |
scipy_bounded_optimizer and the verification of solver proposals |
search_state |
Result records such as CommonDesignResult, SubproblemResult, SubsetResult, and AssignmentResult, the verification evidence SubproblemEvidence with its SubproblemCheck records, and SearchOutcome |
iter_assignment_schemes, iter_binary_vectors, and iter_commonality_patterns yield results one at a time in the order of the eager functions.
The eager functions all_assignment_schemes, all_binary_vectors, and all_commonality_patterns have no item cap.
They cost time and memory proportional to the result size, for example bell_number(n) * n entries for assignments, and raise MemoryError when the result does not fit.
Estimate the count first.
enumerate_assignment_schemes(n, order="by-groups", evaluation_budget=None) bounds the work instead.
Its evaluation_budget limits the visited search states, the unit of restricted_assignment_schemes: a search state is one partial assignment, counted when the search enters it.
It returns an AssignmentEnumeration with schemes, complete, stop_reason ("completed" or "evaluation-budget"), and visited_states.
A budget stop returns a prefix of the complete enumeration in the same order, without a checkpoint for resumption.
A prefix of an iterator, taken with itertools.islice, bounds only the number of returned items.
Common-design search records a SearchOutcome on CommonDesignResult:
| Outcome | Meaning |
|---|---|
FEASIBLE |
A verified witness exists. |
CERTIFIED_INFEASIBLE |
A proof shows that no witness exists. Larger groups that contain this group are also infeasible. |
SEARCH_MISS |
A bounded search found no witness. This proves nothing. |
Adding variants cannot create a witness for a certified infeasible group, so only a certificate supports pruning larger groups.
Never cache a search miss as infeasible. The feasible property simplifies success checks; inspect outcome before you prune or stop.
Certificates of find_common_design:
disjoint-bounds: the declared bounds and membership boxes do not intersect.linear-program-certificate: when every region is aPlanarRegionor aBoundingBoxRegion, the common part is a polyhedron. Without a witness from the earlier steps,polyhedral_intersectionsolves one linear program (LP) for it in unit-box coordinates, with each row scaled by its largest coefficient and then by its norm: minimizessubject to every normalized row residual and every box-face distance at mosts. Its solution is the Chebyshev center, the center of the largest inscribed ball.s < 0gives a point far from every boundary, which is verified like any witness (reasonlinear-program). Otherwise the LP multipliersy >= 0are checked as a Farkas certificate in design units: for the rowsP @ x <= q,M = sum(min(g * lower, g * upper))withg = y @ Pboundsg @ xfrom below over the box, soM > y @ (q + delta)proves that no accepted design satisfies every row. Each plane row is relaxed by the largest rounding allowance of its membership test, and each caller row byfeasibility_toleranceplus the rounding allowanceK * eps * (|A_row| @ reach + |b|), withK = max(10, d + 2)andreach = max(|lower|, |upper|). The check adds a rounding allowance of(n_rows + n_equalities + d + 3) * epstimes its term magnitudes. Any multipliers that pass prove emptiness, so the check trusts no LP output. The LP point of every optimum is kept asminimax_point: the design whose largest normalized residualsis smallest. It equals the center for an interior decision.- An intersection of zero volume, such as two regions that touch along one plane, is undecided (
s = 0). The minimax point of an undecided test is checked like any witness: a membership-signed score at most zero, the exact common bounds, the linear rows, and physical residuals at mostfeasibility_tolerance. So a point on a shared plane that every region accepts becomes the witness (reasonlinear-program,linear_program.decision == "undecided"); otherwise the search miss stands. The same holds for a system that is empty only by a margin below the allowance of its caller rows: its point can be a physically feasible design. The check trusts no LP output, so a verified point cannot be false. It costs at most one scored row and one physical call per undecided test. check_with_linear_program(defaultTrue) switches the step; another region class makes it not applicable.physical_linear_inequalitiesadds caller rowsA @ x <= bthat every physically feasible design satisfies withinfeasibility_tolerance(A @ x - b <= feasibility_tolerance), for example component hull facets, whose physical residual is the facet residual. A system that is empty only by a margin below this allowance is undecided, because the physical check accepts a design that violates a row by up to the tolerance.linear_inequalities=(A, b)andlinear_equalities=(E, e)(defaultNone) are hard linear requirements of every witness:A @ x <= bandE @ x = ewithinfeasibility_tolerance. A design passes when every residual is finite, every inequality residual is at most the tolerance, and every absolute equality residual is at most the tolerance. A residual that overflows, such as[max, -max] @ [2, 1.5] = inf - inf, rejects its design: the rule is conservative. The rows qualify the known designs and retained samples, constrain the score search, and decide the verification of every point (see Bounded subproblems). The linear-program test takeslinear_inequalitiesfollowed byphysical_linear_inequalitiesas its caller inequality rows, andlinear_equalitiesas its equality rows, so a certificate excludes every design that the search could accept. A matrix needs one column per design variable; another width raisesValueErrorbefore the bound intersection. Unlike the physical rows, which only describe the physical constraint for the linear program, the linear rows bind every step.polyhedral_intersectionitself also accepts caller equality rowsphysical_equalities=(E, e). They hold exactly in the LP, and the certificate addsz @ Etogandz @ e + |z| @ delta_eto its bound, with multiplierszof any sign and the allowancedelta_e = feasibility_tolerance + K * eps * (|E_row| @ reach + |e|). An equality system without a solution in the box gives an undecided test without a point. An interior point meets the equality rows only up to the LP solver tolerance, so check|E @ x - e| <= feasibility_tolerancebefore you use it.find_common_designpasseslinear_equalitiesas these equality rows.CommonDesignResult.linear_programkeeps the evidence: decision, row count, equality count, LP status, the optimals, the minimax point, the certificate residual, and for an empty decision the candidate infeasiblecore: the regions that own a row with a positive multiplier or set a bound that the check uses.store_certificate_core(defaultFalse) makes a family subset search prove that core again with its own common bounds. A checked core certificate is stored, so it prunes every later superset of the core, for example in the top-down exhaustive traversal. Every stored core is a proof, but signals change: a superset whose own search would miss is reported certified infeasible,subset_resultsgains cores that no traversal requested, and the search counters fall.linear_program_before_score_search(defaultFalse) runs the LP before the score search when no retained witness exists. A certificate then ends the search without the score solve; other decisions continue as before, and step 5 reuses the test. It needs the defaultscore_optimizerand nocancellation. Certified outcomes stay the same, butevaluationsfall andevidenceisNone. Caller rows that wrongly exclude a physically feasible design make the early certificate win where the score search could find a witness.accept_linear_program_witness(defaultFalse, requires the early test) also returns the verified point of the test instead of running the score search: the Chebyshev center of an interior test or the minimax point of an undecided test. A point that fails the check continues with the score search. This reduces search thoroughness: the point is not the design with the best score, so witnesses and the starts of later cost solves change.
The score search of find_common_design runs one local solve.
Start and objective:
- The default solver is
scipy_bounded_optimizer(SLSQP). It starts frominitial_design, else from the selected pooled row clipped to the box, else from the box midpoint. In this role, DesignOptRs uses a native algorithm: sequential quadratic programming (ContinuousSearchMethod::SequentialQuadraticProgramming). - The selected pooled row is the best verified known design or retained sample. When no row passes, it is the first pooled row.
The physical check of the pooled rows visits the membership-valid rows in ranking order and stops at the first pass,
because no later row can be selected.
constraint_functiontherefore does not run on the later rows, and their errors do not surface. CommonDesignResult.pooled_rowscounts the scored pooled rows (known designs plus retained inside samples), andpooled_member_rowsthe pooled rows inside the exact common bounds with a signed score at most zero and passing linear rows, before the physical check. These are the candidates of the physical check; without a physical constraint each of them is a verified witness. Both are zero when the search scores no pool. The count of physically passing rows does not exist, because the check stops at the first pass.SearchDiagnosticssums both counts over the searches of a family call; reused answers add nothing.- The objective is the membership-signed cumulative score:
-|s|inside every region andmax(|s|, tiny)outside. It is at most zero exactly for shared designs and still changes continuously near a smooth boundary. - The inequalities are, in this order, the physical
constraint_functionresiduals, the same signed score, optionalmembership_residual_functionguidance columns, and the linear inequality columnsA @ x - b. The linear equality columnsE @ x - eare the equalities. Every score optimizer, built-in or supplied, receives them. - The workflow verifies the start and the solver proposal, independently of the solver unless the reuse option is on (see Bounded subproblems). A feasible point that the solver only visits is never returned.
Solver choice and ranking:
- The local default is much cheaper than a global search but can miss a witness of a nonconvex or disconnected intersection, so groupings can need more groups.
- A global optimizer with the
BoundedOptimizersignature, supplied asscore_optimizer, searches more thoroughly at a much higher cost. existing_sample_ranking="worst-case"(default) ranks verified retained rows by their largest region score, the maximin margin."cumulative"ranks them by the optimization score.- The retained witness stays unless the verified refinement has a strictly lower optimization score.
cancellationis checked before each scoring step (the batch of retained rows, and every row that the solver or the verification scores). A stopped search keeps a verified retained witness or reports a search miss, never an infeasibility proof.evaluationsreports scored rows as a diagnostic, andevidencerecords the checks of the score-search start and proposal.- With
CommonDesignOptions.reuse_observations=True(default), one search scores each distinct row once. The solver requests the objective and the inequalities at the same points, and the result steps score the returned design again. Within the score solve,constraint_functionandmembership_residual_functionalso run once per distinct design.evaluationsthen counts the rows that were actually scored. The membership check of the verification still classifies again, andcancellationis still checked before every request. The reuse assumes deterministic regions and callbacks; setFalsefor a model that can change between calls. - Product-family results keep a read-only snapshot of the
SearchDiagnosticscounters. Assigning to or deleting a field raisesdataclasses.FrozenInstanceError.
Feasibility tolerance:
- The workflow decides feasibility once, at verification, with one absolute
feasibility_tolerance(default1e-6). - An inequality residual
rpasses whenr <= feasibility_tolerance, and an equality residual whenabs(r) <= feasibility_tolerance. - Bounds and region membership have no tolerance, so a returned design never lies outside its box or a member region.
- A local solver often stops on an active constraint with a small positive residual. A zero allowance would reject that proposal and silently keep the start.
- The tolerance scales with the residual units: it is strict for residuals in large units and loose for residuals in tiny units.
Passing the common-design search:
- Every grouping and component-optimization function takes the common-design search through one
common_designargument.Noneselectsfind_common_designwith default options.- A
CommonDesignOptionsrecord selectsfind_common_designwith those options. - A function with the
CommonDesignFindersignature replaces the search. The workflow still verifies every witness that it claims.
- The component optimizers define
constraint_function,constraint_options,use_variant_score,variant_score_policy, andfeasibility_tolerancefor the whole family problem. Their built-in common-design search inherits these values. It reuses observations only when both the familyreuse_observationsand its own option allow it. - Options that set the constraint fields,
use_variant_score=False, avariant_score_policy, or the linear rowslinear_inequalitiesandlinear_equalitiestherefore raiseValueError. The family cost searches take their linear rows per sharing assignment (see Constraint functions), so one family has one set of linear requirements: rows in the witness search alone would make a certified-infeasible group refer to requirements that the cost check does not apply to the returned design. The grouping functions keep the linear rows of their options.
Variant-score weights and rules:
variant_score_policy(adesignoptpy.core.DeficitScoringPolicy, defaultNone) sets the weights and the good and bad rules of the variant score.component_cumulative_score,CommonDesignOptions,component_product_family_constraints, and the three component optimizers take it. With region scoresd_i(inactive-infentries dropped) and weightsw_i, a satisfying row scores-prod(|d_i| ** (w_i / sum(w_i)))("geometric-mean", the default) and a violating rownorm(w_i * max(d_i, 0))("euclidean-norm", the default)."worst-case"takes the largest weighted deficit. A custom scorer runs once per scored batch.- Membership alone decides feasibility: the sign of the score follows region membership, whatever the policy. The policy changes rankings, solver guidance, starts, and witnesses. The good score is invariant to a common factor of the weights; the violation norm is not.
deficit_weightis a scalar or one weight per region of the call: the supplied regions ofcomponent_cumulative_scoreandfind_common_design, or the product variants ofclique_compatible_groups,validate_component_commonality, and the family optimizers. Each subset search, witness check, and group coverage column uses the weights of its members, in member order. A scalar applies unchanged to every subset. For example, weights[1, 2, 3]and the assignment(0, 1, 0)give the group of variants 0 and 2 the weights[1, 3].- In
find_common_design, the policy reaches the solver objective, the membership inequality, the"cumulative"ranking of the pooled rows, and the comparison of the refinement with the retained witness. - A policy together with
use_variant_score=Falseor a customscore_function, or with a weight width other than one and the region count, raisesValueErrorbefore any region classification. The observation reuse of the searches assumes deterministic scorers. random_compatible_groupskeeps its fixed default cumulative score and takes no policy. Options whosefeasibility_tolerancediffers from both the default1e-6and the familyfeasibility_toleranceraiseValueErrortoo. The default counts as unset.- One family run decides feasibility with one tolerance: the witness search supplies the starts, gates metaheuristic assignments, and reports subset results as feasible.
Memoization:
- Within one call, the grouping and optimization functions store verified shared designs and certified infeasibility in a memo and reuse them for repeated subsets and equivalent assignments. Reusing a completed solve for the same canonical group or assignment key is memoization.
- Stored infeasibility proofs also prune larger groups.
- A bounded search that finds no design is not stored as an answer, so a later query searches again. The repeated search reuses the linear-program test of the miss, because that test depends only on the regions, their common bounds, and the caller rows.
reuse_search_misses=True(defaultFalse) on the component optimizers and onCliqueSearchOptionsreturns the stored miss of the call instead of a new search. The default search is deterministic, so outcomes stay identical. A stochastic score optimizer or a caller finder loses its retries and can find fewer witnesses. A reused miss counts incache_hits, not insearch_misses. It never prunes a group and never enterssubset_results.- Nothing is reused across calls: a second call on the same problem repeats its numerical work, and a changed problem never meets an obsolete answer.
optimize_component_product_family_metaheuristic_runsrepeats the metaheuristic search in one call, one run per generator ofrngs, in order. Each run has its own common-design memo, diagnostics, and result, anddiagnostics.elapsed_secondsholds its run time. By default each run equals a separate call with its generator.- With
share_solved_assignments=True(defaultFalse), one store of solved assignments, created by the call, serves all its runs. A run reads the verified or certified-infeasible answer of an earlier run instead of a new cost solve; the answer counts as a cache hit, not as an assignment evaluation, and joins theassignment_resultsof the run. For deterministic callbacks, optimizer, and witness search, a stored answer equals a new solve and draws no random number, so the genetic decisions, designs, and costs stay those of separate calls. Tradeoff: the run times and work counters of the later runs no longer describe independent runs. A run with fewer own group searches can also report an assignment with an infeasible group as a search miss instead of certified infeasible; its cost is infinite either way. After a cancellation request throughCommonDesignOptions.cancellation, a run reads no stored answer, so its requests reach the cancelled group searches as in a separate call. - Results list the conclusive answers of the call in
subset_results(SubsetResult: members and theirCommonDesignResult). The metaheuristic also lists them inassignment_results(AssignmentResult: canonical assignment, recomputed cost, andSearchOutcome). MetaheuristicFamilyResult.final_statusnames the outcome of the selected assignment:"feasible"(it has a verified design),"certified-infeasible"(the memo of the call stores it without a design, because one of its groups is certified infeasible),"search-miss"(neither; this proves nothing), or"empty-family". The status describes the selected assignment only, not the best assignment that the search evaluated.- A family without product variants (
regions=[]) is valid for the two metaheuristic functions. They check every input that needs no region (tolerance, flags, thecommon_designform and its nested rules,variant_score_policy, the outer-search options,rng, and the type, keys, and key widths oflinear_inequalitiesandlinear_equalities, so every key exceptAssignmentScheme(())raises), then return the empty assignment without a design (cost+inf, evidence reason"empty-family"), zero counters, andfinal_status="empty-family". No cost, metaheuristic, constraint, or finder callback runs. The runs function returns one such result per generator and still callsrun_startedper run. The exhaustive optimizers keep theirValueErrorfor zero regions.
Constraint functions:
- Per-group and per-design constraint functions return inequality residuals only. A tuple raises
TypeError. - The cost workflows accept
family_constraint_function(design, assignment, **family_constraint_options)for the complete packed design. It returns an inequality array or an(inequality, equality)tuple, so it can couple the designs of different groups or depend on the assignment, for example a family mass budget. - Its equalities reach the solver as equalities:
BoundedOptimizerandscipy_bounded_optimizertake anequality_constraintargument afterconstraint. - The cost searches also take linear rows per canonical sharing assignment:
linear_inequalitiesandlinear_equalitiesof the three component searches, andlinear_inequalities_by_componentandlinear_equalities_by_component(one mapping per component) ofoptimize_box_product_family_exhaustive. Each mapping takes anAssignmentSchemeto(A, b)forA @ x <= b(or(E, e)forE @ x = e) on the packed design of that assignment: one block of component coordinates per group, in group-label order, soAneeds the component width timeskey.number_of_groupscolumns. An assignment without an entry has no rows. The packed width depends on the assignment, so one matrix for a whole call would fit only the assignments of one group count. The search checks every entry before any solve or callback: a key of another width than the variant count, a malformed pair, or another column count raisesValueError. The solver receives the rows as residual columns, and the verification applies them withfeasibility_tolerance(see Bounded subproblems). Rows that exclude every checked point givedesign=Noneandcost=inf, a search miss; the rows never certify infeasibility, so thefinal_statusof a metaheuristic can become"search-miss", never"certified-infeasible", because of them.
Bounded subproblems:
- Every bounded subproblem is solved once and then verified: the start design (the incumbent) first, the solver proposal (the candidate) second.
- The workflow ignores the solver's reported cost and recomputes the cost of each accepted point.
- The proposal replaces the start only for a strictly lower recomputed cost, so equal costs keep the start.
- The solver receives the raw cost objective, also
+inf. Infinite inequality residuals become the placeholders-1and+1. Linear rows follow the raw columns:A @ x - bafter the inequalities andE @ x - eafter the equalities. A nonfinite linear column (also NaN) reaches the solver as+1, a violated row. - The checks of a point run in this order and stop at the first failure: a finite design of the bound width (
"invalid-design"), the exact bounds ("bounds"), the linear rows when the subproblem has them ("nonfinite-linear-residual","linear-inequality","linear-equality"), region membership ("membership"), the nonlinear residuals ("invalid-nonlinear-residual","nonlinear-inequality","nonlinear-equality"), and a finite recomputed cost ("invalid-cost"). The linear check uses the raw residuals without placeholders, so a point whose linear residual overflows is rejected.SubproblemCheck.linear_inequalityandlinear_equalitykeep the linear residuals of every check that reached this step,Nonewithout rows. SubproblemResult.evidencenames the returned point ("candidate","incumbent", or"none") and records each check as aSubproblemCheckwith its rejection reason and residuals.- Exact observation reuse: with
reuse_observations=True(the default of the cost workflows), a cost subproblem scores each group block, and computes itsconstraint_functionresiduals, once per distinct block value within one solve. A finite-difference step of the solver changes one coordinate, so it repeats the blocks of the other groups. Onefamily_constraint_functioncall per design serves its inequalities and its equalities. - The checks of the start and the proposal are independent unless the reuse option is on. With it, each solve keeps the cost and the residuals of every design that the solver requested, keyed by the exact design bits, and a check at the same design reads them instead of new calls. Region membership and the tolerance tests still run fresh.
- The reuse assumes deterministic regions and callbacks whose values depend on the design alone; results are then identical.
The memo stores its own copies of the residual arrays, so a callback may write every result into one output buffer.
Set
reuse_observations=Falsefor fully independent checks or for a model that can change between calls.
Clique grouping has several candidate searches. AUTO selects one by the input variant count:
- Repeat search runs through eight variants.
- Depth-level search runs through thirty variants.
- Pure backtracking runs above thirty variants.
How the searches work:
- Repeat search uses no seed. It tests pairwise-eligible remaining subsets from largest to smallest and accepts the first witnessed one.
- Depth-level search builds one greedy clique.
After a failed search, it replaces the last member by the next recorded alternative at that depth. When a depth has no alternative left, it drops the last member.
One pass needs at most about
n**2searches. - Pure backtracking removes the greedy clique's last member repeatedly.
- Every greedy clique ranks candidates by witnessed links to the clique, then by witnessed and eligible degree among the remaining variants, then by index.
- Restricted searches save work but can produce more groups. No mode certifies a globally minimum group cover.
Budget and stop reasons:
CliqueSearchOptions.evaluation_budgetlimits the new common-design searches of the complete run. Reused answers are free.CliqueGroupingResult.stop_reasonis"completed"for a complete cover, and"evaluation-budget"or"cancelled"for a partial cover.CommonDesignOptions.cancellation, or a finder result with the reason"cancelled", also gives"cancelled", because a cancelled search is not evidence about a subset.- A singleton is searched once. When its search finds no witness,
clique_compatible_groupsraisesValueErrorat once, also at an exhausted budget. SearchDiagnostics.singleton_fallbackscounts completed clique-selection passes that query a singleton while several variants remain. It counts grouping decisions, not new physical evaluations.SearchDiagnostics.search_missescounts the common-design searches of the call that ended as a search miss: neither a verified witness nor a proof of infeasibility. Every search ends in one of these three ways, socommon_design_evaluations - search_missesis the number of conclusive searches. The count cannot be derived from the memo: pruned supersets and, withstore_certificate_core, stored certificate cores enter it without a search. A search that an inner cancellation stopped without a witness also counts, because it decided nothing. The family optimizers count their searches in the same field.
Controlled policy comparison:
the lesson product_family_clique_policies.py runs the four methods on five constructed families.
Each region accepts only a few known points, the sites, and the search checks only the retained samples, so every count is deterministic and the exact minimum group count is known.
For nine products with three separated sites, repeat search needs 463 common-design searches, depth-level search 66, and pure backtracking 48; all three reach the minimum of three groups.
Pure backtracking needs one group more than the minimum on two families: nine products with overlapping sites (4 groups instead of 3), and six products in which every pair of the first three shares a site but no site is shared by all three (3 instead of 2).
The counts explain the policy differences. They do not calibrate the thresholds of AUTO or predict engineering workloads.
Random grouping:
random_compatible_groupsacceptsconstraint_function,constraint_options, andfeasibility_tolerance. A sample whose physical residual exceeds the tolerance loses all memberships before coverage counting. The filter tests coverage levels from the highest downward and stops after the first level with a passing sample. A sample of a lower level cannot become the witness, soconstraint_functiondoes not run on it.sample_ranking="worst-case"(default) or"cumulative"selects the score that picks the witness and breaks ties among equally frequent patterns."cumulative"is the fixed default cumulative score (unit weights, the negative geometric mean of the member margins). Random grouping offers no cumulative-score options.- A NaN physical residual raises
ValueError, and+infrejects the sample, for both inequality and equality constraints. These errors come only from the tested samples.
Commonality validation and restricted assignments:
validate_component_commonalityreports witnessed, certified-infeasible, and unresolved patterns separately. Itsevaluation_budgetcounts explicit pattern checks. Pruned supersets of a certified-infeasible pattern are free. After a budget stop,completeis false,stop_reasonis"evaluation-budget", andnext_patternnames the next check.restricted_assignment_schemesreturns only assignments whose groups match allowed pattern rows exactly. Itsevaluation_budgetlimits the visited search states, shared across component types. Itsorderis"by-groups"(default: increasing group count, then labels) or"restricted-growth"(depth-first generation order), as foriter_assignment_schemes,all_assignment_schemes, andenumerate_assignment_schemes. Other spellings raiseValueError. It returns aRestrictedAssignmentEnumerationwithschemes,complete,stop_reason("completed"or"evaluation-budget"), andvisited_states. Component types after a stop receive empty scheme tuples. An empty pattern matrix returns no assignment schemes.- The genetic assignment trace starts with the initial population at index zero.
Later entries keep the cumulative best evaluated cost, even when the population loses its best member with
elite_count=0. AssignmentGeneticOptions.reuse_elite_costs=True(default) lets each elite keep its cost instead of a new objective call. An elite is an unchanged copy, so a deterministic objective gives the same search. SetFalsefor an objective that can change between calls.
Exhaustive optimizers:
- Exhaustive box and component family optimizers accept
evaluation_budgetandcancellation_function. evaluation_budgetlimits the processed assignments across all components of one operation. The value0returns an empty partial result.- Every processed assignment is retained, including reused answers and unavailable assignments.
keep_solver_output=Falseandkeep_evidence=False(both defaultTrue) drop the raw optimizer output and the verification evidence of each candidate, also in the per-call memo, so a large enumeration keeps the assignment, the design, and the cost only. Assignments with a certified-infeasible group share one read-only result record.cancellation_functionis a caller-supplied function checked between assignments. The optimizer checks the budget and the function between subproblems. They do not limit calls inside a continuous solver.- Automatic enumeration generates the assignments one at a time, so a budget stops before all assignments exist.
- Each
ExhaustiveFamilyResultreportscompleteandstop_reasonand retains useful verified candidates.stop_reasonis"completed"after the full traversal, and"evaluation-budget"or"cancelled"after a stop.completeis true exactly for"completed". completemeans that the requested assignment traversal finished. It does not certify a global continuous optimum, because the default SLSQP solver is local.- Without supplied bounds, the component optimizer cost-solves every assignment whose groups are not certified infeasible. A group whose witness search missed starts at the midpoint of its common bounds, so a search miss does not look like infeasibility.
optimize_box_product_family_exhaustiveacceptsinitial_designs_by_component, nested likeassignment_bounds_by_component, for explicit starts.bestselects among eligible finite witnesses and raises when none exists.- Partial results do not save enough internal search state to resume at the stopping point.
Projections and plots
evaluate_selective_projection evaluates two-variable projections.
For each pair, it samples those two coordinates over the design space and the other coordinates inside the solution box.
Each point is one sampled full design. Other completions of the same two coordinates can have different labels.
Projection records:
- Projection records keep raw measures, raw deficits, the performance active mask, evaluator metadata, and labels.
- With several evaluation batches, the metadata keeps
batch_metadata, the complete evaluator metadata of each batch in batch order. It sits beside the concatenated known numeric arrays andchunk_lengths. The batch size therefore never removes an evaluator field, such as an uncertainty array. - Memory grows with
number_samplestimes the number of pairs. maximum_total_samples, default 2,000,000, caps the pairs timesnumber_samplesand raisesValueErrorbefore any sample is drawn.Noneremoves the cap.retain_full_evidence=Falsekeeps only the projected coordinates, labels, and violation diagnostics. The raw measures and deficits are then unavailable.plot_selective_projectiondraws them and returns aSelectiveProjectionPlotResult: the figure, its axes, the records, the effective options, and the generator's initial state.batch_across_pairs=True(defaultFalse) draws the rows of all pairs first, evaluates them in batches that span pairs, splits the evaluated rows by pair, and classifies each pair by itself. It needs fewer evaluator calls, which helps a model with a fixed cost per call. It requires a row-independent evaluator. With a sampler that draws only fromrng, the samples and the markers stay the same for both marker criteria, because the"random"markers come from a separate marker stream in pair order. The metadata of a pair is then a row slice of the combined evaluation. Every pair refers to one shared read-only record of the combined metadata, so it is retained once.
Projection colors show performance, physical feasibility, and model rejection separately. They are not the Omega acceptance set. For the same rows, changing Omega does not change these masks or performance scores.
performance_activedisables performance requirements. Their deficits count as the neutral value negative infinity in the labels, scores, and violation indices. The records keep the raw deficits, and explicit rejection stays active.- Physical feasibility is mandatory: every physical deficit decides the feasibility label, so a positive physical deficit always gives an infeasible row. To ignore a physical quantity, remove its column in the evaluator.
- A projection row is model rejected when any of its deficits is positive infinity, such as an out-of-range surrogate prediction.
evaluate_selective_projectiondefines this rule and the sampler call. X-Ray sessions use the same rule. - Projection results retain
model_rejectedflags even when full numeric evidence is omitted.
Categories drawn by plot_projection:
- physically infeasible rows (dark-red open rings);
- rows of each violated requirement (marks in the requirement color, red by default: a cross for requirement 1, then an open triangle, square, diamond, and downward triangle), labeled "violates requirement k" without
requirement_labels; - model-rejected rows (plus signs in
rejected_color, dark grey by default); - valid rows (green dots), labeled "valid design", or "good design" when the problem has no physical feasibility requirement.
Rejected rows have no ordinary requirement violation category.
A model rejection does not establish physical infeasibility. A row has a ring only when its physical feasibility label is false.
This keeps unavailable model results separate from finite requirement violations.
requirement_labels names the requirement categories, and plot_solution_box=False omits the box outline for a caller that draws its own bound lines.
plot_region and the plot_candidate_space_* functions draw region slices on a finite grid.
Grid and envelope:
- A slice fixes the omitted coordinates.
- The grid covers the region's
plot_envelopeat the displayed coordinates withceil(1 / step_size)equal segments per axis, so every spacing is at moststep_sizetimes the interval. step_sizeis a fraction in(0, 1]. A value above one raisesValueError, because it most likely is a step in physical units.- The region class owns the envelope:
- a box or fitted hull region uses its relaxed evidence box (the domain without evidence);
- a hull before fitting uses its pending box;
- a planar or corner region uses its envelope
sampling_box; - an analytical region uses its
sampling_boxwith the box check, otherwise the domain.
Boundary drawing:
- The membership labels decide the side of each grid node, and the signed scores locate the boundary between nodes by linear interpolation.
- A score that is NaN or disagrees in sign with its label gets a tiny score of the label's sign, so the drawn region equals the membership at every grid node.
- One-dimensional slices draw the inside intervals, two-dimensional slices a filled region (
contourf), and three-dimensional slices one triangulated surface (Poly3DCollection), closed at the envelope. - In two and three dimensions, the boundary is exact for an affine score when no grid node has an exact zero score. When scores carry no magnitude, it falls at the midpoints between nodes of different labels.
- An accepted zero score is replaced by
-e, withe = numpy.spacing(max(1, max |finite score|)). A neighbor score neareor smaller can therefore move that crossing by up to one grid step, for example for an affine score whose values are all far below one. - Features narrower than the grid spacing can be missed. A smaller
step_sizeadds resolution, evaluations, and memory.
Grid limits:
maximum_grid_points, default 2,000,000, caps the queried grid nodes,(ceil(1 / step_size) + 1) ** kforkdisplayed coordinates, and raisesValueErrorbefore any allocation. To pass the cap, increasestep_sizeor passNone.- The default admits the default steps (0.001 in one and two dimensions, 0.01 in three) and rejects a two-dimensional step below 1/1413 (about 0.00071) or a three-dimensional step below 1/124 (about 0.0081).
membership_batch_size, default 10,000, sets the rows of one membership query.Nonequeries every node at once. It changes only time and memory, not the drawn region.coarse_factor, defaultNone, classifies every node. A positive integerfclassifies everyf-th node per axis first, then only the fine nodes of the coarse cells whose corner labels differ and of their neighbor cells; the other nodes take the common label of their coarse cell. It cuts the classified rows, for example 1,002,001 to 99,778 for a two-cut polygon at the default 2-D step withf=10. Tradeoff: it misses a hole, an island, or a thin part that changes no coarse corner label, so the picture can change. In 3-D the surface extraction usually dominates the time.- In
fixed_variables, NaN marks a displayed coordinate. Withdimensions, omitted coordinates default to box midpoints. dimensionsalso sets the axis order. Theplot_candidate_space_*functions accept it for the NaN coordinates offixed_variables.
component_product_mesh(xy_samples, xy_inside, z_samples, z_inside) builds a three-dimensional display surface of the product of a two-variable component region (the xy plane) and a one-variable component interval (the z axis).
Its inputs are the definition samples and labels of the two regions (region.definition.samples and region.definition.is_inside); numeric labels must be zeros and ones.
It extrudes every accepted xy sample between the smallest and the largest accepted z value and returns a ComponentProductMesh: vertices (two rows per accepted xy sample), outward-oriented triangle faces, projection_defined (one flag per component, each independent of the other), has_definition (both flags), and product_dimension.
The product of a convex polygon and an interval is a prism, so the faces are the two caps and the side walls of the prism over the convex hull of the accepted xy samples (Andrew's monotone chain). They enclose the hull area times the z range.
Outcomes: without accepted samples in a component, no product exists and the dimension is None; a point, a line, or a plane (dimension 0, 1, or 2) spans no volume and has no faces; an orientation value that overflows float64 (coordinates above about 1e153) gives the dimension None and no faces; otherwise the dimension is 3 and the surface is closed.
The orientation test has no tolerance, so nearly collinear samples can give a thin prism.
Limit: the surface is a sample envelope for display, not a certificate. For a convex region, such as planar trimming, it lies inside the region but can cover less. For a nonconvex region, such as corner removal, it can cover the removed corners; plot_region shows the region shape from its membership test.
Draw the faces with designoptpy.core.plotting.plot_convex_hull_3d(axes, mesh.vertices, mesh.faces, color=..., alpha=...) when mesh.faces has rows.
plot_component_boxes(axes, box, layout) and plot_component_regions(axes, regions) draw each component in its own variables.
A component is a group of design variables, such as the bar properties of one truss element or the coordinates of one movable node.
plot_component_boxes splits a full design box (a Box or a (2, n) array) by a ComponentLayout and draws each component box with plot_box.
plot_component_regions draws each region of a sequence, such as ComponentOptimizationResult.candidate_regions, whole with plot_region, with its grid options and tradeoffs.
A component solution space is a Cartesian product of component regions, so each component can be shown without a slice through the others.
Both functions take one Axes per component (a sequence, or the array of plt.subplots in row-major order) and draw one panel per component.
One Axes overlays every component; an overlay needs components of one count, two or three.
Each component has one to three coordinates; three coordinates need Axes3D, one or two need two-dimensional axes.
A layout may leave variables uncovered (require_complete=False), so a subset of components can be plotted.
The functions check the axes and the layout before drawing. A dimensions keyword (or fixed_variables for regions) raises TypeError, because the layout selects the coordinates.
Limit: plot_region classifies each region only when it draws it, so a later region that fails, for example on its grid cap, leaves the earlier regions drawn.
The caller creates the figure and sets the labels and titles.
import matplotlib.pyplot as plt
from designoptpy.sso import ComponentLayout, optimize_components
from designoptpy.sso.plotting import plot_component_boxes, plot_component_regions
# evaluator, initial_design, design_space (a Box), and layout as in "Component solution spaces".
result = optimize_components(evaluator, initial_design, design_space, layout)
components = ComponentLayout(result.component_indices, dimension=design_space.dimension)
figure, axes = plt.subplots(1, len(components.indices))
plot_component_regions(axes, result.candidate_regions, step_size=0.005)
plot_component_boxes(axes, design_space, components, color="#444444", line_width=1.0)
for index, panel in enumerate(axes):
panel.set_title(f"component {index + 1}")
plot_component_evolution needs evidence that the compact defaults do not keep.
Set save_candidate_regions_before_trim=True and save_candidate_regions_after_trim=True before the run for geometry. Also set save_evaluated_samples=True and save_is_acceptable=True to plot sample points.
The plot supports one to three coordinates per component. Close generated figures after use.
By default (layout="separate"), it draws one figure per component and iteration, all with the same plot rectangle. layout="series" draws one figure per component with one panel per selected iteration (small multiples, at most columns per row) and one legend above them; choose a few iterations, for example the first, a middle, and the last one.
A three-coordinate figure of the separate layout adds three two-dimensional slices through the center of the trimmed region (slice_panels=True, the default), because samples drawn over surfaces can look inside a region they lie outside. Each slice costs two grids of 63,001 nodes with the default step; slice_panels=False draws the surface view alone.
Its step_size, maximum_grid_points, and membership_batch_size set the grid of every drawn region, with the defaults of plot_region.
Up to three regions are drawn per figure, so a coarser step, such as 0.004 (63,001 two-dimensional nodes instead of 1,002,001), speeds up a long history at the cost of resolution.
With reuse_trimmed_grid=True, the default, a state that draws the same region object as the state before it reuses that classified grid. The initial region of an iteration is the trimmed region of the iteration before, so consecutive iterations classify about one region in three less. The reuse assumes a deterministic classify; pass False for a region whose classification can change between calls.
Metric plotters return figures and close only figures that they created when a step fails. No plotter calls show.
plot_box_metrics(..., column="single") and plot_component_metrics(..., column="single") draw the views for one column of a paper (3.4 inches wide, 9-point text); the default "full" draws them for a full text width (6.4 inches, 12-point text). Save a figure at its own size, so its text keeps the designed size in print.
At the full width, a view with one or two stacked axes is a golden landscape of 6.4 by 3.955 inches (see Figure shapes): its legend and caption take their room from the axes, so the saved image keeps the shape.
A long legend at the full width may fill up to three balanced columns (all entries in order, the column lengths differing by at most one) when that makes it lower than the grouped layout, which keeps related entries in one column.
At one column, a 2.1-inch golden frame would leave the axes almost no height beside the legend and the caption, so a view with one axes keeps an axes height of 1.92 inches and its figure grows with the legend and the caption.
The same 1.92 inches are the floor at the full width: when the legend and the caption would leave a lower axes, as a timing legend with nine stages does, the figure grows to keep that height and is no longer golden. Views with room keep 6.4 by 3.955 inches (1280 by 791 pixels at 200 dots per inch).
A full-width view also grows when its vertical axis label is longer than the axes and would reach past the canvas.
The views with one line per variable or component name each line at its end; the labels are spaced for a 1.92-inch axes and kept inside it, and when they do not fit, as for 36 variables, only the legend names the lines.
IntervalBounds with three or more variables and TotalTimeElapsed keep a height per row of panels or bars.
With save_folder, every view is saved through designoptpy.core.plotting.save_figure: PNG files at 200 dots per inch (unless save_options gives "dpi"), the whole figure without a tight crop, and the editable figure file <name>.pickle.gz (save_options={"pickle_file": False} leaves it out).
When any file of a view would replace an existing file, all files of that view get the same suffix _1, _2, and so on.
The GrowthRate view of plot_box_metrics and plot_component_metrics draws the target purity of the run, read from the options of the result when its growth rate adapts; a different target_accepted_fraction raises ValueError, because a target that the adaptation never used makes the growth rule look broken. Precomputed metrics hold no options, so there the argument sets the drawn target.
The batch comparison and sensitivity views are unmanaged Figure objects: pyplot does not register them, so they need no closing.
The per-run views of plot_batch_box_metrics and plot_batch_component_metrics are pyplot figures; their close_after_saving closes them after saving.
Each run adds about ten such figures.
plot_families selects the figure families: "individual" (the per-run views), "comparison", and "sensitivity", as BatchPlotFamily members or their texts (the choice-name rule of designoptpy.core.choices); the default draws all three.
Pass plot_families=("comparison", "sensitivity") to draw only the cross-run views, for example to inspect a large batch without saving. An empty collection draws nothing, and an unknown name raises ValueError before any figure is drawn.
case_ids draws only the cases with these exact IDs, in case order; None (the default) draws every case. An empty or unknown selection raises ValueError. The other checks run on the full batch first, so a selection does not repair a misaligned batch.
batch_box_metric_series and batch_component_metric_series, exported from designoptpy.sso, return the drawn data without a figure: per case, the measure before trimming (divided by the box measure when one applies), the sample purity, and the cumulative evaluations of each retained iteration as float64 arrays.
Each series has finite-value masks (MetricAvailability), so a missing value is never read as zero, and a BatchSeriesStatus: available (some iteration has finite values of all three series), processed-unavailable (iterations, but none with three finite values), or unavailable (no retained iteration).
run_status holds the termination reason of an optimization result; precomputed metrics hold none, so it is None for them.
The plots leave out a run whose series is unavailable, also the box run of a component batch, and name it in the comparison captions: "omitted (no retained history): , ...". Reference roles and sensitivity groups form over the drawn runs.
A processed-unavailable run stays; its nonfinite values draw no marker and no value, and the final-value view keeps its row and name.
The cross-run views are PerformanceComparison-Evaluations (measure and sample purity over the evaluations), PerformanceComparison-Cost (last measure against total evaluations, one labeled point per run), PerformanceComparisonFinal (one row per run: last measure, last purity, total evaluations), and one OptionSensitivity/<option>/<reference ID>/Sensitivity figure per numeric option and reference case.
The sensitivity axis names the source of its values, (executed) or (declared); executed_options supplies the executed values (see Batch studies).
In a large batch, the Cost view labels clusters of overlapping points with letters, named in a key below the plot.
Reference runs are dark grey with diamonds. Up to six runs, each other run has its own color, line style, and marker; with more runs, the others become grey context lines. Open markers flag runs whose last sample purity is below 1.
plot_sso_comparison_box_component_metrics draws up to nine views, including ComparisonFinal (the end values of each run by name); box runs are dashed lines and component runs solid, dotted, or dash-dot lines, and color and marker give the run position within each method.
When no run has a retained iteration, it validates its inputs and then returns no view, as plot_box_metrics does for one such run.
With more than four runs of both methods, the history views stack the two methods in separate blocks.
plot_batch_box_metrics, plot_batch_component_metrics, and plot_sso_comparison_box_component_metrics take the same column option as the per-run plotters, and pass it on to the per-run views.
column="single" draws every batch view 3.4 inches wide with 9-point text and no text below 7 points.
At that width, legends take more rows, captions wrap at fewer characters, and each figure grows by its legend and caption, so the axes keep their height.
At the full width, a history of one panel and the Cost view are golden landscapes of 6.4 by 3.955 inches: they keep their shape, and the legend and the caption take room from the axes. Stacked history panels, such as the measure above the sample purity, keep a height per row, because the legend of every run and the caption would leave them almost no height. The cluster key of a large batch still adds its own height below the Cost view.
The final-value views write wrapped axis labels under narrower panels and give the measure axis two ticks; the Cost key has two tables side by side, and PurityNormalizedMeasure has two small panels per row.
Caller line options keep their sizes. An unknown column raises ValueError before any figure is drawn.
Box X-Ray engine
Box X-Ray displays two-variable projections against quantity-of-interest (QOI) limits.
A quantity of interest is a direct measured or computed response with acceptance limits.
designoptpy.sso.xray holds the engine. It runs without a display.
The designoptpy-xray application adds the interactive window.
Projections use the evaluate_selective_projection sampling and classification above, with 3,000 samples per plot by default.
Stored observations
XRaySampleData replaces the model with aligned design rows and their direct responses:
from designoptpy.sso.xray import XRayDomain, XRaySampleData, XRaySession
data = XRaySampleData(
design_samples=[[0.0, 0.0, 0.2], [1.0, 0.5, 0.8]],
performance_measures=[[1.0], [3.0]],
variable_names=("width", "height", "depth"),
quantity_names=("mass",),
)
domain = XRayDomain.from_sample_data(data, quantity_upper=2.0)
session = XRaySession(domain)
projections = session.evaluate_projections()
The default design space spans the data range with 2% padding at each end.
The initial solution box equals that space, every pair is selected, and quantity limits default to no restriction.
design_space, solution_box, desired_pairs, quantity_lower, quantity_upper, and quantity_colors override these defaults.
For existing records or a workbook, configure(sample_data=data) binds the named columns to those records.
Reordering variable or quantity records preserves each column's identity. Plot pairs continue to refer to the same variables.
Each panel retains rows whose plotted coordinates lie in the design space and whose other coordinates lie in the solution box.
Panels can contain different row counts, including zero. The session neither samples nor evaluates a model.
The current quantity limits, active flags, and deficit options classify the stored responses.
Optional physical_measures use the domain's physical limits. NaN raises a data error; +Inf explicitly marks rejection.
The domain accepts one source: an evaluator or stored observations. A window keeps its original source mode.
optimize() starts from the smallest box that holds the valid stored rows in the design space.
It trims against the other stored rows, without growth or new model evaluations.
Its default search uses reduced passes and a 200-pass limit. Explicit optimization options can change that search.
No valid row raises an error before the session changes. Remaining invalid rows and incomplete trimming stay visible in the result.
XRayStoredBoxResult records the box, retained row counts, and trimming completion; it creates no SSO iteration trace.
The box states sampled evidence only. Gaps between observations remain untested.
The application keeps Update Plot manual in both modes. Stored mode displays the total data count and each panel's row count. The source example xray_stored_data.py evaluates the car-crash model once and then explores its stored responses.
Domain configuration
XRayDomain holds design variables (DesignVariable), quantities of interest (QuantityOfInterest), constant parameters (DesignParameter),
the design space, the solution box, and the evaluator.
configure(**options) accepts option field names, such as number_samples_per_plot, and validates the complete proposal before it stores anything.
Names are exact. Another spelling, such as NumberOfSamplesPerPlot, raises ValueError.
Read the records directly: variables, quantities_of_interest, parameters, and desired_pairs.
design_space and solution_box give them as boxes.
limit_evaluator() returns the evaluator that applies the declared limits of every quantity.
Projections use it and apply quantity activation only to their labels, so an inactive quantity keeps its finite raw deficit in the records and exports.
effective_evaluator() wraps it in a mask adapter that sets the deficits of inactive quantities to negative infinity and keeps positive-infinity rejections; the optimizer uses it.
set_design_variables, set_quantities_of_interest, set_system_parameters, set_plot_desired_pairs, and set_solution_box replace one record group.
To edit one field, build the record with dataclasses.replace and pass the complete group:
from dataclasses import replace
first, *others = domain.quantities_of_interest
domain.set_quantities_of_interest([replace(first, active=False), *others])
with_solution_box returns a modified copy.
Option mappings are stored as read-only copies. Replace them with configure(sampling_options=...) or configure(optimization_options=...).
A direct assignment to an option field, such as domain.patch_alpha = 0.5, runs the same value checks as configure; a rejected value raises and changes nothing.
Plot option keys are the exact keyword names of the Matplotlib object that draws them, and they reach Matplotlib unchanged.
The sample classes (plot_options_valid, plot_options_bad, plot_options_physically_infeasible) are drawn with Axes.scatter.
Their keys include s, the marker area in points squared, facecolors, edgecolors, linewidths, color, marker, alpha, and label.
A marker of diameter d points has the area s = d**2.
The line groups (plot_options_intervals, plot_options_box, draggable_line_options) are Line2D lines.
Their keys include markersize, the marker diameter in points, markerfacecolor, markeredgecolor, linewidth, linestyle, and color.
axis_labels_options takes Text keys, such as fontsize, fontweight, fontfamily, and fontstyle.
legend_options takes Axes.legend keys, and patch_options takes Patch keys, such as facecolor, edgecolor, and linewidth.
Matplotlib checks the keys when it draws, so an unknown key raises then. It also accepts its own short aliases, such as lw.
DesignOptRs honors a portable subset of these keys; see its X-Ray README.
marker_colors_criterion selects the violated requirement that colors each bad sample:
"worst"(default) selects the largest deficit."random"draws the requirement from a marker stream derived from the sampling generator; the samples do not depend on the criterion. The stream starts from a seed that is drawn from a copy of the generator before its first draw, so the generator does not advance, and the recordedinitial_rng_staterepeats the markers.Nonecomputes with"worst", and the application draws every bad sample in one color.
maximum_evaluation_batch_size (default 10,000) bounds the rows of one evaluator call of a model projection.
The keyword of the same name of evaluate_projections and compute_projections replaces it for one call; None, the default, uses the domain value.
It is a positive integer: a Boolean raises TypeError, 2.0 becomes 2, and 2.5 or 0 raises ValueError.
It is a work setting, not a computation input. The deficits of a row-independent evaluator do not depend on it, so a change keeps every retained result current.
The result records the effective value in evaluation_options, so a change makes the next computation draw every pair again also with reuse_unchanged_projections.
Tradeoff: fewer, larger calls need more memory per call.
Each accepted change of a computation input increments the domain revision. A display-only quantity edit, such as a color or a violation text, keeps the revision. A domain identity and its revision bind each result to its inputs.
An evaluator that returns raw measures lets the domain convert them with the QOI limits and performance_deficit_options.
physical_lower and physical_upper set the physical limits, default (-inf, 0].
An evaluator with an evaluate method returns normalized deficits and owns its conversion.
Its QOI limits are then display values only, and the application rejects edits of them.
A model can declare its result-affecting inputs with configuration_snapshot() -> (inputs, is_complete) and clone_configuration() -> model.
X-Ray uses these declarations to detect stale results. It does not inspect other model attributes, so hidden state stays unverifiable.
Workbook schema
parse_xray_workbook(path, evaluator=..., input_limits=...) reads a configuration workbook, an .xlsx workbook or an .ods OpenDocument spreadsheet, and returns (XRayDomain, XRaySession).
The suffix decides the format, in any letter case; a path without a suffix gets .xlsx, and another suffix fails.
It needs the io extra and no office program. Put column headers in the first row of each sheet.
input_limits is the designoptpy.core.InputLimits object that every DesignOptPy reader uses; None selects its defaults.
After the size and archive checks, and before it parses any sheet, the reader records the file identity in XRayDomain.source_workbook, a SourceWorkbook with the resolved path, size_bytes, modified_utc (UTC with nine fraction digits, such as 2000-02-29T12:34:56.123456700Z, or None outside 1970 to 9999), and the sha256 digest of the file bytes.
This record is provenance: the recorded origin of the imported values. A path, a size, and a time do not identify content, so the digest identifies the bytes that the reader read.
It is not a computation input, so it never makes a result stale. A domain that no workbook created has None.
| Worksheet | Required columns |
|---|---|
| Design Variables | Variable Name; Display Name; Description; Unit; Design Space Lower Bound; Design Space Upper Bound; Solution Box Lower Bound; Solution Box Upper Bound |
| Constant Parameters | Variable Name; Display Name; Description; Unit; Value |
| Quantities of Interest | Variable Name; Display Name; Description; Unit; Critical Lower Value; Critical Upper Value; Text when violated; Color of points where violated |
| Desired Plots | Design Variable x-axis; Design Variable y-axis |
| Other Options | Description; Value |
| Stored Samples (optional) | Named design-variable and quantity columns; optional physical measure columns |
Sheet names are exact. Column heading matching ignores capitalization, spaces, and punctuation, because headings are layout labels. Fully blank rows are skipped.
At least one variable is required. The other sheets can contain only headers.
Numbers can be numeric cells or numeric text. Formula cells need cached results, so recalculate and save first.
For text, the reader removes the surrounding white space, replaces every comma with a period (a decimal comma), and requires one number token of the spreadsheet literal grammar: an optional sign, ASCII digits with an optional decimal point, and an optional e, E, d, or D exponent, or inf, infinity, or nan in any ASCII letter case.
The token nan means not given, as a blank cell does. Other text, such as 1_000 or 1.000,5, fails. A decimal that overflows to infinity, such as 1e999, fails; only inf or infinity gives infinity.
A numeric cell that holds NaN fails, and so does a Boolean, error, or date cell. A comma is always a decimal separator, so thousands separators are not supported. DesignOptRs reads the same numbers.
Text cells, such as names, units, plot axes, and the Stored Samples headers, give their text. A numeric text cell gives the shortest decimal text that reads back to the same number, without an exponent, and a Boolean cell gives true or false. An Excel error cell, such as #N/A, and a date cell fail.
Design-space bounds must be finite and ordered.
A blank solution lower or upper bound selects the one-quarter or three-quarter point of the design interval.
A blank quantity limit removes that side of the inclusive requirement.
The optional Active column of Quantities of Interest holds a Boolean. False makes the quantity inactive, so its requirement is not checked. A blank cell or an absent column keeps it active.
DesignOptRs writes this column, so an inactive quantity of a DesignOptRs workbook stays inactive.
Each desired plot row names the horizontal and then the vertical variable. Without rows, every pair is plotted.
Each Description cell of Other Options holds the exact name of one option. The names are:
number_samples_per_plot,monitor,maximum_number_of_plots_per_row,marker_colors_criterion,initial_view,reuse_transposed_pair_samples, andmaximum_evaluation_batch_size;optimization_options, a name-value cell with the box batch-table names, andsampling_options, a name-value cell with the keywords of the projection sampler. Nonempty sampler options needsampling_method; a model projection without one raisesValueError;- the plot option groups above,
draggable_lines_color,patch_relative_width,patch_alpha,physical_lower, andphysical_upper; physical_feasibility_columns, described below.
Names are exact, and no name has an alias. An unknown name raises ValueError, also when its value is blank.
A repeated name raises ValueError. A row whose name is empty or holds only white space is ignored.
evaluator, sample_data, sampling_method, performance_deficit_options, and physical_deficit_options hold code objects, so the workbook cannot set them. Pass them to parse_xray_workbook or configure instead.
Values use bounded literal parsing, which executes nothing. A blank value or [] sets nothing: the option keeps the value of the supplied domain_configuration, or the field default for a new domain.
The quoted empty text '' is text, not blank. Whole numbers inside sampling_options become integers. An Excel error cell in Value fails.
The text of a real-scalar option (number_samples_per_plot, monitor, maximum_number_of_plots_per_row, maximum_evaluation_batch_size, patch_relative_width, patch_alpha, and a scalar physical_lower or physical_upper) reads a decimal comma, as the numeric sheets do: monitor 2,0 is 2, and patch_alpha 0,5 is 0.5.
A comma is always a decimal separator, so 1,000 is 1. Text that starts with [ stays a literal matrix, in which a comma separates entries.
physical_lower and physical_upper also accept a one-row or one-column matrix, such as [-1 -2], one entry per physical measure column.
A name-value cell has one of two forms: one row of alternating names and values, such as {'color','red','linewidth',2}, or rows of one name and one value, such as {'color','red';'linewidth',2}.
optimization_options uses the box batch-table names and the batch-table cell rules, such as {'trimming_slack',0.25;'maximum_trimming_passes',Inf}.
Unset names keep the source defaults: the BoxSsoOptions defaults for a model, and reduced trimming passes with a 200-pass cap for stored samples. A cell value replaces these defaults, for example [] or Inf for no pass cap.
The reader builds these options once while it reads the workbook. An unknown name or an invalid value therefore raises ValueError before any projection or optimization, and the supplied domain stays unchanged.
The name requirement_space (Omega0 to Omega3) selects the rule that labels samples acceptable and useful during the box optimization. It matters only with physical feasibility requirements: without them, the four rules give the same labels.
The plots do not use the requirement space. Their categories come from the performance and physical feasibility labels alone.
A Boolean value is a Boolean cell, true or false in any ASCII letter case, also when quoted, or the number 1 or 0.
marker_colors_criterion (worst or random) and initial_view (normal or matrix) ignore surrounding white space of the cell; the trimmed name follows the choice-name rule of designoptpy.core.choices.
The optional Stored Samples sheet opens a stored-data session. A physical_feasibility_columns row in Other Options names its physical columns: one quoted name, such as 'mass', or a one-row or one-column cell of names, such as {'mass','cost'}.
A blank physical-column row means none; a malformed row raises a clear error.
Passing sample_data= replaces the sheet and ignores the sheet's physical-column declaration. Supplying a model together with stored rows raises an error.
Quantity colors use this precedence:
- An explicit color name, hexadecimal color, or red-green-blue (RGB) triple, such as
[1 0 0], inColor of points where violated. RGB components lie in[0, 1]. Surrounding white space is ignored. The textnoneraisesValueError, because it would draw nothing. DesignOptRs rejects it with the same message. - A packed Excel color in the optional
Color of points where violated backgroundcolumn. - The color cell's fill, including its theme and tint. Excel theme colors 0 to 3 are light 1, dark 1, light 2, and dark 2, in that order. An OpenDocument cell gives its background color: the
fo:background-colorof its cell style or of the nearest parent style that sets one. It has no theme or tint. - Red when no usable color is available.
The source checkout includes designoptpy/examples/application_examples/data/XRayInputCarCrash.xlsx as a complete example.
Installable package archives exclude it.
Sessions, freshness, and exports
XRaySession holds the runtime state of one domain. Sessions compare by identity.
evaluate_projections(rng=...) computes the configured projections.
It assigns each bad row the violated requirement that the domain's marker_colors_criterion selects, and the result records that criterion in evaluation_options.
optimize(rng=...) runs box SSO for a model source, or trims stored evidence for a stored source, and updates the solution box.
compute_projections and compute_optimization return isolated results; commit_result validates their domain identity, revision, and declared inputs before it applies them.
The session keeps the accepted records as projection_result and optimization_result; projections and optimization read them.
Each ProjectionEvaluation carries its samples, labels, raw deficits, the quantity activation in performance_active, and the evaluator metadata in evaluation_metadata.
A stored-data session labels its observations once, in one StoredRowsEvaluation.
Each of its panels is a StoredProjectionEvaluation that holds only source_row_indices into that shared record, so the result stores each observation once.
Its properties have the names and values of the ProjectionEvaluation fields, and as_projection_evaluation() returns all arrays of one panel at once.
That metadata holds the raw measures and the other named numeric arrays; the *_measure fields stay None, so the measures are stored once.
reset_for_new_domain and bind_domain clear results that belong to another domain and keep the save directory.
Results also keep their declared producing inputs.
is_current(kind) is true while a retained result belongs to the current identity, revision, and declared inputs.
result_configuration_status(kind) separates known input changes, verified matches, unverifiable matches, and unavailable records.
A changed model coefficient makes a result stale even if the revision did not change. Counter updates alone do not.
Both methods accept current=, one capture of the domain from capture_configuration. Several checks of one event then share one capture.
Stored observations enter a capture as their row and column counts, their column names, and one SHA-256 digest of their exact bits.
XRaySampleData computes this digest once at construction, so a check does not hash the stored rows again.
Its arrays keep their elements in immutable bytes objects, and NumPy refuses to enable writes on them (ValueError), so the digest stays equal to the values.
A copy restored by pickle or copy.deepcopy holds ordinary read-only arrays, and each check hashes them again. An accidental digest collision is negligible.
projection_rows_current() is the weaker check for one retained row: it ignores the design-space and solution-box bounds.
A bound decides only where samples are drawn, so after a bound edit each retained row still holds the model values of its design.
The domain option reuse_unchanged_projections (default False) uses this fact to save model work after a bound edit.
A pair samples its two variables over the design space and the others inside the solution box (projection_box), so a box edit of variable k leaves the sampling box of every pair that shows k unchanged.
With the option, compute_projections copies each such retained model pair with the current bounds and evaluates only the other pairs.
It copies nothing without a bound edit, after any other declared input edit, or with other evaluation options.
Turning the option on declares that the model responses do not depend on the bounds; the evaluator receives the whole configuration, so the computation cannot check this.
A copied pair draws nothing from the generator, so a seeded result differs from a full recomputation, and a stateful custom sampler gets fewer calls.
XRayProjectionResult.reused names the copied pairs and the generator state and producing inputs of the runs that drew them, XRayWorkPlan.copied_pair_count counts them, and session_record() writes them as projection_reused.
compute_relabeled_projections() labels the retained model samples again after a quantity-limit or activation edit, without a sampler or model call.
After an activation edit it labels the retained deficits again. After a limit edit it converts the retained raw measures with the new limits, as a new evaluation of the same rows does; this needs a model that returns raw measures, not one with its own evaluate method.
Any other declared input edit needs compute_projections.
The result keeps the samples and the generator state of the model run, and XRayProjectionResult.relabel records the scope, the relabel generator state, and the inputs of that run.
The domain option batch_across_pairs (default False) evaluates the samples of all pairs that need new samples in batches that span pairs, as the keyword of evaluate_selective_projection does.
It cuts the evaluator calls to ceil(evaluated pairs * samples per pair / maximum_evaluation_batch_size) and requires a row-independent evaluator.
discard_optimization() removes optimization evidence and keeps manual bound edits and current projections.
session_record() returns a portable record with the effective options, termination fields, random-state input, and work plans.
Its key source_workbook holds the four fields of the imported workbook identity, or {"state": "unavailable"}.
export_results_table writes a CSV table and requires current projections.
export_npz writes a compressed NumPy archive and rejects stale optimization evidence.
export_npz(..., compressed=False) stores the same members without compression: the file is larger and the write is faster.
export_results_table, export_npz, and session_record take an optional current capture of the domain inputs, capture_configuration(session.domain).
A writer on another thread passes the capture that it took when it checked the export, so it reads no evaluator or sampler configuration that a domain snapshot shares with the live domain.
Both preserve model_rejected flags. No row or byte limit applies to an export.
Stored-data NPZ archives (session schema designoptpy.xray.session.v3) write the complete input observations and their shared labels, deficits, and normalization factors once, as stored_<name> members.
Each stored panel then writes only projection_<index>_dimensions and its zero-based projection_<index>_source_row_indices into these members.
An export never replaces an existing file: an existing destination raises FileExistsError before anything is written.
They write a temporary file and then rename it to the destination.
CSV headings that start with formula characters receive an apostrophe prefix, so spreadsheet programs do not run them.
export_results_workbook writes the same rows as an Excel workbook (.xlsx) and needs the io extra.
Its sheet Results adds three leading columns: projection (the zero-based panel index), x_variable, and y_variable (the names of the panel axes).
The other columns are those of the CSV table, and the uniqueness suffix of repeated headings covers the three leading columns too.
After 1,048,575 data rows, the rows continue on Results 2, Results 3, and so on, each with the header row; no row limit rejects the export.
The last sheet Columns describes every Results column: column (the written heading), kind (projection, axis, design, measure, deficit, or label), source (the name before the suffix), index (the zero-based variable or quantity index), and unit.
A finite number is a numeric cell. An infinity or NaN is the text inf, -inf, or nan, because an XLSX numeric cell cannot hold it; an unavailable value is a blank cell.
Names and units get the apostrophe rule of the CSV table, which OpenPyXL also needs: it would write a text that starts with = as a formula.
Every name and unit is an explicit text cell, so a name such as #N/A that equals an Excel error value stays text.
A name or unit with a control character other than tab, line feed, or carriage return fails before anything is written, and so does a table wider than 16,384 columns.
So does a name or unit with more than 32,767 characters after the apostrophe rule, the length limit of an XLSX text cell; OpenPyXL would cut it silently.
Writing takes about 0.2 ms per row with OpenPyXL, about 20 times the CSV table. The X-Ray window keeps writing results.csv.
Resource limits and trust
Model projection work admits at most 2,000,000 samples per request, the pairs times the samples per pair.
Stored sessions sum the actual panel row counts and report zero evaluator rows. They have no projection-row cap.
The projection request checks the rule before any sample is drawn or any evaluator row runs. Select fewer pairs or fewer samples per pair for a larger study.
The configuration itself accepts any size, so its settings can change in any order: for example, raise the samples per plot first and select fewer pairs next.
A configuration above the rule fails only when a projection request, such as evaluate_projections or an application job, plans its work.
No count of variables, quantities, pairs, or figures has its own limit, and no memory, evaluator-row, or output limit rejects work or exports; a request larger than the available memory raises MemoryError.
The workbook reader takes its file, archive, worksheet, and literal limits from designoptpy.core.InputLimits, as every DesignOptPy reader does.
These workbook and input limits are input-security validation of an untrusted file, not resource caps on the work.
| Scope | Owner | Default limits |
|---|---|---|
| Model projection work | fixed | 2,000,000 total samples per request |
| Background job | XRayResourceLimits |
3,600 s deadline |
| Workbook structure | XRayResourceLimits |
16 sheets, 1 MiB theme |
| Workbook file and archive | InputLimits |
50 MiB file, 2,048 archive members, 200 MiB expanded, compression ratio 200 |
| Worksheet and literals | InputLimits |
200,000 rows, 1,024 columns, 5,000,000 cells; 1,000,000 characters, depth 32, and 100,000 elements per literal |
Every XRayResourceLimits value is a positive finite number. Pass a larger value directly, for example XRayResourceLimits(maximum_wall_time_seconds=7_200.0).
None and environment variables cannot disable a limit.
XRayDomain.plan_workload() returns an XRayWorkPlan with the pairs, samples, evaluator rows, and figures of a request.
It rejects a model request above the total-sample rule. Stored plans record each panel's actual count.
The plan of a computed result also records the numeric array layout of the evaluator output and the retained numeric bytes.
XRaySession.plan_optimization() returns an XRayOptimizationWorkPlan with the phase iteration limits, evaluator rows, and the largest batch.
The plans are diagnostic records of exact counts; they hold no memory or output estimates, and the optimizer's own evaluation caps stop its work.
The in-process worker cannot stop a running evaluator.
The workbook reader opens .xlsx files read-only with OpenPyXL. It checks the ZIP container first and rejects encryption and duplicate members.
It parses theme XML with defusedxml. An .ods file passes the OpenDocument preflight of designoptpy.core.io before python-calamine parses it.
That preflight checks every sheet, also a Stored Samples sheet that sample_data replaces, because the parser builds every sheet when it opens the file.
These checks bound what the parser reads; they do not sandbox code.
An evaluator is ordinary Python code that runs with the permissions of the current process. Use trusted workbooks and evaluator modules.
Supported numeric domain
The region, trimming, and sampling formulas support ordinary engineering magnitudes in double precision. They use their plain form, such as the planar deficit above. They do not rescale differences, products, ratios, or volumes that leave the float64 range. Outside the domain, a local check raises an error and never changes a membership label:
- Planar membership, reconstruction, and redundancy checks raise
GeometryUnavailableErrorwitharithmetic-unavailablestatus when a projection or a unit-box coefficient is not finite.convex_hull_evidenceand geometry comparisons report this status instead of a result. PlanarCutraisesValueErrorwheninward_normal / normalizationis not finite or is zero in every entry.planar_trimming_candidatesandcorner_removal_candidatesraiseTrimmingGeometryUnavailableErrorwhen a span, distance, projection, anchor, or cut direction is not finite. Component trimming records the proposal as unavailable; it never treats it as a proposal that removes no rows. Results and unavailable data states the resulting termination reason.- A normalized
ConvexHullRegion.fitraisesGeometryUnavailableErrorwitharithmetic-unavailablestatus when a physical facet coefficient is not finite or underflows to zero, because the facets then decide another membership. - A
ConvexHullRegion.fitwhose physical volume underflows to zero or overflows keeps its facets and membership. ItsvolumeandmeasureareNone: the measure is unavailable, not zero. For example, on[0, 1e-155]**2a triangle of unit area 5e-17 has the physical area 5e-327. In physical coordinates, the six-dimensional simplex with edges1e60has the volume1e360 / 720, above the float64 range. A normalized fit multiplies the unit-domain volume by the domain measure withbox_measure, which has no intermediate overflow: on[0, 1e155]**2the hull area5e299stays available although the domain area1e310overflows. Component trimming ranks such a trial by its membership. A ranking that reads a measure drops the trial and recordsarithmetic-unavailable. A returned region without a measure makestrim_componentsraiseGeometryUnavailableError(arithmetic-unavailable), and component SSO then keeps its last accepted regions. - Geometry changes and containment checks raise
GeometryUnavailableErrorwitharithmetic-unavailablestatus when Qhull cannot build the hull of nearly flat convex vertices.geometry_change_evidencerecords this status instead of a result. sample_set_hit_and_runwith the default chord locator raisesValueErrorwhen a proposal box side length is not finite.
The finite checks cannot detect precision loss in finite results.
For example, (1e308 - 1) - 1e308 rounds to zero instead of minus one.
Keep coordinates, bounds, and cut anchors at comparable, ordinary magnitudes.
Growth, trimming, and walk directions divide each vector by its largest magnitude before its Euclidean norm.
This step keeps tiny and large finite directions from becoming zero or infinite.
It stays because it also sets the rounding of every in-domain direction; removing it changes in-domain results.
Box belongs to designoptpy-core. Its README section "Supported numeric domain" states its signals.
Box unit coordinates and growth accept every finite box. Region operations that use them raise its ValueError for a point whose unit coordinate is not finite.
box_measure_volume uses the range-safe designoptpy.core.geometry.box_measure: compensating side lengths give their finite product.
A final volume above the float64 range returns inf, which box SSO rejects as a measure result. A zero fraction_useful returns zero.
Its reference_box divides each side length by a reference side length, such as the design-space width, which gives a dimensionless relative volume.
Metadata
Release files for designoptpy-sso 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| designoptpy_sso-0.1.0.tar.gz | 1.4 MB | Without provenance | Details for designoptpy_sso-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| designoptpy_sso-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for designoptpy_sso-0.1.0-py3-none-any.whl |
Total release size: 2.3 MB
Release files / designoptpy_sso-0.1.0.tar.gz
| Download URL | designoptpy_sso-0.1.0.tar.gz |
|---|---|
| Size | 1.4 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
64b8b735d0e10dfdb7858d47b4cb6452759f3b7510c36c77471081578cba7f80
|
|
BLAKE2b-256 checksum How to use checksums |
628f0b119b0d5d3938e2e22d8567a501305eee27b4118da58dfe81d92b2afafd
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.17
|
Release files / designoptpy_sso-0.1.0-py3-none-any.whl
| Download URL | designoptpy_sso-0.1.0-py3-none-any.whl |
|---|---|
| Size | 892.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
231e4a1b13933f30654bbad6a7abf0fe474424a6e6761aefaf956d150ea08e84
|
|
BLAKE2b-256 checksum How to use checksums |
e68d3aff9782713108df4263b890de01ea165966a48743ff91a2cee8288f7513
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.17
|
Security for designoptpy-sso 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.