Metadata-Version: 2.5
Name: designoptpy-truss
Version: 0.1.0
Summary: DesignOptPy truss algorithms and utilities
Author: Eduardo Rodrigues Della Noce
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: NOTICE
Requires-Python: <3.15,>=3.12
Requires-Dist: designoptpy-core<0.2,>=0.1.0
Requires-Dist: matplotlib<4,>=3.11
Requires-Dist: numpy<3,>=1.26
Requires-Dist: scipy<2,>=1.12
Description-Content-Type: text/markdown

# designoptpy-truss

This package provides truss analysis, plotting, parametric design models, and topology catalogues.
This package has its own installation and version. Import its functions through `designoptpy.truss`.

- After publication, install with `python -m pip install designoptpy-truss`.
- In the source workspace, run `uv sync --package designoptpy-truss`.
- To install all DesignOptPy components, including X-Ray and optional workbook and palette support, install `designoptpy`.
See the [workspace documentation](../../README.md) for development and release procedures.

## Analyze one supported bar

This bar has one free axial coordinate. Its fixed end has zero displacement.
Use a numeric NaN to mark the free coordinate.

```python
import numpy as np

from designoptpy.truss import TrussModel, analyze_truss

model = TrussModel(
    node_positions=[[0.0], [2.0]],
    connectivity=[[0, 1]],
    cross_section_areas=2.0,
    young_moduli=100.0,
    node_forces=[[0.0], [10.0]],
    prescribed_displacements=[[0.0], [np.nan]],
)
result = analyze_truss(model)
print(result.displacements[1, 0])  # 0.1
```

Axial stiffness is E*A/L, where E is Young's modulus, A is area, and L is length.
Here, stiffness is 100 and applied force F is 10. The extension F*L/(E*A) is 0.1.
The fixed end reacts with force -10. The bar carries `result.axial_force[0] = 10`.
Positive extension, axial force, and stress indicate tension.

## Mechanical model and units

The solver returns nodal displacements, support reactions, bar axial forces, strain, and stress.
Use one consistent unit system for coordinates, displacements, cross-section areas, loads, and Young's moduli.
For example, use metres, square metres, newtons, and pascals.

The direct-stiffness model assembles bar force/displacement relations into one stiffness matrix.
It assumes small displacements and linear axial elasticity.
`axial_force` holds one value per bar. Positive values are tension and negative values are compression.
The compressive force of a bar is `max(-axial_force, 0)`.
Stress is `axial_force / cross_section_areas`; `truss_stress` computes the same quotient for any force vector.
Positive stress and strain indicate tension and satisfy `stress = young_moduli * strain`.
`truss_strain` separately computes geometric strain from the change in element length.
Geometric strain can differ from linear constitutive strain for large displacements.

Require real mechanical arrays and material callback results before numeric conversion.
Boolean support masks remain supported: `True` fixes a displacement coordinate at zero.
Numeric `NaN` values mark free degrees of freedom (DOFs), meaning free nodal displacement coordinates.
Movable-node definitions use `NaN` placeholders for design-dependent node coordinates.
Complex values raise a `ValueError` that names the invalid input or estimator.

## Rigidity and numerical accuracy

The solver rejects unsupported mechanisms regardless of load values or positive material magnitudes.
A mechanism is a free displacement pattern that produces no first-order axial extension.
The compatibility matrix maps nodal displacement to first-order bar extension.
Its rank checks whether the supported geometry prevents such motion.

The solver finds equilibrium in four steps:

1. It scales the stiffness equations by the square roots of their diagonal entries.
   This scaling is equilibration; it reduces differences in equation magnitudes.
2. It factors the scaled matrix and solves.
   Small free systems use dense Cholesky factorization.
   Larger systems use sparse LU (lower-upper) factorization with symmetric ordering and positive pivots.
3. It applies one step of iterative refinement with the same factor.
   It computes the residual of the solution and adds the solved correction.
4. It checks two componentwise backward errors against a tolerance of `1e-8`.

The difference between internal and applied forces is an equilibrium residual.
The solver divides each residual by the sum of the magnitudes of the terms that form its equation.
This ratio is a componentwise backward error: the smallest relative change of those terms that makes the equation exact.
A correct solve gives a value near `1e-16`.
The first check uses the solved stiffness equations `K u = f`, with the scale `|K| |u| + |f|`.
The second check uses the equilibrium of the recovered bar forces.
Its scale per bar is the stiffness times the summed magnitudes of the displacement terms that form the bar extension.
The recovered force alone is not a suitable scale.
In a bar that carries almost no force, those terms cancel, so the rounding error is large relative to the force.

Positive definite stiffness permits stable factorization without pivot exchanges.
One equation can still keep a relative error well above rounding level, even for a well-conditioned rigid truss.
One step of iterative refinement in working precision makes the solve componentwise backward stable.
This holds when the matrix is not too ill-conditioned (Skeel, 1980).
The step costs one sparse matrix-vector product and one extra solve with the existing factors for each design.
This cost is small next to the factorization.

### Ill-conditioning

Strong sensitivity to small input changes is ill-conditioning.
Stable systems with verified equilibrium can remain usable despite ill-conditioning.

- A condition number above `1e12` produces a warning.
  It indicates sensitivity to perturbed input data.
- A scaled condition number above `1 / eps` raises `TrussDesignRejectedError`.
  Here, `eps` is the gap between one and the next larger double-precision number.
  Beyond this limit, rounding can decide the displacements even when force balance has a small residual.
