API reference¶
The table maps the most common operations across both packages. For Python signatures, see Python. The TypeScript declarations and C++ headers below are included directly from the source tree.
For a runnable example, start with Getting started. The module guides explain implementation details. For analytic coverage, fallback behavior and report flags, see Derivative coverage and reports. Element implementers can use the live C++ contexts and facets in Native element derivative API.
Operation |
JavaScript / WebAssembly |
Python / native C++ |
|---|---|---|
Import a model |
|
|
Run statics |
|
|
Evaluate a design |
|
|
JavaScript and TypeScript¶
Load the built package from build/wasm/dist/index.js. The declarations below describe its public interface.
1import type { OptimizationProblem, OptimizationDeclarations, OptimizationSettings } from "./optimization.js";
2export * from "./optimization.js";
3export * from "./study.js";
4export * from "./study-workers.js";
5
6// Types of the oos-solver package (index.js).
7//
8// Every name the interface gives or takes is an exact neutral name of O_o_Reader: card and result element types use
9// UpperCamelCase ("ShellQuad4"); table kinds ("singlePointConstrForces") and columns ("bendingMomentA1") use lowerCamelCase.
10// Messages (Diagnostic.message, Diagnostic.card, Diagnostic.field and errors) use the same neutral names.
11
12export declare function supportsMemory64(): boolean;
13export declare function supportsWasmThreads(): boolean;
14export declare function loadOosSolver(options?: Record<string, unknown> & { threads?: number }): Promise<OosSolver>;
15
16export type Analysis = "statics" | "modes" | "buckling" | "aeroelastic";
17
18// An edge by its two grid point IDs, or the side of one shell element of it (which matters at an edge of three shells
19// or more).
20export type EdgeSide = [number, number] | [number, number, number];
21
22// The geometry declarations of the mixed hybrid formulation: where the surface of the shells and the skin of the
23// solids are smooth, where they fold, and which mesh line goes on into which (grid point and element IDs). Where
24// nothing is declared, the model's ShellNormalAngle decides the state of an edge.
25export interface FormulationGeometry {
26 // The surface is smooth across the edge.
27 smoothEdges?: EdgeSide[];
28 // The surface folds along the edge, which keeps its own line.
29 sharpEdges?: EdgeSide[];
30 // The surface of the shells folds along the edge, which is straight.
31 rawEdges?: [number, number][];
32 // Shell elements whose edges are all raw: facets.
33 rawElements?: number[];
34 // [g1, g, g2]: at grid point g, the mesh line of edge g1 - g goes on into edge g - g2.
35 lineContinuations?: [number, number, number][];
36 // [g1, g]: the mesh line of edge g1 - g ends at grid point g.
37 lineEnds?: [number, number][];
38}
39
40// The edges of the surfaces that MixedHybridFormulation read from the mesh, column by column, one entry per edge.
41export interface SurfaceEdges {
42 // The IDs of the two grid points of the edge, the lower first.
43 grid1: Int32Array;
44 grid2: Int32Array;
45 surface: ("Shells" | "SolidSkin")[];
46 // At a junction of three shells or more, "Sharp" when one side at least ends there.
47 state: ("Smooth" | "Sharp" | "Raw")[];
48 // Where the state comes from: a declaration, a raw element, the model's ShellNormalAngle, a shell of a junction that
49 // no other faces, or an edge of one element.
50 origin: ("Declared" | "RawElement" | "Angle" | "Junction" | "Outline")[];
51 // Degrees: the angle measured between the normals of the elements of the edge at its grid points; the angle left
52 // between the normals of the surface read on both sides; how far the surface read turns from the plane of the
53 // corners of an element (the last two on the shells only).
54 angle: Float64Array;
55 kink: Float64Array;
56 rounding: Float64Array;
57}
58
59// The options of modelFromReader.
60export interface ModelOptions {
61 // The formulation of the elements of some card types ({ ShellQuad4: "ClassicFormulation" }).
62 elementFormulations?: Record<string, string>;
63 // The formulation of the whole model ("ClassicFormulation", "MixedHybridFormulation").
64 elementFormulation?: string;
65 // Mandatory for a model with shells or solids in MixedHybridFormulation.
66 formulationGeometry?: FormulationGeometry;
67 // Also take the component tables of the reader, which a condensed static analysis reads.
68 condensation?: boolean;
69}
70
71// The units a condensed analysis condenses: the components of the reader. "recommended": every unit but those
72// whose condensed stiffness would cost more than their interior; an array: these unit IDs.
73export type CondensedUnits = "all" | "recommended" | "none" | number[];
74export type CondensationSettings = CondensedUnits | {
75 units: CondensedUnits;
76 fullUnits?: number[]; // kept full whatever `units` says
77 retainedNodes?: number[]; // grid points kept on the boundary of their unit
78 modeCount?: number; // modes and buckling: fixed-interface modes per unit; 0: those below a cut-off
79 memoryMode?: "auto" | "speed" | "low_memory"; // statics: what the analysis keeps in memory (same results)
80 cache?: CondensationCache; // units found in it are not condensed again
81 cacheModelTag?: string; // the name of the model in the entries stored
82};
83
84// An external unit of a static analysis given by its matrices: the zone whose elements it replaces, and K* (and M*) of
85// the zone on its contour, one row and column per label [grid, component], column by column.
86export interface ExternalUnitSettings {
87 zone: { id: number; name?: string; elements: number[]; boundary: { grid: number; components?: string }[] };
88 labels: [number, number][];
89 stiffness: number[] | Float64Array;
90 mass?: number[] | Float64Array;
91}
92
93// A condensation cache in memory (OosSolver.condensationCache).
94export interface CondensationCache {
95 statistics(): { memoryHits: number; diskHits: number; misses: number; stores: number; refusedStores: number;
96 evictions: number; missCauses: Record<string, number> };
97 delete(): void;
98}
99
100// What the condensed path did.
101export interface CondensationSummary {
102 condensedUnits: number[];
103 fullUnits: number[];
104 interfaceDofs: number; // the DOFs of the interface problem, as the plan estimates them
105 note: string; // why the plan differs from the request (a model of one unit and no connection), or ""
106 // Statics: whether a constraint set recovered its units unit by unit (each unit's recovery made once for every case;
107 // with memoryMode "low_memory", envelopes and keepsCaseTables false).
108 unitByUnit: boolean;
109}
110
111// An envelope asked of a static analysis: a table kind ("displacements", "singlePointConstrForces",
112// "multiPointConstrForces", "appliedLoads", "stress", "strain", "forces", "strainEnergy"), a quantity (a component of
113// its tables, or "magnitude" for a nodal one) and the extreme kept.
114export interface EnvelopeSpec {
115 kind: string;
116 quantity: string;
117 mode: "max" | "min" | "absMax";
118}
119
120// The envelope of one table: per row the extreme over the load cases and the subcase that gives it.
121export interface EnvelopeTable {
122 kind: string;
123 elementType: string; // "" for a nodal table
124 quantity: string;
125 mode: string;
126 ids: Int32Array;
127 nodeIds: Int32Array;
128 layers: Int32Array;
129 positions: Float64Array; // empty unless the tables have stations
130 values: Float64Array;
131 cases: Int32Array;
132}
133
134export interface Diagnostic {
135 severity: "error" | "warning" | "info";
136 code: string;
137 message: string;
138 card: string; // the neutral card type, for example "ShellQuad4"
139 id: number;
140 field: string; // the neutral field name, for example "offsetZ"
141 text: string; // one line: severity, code, card and ID, field, message
142}
143
144export interface SupportCheck {
145 supported: string[];
146 refusals: Diagnostic[];
147 ignored: Diagnostic[];
148 isComplete: boolean;
149}
150
151// One nodal table: one step, one row per point, six components in the displacement system of the grid point.
152export interface NodalTable {
153 // "displacements", "singlePointConstrForces", "multiPointConstrForces", "appliedLoads", "eigenvectors"
154 kind: string;
155 subcase: number;
156 analysis: "static" | "modes" | "buckling" | "aeroelastic";
157 step: number; // the mode number of a modal or buckling table, 0 for statics
158 eigenvalue: number; // the eigenvalue of the mode (omega squared, or the load factor), 0 for statics
159 components: string[]; // ["t1", "t2", "t3", "r1", "r2", "r3"]
160 ids: Int32Array;
161 pointTypes: Int8Array; // 1 a grid point, 2 a scalar point
162 values: Float64Array; // rows x 6, row-major
163}
164
165// One element table: one element type, one step; values row-major (rows x components).
166export interface ElementTable {
167 kind: string; // "stress", "strain", "forces", "strainEnergy", "failureIndices"
168 // The result element type of O_o_Reader: the exact neutral card type ("ShellQuad4",
169 // "ShellTria3"), or a layout of its own ("ShellQuad4Composite": the plies of a laminate).
170 elementType: string;
171 subcase: number;
172 analysis: "static" | "modes" | "buckling" | "aeroelastic";
173 step: number;
174 eigenvalue: number;
175 components: string[];
176 ids: Int32Array;
177 nodeIds: Int32Array; // the grid point of the row, 0 for the centre
178 layers: Int32Array;
179 positions?: Float64Array;
180 values: Float64Array;
181}
182
183// The grid point forces of a subcase: per grid point, the applied load, the constraint forces, the force of each
184// element connected and their total (zero to round-off).
185export interface GridPointForceTable {
186 subcase: number;
187 analysis: string;
188 // The row names: "appliedLoad", "singlePointConstrForce", "multiPointConstrForce", "total", then the result element
189 // types of the elements ("ShellQuad4"), "condensedUnit" (a condensed component on its boundary) and
190 // "elementFormulation" (MixedHybridFormulation: the forces of the formulation's own relations at the grid point).
191 // In MixedHybridFormulation the forces on the unknowns of the edges, faces and interiors are carried to the grid
192 // points of their entities with their resultant: the rows of a grid point sum to zero as in ClassicFormulation.
193 names: string[];
194 nodeIds: Int32Array;
195 elementIds: Int32Array;
196 nameIndices: Int32Array; // into names
197 values: Float64Array; // rows x 6
198}
199
200export interface EigenvalueTable {
201 subcase: number;
202 analysis: "modes" | "buckling";
203 rows: {
204 mode: number; extractionOrder: number; eigenvalue: number; radians: number; cycles: number;
205 generalizedMass: number; generalizedStiffness: number;
206 }[];
207}
208
209export interface AnalysisResult {
210 selectedQuarticShells?: number[]; // IDs selected by MixedHybridDegree Auto in full statics
211 nodalTables: NodalTable[];
212 elementTables: ElementTable[];
213 gridPointForces: GridPointForceTable[];
214 eigenvalues: EigenvalueTable[];
215 envelopes: EnvelopeTable[]; // statics: those settings.envelopes asks for
216 diagnostics: Diagnostic[];
217 aeroelastic: AeroelasticResult | null;
218 // A static analysis asked to condense: what its plan decided; null otherwise.
219 condensation: CondensationSummary | null;
220}
221
222export interface StabilityDerivative {
223 label: string;
224 // Six coefficients in order: CX, CY, CZ, CMX, CMY, CMZ.
225 rigidUnsplined: Float64Array; rigidSplined: Float64Array;
226 elasticRestrained: Float64Array; elasticUnrestrained: Float64Array;
227 inertialRestrained: Float64Array; inertialUnrestrained: Float64Array;
228}
229export interface TrimSubcaseResult {
230 subcase: number; trimSet: number; mach: number; dynamicPressure: number; hasUnrestrained: boolean;
231 variables: { id: number; label: string; kind: "rigidBody" | "controlSurface" | "user" | "undefined";
232 state: "fixed" | "free" | "linked" | "scheduled"; value: number }[];
233 derivatives: StabilityDerivative[]; reference: StabilityDerivative;
234 hingeMomentDerivatives: { surface: string; atReference: Float64Array; perVariable: Float64Array }[];
235 pressures: Float64Array; boxForces: Float64Array; boxMoments: Float64Array;
236 hingeMoments: Float64Array; supportAccelerations: Float64Array;
237 monitorLoads: { name: string; loads: Float64Array }[];
238 monitor3Loads: { name: string; loads: Float64Array }[];
239}
240export interface AeroelasticResult {
241 boxIds: Int32Array; surfaces: string[]; referenceChord: number; referenceSpan: number; referenceArea: number;
242 symmetryXz: number; symmetryXy: number; configuration: string; subcases: TrimSubcaseResult[];
243 basicToReference: Float64Array; referenceOffset: Float64Array;
244 surfaceDefinitions: { id: number; label: string; referenceChord: number; referenceArea: number;
245 positionLower: number; positionUpper: number; hingeMomentLower: number | null; hingeMomentUpper: number | null }[];
246 monitorPoints: { name: string; label: string; positionFrameId: number; displacementFrameId: number;
247 point: Float64Array; component: string; pointClass: string }[];
248 monitorPoints3: { name: string; label: string; positionFrameId: number; displacementFrameId: number; point: Float64Array }[];
249}
250
251export interface Model {
252 tableNames(): string[];
253 checkSupport(analysis: Analysis): SupportCheck;
254 // What MixedHybridFormulation read at every edge of the surface of the shells and of the skin of the solids; every
255 // array is empty for a model in another formulation.
256 surfaceEdges(): SurfaceEdges;
257 delete(): void;
258}
259
260export interface OptimizationCapabilities {
261 version: number;
262 analyses: { analysis: Analysis; solution: 101 | 103 | 105 | 144; sizingFirstOrder: boolean;
263 shapeFirstOrder: boolean; secondOrder: boolean; restrictions: string[] }[];
264 responses: string[];
265 fields: { targetKind: "property" | "material" | "element"; targetCard: string; field: string;
266 type: string; requiresItem: boolean }[];
267}
268export interface OptimizationPreparation {
269 stage: "preparation"; canPrepare: boolean; error: string | null;
270 metadata: import("./optimization.js").OptimizationMetadata | null;
271 analyses: (SupportCheck & { analysis: Analysis })[];
272 capabilities: OptimizationCapabilities["analyses"];
273}
274
275export declare class OosSolver {
276 createStudy(reader: import("oor-reader").OorReader, deck: import("oor-reader").Deck,
277 definition: import("./study.js").StudyDefinition, settings?: import("./study.js").StudySettings,
278 hooks?: import("./study.js").StudyHooks): import("./study.js").OptimizationStudy;
279 restoreStudy(reader: import("oor-reader").OorReader, deck: import("oor-reader").Deck,
280 hooks?: import("./study.js").StudyHooks): ReturnType<typeof import("./study.js").restoreStudy>;
281 shapeBasisFromReader(reader: import("oor-reader").OorReader, auxiliary: import("oor-reader").Deck,
282 options: { variableId: number; cases?: { subcase: number; coefficient?: number }[]; gridIds?: number[] }):
283 { variableId: number; gridIds: Int32Array; directions: Float64Array };
284 version(): string;
285 threading(): { enabled: boolean; maximumThreads: number; activeWorkers: number; defaultThreads: number };
286 // `oor` is a loaded OorReader (package oor-reader), `deck` one of its decks.
287 // Every element card type the solver computes ("ShellQuad4") with its formulations, the default first.
288 elementFormulations(): { card: string; formulations: string[] }[];
289 capabilities(model?: Model | null): OptimizationCapabilities;
290 checkOptimization(model: Model, declarations?: OptimizationDeclarations,
291 settings?: OptimizationSettings): OptimizationPreparation;
292 // `options.elementFormulations` chooses the formulation of the elements of some card types
293 // ({ ShellQuad4: "ClassicFormulation" }), before the model's ShellQuad4Formulation parameter. The keys are the neutral card types
294 // of elementFormulations(), exactly: an unknown card type throws an Error.
295 // `options.elementFormulation` chooses the formulation of the whole model ("MixedHybridFormulation"), and
296 // `options.formulationGeometry` gives its geometry declarations (grid point and element IDs).
297 // The model's ModelParams OffsetDefinition is read (where the mass of an offset element is).
298 modelFromReader(oor: unknown, deck: unknown, options?: ModelOptions): Model;
299 createOptimization(model: Model, declarations?: OptimizationDeclarations, settings?: OptimizationSettings): OptimizationProblem;
300 // `modelOptions`: those of modelFromReader (a model in MixedHybridFormulation: elementFormulation and
301 // formulationGeometry).
302 optimizationFromReader(oor: unknown, deck: unknown, declarations?: OptimizationDeclarations,
303 settings?: OptimizationSettings, modelOptions?: ModelOptions): OptimizationProblem;
304
305 // What the solver refuses of the model for the analysis, without running it: the cards, fields and selections it
306 // does not take, then what the element formulation of the model refuses (a geometry declaration that names no
307 // edge, an element it cannot compute).
308 checkSupport(model: Model, analysis?: Analysis): SupportCheck;
309 run(model: Model, analysis?: Analysis,
310 settings?: { subcases?: number[]; memoryBytes?: number; threads?: number;
311 condensation?: CondensationSettings; streamed?: boolean;
312 externalUnits?: ExternalUnitSettings[];
313 // statics: envelopes over the load cases, and whether the per-case tables of their kinds are kept
314 envelopes?: EnvelopeSpec[]; keepsCaseTables?: boolean }): AnalysisResult;
315 condensationCache(options?: { memoryBytes?: number }): CondensationCache;
316 // The residual structure with superelements upstream of it (statics or modes).
317 runSuperelements(residual: Model, parts: { id: number; model: Model; boundary: [number, number][] }[],
318 analysis?: "statics" | "modes",
319 settings?: { subcases?: number[]; memoryBytes?: number; threads?: number }):
320 { superelements: { id: number; nodalTables: unknown[]; elementTables: unknown[]; eigenvalues: unknown[] }[];
321 diagnostics: Diagnostic[] };
322}
Optimization declarations¶
DesignResponse.mode selects a modal field with a positive, one-based mode number. A modal result item includes
its mode label. ProductReport distinguishes static Hessian blocks from modal, buckling and trim tangent
paths; the flags are described in Derivative coverage and reports.
1import type { AnalysisResult } from "./index.js";
2export type Numbers = number[] | Float64Array;
3export interface DesignVariable {
4 id: number; label?: string; initialValue: number; lower: number; upper: number; moveLimit?: number;
5}
6export interface DesignRelation {
7 id: number; card?: string; targetKind: "property" | "material" | "element";
8 targetCard: string; targetId: number; field: string; fieldItem?: number;
9 form?: "linear" | "equation" | "supplied"; constant?: number;
10 terms?: { variableId: number; coefficient: number }[];
11 equationId?: number; arguments?: { variableId?: number; constantLabel?: string }[];
12 lower?: number; upper?: number;
13}
14export interface DesignResponse {
15 id: number; label?: string; type: string; propertyType?: string; region?: number;
16 attributeA?: number; attributeB?: number; componentName?: string;
17 targets?: number[]; plies?: number[]; subcases?: number[]; tracksMode?: boolean;
18 /** Positive, one-based mode selector for a modal field response; omitted for a static field. */
19 mode?: number;
20 sections?: SectionDefinition[]; cuts?: CutDefinition[]; zones?: number[];
21}
22export interface SectionDefinition {
23 id: number; name?: string; members: { elementId: number; weight?: number }[];
24 axis?: [number, number, number]; frameId?: number; reduce?: "average" | "sum";
25}
26export interface CutDefinition {
27 id: number; name?: string; grids: number[]; elements: number[];
28 point?: [number, number, number]; positionFrameId?: number; displacementFrameId?: number;
29}
30export interface ZoneDefinition {
31 id: number; name?: string; group?: number; frameId?: number; elements: number[];
32 enclosedPolicy?: "warn" | "include" | "exclude";
33 boundary?: { grid: number; components?: string; isPiercedPoint?: boolean;
34 causes?: { kind: string; card: string; id: number; components?: string }[] }[];
35 enclosed?: { elementId: number; card: string; isPointElement?: boolean }[];
36}
37export interface EquationArgument { kind: string; id?: number; component?: number; label?: string; name?: string }
38export interface BatchArgument { name: string; components: number; values: Float64Array; isResponse: boolean }
39export interface BatchCall { arguments: BatchArgument[]; items: number }
40export interface BatchResult { outputs?: number; values: Numbers; partials?: Numbers[] }
41export interface BatchCallable {
42 evaluate(request: BatchCall): BatchResult;
43 evaluateWithPartials?(request: BatchCall): BatchResult;
44 hessianVector?(request: BatchCall & { outputs: number; weights: Float64Array; directions: BatchArgument[] }): Numbers[];
45}
46export interface SuppliedField { relationIndex: number; value: number; gradient: Numbers }
47export interface OptimizationDeclarations {
48 tables?: Record<string, Uint8Array>;
49 variables?: DesignVariable[];
50 links?: { dependentId: number; constant?: number; multiplier?: number;
51 terms: { variableId: number; coefficient: number }[] }[];
52 relations?: DesignRelation[];
53 constants?: Record<string, number>;
54 shapes?: { variableId: number; gridId: number; coefficient?: number; direction: [number, number, number] }[];
55 shapeBatches?: { variableId: number; gridIds: ArrayLike<number>; directions: Numbers }[];
56 responses?: DesignResponse[];
57 zones?: ZoneDefinition[];
58 zoneSubcases?: { subcase: number; spcSet?: number; loadSet?: number }[];
59 equationResponses?: { id: number; label?: string; callable?: string; equationId?: number;
60 byLabel?: boolean; subcases?: number[]; arguments: EquationArgument[] }[];
61 constraints?: { responseId: number; lower?: number; upper?: number; subcases?: number[] }[];
62 objective?: { responseId: number; sense?: "min" | "max"; subcase?: number };
63 callables?: Record<string, BatchCallable>;
64 suppliedAt?(x: Float64Array): SuppliedField[];
65}
66export interface OptimizationSettings {
67 derivatives?: "native" | "numerical";
68 threads?: number; memoryBytes?: number; maximumOutputBytes?: number; blockItems?: number; deckOutputs?: boolean;
69 // Missing kind: disabled. Empty array: all subcases of that kind. Default: statics only.
70 analyses?: { statics?: number[]; modes?: number[]; buckling?: number[]; aeroelastic?: number[] };
71}
72export interface OptimizationMetadata {
73 variables: (DesignVariable & { label: string; moveLimit: number | null })[];
74 independentIndices: Float64Array; initialValues: Float64Array; maximumOutputBytes: number;
75 relations: { id: number; targetCard: string; targetId: number; field: string; fieldItem: number;
76 lower: number | null; upper: number | null }[];
77 objectiveResponseId: number | null; objectiveSense: "min" | "max"; objectiveSubcase: number;
78}
79export interface SparseGradient { columns: Float64Array; values: Float64Array }
80export interface DesignPoint {
81 variables: Float64Array; variableGradients: SparseGradient[];
82 fields: (SparseGradient & { value: number })[];
83}
84export interface ResponseItem { subcase: number; entity: number; component: number; layer: number; mode?: number }
85export interface ResponseValues {
86 id: number; label: string; values: Float64Array; items: ResponseItem[];
87 statuses: ("ok" | "failed" | "not_evaluated")[];
88}
89export interface ConstraintValue {
90 setId: number; responseId: number; item: number; label: ResponseItem; side: "lower" | "upper";
91 bound: number; value: number; normalised: number; derivativeScale: number;
92}
93export interface OptimizationValues {
94 x: Float64Array; subcases: Int32Array; objective: number | null;
95 responses: ResponseValues[]; constraints: ConstraintValue[];
96 trackedModes: { responseId: number; subcase: number; mode: number; mac: number; isUncertain: boolean;
97 shape: Float64Array }[];
98}
99export interface GradientSettings {
100 method?: "automatic" | "direct" | "adjoint" | "chained" | "finiteDifference";
101 relativeStep?: number; absoluteStep?: number;
102 responseIds?: number[]; itemMasks?: { responseId: number; isRetained: number[] | Uint8Array }[];
103}
104export interface DesignGradients {
105 variableCount: number; responses: { id: number; itemCount: number; values: Float64Array }[];
106 objective: Float64Array | null; constraints: Float64Array[];
107 report: { solves: number; factorisations: number; analyticDerivatives: number;
108 fieldPerturbations: number; shapePerturbations: number; analysisPerturbations: number;
109 method?: "finiteDifference"; evaluations?: number; order?: number };
110}
111export interface SparseWeights { rowStart: number[] | Float64Array; items: number[] | Float64Array; values: Numbers }
112export interface ProductWeights { rows?: number; responses: Record<number, Numbers | SparseWeights> }
113export interface ProductBlock { first: number; count: number; rows: number; columns: number; values: Float64Array }
114export interface ProductReport {
115 solves: number; blocks: number; factorisations: number; lineariseSeconds: number; productSeconds: number;
116 isLinearisationReused: boolean; linearisationBytes: number; adjointSolves: number; isAdjointReused: boolean;
117 perturbedLinearisations: number;
118 hasHessianBlocks: boolean; areHessianBlocksReused: boolean; hessianBlocksReason: string;
119 /** Analytic coupled Hessian paths; hasHessianBlocks identifies the separate static block path. */
120 usesModalTangents: boolean; usesBucklingTangents: boolean; usesTrimTangents: boolean;
121}
122export interface ProductResult { rows: number; columns: number; values?: Float64Array; report: ProductReport }
123export interface ProductSettings {
124 count?: number; block?: number; onBlock?(block: ProductBlock): void;
125 responseIds?: number[]; subcases?: number[];
126}
127export interface GradientBlock {
128 rowBegin: number; rowCount: number; columnBegin: number; columnCount: number; values: Float64Array;
129}
130export interface SparseSupport { rows: number; columns: number; row: Float64Array; column: Float64Array }
131export interface SparseTriplets extends SparseSupport { values: Float64Array }
132export interface DesignBlocks {
133 sets: { stiffness: SparseTriplets; stiffnessSupport: SparseSupport; transform: SparseTriplets;
134 equationDofs: Float64Array }[];
135 subcases: { subcase: number; set: number; pseudoLoads: SparseTriplets; pseudoLoadSupport: SparseSupport;
136 hessianDisplacement: Float64Array; hessianMixed: Float64Array; adjoint: Float64Array }[];
137 itemWeights: SparseTriplets; itemWeightSupport: SparseSupport;
138 explicitParts: SparseTriplets; explicitPartSupport: SparseSupport; itemSubcases: Int32Array;
139 hasHessian: boolean; designSupport: SparseSupport; hessianDesign: Float64Array;
140 hessianReport: ProductReport; hessianAsymmetry: number; dofPoints: Int32Array; dofComponents: Int8Array;
141}
142export declare class OptimizationProblem {
143 metadata(): OptimizationMetadata;
144 designPoint(x: Numbers): DesignPoint;
145 evaluate(x?: Numbers, modeReferences?: { responseId: number; subcase: number; shape: Numbers }[]): OptimizationEvaluation;
146 delete(): void;
147}
148export declare class OptimizationEvaluation {
149 values(): OptimizationValues;
150 analysisResults(): AnalysisResult;
151 gradients(settings?: GradientSettings): DesignGradients;
152 streamGradients(onBlock: (block: GradientBlock) => void, block?: number): {
153 solves: number; blocks: number; rows: number; columns: number; orientation: string;
154 };
155 jvp(directions: Numbers, settings?: ProductSettings): ProductResult;
156 vjp(weights: ProductWeights, settings?: Pick<ProductSettings, "block" | "onBlock">): ProductResult;
157 hessianVector(weights: ProductWeights, directions: Numbers, count?: number): { values: Float64Array; report: ProductReport };
158 hessian(weights: ProductWeights): Float64Array;
159 blocks(weights?: ProductWeights | null): DesignBlocks;
160 lagrangianWeights(objectiveFactor?: number, multipliers?: Numbers | null): ProductWeights;
161 clearLinearisation(): void;
162 delete(): void;
163}
External studies and workers¶
1import type { Deck, OorReader, PartDefinition, CardScalar, WriteReport } from "oor-reader";
2import type { Analysis, AnalysisResult, OosSolver } from "./index.js";
3import type { OptimizationValues, ResponseItem } from "./optimization.js";
4
5export interface StudyVariable {
6 id: number; label?: string; initialValue: number; lower: number; upper: number; scale?: number;
7 kind?: "continuous" | "integer" | "choice"; choices?: number[];
8}
9export type ParameterTarget =
10 { kind: "card"; type: string; id?: number; key?: number; field?: string; slot?: number; forceReal?: boolean; part?: PartDefinition } |
11 { kind: "case"; command: string; subcase?: number; sectionKey?: number; variant?: string; options?: string[] } |
12 { kind: "solution" };
13export interface StudyParameter {
14 target: ParameterTarget; variableId?: number; coefficient?: number; constant?: number;
15 terms?: { variableId: number; coefficient?: number }[];
16 callback?: string;
17}
18export interface StudyResponse {
19 id: number; label?: string; analysis?: number;
20 source: "nodal" | "element" | "gridPointForce" | "eigenvalue" | "trimVariable" |
21 "stabilityDerivative" | "pressure" | "boxForce" | "boxMoment" | "hingeMoment" | "callback" | "query";
22 query?: string; column?: string; idColumn?: string; args?: Record<string, unknown>;
23 kind?: string; subcase?: number; elementType?: string; ids?: number[]; nodeIds?: number[]; layers?: number[];
24 components?: string | number | (string | number)[]; rowNames?: string[];
25 step?: number; mode?: number; tracksMode?: boolean; minimumMac?: number;
26 variable?: string; derivativeColumn?: "rigidUnsplined" | "rigidSplined" | "elasticRestrained" |
27 "elasticUnrestrained" | "inertialRestrained" | "inertialUnrestrained";
28 reduce?: "none" | "sum" | "mean" | "max" | "min" | "maxAbs" | "norm";
29 scale?: number; callback?: string;
30}
31export interface StudyDefinition {
32 version: 1; variables: StudyVariable[]; parameters?: StudyParameter[];
33 analyses: { analysis: Analysis; subcases?: number[] }[];
34 responses: StudyResponse[];
35 objective?: { responseId: number; item?: number; sense?: "min" | "max" };
36 constraints?: { responseId: number; items?: number[]; lower?: number; upper?: number; scale?: number }[];
37 update?: string;
38}
39export interface StudyContext {
40 deck: Deck; reader: OorReader; solver: OosSolver; x: Float64Array; variables: Record<number, number>;
41}
42export interface StudyHooks {
43 parameters?: Record<string, (context: StudyContext) => CardScalar>;
44 updates?: Record<string, (context: StudyContext) => void>;
45 responses?: Record<string, (context: StudyContext & { runs: AnalysisResult[]; response: StudyResponse;
46 mode?: number; modeSign: number }) => number | ArrayLike<number> | { values: ArrayLike<number>; items?: ResponseItem[] }>;
47}
48export interface StudySettings {
49 threads?: number; memoryBytes?: number; maximumOutputBytes?: number; maximumCachedPoints?: number;
50 applyDefaults?: boolean; checkReferences?: boolean;
51 model?: import("./index.js").ModelOptions;
52}
53export interface DifferenceSettings {
54 relativeStep?: number; absoluteStep?: number; side?: "central" | "forward" | "backward";
55 allowNonsmooth?: boolean; signal?: AbortSignal;
56}
57export interface StudyMatrix {
58 rows: number; columns: number; values?: Float64Array; keys?: string[];
59 report: { method: "finiteDifference"; evaluations: number; order?: number };
60}
61export interface StudyVector { values: Float64Array; keys: string[] }
62export interface StudyPoint { values: OptimizationValues; analyses?: AnalysisResult[] }
63
64export declare class OptimizationStudy {
65 constructor(solver: OosSolver, reader: OorReader, deck: Deck, definition: StudyDefinition,
66 settings?: StudySettings, hooks?: StudyHooks);
67 metadata(): { version: number; revision: number; variables: StudyVariable[]; initialValues: Float64Array;
68 maximumOutputBytes: number; derivativeMethod: "finiteDifference"; analyses: StudyDefinition["analyses"] };
69 evaluate(x?: ArrayLike<number>, references?: StudyEvaluation | null): StudyEvaluation;
70 evaluateMany(points: ArrayLike<ArrayLike<number>>, options?: { signal?: AbortSignal; includeResults?: boolean;
71 onPoint?(point: StudyPoint, index: number): void | Promise<void> }): Promise<StudyPoint[]>;
72 saveDefinition(deck: Deck, x?: ArrayLike<number>, state?: unknown): void;
73 rebuild(deck: Deck, definition?: StudyDefinition, settings?: StudySettings, hooks?: StudyHooks): OptimizationStudy;
74 clearCache(): void;
75 delete(): void;
76}
77export declare class StudyEvaluation {
78 values(): OptimizationValues;
79 vector(): StudyVector;
80 analysisResults(): AnalysisResult[];
81 model(): Deck;
82 gradients(settings?: DifferenceSettings & { onBlock?(block: { rowBegin: number; rowCount: number;
83 columnBegin: number; columnCount: number; values: Float64Array }): void }): StudyMatrix;
84 jvp(directions: ArrayLike<number>, settings?: DifferenceSettings & { count?: number }): StudyMatrix;
85 vjp(weights: ArrayLike<number>, settings?: DifferenceSettings & { rows?: number }): StudyMatrix;
86 lagrangianWeights(objectiveFactor?: number, multipliers?: ArrayLike<number> | null): Float64Array;
87 hessianVector(weights: ArrayLike<number>, directions: ArrayLike<number>, settings?: DifferenceSettings & {
88 count?: number; outerRelativeStep?: number }): StudyMatrix;
89 hessian(weights: ArrayLike<number>, settings?: DifferenceSettings & { outerRelativeStep?: number }): StudyMatrix;
90 save(path: string, options?: { state?: unknown; compressionLevel?: number; shuffle?: boolean }): WriteReport;
91 delete(): void;
92}
93export declare function restoreStudy(solver: OosSolver, reader: OorReader, deck: Deck,
94 hooks?: StudyHooks): { study: OptimizationStudy; state: unknown; diagnostics: AnalysisResult["diagnostics"][];
95 trackedModes: Omit<OptimizationValues["trackedModes"][number], "shape">[] };
96export declare const STUDY_DOCUMENT: string;
1import type { AnalysisResult } from "./index.js";
2import type { OptimizationDeclarations, OptimizationSettings, OptimizationValues, OptimizationMetadata,
3 GradientSettings, DesignGradients } from "./optimization.js";
4import type { StudyDefinition, StudySettings, StudyMatrix, DifferenceSettings, StudyPoint } from "./study.js";
5
6export interface WorkerPoolConfig {
7 readerURL: string | URL; solverURL?: string | URL; hooksURL?: string | URL;
8 model: Uint8Array; mode?: "study" | "native";
9 definition?: StudyDefinition | OptimizationDeclarations;
10 settings?: StudySettings | OptimizationSettings;
11 workers?: number; initializationTimeoutMs?: number; maximumQueuedPoints?: number;
12 solverOptions?: { threads?: number };
13}
14export interface WorkerEvaluationOptions {
15 signal?: AbortSignal; timeoutMs?: number; includeResults?: boolean;
16 gradients?: boolean | GradientSettings | DifferenceSettings;
17 modeReferences?: { responseId: number; subcase: number; shape: ArrayLike<number> }[];
18 referencePoint?: StudyPoint & { analyses: AnalysisResult[] };
19}
20export interface WorkerEvaluation {
21 values: OptimizationValues; analyses?: AnalysisResult[]; gradients?: DesignGradients | StudyMatrix;
22}
23export declare class OptimizationWorkerPool {
24 metadata(): OptimizationMetadata | ReturnType<import("./study.js").OptimizationStudy["metadata"]>;
25 evaluate(x?: ArrayLike<number>, options?: WorkerEvaluationOptions): Promise<WorkerEvaluation>;
26 evaluateMany(points: ArrayLike<ArrayLike<number>>, options?: WorkerEvaluationOptions & {
27 onPoint?(point: WorkerEvaluation, index: number): void | Promise<void> }): Promise<WorkerEvaluation[]>;
28 close(reason?: Error): void;
29}
30export declare function createOptimizationWorkerPool(config: WorkerPoolConfig): Promise<OptimizationWorkerPool>;
Python¶
Import model_from_reader(deck, *, formulation=None) and
optimization_from_reader(deck, *, analysis="statics", formulation=None, threads=1) from oo_solver.
Model.run(analysis="statics", *, threads=1, subcases=[])returns a dictionary with read-only NumPy result arrays. Analyses arestatics,modes,bucklingandaeroelastic.OptimizationProblem.variablesandinitial_valuesgive the independent variables in vector order.problem.evaluate(x)returns a retainedDesignPoint.point.objective,point.constraintsandpoint.responsesdescribe that evaluation.point.gradients(),point.jvp(direction)andpoint.vjp(weights)reuse it.
See Native Python package for paired examples and installation details. The public Python module and native bindings define the available calls.
C++ entry points¶
ModelInput.hpp¶
1#pragma once
2
3#include "oos/input/snapshot/ModelSnapshot.hpp"
4#include "oos/input/snapshot/SnapshotBuilder.hpp"
5
6#include <cstdint>
7#include <memory>
8#include <string>
9#include <utility>
10#include <vector>
11
12// The simple entry points of the solver: what the WebAssembly module (wasm/) offers to JavaScript, in plain C++ so that
13// they also build and run natively. They take plain types (byte vectors, numbers, texts) and hide the snapshot, the
14// solution options and the memory budget.
15namespace oos::api
16{
17
18// A real column added after the columns of a table, one value per row (NaN for none): what the caller computes for a
19// table of O_o_Reader that the solver reads with one more column (the neutral axes n1, n2 of sections_table).
20struct AddedColumn
21{
22 std::string name;
23 std::vector<double> values;
24};
25
26struct SourceCard
27{
28 std::string card;
29 std::int64_t count = 0;
30};
31
32// The model of one analysis, gathered table by table: the tables of O_o_Reader as table packages (the bytes of its
33// QueryTable.toPackage(), which keep the exact Arrow layout), the rotations of the displacement systems and the version
34// counters of the model. build() checks every table against what the solver reads and makes the snapshot the analyses
35// run on.
36//
37// The names are those of the snapshot: the query tables under their own names ("nodes", "singlePointConstrTable",
38// "subcasesTable", ...; see input/contract/TableRole.cpp), and the card tables, by their neutral card types
39// ("ShellQuad4"), through their own methods.
40//
41// Thread-safety: none (one object per model, on one thread). Ownership: owns the tables until build().
42class ModelInput
43{
44public:
45 ModelInput() = default;
46
47 void setVersions(std::int64_t structureVersion, std::int64_t contentVersion);
48
49 // All source card types and counts, including data not present in the exported tables.
50 void setSourceCards(std::vector<SourceCard> cards);
51
52 // A table of a snapshot role ("nodes", "singlePointConstrTable", ...), with optional added columns. Throws
53 // ContractError for a name that is not a role or bytes that are not a table package.
54 void setTable(const std::string& name, std::vector<std::uint8_t> package, std::vector<AddedColumn> added = {});
55
56 // The card tables, by neutral card type: the elements of one card type ("ShellQuad4"), the properties
57 // ("ShellProp"), the eigenvalue methods ("LanczosEigenMethod", with the column of their ID), the material cards the
58 // shells and solids read field by field ("OrthoMat2D"), the load cards with their field formats
59 // ("PointForceLoad"), the aeroelastic cards ("AeroBeamSpline2", with their ID column).
60 void addElementTable(const std::string& card, std::vector<std::uint8_t> package);
61 void addPropertyTable(const std::string& card, std::vector<std::uint8_t> package);
62 void addMethodTable(const std::string& card, const std::string& idColumn, std::vector<std::uint8_t> package);
63 void addMaterialTable(const std::string& card, std::vector<std::uint8_t> package);
64 void addLoadCardTable(const std::string& card, std::vector<std::uint8_t> package);
65 void addAeroCardTable(const std::string& card, const std::string& idColumn, std::vector<std::uint8_t> package);
66
67 // The rotation of each grid point's displacement system to the basic system, 9 values per grid point in the rows
68 // of the "nodes" table (O_o_Reader's displacementRotations).
69 void setDisplacementRotations(std::vector<double> rotations);
70
71 // ModelParams OffsetDefinition: "ElemOffsetsOnly" (the default), "LoadRecoveryOffsets" or "ElemOffsetZ"; another
72 // value is reported by the support check.
73 void setOffsetDefinition(const std::string& value);
74
75 // The formulation of every element of one card type ("ShellQuad4", "ClassicFormulation"; elementFormulations()
76 // lists them), before the model's <Card>Formulation parameter; a second call for the same card replaces the first.
77 // The card is the neutral card type exactly as elementFormulations() names it: a deck keyword ("ShellQuad4") is
78 // refused, so that a program names a card one way only. A formulation the card does not have is reported by the
79 // support check. Throws std::invalid_argument for an empty name or a card that is not an element card type of the
80 // solver.
81 void setElementFormulation(const std::string& card, const std::string& formulation);
82
83 // The formulation of the whole model ("ClassicFormulation", "MixedHybridFormulation"), before the model's
84 // ElementFormulation parameter. Under MixedHybridFormulation every shell, line and solid card takes it together
85 // (docs/mixed-hybrid-formulation-spec.md section 4.5). Throws std::invalid_argument for a name the solver does not
86 // know.
87 void setModelFormulation(const std::string& formulation);
88
89 // The geometry declarations of the mixed hybrid formulation (section 4.4 of the specification), as flat lists of
90 // IDs. Mandatory for a model with shells or solids in that formulation; empty lists say that the model's
91 // ShellNormalAngle decides every edge. Throws std::invalid_argument for a list whose length is not a multiple of
92 // its group, an edge of one grid point or a mesh line that names a grid point twice.
93 struct FormulationGeometryLists
94 {
95 // Three values per edge: its two grid point IDs, then the shell element whose side is meant (0: every side).
96 std::vector<std::int32_t> smoothEdges;
97 std::vector<std::int32_t> sharpEdges;
98 // Two grid point IDs per edge.
99 std::vector<std::int32_t> rawEdges;
100 std::vector<std::int32_t> rawElements;
101 // Three grid point IDs per continuation: the far end of one edge, the grid point the line goes through, the
102 // far end of the edge it goes on into.
103 std::vector<std::int32_t> lineContinuations;
104 // Two grid point IDs per end: the far end of the edge, then the grid point its line ends at.
105 std::vector<std::int32_t> lineEnds;
106 };
107 void setFormulationGeometry(const FormulationGeometryLists& lists);
108
109 // Checks every table and makes the snapshot; the object is empty afterwards. Throws ContractError naming the
110 // table, column, expected type and actual type when a table is not what the solver reads. Messages use the model's
111 // neutral card and field names.
112 [[nodiscard]] std::shared_ptr<const input::ModelSnapshot> build();
113
114private:
115 input::SnapshotBuilder m_builder;
116};
117
118} // namespace oos::api
Analyses.hpp¶
1#pragma once
2
3#include "oos/base/diagnostics/Diagnostic.hpp"
4#include "oos/base/memory/MemoryBudget.hpp"
5#include "oos/input/snapshot/ModelSnapshot.hpp"
6#include "oos/output/arrays/EigenvalueTable.hpp"
7#include "oos/output/arrays/ResultArrays.hpp"
8#include "oos/output/envelopes/EnvelopeAccumulator.hpp"
9#include "oos/output/sections/ZoneDefinition.hpp"
10#include "oos/reduction/cache/CondensationCache.hpp"
11#include "oos/reduction/scheduling/MemoryMode.hpp"
12#include "oos/solutions/sol144/TrimSolution.hpp"
13
14#include <cstdint>
15#include <memory>
16#include <optional>
17#include <string>
18#include <string_view>
19#include <utility>
20#include <vector>
21
22namespace oos::api
23{
24
25// The analyses a model can be run with.
26enum class Analysis : std::uint8_t
27{
28 Statics, // linear statics (SOL 101)
29 Modes, // real eigenvalues, normal modes (SOL 103)
30 Buckling, // linear buckling (SOL 105): a static preload, then the load factors
31 Aeroelastic, // static aeroelastic trim (SOL 144)
32};
33
34// Which units of condensation an analysis condenses. The units are the components of the model as O_o_Reader
35// computes them (connectedComponents: elements joined through shared grid points; rigid elements, multipoint
36// constraints, fasteners, springs and glued contacts between them are the connections), so the model must carry the
37// component tables (in JavaScript: modelFromReader(oor, deck, { condensation: true })).
38enum class CondensedUnits : std::uint8_t
39{
40 None, // the full path (the default)
41 All, // every unit
42 Recommended, // every unit but those whose condensed stiffness would hold more values than their interior factor
43 Listed // the units of CondensationSettings::condensedUnits
44};
45
46// The condensed path of an analysis (solutions::CondensationPlanner, reduction::CondensationPlan): each condensed unit
47// reduced to its boundary, the interface problem solved, the units recovered. A static analysis and a trim condense
48// their units statically, with the results of the full path to round-off; normal modes and buckling reduce them by
49// Craig-Bampton (their fixed-interface modes kept beside their boundary), whose roots approach those of the full
50// path as more modes are kept. A model of one unit and no connection takes the full path whatever the settings.
51struct CondensationSettings
52{
53 CondensedUnits units = CondensedUnits::None;
54 std::vector<std::int64_t> condensedUnits; // with Listed: the component IDs
55 std::vector<std::int64_t> fullUnits; // kept full whatever `units` says
56 std::vector<std::int32_t> retainedNodes; // grid points kept on the boundary of their unit
57 // Normal modes and buckling: the fixed-interface modes kept per unit; 0: those below the cut-off of
58 // reduction::CB_CUTOFF_FACTOR times the highest root asked for.
59 std::int32_t modeCount = 0;
60 // Statics: what the analysis keeps in memory (reduction::MemoryMode: every mode gives the same results to the bit;
61 // LowMemory recovers the units in sequence and builds their equations again at their recovery).
62 reduction::MemoryMode memoryMode = reduction::MemoryMode::Speed;
63 // The condensation cache the units are taken from and stored in (null: none). It outlives the analysis; an analysis
64 // that finds a unit in it condenses nothing of that unit, with the same results to the bit. `cacheModelTag` names
65 // the model in the entries the analysis stores.
66 std::shared_ptr<reduction::CondensationCache> cache;
67 std::string cacheModelTag;
68};
69
70// An external unit of a static analysis given by its matrices (solutions::ExternalUnitPath): the zone whose elements
71// it replaces (its elements and its boundary grid points, as O_o_Reader's zone boundaries give them) and the matrices
72// of the zone condensed onto its contour, on `labels` (grid point and component 1 to 6, in the displacement systems of
73// the grid points), column by column. No load source: a zone loaded inside is refused.
74struct ExternalUnitSettings
75{
76 output::ZoneDefinition zone;
77 std::vector<reduction::UnitDofLabel> labels;
78 std::vector<double> stiffness; // K*, labels × labels
79 std::vector<double> mass; // M*, labels × labels; empty: not given
80};
81
82// What an analysis is asked to do. Every field has a default that runs the deck as it is written.
83struct AnalysisSettings
84{
85 // The subcases to solve, in this order; empty: every subcase of the Case Control.
86 std::vector<std::int32_t> subcases;
87 std::size_t threads = 1;
88 // The memory the analysis may use, in bytes; 0: what is left in the module's memory.
89 std::uint64_t memoryBytes = 0;
90 // Additional links; links exported in the snapshot are read automatically.
91 std::vector<aero::AeroLink> links;
92 // The units to condense (none: the full path).
93 CondensationSettings condensation;
94 // Statics only: the full path streamed (solutions::StreamedStatics: the equations solved without a factor of the
95 // whole model, the outputs made region by region), for a model whose factor would not fit the memory. Refused with
96 // a condensation.
97 bool isStreamed = false;
98 // Statics only: the external units whose matrices replace zones of elements (empty: none).
99 std::vector<ExternalUnitSettings> externalUnits;
100 // Statics only: the envelopes computed over the load cases (output::EnvelopeAccumulator; empty: none), and whether
101 // the per-case tables of a kind that has an envelope are kept too (false: only the envelope; the condensed path
102 // recovered in sequence may then recover its units unit by unit).
103 std::vector<output::EnvelopeSpec> envelopes;
104 bool keepsCaseTables = true;
105};
106
107// What the condensed path of an analysis did.
108struct CondensationSummary
109{
110 std::vector<std::int64_t> condensedUnits; // by increasing ID
111 std::vector<std::int64_t> fullUnits; // the units kept full, by increasing ID
112 std::int64_t interfaceDofs = 0; // the DOFs of the interface problem, as the plan estimates them
113 std::string note; // why the plan differs from the request (the one-unit rule), or empty
114 // Statics: whether a constraint set recovered its units unit by unit (CondensedStatics::GroupInputs::visitUnit).
115 bool isUnitByUnit = false;
116};
117
118// The outcome of an analysis: the result tables, the eigenvalues and the warnings.
119struct AnalysisOutput
120{
121 // The memory budget of the run: the result buffers hold their reservations in it, so it is declared first and
122 // destroyed last.
123 std::shared_ptr<base::MemoryBudget> budget;
124 // The applied quartic shell IDs chosen by Auto in full statics.
125 std::optional<std::vector<std::int32_t>> selectedQuarticShells;
126 // The nodal and element tables, in the layout of O_o_Reader's results ({kind, subcase, step, ids, values}).
127 output::ResultArrays tables;
128 // The eigenvalue table of each modal or buckling subcase (empty for statics).
129 std::vector<output::EigenvalueTable> eigenvalues;
130 // Aerodynamic and trim results for SOL 144; its structural tables are in tables.
131 std::shared_ptr<solutions::TrimResults> aeroelastic;
132 // The warnings and information of the run (an error stops the run with an exception instead).
133 std::vector<base::Diagnostic> diagnostics;
134 // An analysis asked to condense: what its plan decided (empty otherwise).
135 std::optional<CondensationSummary> condensation;
136 // Statics: the envelopes asked for (AnalysisSettings::envelopes).
137 std::vector<output::EnvelopeTable> envelopes;
138};
139
140// The cards and fields of the model the analysis cannot take (refusals: errors) or will not use (ignored: warnings),
141// all found in one pass before anything is computed.
142// Supported cards and diagnostics use the neutral model card types ("ShellQuad4") and field names ("offset").
143struct SupportCheck
144{
145 std::vector<std::string> supported;
146 std::vector<base::Diagnostic> refusals;
147 std::vector<base::Diagnostic> ignored;
148};
149
150// What the formulation that reads its geometry from the mesh (MixedHybridFormulation) made of every edge of the
151// surface of the shells and of the skin of the solids (docs/mixed-hybrid-formulation-spec.md section 10.5), one row
152// per edge and column by column, for a program that shows the model: the IDs of its two grid points (the lower
153// first); the surface ("Shells", "SolidSkin"); its state ("Smooth", "Sharp", "Raw"); where the state comes from
154// ("Declared", "RawElement", "Angle", "Junction", "Outline"); and, in degrees, the angle measured between the normals
155// of its elements at its grid points, the angle left between the normals of the surface read on both sides, and how
156// far the surface read turns from the plane of the corners of an element (the last two on the shells only).
157struct SurfaceEdgeTable
158{
159 std::vector<std::int32_t> grid1;
160 std::vector<std::int32_t> grid2;
161 std::vector<std::string> surface;
162 std::vector<std::string> state;
163 std::vector<std::string> origin;
164 std::vector<double> angle;
165 std::vector<double> kink;
166 std::vector<double> rounding;
167};
168
169// The edges read of a model: empty when no card of the model is in a formulation that reads its geometry from the
170// mesh. The model of the formulation is built as an analysis builds it; the problems that would stop the analysis
171// (checkSupport lists them: a model without geometry declarations...) do not stop the table, which then shows what
172// the fold angle of the model alone decides.
173[[nodiscard]] SurfaceEdgeTable surfaceEdges(const input::ModelSnapshot& snapshot);
174
175// The formulations of one element card, the default first (elements/core/ElementFormulation.hpp).
176struct ElementFormulations
177{
178 std::string card;
179 std::vector<std::string> formulations;
180};
181
182// Every element card the solver computes, with its formulations, in the order of the element library.
183[[nodiscard]] std::vector<ElementFormulations> elementFormulations();
184
185// What the solver refuses of the model for the analysis, without running it: the cards, fields and selections it does
186// not take and, when there is none, what the element formulation of the model refuses (the problems of its model, as
187// a geometry declaration that names no edge, and the elements it cannot compute), which a run reports before it
188// assembles anything.
189[[nodiscard]] SupportCheck checkSupport(const input::ModelSnapshot& snapshot, Analysis analysis);
190
191// Runs the analysis on the model. Throws UnsupportedCardError when a card is refused (checkSupport lists them all),
192// SolverError for a problem of the model (a mechanism, a singular matrix, a missing card), MemoryBudgetError when the
193// memory does not suffice.
194[[nodiscard]] AnalysisOutput runAnalysis(const input::ModelSnapshot& snapshot, Analysis analysis,
195 const AnalysisSettings& settings);
196
197// One superelement upstream of the residual structure (solutions::SuperelementSolution): its own model, read with
198// the Case Control of the residual structure (its subcases select the sets of its own model), and its boundary
199// points, each a point of the part and the point of the residual structure it is.
200struct SuperelementPartSettings
201{
202 std::int32_t superelementId = 1;
203 std::shared_ptr<const input::ModelSnapshot> snapshot;
204 std::vector<std::pair<base::EntityId, base::EntityId>> boundary; // (part point, residual point)
205};
206
207// The results of a run with superelements: the tables of each superelement (the residual structure, 0, first), the
208// eigenvalues of a modal analysis, and the warnings.
209struct SuperelementOutput
210{
211 std::int32_t superelementId = 0;
212 output::ResultArrays tables;
213 std::vector<output::EigenvalueTable> eigenvalues;
214};
215struct SuperelementAnalysisOutput
216{
217 std::shared_ptr<base::MemoryBudget> budget; // declared first: the result buffers hold their reservations in it
218 std::vector<SuperelementOutput> superelements;
219 std::vector<base::Diagnostic> diagnostics;
220};
221
222// Runs a static (Statics) or modal (Modes) analysis of the residual structure `residual` with the superelements
223// `parts`, each reduced on its boundary (static condensation, or Craig-Bampton on its generalised coordinates in a
224// modal analysis), the residual structure solved with them, each part recovered. Every subcase of the residual's Case
225// Control applies to every superelement. Throws as runAnalysis, SolverError for another analysis.
226[[nodiscard]] SuperelementAnalysisOutput runSuperelements(const input::ModelSnapshot& residual,
227 std::vector<SuperelementPartSettings> parts,
228 Analysis analysis, const AnalysisSettings& settings);
229
230// The name and version of the solver: "O_o_Solver 0.2.0".
231[[nodiscard]] std::string programName();
232
233// A condensation cache that lives in memory, for the analyses of the process to share (CondensationSettings::cache):
234// its entries at most `memoryBytes` (0: reduction::CacheOptions::DEFAULT_MEMORY_BYTES), the least recently used dropped
235// first.
236[[nodiscard]] std::shared_ptr<reduction::CondensationCache> makeCondensationCache(std::uint64_t memoryBytes);
237
238} // namespace oos::api
Optimization.hpp¶
1#pragma once
2
3#include "oos/design/external/VectorJacobianProducts.hpp"
4#include "oos/design/sensitivity/GradientStream.hpp"
5
6#include <functional>
7#include <map>
8#include <memory>
9#include <string>
10#include <vector>
11
12namespace oos::api
13{
14
15// Tables travel as owned packages between the independent reader and solver memories.
16struct OptimizationInput
17{
18 std::map<std::string, std::vector<std::uint8_t>> tables;
19 design::DesignModelParts model;
20 design::ResponseParts responses;
21 design::ConstraintParts constraints;
22 std::map<std::string, std::shared_ptr<design::BatchCallable>> callables;
23 std::function<std::vector<design::SuppliedField>(std::span<const double>)> suppliedAt;
24};
25
26struct OptimizationSettings
27{
28 std::uint64_t memoryBytes = 0;
29 std::size_t threads = 1;
30 std::uint64_t maximumOutputBytes = 256ULL * 1024 * 1024;
31 std::size_t blockItems = design::EQUATION_BATCH_ITEMS;
32 design::DesignAnalyses analyses;
33 solutions::StaticOptions analysisOptions;
34 bool deckOutputs = false;
35};
36
37class OptimizationEvaluation;
38
39// A fixed model and declarations. Rebuild it after changing the reader's model.
40// Evaluations share this owner, so deleting the JavaScript problem cannot invalidate their factors or callbacks.
41class OptimizationProblem : public std::enable_shared_from_this<OptimizationProblem>
42{
43public:
44 OptimizationProblem(std::shared_ptr<const input::ModelSnapshot> snapshot, OptimizationInput input,
45 OptimizationSettings settings);
46 OptimizationProblem(std::shared_ptr<const input::ModelSnapshot> snapshot, OptimizationInput input,
47 OptimizationSettings settings, std::map<std::string, base::ImportedTable> nativeTables);
48 [[nodiscard]] const design::DesignProblem& problem() const noexcept { return m_problem; }
49 [[nodiscard]] const OptimizationSettings& settings() const noexcept { return m_settings; }
50 [[nodiscard]] design::CallableRegistry callables() const;
51 [[nodiscard]] std::vector<design::SuppliedField> supplied(std::span<const double> x) const;
52 [[nodiscard]] std::shared_ptr<OptimizationEvaluation> evaluate(std::vector<double> x,
53 const design::ModeReferences& references = {});
54
55private:
56 OptimizationInput m_input;
57 OptimizationSettings m_settings;
58 std::shared_ptr<base::ThreadPool> m_pool;
59 design::DesignProblem m_problem;
60};
61
62// One retained point. Budget precedes the evaluation and linearisation so it outlives their reservations.
63// All methods run synchronously on the calling thread; one operation per evaluation at a time.
64class OptimizationEvaluation
65{
66public:
67 OptimizationEvaluation(std::shared_ptr<OptimizationProblem> owner, std::vector<double> x,
68 const design::ModeReferences& references = {});
69 [[nodiscard]] const design::DesignEvaluation& evaluation() const noexcept { return m_evaluation; }
70 [[nodiscard]] const std::vector<double>& x() const noexcept { return m_x; }
71 [[nodiscard]] const OptimizationProblem& owner() const noexcept { return *m_owner; }
72 [[nodiscard]] std::shared_ptr<OptimizationEvaluation> evaluateAt(
73 std::vector<double> x, const design::ModeReferences& references = {}) const
74 {
75 return m_owner->evaluate(std::move(x), references);
76 }
77 [[nodiscard]] design::DesignGradients gradients(const design::GradientOptions& options = {});
78 [[nodiscard]] design::GradientStreamReport streamGradients(design::GradientSink& sink, std::size_t block);
79 [[nodiscard]] design::ProductReport jvp(std::span<const double> directions, std::size_t count, std::size_t block,
80 design::ProductSink& sink, const design::ProductSelection& selection = {});
81 [[nodiscard]] design::ProductReport vjp(const design::ProductWeights& weights, std::size_t block,
82 design::ProductSink& sink);
83 [[nodiscard]] design::ProductReport hessianVector(const design::ProductWeights& weights,
84 std::span<const double> directions, std::size_t count,
85 std::vector<double>& values);
86 // Dense reduced Hessian of a weighted sum, column by column using the same second-order engine as H*v.
87 [[nodiscard]] std::vector<double> hessian(const design::ProductWeights& weights);
88 [[nodiscard]] design::DesignBlocks blocks(const design::ProductWeights* weights = nullptr);
89 void clearLinearisation() noexcept { m_linearisation.clear(); }
90 void requireOutput(std::size_t rows, std::size_t columns) const;
91
92private:
93 [[nodiscard]] design::ProductContext context(const design::CallableRegistry& callables) const;
94 std::shared_ptr<OptimizationProblem> m_owner;
95 std::vector<double> m_x;
96 base::MemoryBudget m_budget;
97 design::DesignEvaluation m_evaluation;
98 design::ProductLinearisation m_linearisation;
99};
100
101} // namespace oos::api
Capabilities.hpp¶
1#pragma once
2
3#include "oos/input/snapshot/ModelSnapshot.hpp"
4
5#include <cstdint>
6#include <string>
7#include <vector>
8
9namespace oos::api
10{
11struct AnalysisCapability
12{
13 std::string analysis;
14 std::int32_t solution = 0;
15 bool sizingFirstOrder = true;
16 bool shapeFirstOrder = true;
17 bool secondOrder = false;
18 std::vector<std::string> restrictions;
19};
20
21// Real columns bindable by a native design relation. List fields require a zero-based fieldItem, checked against
22// the selected target row when the problem is prepared. This is a candidate catalogue, not a promise that changing
23// every field has a physical effect in every element formulation.
24struct DesignFieldCapability
25{
26 std::string targetKind;
27 std::string targetCard;
28 std::string field;
29 std::string type;
30 bool requiresItem = false;
31};
32
33struct OptimizationCapabilities
34{
35 std::int32_t version = 1;
36 std::vector<AnalysisCapability> analyses;
37 std::vector<std::string> responses;
38 std::vector<DesignFieldCapability> fields;
39};
40
41[[nodiscard]] OptimizationCapabilities optimizationCapabilities(const input::ModelSnapshot* snapshot = nullptr);
42} // namespace oos::api
Threading.hpp¶
1#pragma once
2
3#include "oos/base/threading/ThreadPool.hpp"
4
5#include <cstddef>
6#include <memory>
7
8namespace oos::api
9{
10struct ThreadingInfo
11{
12 bool enabled = false;
13 std::size_t maximumThreads = 1;
14 std::size_t activeWorkers = 0;
15};
16
17[[nodiscard]] ThreadingInfo threadingInfo();
18// One thread means no pool. Owners requesting the same size share a pool; the module's preloaded worker
19// capacity is checked before any worker is created. Retained analyses must retain this owner too.
20[[nodiscard]] std::shared_ptr<base::ThreadPool> acquireThreadPool(std::size_t threads);
21} // namespace oos::api