- The test uses scaled stiffness, so a contrast between orthogonal bar moduli can still pass after equilibration.
- Unresolved rigidity at floating-point precision raises `TrussDesignRejectedError`.
- Results include `conditioning_estimate`, `equilibrium_backward_error`, and the `condition_method` that computed the condition numbers.
  The default method is exact; an estimate is available (see [Condition number computation](#condition-number-computation)).

## Tube section properties

A hollow circular section, or tube, has an outer radius `r` and a wall thickness `t`.
`tube_section_properties(radius, thickness)` returns a `TubeSectionProperties` record with three arrays of the input shape:

- `area = pi * t * (2*r - t)`, the outer circle minus the concentric inner circle of radius `r - t`;
- `moment_of_inertia = area * (r**2 + (r - t)**2) / 4`, the second moment of area about a diameter;
- `geometry_deficit = t - r`, which is at or below zero for a valid section.

The inputs are real arrays of equal shape in one length unit; the function does not broadcast.
A wall equal to the radius is a solid circular bar and is valid.
A wall thicker than the radius has a negative inner radius, so the formulas would describe a fictitious annulus.
Its positive deficit reports the condition, and its area and second moment of area are NaN (unavailable).
A radius or thickness that is NaN, infinite, zero, or negative is an invalid primitive dimension, not an error.
Its deficit is `+inf`, and its properties are NaN.

```python
from designoptpy.truss import tube_section_properties

sections = tube_section_properties([0.03, 0.03, 0.03], [0.003, 0.03, 0.04])
print(sections.area)  # [0.00053721 0.00282743        nan]
print(sections.geometry_deficit)  # [-0.027  0.     0.01 ]
```

The factored area avoids the cancellation of two nearly equal squared radii for a thin wall.
The tube evaluators below use the same function, so their section values agree with it.
The area and the second moment of area of a valid section must be positive and finite (see [Supported numeric domain](#supported-numeric-domain)).

## Application models as mappings

Application models return a `designoptpy.core.mapping.MappingResult`, so an evaluator can serve directly as a mapping.
The result has a `performance` group, a `physical_feasibility` group, and `metadata`.
The metadata is the tuple of performance column names.
Use it to align requirements with output columns.

The performance columns start with one `displacement_in_load_direction` column.
Its value is `dot(force, displacement) / norm(force)` over the complete load case.
For zero load, this value is zero.
Mass, stress, and buckling columns follow in that order.
Compression gives nonnegative buckling demand; tension gives zero buckling demand.

Tube models return dimensionless `stress_to_yield_ratio[index]` columns.
An upper acceptance limit of one represents the yield-strength condition.
Their layout is `truss_performance_names(definition, normalized_stress=True)`.
Their physical feasibility group holds one geometry deficit per bar: `thickness - radius`, or `+inf` when a radius, thickness, or material value of that bar is not positive.
A deficit is nonpositive when its condition is satisfied.
A supplied `material_feasibility_estimator` appends one material score per bar.
The group ends with one structural-rejection column (see the next section).
Each tube evaluator retains every supplied `material_feasibility_estimator`.
This includes callable objects whose Boolean value is false. A callable object supports calls with parentheses, like a function.
Only `None` omits the material-feasibility output group.
The keyword `material_feasibility_estimator_batch` is the batch form: one call with the sample-by-element modulus and density matrices returns all scores.
Supply at most one of the two forms. Each row must get the score that it would get alone.
Empty batches retain the defined output widths.

Movable-node models return physical `stress[index]` columns in force-per-area units.
They return the mass column only with `density`, and the buckling columns only with `moments_of_inertia`.
The default `truss_performance_names(definition)` gives their complete layout; the result metadata names the returned columns.
Their physical feasibility group has one structural-rejection column (see the next section).

`movable_node_positions(designs, definition)` returns the complete node coordinates of each design, shape `(n_samples, n_nodes, n_dimensions)`.
It replaces the NaN entries of `definition.node_positions` by the values of each design row in row-major order: node rows first, then coordinate columns within a row.
For the base `[[0, NaN], [NaN, 2], [NaN, NaN]]`, the design `[1, 3, 4, 5]` gives `[[0, 1], [3, 2], [4, 5]]`.
A wrong column count raises `ValueError`.
Both movable-node evaluators and the truss figures use this function, so a figure shows the geometry that a model evaluates.

This example uses metres, newtons, kilograms, and pascals.
Each design row holds `radius, thickness, modulus` for each of the two bars.

```python
import numpy as np

from designoptpy.core.arrays import FloatArray
from designoptpy.core.mapping import CallableMapping, MappingResult
from designoptpy.truss import evaluate_truss_bar_properties_fixed_material, two_bar_definition

definition = two_bar_definition()  # 60 kN downward load at the free node


def evaluate(designs: FloatArray) -> MappingResult:
    """Evaluate two-bar tube designs with fixed density and yield strength.

    Parameters
    ----------
    designs : ndarray of shape (n_designs, 6)
        Finite real rows containing radius, wall thickness, and modulus for each bar.

    Returns
    -------
    MappingResult
        Displacement, mass, stress-to-yield ratios, buckling demand, and physical deficits.
        Density is 7800 kg/m**3 and yield strength is 250 MPa for both bars.

    Notes
    -----
    The direct-stiffness model assumes small displacements and linear axial elasticity.
    Rejected designs retain the signals described in Response signals below.
    """
    return evaluate_truss_bar_properties_fixed_material(
        designs, definition, density=7800.0, yield_strength=250e6
    )


result = CallableMapping(evaluate).response([[0.03, 0.003, 210e9, 0.03, 0.003, 210e9]])
print(dict(zip(result.metadata, np.round(result.performance[0], 3))))
```

Both bars use half their yield strength (`stress_to_yield_ratio` 0.499).
The compressed bar uses 0.185 of its Euler buckling load; the bar in tension has zero buckling demand.
The physical feasibility group holds one wall-thickness deficit per bar, `thickness - radius`, here -0.027.
Its last column is the structural-rejection value `-inf` of an evaluated design.

### Tube bars with movable nodes

`evaluate_truss_bar_properties_movable_nodes` evaluates tube bars and movable nodes together.
Each design row holds `radius, thickness, modulus` for every bar in connectivity order, then the movable coordinates in the order of `evaluate_movable_node_truss`.
For two bars and one movable node in a plane, a row is `[r0, t0, E0, r1, t1, E1, x, y]`.
Without movable coordinates, a row holds only the bar triples, and all rows share one geometry.

The keywords `density`, `yield_strength`, and the optional `poisson_ratio` take a fixed value or a material relation.
A fixed value is a scalar, one value per bar, or one value per design and bar.
A material relation is a `ModulusFunction`: it maps the `(n_samples, n_elements)` modulus matrix of the batch to one value per design and bar.
The evaluator calls each relation once per nonempty batch.
An empty batch calls no relation and no material-feasibility estimator; its outputs keep their widths.
A relation must be elementwise: each row must get the values that it would get alone.

The performance and physical feasibility groups have the layout of the tube models.
With `poisson_ratio`, one `local_buckling_ratio[index]` column per bar follows the buckling columns.
`truss_performance_names(definition, normalized_stress=True, local_buckling=True)` names this layout; the default `local_buckling=False` keeps the former names.
Without movable coordinates, with fixed density and yield strength, and without a Poisson ratio, the result equals that of `evaluate_truss_bar_properties_fixed_material`.

The local buckling ratio checks thin-shell buckling of the tube wall.
Under axial compression, a thin wall can buckle locally, as short wrinkles, before the whole bar bends (Euler buckling).
The ratio is `max(-stress, 0) / sigma_local`, where `stress = N / A` is positive in tension, so tension has zero demand.
The critical stress is `sigma_local = E / sqrt(3*(1 - nu**2)) * (t / r)`, with the Poisson ratio `nu`, in the units of the modulus.
Linear shell theory gives this classical value for a perfect thin cylinder with the mid-surface radius `r - t/2`.
The formula uses the outer radius `r` instead, which lowers the critical stress by the factor `(r - t/2) / r`, so the ratio is slightly conservative.
It has no knock-down factor for imperfections. Real tubes often buckle at 0.2 to 0.6 times the classical stress, so for imperfect tubes the ratio is optimistic.
The formula assumes a thin wall. For a thick wall or a solid bar, it is an extrapolation, and the Euler ratio governs.
`1 - nu**2` must be positive, so `nu` must lie in (-1, 1); isotropic materials have values in (-1, 0.5].

This example uses the four-bar library truss with its movable node 1, in metres, newtons, kilograms, and pascals.
The material relation interpolates four illustrative metals (magnesium, aluminium, titanium, steel) and is undefined (NaN) outside the table.
Interpolation between the points does not prove that an intermediate alloy exists.

```python
import numpy as np

from designoptpy.truss import (
    ModulusFunction,
    evaluate_truss_bar_properties_movable_nodes,
    truss_topology,
)

moduli = [45e9, 70e9, 116e9, 200e9]


def relation(values: list[float]) -> ModulusFunction:
    """Return a linear table relation of Young's modulus; NaN outside the table."""
    return lambda modulus: np.interp(modulus, moduli, values, left=np.nan, right=np.nan)


tube = [0.03, 0.003, 116e9]  # radius, wall thickness, and modulus of one bar
result = evaluate_truss_bar_properties_movable_nodes(
    [tube * 4 + [1.0, 0.5]],  # four bars, then the coordinates of node 1
    truss_topology("4-bar-planar").definition,
    density=relation([1740.0, 2700.0, 4500.0, 7850.0]),
    yield_strength=relation([200e6, 110e6, 1200e6, 250e6]),
    poisson_ratio=relation([0.35, 0.33, 0.32, 0.30]),
)
print(np.round(result.performance[0, 1:6], 4))  # [9.0318 0.1041 0.0931 0.     0.1041]
print(result.metadata[-1])  # local_buckling_ratio[3]
```

At 116 GPa the relation gives titanium: density 4500 kg/m**3 and yield strength 1200 MPa.
The mass is therefore 4500/7850 of the steel mass, and each stress ratio is 250/1200 of the steel ratio.
A modulus of 30 GPa lies outside the table, so its density is NaN (see [Response signals](#response-signals)).

## Response signals

Every performance value of an evaluated design is finite: it cannot contain NaN or infinity.
Every physical feasibility value is finite too, except the structural-rejection column and, with `nonfinite_material_policy="reject"`, the material scores (see below).
An evaluated design holds the acceptance marker `-inf` in that column.
A design that the model cannot evaluate has `+inf` in every performance column and in its structural-rejection column.
This value is a model rejection signal. The other rows of the batch remain usable.

- A tube with `thickness > radius` in any bar has no physical tube.
  Its inner radius `radius - thickness` is negative, so the section formulas would describe a fictitious annulus.
  A wall with `thickness >= 2 * radius` would even give a nonpositive area.
  The evaluator skips the section formulas and the solve for this design.
  Its positive `thickness - radius` deficit and its `+inf` performance report it as infeasible.
  A wall equal to the radius is a solid bar and is evaluated.
- A finite nonpositive radius, thickness, modulus, density, or yield strength in a design row is a physically impossible design.
  That bar gets the geometry deficit `+inf`, and the row skips the solve like a wall thicker than its radius.
  The other rows continue, so a design-space bound at zero cannot abort a batch.
  NaN or infinity in a design row is a caller error, not a design, so it raises `ValueError`.
  Fixed `density` and `yield_strength` of `evaluate_truss_bar_properties_fixed_material` are model parameters: a nonpositive value raises.
- A positive material score does not skip the solve.
  The structure is still well defined, so the row keeps true structural predictions, and the material column reports the violation.
- A material score that is not finite is an invalid estimator result by default (`nonfinite_material_policy="raise"`): it raises `ValueError`.
  With `nonfinite_material_policy="reject"`, a NaN or `+inf` score becomes the deficit `+inf`: that material condition is violated, so the design is physically infeasible.
  A `-inf` score stays a satisfied condition without margin.
  The score still does not gate the solve, and the other rows continue.
  Use `"reject"` when an estimator marks an undefined material with NaN or `+inf`, for example a lookup outside its table.
  The default raises, because a NaN score usually means a broken estimator, and raising finds it.
- In `evaluate_truss_bar_properties_movable_nodes`, a density or yield strength from a material relation that is not positive and finite rejects its bar like a nonpositive design value: `+inf` deficit, no solve.
  The policy also covers these values. Under `"raise"`, a NaN or infinite value raises `ValueError`, unless the design values of its row already reject the row.
  So a design-space bound at zero modulus, where a relation is undefined, cannot abort a batch.
  Under `"reject"`, such a value never raises.
- A Poisson ratio must be finite with magnitude below one, so that `1 - nu**2` is positive.
  An invalid fixed `poisson_ratio` is a model parameter error: it raises `ValueError` for the whole call, also for an empty batch.
  A Poisson ratio from a material relation is checked only in rows that pass the geometry deficits; an invalid value there raises under both policies.
- A known geometry or equilibrium failure, identified by `TrussDesignRejectedError` in the analysis, rejects only its design.
  In movable-node models and in `evaluate_truss_bar_properties_movable_nodes` with movable coordinates, a collapsed node or a mechanism is such a failure.
- Every rejected design has `+inf` in the structural-rejection column, the last physical feasibility column.
  Evaluated designs have `-inf` in this column.
  This value is the neutral satisfied deficit: the check has no margin to report.

A `+inf` performance value alone is not a reliable rejection signal.
A lower-only performance limit, such as a minimum displacement, counts `+inf` as satisfied unless the deficit conversion rejects positive infinity.
A physical feasibility deficit of `+inf` rejects the design for every performance-limit direction.

Malformed inputs and numeric range failures remain `ValueError` diagnostics.
A tube evaluator raises `TrussDesignRejectedError` for the whole call when its fixed geometry is a mechanism, because every design shares that geometry.
`evaluate_truss_bar_properties_movable_nodes` does the same without movable coordinates.

For tube designs, specify radius and wall fraction with `thickness = radius * fraction` and `0 < fraction <= 1`.
This parameterization avoids invalid independent radius and thickness draws.
The tube area uses the factored form `pi*t*(2*r - t)` instead of subtracting nearly equal squared radii.

## Topology catalogues

The module `designoptpy.truss.topologies` names truss topologies for teaching studies; `designoptpy.truss` exports its functions.
A topology is the node layout, the bars (connectivity), the supports, and the loads of a truss.
A movable coordinate is a node coordinate that a design chooses; the base node positions hold NaN there.
"Planar" means two coordinates per node and "spatial" three.
The number before `-bar` counts the bars, and the number before `-coordinate` counts the movable coordinates.
Each name has one spelling; another spelling raises `ValueError` that lists the valid names.

| Function | Names | Contents | Units |
| --- | --- | --- | --- |
| `truss_topology(name)` | `TRUSS_TOPOLOGY_NAMES`: `2-bar-planar`, `4-bar-planar`, `2-coordinate-planar`, `6-bar-planar`, `18-bar-planar`, `38-bar-planar`, `12-bar-spatial`, `21-bar-spatial`, `39-bar-spatial`, `crane-jib` | `TrussTopology`: `definition`, `initial_design` (start of the movable coordinates), `design_space` (a `Box`, or `None` without movable coordinates), `figure_size_multiplier`, `camera_position` | m, N (60 kN; the crane jib 12 kN) |
| `bar_property_truss_study(name)` | `BAR_PROPERTY_TRUSS_STUDY_NAMES`: `2-bar-planar`, `4-bar-planar`, `6-bar-planar`, `18-bar-planar`, `38-bar-planar`, `12-bar-spatial`, `21-bar-spatial`, `39-bar-spatial` | `BarPropertyTrussStudy`: a fixed-node `definition` and the SSO settings `maximum_iterations_per_phase`, `growth_rate`, `trimming_passes` | m, N |
| `movable_node_truss_study(name)` | `MOVABLE_NODE_TRUSS_STUDY_NAMES`: `2-coordinate-planar`, `4-coordinate-planar`, `16-coordinate-planar`, `36-coordinate-planar`, `9-coordinate-spatial`, `18-coordinate-spatial`, `36-coordinate-spatial` | `MovableNodeTrussStudy`: `definition`, bar `cross_section_area`, `young_modulus`, `density`, `units` (`TrussUnits`), `initial_design`, `displacement_design_space`, `mass_design_space`, and the settings of the displacement, mass, and combined studies | mm, N, kg, MPa |

The movable coordinates follow the order of `evaluate_movable_node_truss`: the coordinates of the first movable node, then those of the next movable node (node-major order).
`initial_design`, the design spaces, and the evaluator columns share this order, so a start evaluates directly:

```python
from designoptpy.truss import evaluate_movable_node_truss, truss_topology

topology = truss_topology("4-bar-planar")
result = evaluate_movable_node_truss(
    topology.initial_design[None, :],
    topology.definition,
    cross_section_areas=1e-4,
    young_moduli=210e9,
)
print(result.physical_feasibility[0, -1])  # -inf: the start is rigid
```

Every entry is rigid at its start, and every start lies inside its design spaces.
The values are teaching benchmarks, not optimized designs.
The bar-property studies use the library geometry at its start, except `4-bar-planar`, whose node 1 is at (1, 0) instead of (1, 0.5).
The movable-node studies read the library coordinates as millimetres with a 1000 N load.
`36-coordinate-spatial` divides the `39-bar-spatial` coordinates by 5 and has a 50 N load.
The combined displacement-and-mass study uses the displacement design space and growth rate.

The SSO settings are plain values, because the truss package does not import the SSO package.
`trimming_passes` is text with the spelling of the SSO `TrimmingPasses` values (`"single"`, `"reduced"`, `"full"`), which the SSO options accept directly.
Pass `maximum_iterations_per_phase` to both phase limits of the SSO options.

`camera_position` is a viewpoint in data coordinates for spatial figures.
To convert it to Matplotlib view angles, let `d = camera_position - target`, where `target` is the center of the bounding box of the plotted nodes.
Then `azim = degrees(atan2(d_y, d_x))` and `elev = degrees(atan2(d_z, hypot(d_x, d_y)))`.
The angles give the viewpoint exactly only with equal axis scaling (`ax.set_aspect("equal")`), because Matplotlib applies them to the scaled plot box.
`figure_size_multiplier` scales a requested figure size for larger trusses.

### Research tuning values

Not yet in DesignOptRs: this contract can change in DesignOptPy alone.
`truss_topology_tuning(name, *, study)` returns a `TrussTopologyTuning` record with three SSO settings of research runs on one library topology: `maximum_iterations_per_phase`, `growth_rate`, and `trimming_passes`.
`study` is one of `TRUSS_TUNING_STUDIES` (type `TrussTuningStudy`):

- `"bar-properties"` varies the radius, the wall thickness, and Young's modulus of each bar, with the movable coordinates fixed at their start (the design layout of `evaluate_truss_bar_properties_movable_nodes`).
- `"movable-nodes"` varies the movable node coordinates (the design layout of `evaluate_movable_node_truss`).

| Topology | `bar-properties`: iterations, growth, passes | `movable-nodes`: iterations, growth, passes |
| --- | --- | --- |
| `2-bar-planar` | 150, 0.01, `reduced` | none (no movable coordinate) |
| `4-bar-planar` | 150, 0.07, `reduced` | 30, 0.07, `full` |
| `2-coordinate-planar` | none | 30, 0.07, `full` |
| `6-bar-planar` | 200, 0.07, `single` | 35, 0.06, `reduced` |
| `18-bar-planar` | 300, 0.01, `single` | 250, 0.01, `reduced` |
| `38-bar-planar` | 300, 0.007, `single` | 300, 0.007, `reduced` |
| `12-bar-spatial` | 300, 0.04, `reduced` | 100, 0.04, `reduced` |
| `21-bar-spatial` | 300, 0.005, `single` | 300, 0.005, `reduced` |
| `39-bar-spatial` | 300, 0.004, `single` | 300, 0.004, `reduced` |
| `crane-jib` | 20, 0.0004, `single` | none |

A pair marked "none" raises `ValueError` that lists the tuned topologies of the study.
An unknown study or topology name also raises `ValueError`.
The iteration limit applies to each SSO phase, so pass it to both phase limits:

```python
from designoptpy.sso import ComponentSsoOptions, TrimmingPasses
from designoptpy.truss import truss_topology_tuning

tuning = truss_topology_tuning("18-bar-planar", study="bar-properties")
options = ComponentSsoOptions(
    maximum_exploration_iterations=tuning.maximum_iterations_per_phase,
    maximum_consolidation_iterations=tuning.maximum_iterations_per_phase,
    growth_rate=tuning.growth_rate,
    trimming_passes=TrimmingPasses(tuning.trimming_passes),
)
```

The SSO options also accept the `trimming_passes` text directly; `TrimmingPasses(value)` gives the member that a type checker expects.
A larger design space (more bars or more movable coordinates) gets more iterations and a smaller growth rate.
A relative growth step `g` enlarges the measure of a `d`-dimensional region by about `(1 + g)**d`, so a fixed step in many dimensions adds mostly bad designs.
Fewer trimming passes (`single`) do less work than `reduced` or `full` and can return other regions.
The values are selected constants from research runs, not optimized values, and they do not guarantee convergence.
They differ from the teaching settings: `bar_property_truss_study("18-bar-planar")` has 200 iterations per phase, and the research table has 300.

## Prepared geometry and repeated batches

`TrussGeometry` derives lengths, directions, assembly indices, and the sparse compatibility matrices from coordinates, connectivity, and supports.
Callers cannot supply those derived fields.
The compatibility matrices are `compatibility`, its entrywise absolute value `compatibility_magnitude`, and, with supports, the absolute value of its free columns `free_compatibility_magnitude`.
Their data and index arrays are read-only, and record comparison ignores them, because the source fields determine them.
A pickled geometry stores only its source fields and rebuilds the derived fields when it is loaded.
`prepare_truss_geometry(model)` also checks supports with QR factorization of the compatibility matrix after scaling each column to unit length.
QR expresses a matrix as an orthogonal matrix times an upper triangular matrix.
Column pivoting orders the columns so that the diagonal of the triangular factor reveals the numerical rank.
Each independent supported subsystem uses the threshold `eps * max(block.shape)`.
The check computes only the triangular factor, because the rank certificate does not need the orthogonal factor.

The QR factorization is dense.
The check splits the free coordinates into blocks.
Two free coordinates share a block when one bar extension depends on both, directly or through a chain of such bars.
A connected truss usually forms one large block, but bars with axis-aligned directions can split it.
The factorization of a block with `m` bars and `n` free coordinates costs `O(m n**2)` operations and `O(m n)` memory.
This cost dominates the analysis of trusses with many hundreds of nodes.
When the bar count of a block grows in proportion to its free coordinates, doubling the block multiplies the cost of the check by about eight.

### Reuse

- Reuse prepared geometry with `analyze_truss(model, geometry=geometry)` when materials or loads change.
  Coordinates and connectivity must still match.
- If supports change, the solver repeats their rigidity check and slices the free columns of the stored compatibility matrix again.
- Every solve rebuilds material stiffness and factorization.
  It reuses the stored compatibility matrices, so the arithmetic and the results are those of a new assembly.
  The stiffness itself is still assembled from its element triplets in every solve.
  A reuse of its sparsity pattern would have to repeat the duplicate-summation order of SciPy exactly to keep the results bit-identical, so the solver does not do it.
- The tube evaluators prepare their fixed geometry once per call and reuse it for every design of the batch.
  `evaluate_truss_bar_properties_movable_nodes` does so only without movable coordinates; with them, it prepares the geometry of each design.
  All application evaluators validate the loads, supports, and batch-wide bar properties once per call, not once per design.

### Factorization choice

- Free systems with at most 100 coordinates use dense Cholesky factorization. The limit is 250 in three dimensions.
- Larger systems use sparse LU with symmetric ordering and no pivot exchanges.
  Positive pivots certify positive definiteness.
- Global stiffness assembly remains sparse, even with many prescribed coordinates.
- These choices change arithmetic at rounding level and keep the same equilibrium checks.

### Stacked solve of tube batches

The option `stacked_solve` of `evaluate_truss_bar_properties` and `evaluate_truss_bar_properties_fixed_material` solves the equilibrium of all kept designs together.
The default `False` solves one design at a time.

- With `True`, the evaluator stores the free stiffness matrices `K_ff = C_f^T diag(E*A/L) C_f` of all kept designs as one three-dimensional array, a stack.
  It runs the four solve steps on the stack: equilibration, Cholesky factorization with the exact condition numbers, one refinement step, and the two backward-error checks.
- The stack applies when the free system takes the dense path (at most 100 free coordinates, 250 in three dimensions).
  A larger free system is solved one design at a time also with `True`.
- The rejection rule, the limits `1 / eps`, `1e12`, and `1e-8`, and the conditioning warning of each design stay the same.
  Warnings and errors appear in row order, as without the stack.
  A design that the stack cannot decide, such as one whose Cholesky factorization fails or whose values leave the finite range, is solved alone, so its error or rejection is that of the per-design solve.
- The option requires `condition_method="exact"`; the estimate raises `ValueError`.
- The movable-node evaluator and `evaluate_truss_bar_properties_movable_nodes` have no such option, because each of their designs can have its own geometry.

The designs of a tube batch share geometry, supports, and loads; only the bar stiffness changes.
For a truss with few free coordinates, one solve per design spends most of its time in the fixed cost of Python calls and sparse-matrix objects, not in arithmetic.
The stack pays this cost once per chunk of designs.
In one measurement, 200 two-bar designs took 323 ms one design at a time and 7.6 ms stacked (2,000 designs: 3.1 s and 56 ms).
With 40 free coordinates the stack was about 10 times faster, and with 96 free coordinates about 2.7 times faster.

Tradeoff: the stack uses another summation order and other LAPACK routines.
Responses therefore change by rounding error amplified by the condition number of the design.
In the measurement above, well-conditioned designs agreed to about `1e-15` (two bars) and `3e-13` (40 free coordinates), relative to the largest value of each response group.
A design with the conditioning warning can differ in its fourth digit, and a design within rounding of a limit can change its status.

### Condition number computation

The condition number of a matrix `M` is `norm(M) * norm(inverse(M))`; the one-norm of a matrix is its largest absolute column sum.
The solver computes it before equilibration (the reported diagnostic) and after equilibration (the rank test).
The option `condition_method` of `analyze_truss` and of the application evaluators selects how.
`TrussResult.condition_method` records the selected method.

- `"exact"` (default): the solver solves every unit column in blocks of at most 64 columns, using the existing factorization.
  The condition numbers are exact up to rounding.
  This bounds inverse storage by `64 * n_free` entries and uses no random numbers.
  The calculation needs one solve per free coordinate, but it cannot miss a locally singular joint.
- `"hager-higham-estimate"`: Hager's method with Higham's refinements, the method of LAPACK `xLACN2`, estimates each inverse norm.
  It needs at most 10 solves per condition number, whatever the number of free coordinates, and uses no random numbers.
  Each candidate value is `norm(inverse(M) x) / norm(x)` for one vector `x`, so the estimate is a lower bound of the exact value.
  The estimate is often exact. When it is low, a design near the `1 / eps` rank limit can be accepted where the exact method rejects it,
  and the `1e12` conditioning warning can be omitted.
  For example, a locally singular joint among 248 independent supported bars (251 free coordinates in three dimensions)
  is rejected by the exact method and accepted, with a conditioning warning, by the estimate.
  Use the estimate for large batches of large trusses, where the solves of the exact method dominate the run time.
  In one measurement on braced lattices with prepared geometry, the estimate made one analysis about 9 times faster
  at 580 free coordinates and about 23 times faster at 1416 free coordinates.
  For a few free coordinates the estimate is not faster, because the exact method then needs only one block solve.
- `conditioning_estimate` reports the unscaled condition number. The field name reflects finite-precision arithmetic.
- The separate equilibrium backward error checks force balance at the returned displacement.

Definitions accept array-like source values.
At construction, they validate force and support dimensions and exact integer connectivity within node bounds.
For movable-node designs, fill the NaN coordinates with `movable_node_positions` and prepare geometry separately for each design.

## Supported numeric domain

The supported input domain is ordinary engineering magnitudes in double precision.
The formulas use their plain form, for example `E*A/L` for axial stiffness.
They do not rescale products that leave the double-precision range.
A response that is not finite raises `ValueError` that names the quantity, such as stiffness, displacement, mass, or stress.
This error is not a `TrussDesignRejectedError`, so a range failure never appears as a structural rejection.
The tube section area and the second moment of area of every bar with a valid section (positive radius and thickness, wall no thicker than the radius) must also be positive and finite.
The same holds for the Euler load of an evaluated design and, with a Poisson ratio, for its local buckling critical stress `E / sqrt(3*(1 - nu**2)) * (t / r)`.
Otherwise the evaluator raises `ValueError` that names the quantity.
The section check also applies in a row that another value rejects.
For example, radius `1e155` and thickness `1e-155` overflow the second moment of area.
An infinite value would give a compressed bar zero buckling demand, which is a false "safe" signal.

The load-direction displacement divides the forces by their largest magnitude before it normalizes them.
This scaling keeps the load norm inside the double range.
Extreme load scales such as `1e-200` or `1e200` then give the correct projection instead of zero.

## Plotting on caller axes

Plot functions draw on axes supplied by the caller.
They validate inputs and build their line collections and marker settings before they add anything to the axes.
An invalid input or option therefore raises `ValueError` and leaves the caller's axes unchanged.
When an option fails after drawing has started, the functions remove what they added and restore the axes limits.
`plot_truss_deformation` draws the geometry and a magnified deformed copy over a grey reference.
`plot_truss_element_response` colors each bar by a scalar response, such as the axial force, on a scale centered at zero.
`plot_truss_supports_and_loads` marks the supports and draws the nodal loads as arrows.
`plot_truss_response_ranking` sorts the element responses into a bar chart with the same colors, which shows their
distribution also for dense trusses.
The three functions take the node coordinates, connectivity, supports, and loads in the convention of `TrussModel`.
[truss_analysis_cases.py](../../examples/application_examples/truss_analysis_cases.py) solves five planar and spatial trusses and draws their deformation, strain, and stress panels with these functions.

### Structure figure of movable-node trusses

`plot_truss_structure(axes, definition, ...)` draws a truss with movable nodes as a design study presents it:
the initial truss in light grey, the optimized truss in Tol blue, sampled trusses, their magnified deformed copies, a support wall, the applied loads, and an optional legend.
`plot_truss_samples` draws sampled trusses alone, and `plot_truss_wall` draws the wall alone.
The figure draws supplied data; it runs no analysis.

- Designs: `initial_design` and `optimized_design` hold one value per movable coordinate, and `sample_designs` holds one design per row.
  `movable_node_positions` fills them into the base geometry.
  Without `initial_design`, a base without movable coordinates is the initial truss. With no truss to draw, the call raises `ValueError`.
- Displacements: `initial_displacements`, `optimized_displacements` (shape `(n_nodes, n_dimensions)`), and `sample_displacements` (shape `(n_samples, n_nodes, n_dimensions)`) are inputs, for example from `analyze_truss`.
  A truss with displacements shows `geometry + s * displacement` over a dashed reference of its undeformed geometry, with the deformation scale `s`.
  Displacements of a truss that is not drawn raise `ValueError`.
- Options of each truss: `initial_options`, `optimized_options`, and `sample_options` are `TrussDeformationOptions` mappings with the keywords of `plot_truss_deformation`.
  Their defaults are `deformation_scale` 25 (`STRUCTURE_DEFORMATION_SCALE`) and `maximum_linewidth` 3 points (`STRUCTURE_MAXIMUM_LINEWIDTH`); the initial truss also has `truss_options={"colors": PHASE_COLOR}`.
  A caller mapping replaces top-level keys and is merged over the default `truss_options`. An unknown key raises `TypeError`.
- Sample colors: `sample_colors[i]`, else the color of `sample_options["truss_options"]` for every sample, else the cycle cyan, yellow, purple.
  The cycle leaves out blue, the color of the optimized truss, and red and green, which mean bad and good designs.
  The sample color replaces only the color of the shared `truss_options`.
- Reference geometry: the wall, the supports, and the loads sit at the optimized geometry, else at the initial geometry, else at the first sampled geometry.
- Wall (`show_wall=True`): an illustration in the plane `x = wall_position` (default 0); it models no constraint.
  It covers the supported nodes (any prescribed coordinate), or all nodes when none is supported.
  Along each axis parallel to the wall, the covered nodes span `[lo, hi]` with the range `r = hi - lo`, and the wall spans `[lo - f r, hi + f r]`.
  The margin fraction `f` is `wall_margin_fraction`, by default 0.1 in 2-D and 0.5 in 3-D. A zero range uses the largest coordinate span of the truss, so the wall never collapses to a point.
  In 2-D the wall is a dark grey line of 8 points below every truss; in 3-D it is a light grey rectangle of opacity 0.4.
- Loads (`show_loads=True`) and supports (`show_supports=False`) follow `plot_truss_supports_and_loads`: dark grey arrows proportional to the load magnitudes, the largest `load_length` long (default 8 % of the largest span in 2-D, 16 % in 3-D), pushing on the node or pulling along a bar.
- Axes: the figure sets an equal aspect ratio and hides the axis lines, ticks, and labels unless `show_axes=True`.
- Legend (`show_legend=False`; `legend_options` merged over `{"loc": "center left"}`): only drawn groups, in this order:
  `"initial truss"`, `"initial truss, deformed, displacement × s"`, `"optimized truss"`, `"optimized truss, deformed, displacement × s"`, `"sampled trusses (n)"`, `"sampled trusses, deformed, displacement × s"`, `"support wall"`, `"pinned support"`, `"roller support"`, and `"applied load"`.
  The times sign and a minus sign are mathematical text, because the Computer Modern text font lacks them.
- Errors: every input is checked before anything is drawn. A later failure, for example of a display value inside an options mapping, removes every artist that the call added.

This example draws a catalogue topology at its start, an optimized design with the deformation of a steel truss, and three sampled designs:

```python
from matplotlib.figure import Figure

from designoptpy.truss import TrussModel, analyze_truss, movable_node_positions, truss_topology
from designoptpy.truss.plotting import plot_truss_structure

topology = truss_topology("4-bar-planar")
definition = topology.definition
optimized_design = [1.5, 0.8]
optimized = movable_node_positions([optimized_design], definition)[0]
model = TrussModel(
    optimized,
    definition.connectivity,
    1e-3,  # cross-section area in m**2
    210e9,  # Young's modulus in Pa
    definition.node_forces,
    definition.prescribed_displacements,
)
figure = Figure(layout="constrained")
axes = figure.subplots()
plot_truss_structure(
    axes,
    definition,
    initial_design=topology.initial_design,
    optimized_design=optimized_design,
    optimized_displacements=analyze_truss(model).displacements,
    sample_designs=[[1.2, 0.6], [1.0, 0.9], [1.8, 1.2]],
    show_legend=True,
    legend_options={"loc": "upper left", "bbox_to_anchor": (1.0, 1.0)},
)
figure.savefig("truss-structure.png")
```

### Per-element and per-node solution spaces

A truss design vector often holds one block of `d` consecutive variables per element (bar properties, such as thickness and Young's modulus) or per movable node (its coordinates).
The component solution spaces of such a study give each block its own region.
`plot_component_boxes` and `plot_component_regions` of `designoptpy.sso.plotting` draw each block in its own variables: one panel per element or node, or all blocks on one axes.
They live in the SSO package, because the truss package does not import it.
For `n` blocks of `d` consecutive variables, the component layout is `ComponentLayout(tuple(np.arange(n * d).reshape(n, d)), dimension=n * d)`.
Three variables per block need `Axes3D` panels.

```python
import matplotlib.pyplot as plt
import numpy as np

from designoptpy.sso.plotting import plot_component_boxes
from designoptpy.sso.regions import ComponentLayout

n, d = 2, 2  # two elements, each with thickness (m) and Young's modulus (Pa)
layout = ComponentLayout(tuple(np.arange(n * d).reshape(n, d)), dimension=n * d)
box = [[0.002, 70e9, 0.003, 70e9], [0.004, 210e9, 0.006, 210e9]]  # lower row, then upper row
figure, axes = plt.subplots(1, n, layout="constrained")
plot_component_boxes(axes, box, layout)
for element, panel in enumerate(axes):
    panel.set(title=f"element {element + 1}", xlabel="thickness [m]", ylabel="Young's modulus [Pa]")
```

For the regions of a component run, pass `result.candidate_regions` to `plot_component_regions` with the same axes.
The movable-node layout is the same with `d` coordinates per node, in the order of `movable_node_positions`.
