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.
Operation |
JavaScript / WebAssembly |
Python / native C++ |
|---|---|---|
Read a deck |
|
|
Count node rows |
|
|
Save a model |
|
|
JavaScript and TypeScript¶
Load the built package from build/wasm/dist/index.js. The declarations below describe its public interface.
1// Types of the oor-reader package (see index.js).
2
3export interface Diagnostic {
4 severity: "info" | "warning" | "error";
5 code: string;
6 message: string;
7 location: string;
8}
9
10export interface DeckWriteOptions {
11 splitIncludes?: boolean;
12 headerComment?: string;
13}
14
15export interface ArchiveWriteOptions {
16 compressionLevel?: number; shuffle?: boolean; strict?: boolean;
17 title?: string; subtitle?: string; label?: string;
18}
19
20export type CardScalar = number | string | null | { real: number };
21// Group values are arrays of objects; a one-field group also accepts an array of scalars.
22export interface CardData {
23 [name: string]: CardScalar | CardData | readonly (CardScalar | CardData)[];
24}
25export type CardContent = { comment?: string; form?: string } & (
26 { fields: ArrayLike<CardScalar>; values?: never } | { values: CardData; fields?: never }
27);
28export type CardDefinition = CardContent & { type: string };
29// A key identifies a card within its model/part, independently of its editable ID or set ID.
30export interface CardRef { readonly type: string; readonly key: number; readonly id?: number; }
31export interface AddedCard extends CardRef { readonly id: number; }
32export interface CardBatchResult { type: string; ids: Int32Array; keys: Uint32Array; }
33export type CardBatchColumn = CardScalar | ArrayLike<CardScalar>;
34
35export interface LayoutField { name: string; kind: string; slot?: number; offset?: number; default?: string; span?: number; }
36export interface LayoutGroup {
37 name: string; fields: LayoutField[]; firstSlot?: number; period?: number; fixedCount?: number; countField?: string;
38 list?: LayoutGroup;
39}
40export interface CardSchema {
41 fields: LayoutField[]; group?: LayoutGroup; nextGroups?: LayoutGroup[];
42 sections?: { name: string; kinds: { key: string; name: string; fields?: LayoutField[]; list?: LayoutGroup }[] };
43 forms?: (CardSchema & { name: string; when?: { field?: string; values?: string[]; kinds?: string[]; blankSlot?: number; filledSlot?: number } })[];
44 note?: string;
45}
46
47export type ControlValue = number | string | null | ArrayLike<number | string>;
48export interface CaseCommandDescription {
49 name: string; shape: string; variants: string[]; keywords: string[]; sectionKind: string; blockKind: string; inBlock: boolean;
50}
51export interface ControlRecord {
52 name: string;
53 // Use fields for arbitrary catalogue records (sets, parameters, section or output-block headers).
54 fields?: ArrayLike<ControlValue>;
55 value?: ControlValue;
56 options?: string[];
57 variant?: string;
58 comment?: string;
59}
60export interface CaseEntrySnapshot {
61 key: number; name: string; kind: "command" | "output" | "set" | "parameter" | "metadata";
62 value: number | string | number[] | Float64Array | null;
63 variant: string; options: string[]; number: number; members: string[]; comment: string; loadSequence: number | null;
64}
65export type CaseSectionKind = "global" | "subcase" | "subcaseCombination" | "symmetrySubcase" | "symmetryCombination" |
66 "repeatSubcase" | "step" | "substep" | "auxiliaryCase";
67export interface CaseSectionSnapshot {
68 key: number; kind: CaseSectionKind; id: number; entries: CaseEntrySnapshot[]; children: CaseSectionSnapshot[];
69}
70export interface CaseSection {
71 readonly key: number;
72 snapshot(): CaseSectionSnapshot;
73 set(name: string, value?: ControlValue, options?: { options?: string[]; variant?: string; comment?: string }): number;
74 setCommands(commands: readonly ControlRecord[]): Uint32Array;
75 setSet(id: number, members: ArrayLike<number | string>, comment?: string): number;
76 setParameter(name: string, value: ControlValue, comment?: string): number;
77 effective(name: string, variant?: string): CaseEntrySnapshot | null;
78 effectiveOutputs(name: string): CaseEntrySnapshot[];
79 removeEntry(key: number): boolean;
80 remove(name: string, variant?: string): boolean;
81 addStep(id: number, options?: { commands?: readonly ControlRecord[] }): CaseSection;
82 addSubstep(id: number, options?: { commands?: readonly ControlRecord[] }): CaseSection;
83 renumber(id: number): void;
84 removeSection(): boolean;
85}
86export interface CaseControl {
87 readonly global: CaseSection;
88 sections(): CaseSectionSnapshot[];
89 section(key: number): CaseSection;
90 addSubcase(id: number, options?: { kind?: Exclude<CaseSectionKind, "global" | "step" | "substep" | "auxiliaryCase">;
91 commands?: readonly ControlRecord[] }): CaseSection;
92 addAuxiliaryCase(): CaseSection;
93 // Replaces the complete section from structured records. All previous case handles become stale.
94 replace(records: readonly ControlRecord[]): void;
95 records(): ControlRecord[];
96}
97export interface PartDefinition { kind?: string; id?: number; massId?: number; appends?: boolean; }
98
99// A named value of a card: a number, a list (Float64Array), a text, a list of texts, or null when blank.
100export type CardValue = number | Float64Array | string | string[] | null;
101
102// A card read by ID. Each named value is also a property of its own (card.xyz), unless its name is one of the seven below.
103export interface Card {
104 type: string; // "Node"
105 id: number;
106 key: number;
107 values: Record<string, CardValue>; // the stored fields of the card type, and the computed values asked for
108 fields: string[]; // the fields as written, field 1 first ("" for a blank field)
109 text: string; // the card as one model record
110 comment: string; // the comment lines above the card
111 [name: string]: unknown;
112}
113
114// The cards of a category by ID: deck.nodes[11] (undefined when there is none).
115export interface CardsById {
116 [id: number]: Card | undefined;
117 get(id: number): Card | undefined;
118 has(id: number): boolean;
119 ids(): number[];
120}
121
122export interface Deck {
123 /** Application documents are copied with the model and preserved in .ooh5 archives. */
124 documentNames(): string[];
125 document(name: string): string | null;
126 setDocument(name: string, text: string): void;
127 removeDocument(name: string): boolean;
128 copy(): Deck; // independent copy; column buffers are shared until edited
129 // Empty-model construction uses OorReader.createModel(). Each successful insertion returns stable card keys.
130 addCard(card: CardDefinition): AddedCard;
131 addCards(cards: readonly CardDefinition[]): AddedCard[];
132 // Fixed layouts only; scalar columns broadcast. Numeric typed arrays cross the boundary once per column.
133 addCardBatch(type: string, columns: Record<string, CardBatchColumn>, options?: { count?: number }): CardBatchResult;
134 cardByKey(ref: CardRef, computed?: string[]): Card | undefined;
135 updateCard(ref: CardRef, card: CardContent): void;
136 setCardValues(ref: CardRef, values: Record<string, CardScalar>): void;
137 removeCardRef(ref: CardRef): boolean;
138 setCardComment(ref: CardRef, comment: string): void;
139 addInclude(path: string, cards: readonly CardDefinition[]): AddedCard[];
140 addPart(part: PartDefinition): Deck;
141 part(part: PartDefinition): Deck | null;
142 parts(): Required<PartDefinition>[];
143 readonly caseControl: CaseControl;
144 setSolution(solution: string | number): void;
145 setExecutive(records: readonly ControlRecord[]): void;
146 executiveRecords(): ControlRecord[];
147 caseRecords(): ControlRecord[];
148 applyDefaults(): void;
149 checkReferences(): Diagnostic[];
150 compact(): void;
151 // A native archive containing the model alone.
152 writeArchive(path: string, options?: ArchiveWriteOptions): WriteReport;
153 // Writes an O_o model file; returns any content that could not be carried, one description per item.
154 writeModel(path: string, options?: DeckWriteOptions): string[];
155 // The model file text (one file).
156 toModelText(options?: DeckWriteOptions): string;
157 cardCounts(): Record<string, number>;
158 cardCount(): number;
159 diagnostics(): Diagnostic[];
160
161 // ---- cards by ID ("source": "nodes", "elements", "properties", "materials", "coordinates" or a card type)
162 readonly nodes: CardsById; // each node also has xyzGlobal, its position in the basic system
163 readonly elements: CardsById;
164 readonly properties: CardsById;
165 readonly materials: CardsById;
166 readonly coords: CardsById;
167 cardById(source: string, id: number, computed?: string[]): Card | undefined;
168 cardIds(source: string): Int32Array;
169 cardFields(source: string, id: number): string[];
170
171 // ---- editing: an edited card keeps its place, its comment and its link to attached results; a refused edit (a
172 // field the card cannot hold, an ID already taken) changes nothing and throws an Error that says why
173 setCardField(source: string, id: number, field: number, value: string): void; // field 1 is the first after the name
174 setCardFields(source: string, id: number, fields: string[]): void;
175 cardFieldNames(source: string, id: number): { field: number; name: string }[]; // [{ field: 3, name: "thickness" }, ...]
176 setCardValue(source: string, id: number, name: string, value: string): void; // a field by its exact neutral name
177 replaceCard(source: string, id: number, text: string): void; // one model record, same card type
178 addCards(text: string): AddedCard[]; // one card or several, all or none
179 removeCard(source: string, id: number): boolean;
180
181 delete(): void; // frees the C++ object
182}
183
184export interface TableDescription {
185 index: number;
186 kind: string;
187 variant: string;
188 elementType: string;
189 layout: string;
190 subcase: number;
191 analysis: string;
192 stepKind: string;
193 steps: Float64Array;
194 eigenvalues: Float64Array;
195 cycles: Float64Array;
196 rowCount: number;
197 components: string[];
198 valueType: "float32" | "float64" | "complex64" | "complex128";
199 tableName: string;
200 title: string;
201 subtitle: string;
202 label: string;
203}
204
205export interface TableSelection {
206 stepIndices?: number[];
207 components?: string[];
208 ids?: number[];
209 elementIds?: number[];
210}
211
212export interface TableValues {
213 shape: number[]; // [steps, rows, components] (+ [2] for complex values)
214 valueType: string;
215 components: string[];
216 steps: Float64Array;
217 ids: Int32Array;
218 nodeIds: Int32Array;
219 layers: Int32Array;
220 elementIds: Int32Array;
221 texts: Record<string, string[]>;
222 values: Float32Array | Float64Array;
223}
224
225export interface WriteReport {
226 path: string;
227 format: string;
228 finished: boolean;
229 bytes: number;
230 written: { kind: string; container: string; subcase: number; location: string; steps: number; rows: number }[];
231 skipped: { kind: string; container: string; subcase: number; reason: string; message: string }[];
232}
233
234// A table made by a program, for createResults. The values are (steps, rows, components) in C order; a complex table
235// has the real and imaginary parts of each value one after the other. A Float32Array keeps single precision.
236export interface MemoryTable {
237 kind: string; // "displacements", "singlePointConstrForces", "stress", "forces", "eigenvalues", ...
238 elementType?: string; // the element type of an element table: "ShellQuad4", "Bar2", ...
239 variant?: string; // "" (default), "psd", "rms", ...
240 subcase?: number; // 1 by default
241 analysisCode?: number; // taken from the step kind when left out
242 stepKind?: "none" | "time" | "frequency" | "mode" | "loadFactor";
243 steps?: number[]; // one value a step; left out: one step with no value (a static table)
244 eigenvalues?: number[];
245 cycles?: number[];
246 ids: ArrayLike<number>; // the grid point or element of each row
247 pointTypes?: ArrayLike<number>;
248 nodeIds?: ArrayLike<number>;
249 elementIds?: ArrayLike<number>;
250 layers?: ArrayLike<number>;
251 positions?: ArrayLike<number>;
252 texts?: Record<string, string[]>;
253 components?: string[]; // left out: every component of the kind, in the catalogue's order
254 values: Float32Array | Float64Array | number[];
255 complex?: boolean;
256 title?: string;
257 subtitle?: string;
258 label?: string;
259 tableName?: string;
260 units?: string;
261}
262
263export interface Results {
264 named(): NamedResultMeta[];
265 readNamed(index: number): NamedResultMeta & { arrays: Record<string, { type: string; shape: number[];
266 values: Int32Array | BigInt64Array | Float32Array | Float64Array }>; texts: Record<string, string[]> };
267 addNamed(input: NamedResultInput): void;
268 format(): "archive" | "memory";
269 metadata(): {
270 format: string; path: string; fileSize: number; producer: string; createdAt: string;
271 title: string; subtitle: string; label: string; tableCount: number; namedCount: number; complete: boolean;
272 };
273 diagnostics(): Diagnostic[];
274 tables(): TableDescription[];
275 read(index: number, selection?: TableSelection): TableValues;
276 attach(deck: Deck, strict: boolean): void;
277 hasModel(): boolean;
278 // Loads and attaches the embedded model on demand; null when no model is available.
279 model(): Deck | null;
280 // Includes the attached model, or preserves the embedded model when rewriting an archive.
281 writeArchive(path: string, options?: ArchiveWriteOptions): WriteReport;
282 // An Excel workbook (.xlsx) of the tables, for people: an index sheet, one sheet per table.
283 writeXlsx(path: string, options?: {
284 title?: string; subtitle?: string; label?: string; compressionLevel?: number;
285 }): WriteReport;
286 delete(): void;
287}
288
289export interface NamedResultMeta {
290 kind: string; name: string; subcase: number; analysisCode: number; designCycle: number;
291 attributes: Record<string, string>;
292}
293export interface NamedResultInput {
294 kind: string; name?: string; subcase?: number; analysisCode?: number; designCycle?: number;
295 attributes?: Record<string, string>;
296 arrays: Record<string, { type?: "int32" | "float32" | "float64"; shape: number[]; values: ArrayLike<number> }>;
297 texts?: Record<string, string[]>;
298}
299
300export interface QueryColumn {
301 name: string;
302 kind: "number" | "text" | "numberList" | "textList";
303 integer: boolean;
304 values: Float64Array | string[];
305 offsets?: Float64Array; // lists: row i holds values[offsets[i] .. offsets[i + 1])
306 valid?: Uint8Array; // when the column has nulls: 1 a value, 0 a null
307}
308
309export interface QueryTable {
310 columnNames(): string[];
311 rowCount(): number;
312 column(name: string): QueryColumn;
313 columns(): Record<string, QueryColumn>;
314 toCsv(): string;
315 // The table as a table package (docs/table-package.md): bytes that keep its exact Arrow layout, for another module.
316 toPackage(): Uint8Array;
317 delete(): void;
318}
319
320export interface QueryDescription {
321 name: string;
322 family: string;
323 description: string;
324 resultQuery: boolean;
325 needsModel: boolean;
326 parameters: { name: string; default: string; description: string }[];
327}
328
329export declare class OorReader {
330 version(): string;
331 writeFile(path: string, content: string | Uint8Array): void;
332 readFile(path: string, options?: { encoding?: "utf8" | "binary" }): Uint8Array | string;
333 removeFile(path: string): void;
334 readModel(path: string, options?: { strict?: boolean }): Deck;
335 createModel(): Deck;
336 cardTypes(): string[];
337 solutionCatalogue(): { name: string; number: number }[];
338 caseCommandCatalogue(): CaseCommandDescription[];
339 // A detached schema snapshot from the compiled catalogue. Field names are exact and case-sensitive.
340 cardSchema(type: string): CardSchema;
341 openResults(path: string): Results;
342 createResults(tables: MemoryTable[], label?: string): Results;
343 namedResultCatalogue(): { kind: string; description: string;
344 arrays: { name: string; type: string; shape: string; text: boolean; optional: boolean }[] }[];
345 runQuery(name: string, inputs?: { deck?: Deck | null; results?: Results | null; args?: Record<string, unknown> }): QueryTable;
346 optimizationTables(deck: Deck): Record<string, Uint8Array>;
347 designVariables(deck: Deck): {
348 variables: { id: number; label: string; initialValue: number; lower: number; upper: number;
349 moveLimit: number; dependent: boolean }[];
350 problems: string[]; notApplied: { card: string; id: number; reason: string }[];
351 };
352 designCapabilities(deck: Deck): { version: number; nativeCards: string[]; problems: string[];
353 notApplied: { card: string; id: number; reason: string }[]; modelDocuments: boolean; generalCardEditing: boolean };
354 applyDesignPoint(deck: Deck, ids: number[] | Int32Array, values: number[] | Float64Array,
355 options?: { limits?: "error" | "clip" | "ignore"; setInitialValues?: boolean }): {
356 variables: Float64Array; changedFields: number; movedGrids: number;
357 fields: { relation: number; before: number; requested: number; after: number; limit: number; changed: boolean }[];
358 };
359
360 queryCatalogue(): QueryDescription[];
361 writeQueryTables(path: string, tables: { name: string; table: QueryTable }[], compressionLevel?: number): void;
362 cardTable(deck: Deck, source: string, columns?: string[] | null): QueryTable;
363 cardTableColumns(source: string): { stored: string[]; computed: string[] };
364 cardTypesOf(deck: Deck, category: "elements" | "properties" | "materials" | "methods" | "loads" | "constraints" |
365 "coordinates" | "nodes" | "points"): string[];
366 displacementRotations(deck: Deck): Float64Array;
367 modelVersions(deck: Deck): { structure: number; content: number; control: number };
368}
369
370export declare function loadOorReader(options?: Record<string, unknown>): Promise<OorReader>;
371// True when the runtime supports 64-bit WebAssembly (Memory64), which the module needs.
372export declare function supportsMemory64(): boolean;
Python¶
Import read_model(path, *, strict=True) from oo_reader. It returns a Deck.
Inspect
deck.card_counts,deck.diagnosticsanddeck.card_types(group).Select columns with
deck.card_table(name, columns)or rundeck.query(name, **arguments). Both return aTablewithcolumns, a row count vialen(table)and an Arrow capsule.Edit a copy with
deck.copy()andset_card_value(card, id, field, value). Apply design variables withdeck.with_design_point(ids, values)to get a new deck.Save to text with
deck.write_model(path)or to HDF5 withdeck.write_archive(path).
See Native Python package for paired examples and installation details. The public Python module and native bindings define the available calls.
C++ entry points¶
Deck.hpp¶
1#pragma once
2
3#include "oor/model/core/Model.hpp"
4#include "oor/results/archive/ArchiveWriter.hpp"
5
6#include <cstddef>
7#include <memory>
8#include <string>
9#include <utility>
10#include <vector>
11
12// The simple entry points of the library: what the WebAssembly module (wasm/) offers to JavaScript, in plain C++ so
13// that it is tested natively. Each class wraps the library objects behind a few methods with plain types.
14namespace oor::api
15{
16
17struct DeckReadSettings
18{
19 // Strict: the first error raises DeckError. Otherwise the problems are kept in `diagnostics()`.
20 bool strict = false;
21};
22
23struct DeckWriteSettings
24{
25 bool splitIncludes = false; // write each included file to its own file again
26 std::string headerComment; // comment lines at the top of the model file
27};
28
29// A problem found while reading, in plain text.
30struct DiagnosticText
31{
32 std::string severity; // "info", "warning" or "error"
33 std::string code;
34 std::string message;
35 std::string location; // "file:line (CARD, field)"; empty when unknown
36};
37
38// A model: its control sections and cards, read from .oos text or a native .ooh5 archive.
39class Deck
40{
41public:
42 // An empty in-memory model; no virtual file or text parsing is needed.
43 [[nodiscard]] static std::shared_ptr<Deck> createModel();
44 // An independent model sharing column buffers until the first edit, preserving keys and source structure.
45 [[nodiscard]] std::shared_ptr<Deck> copy() const;
46 // Part handles share ownership of the root, so they remain valid after its JS handle is deleted.
47 [[nodiscard]] std::shared_ptr<Deck> addPart(const model::PartInfo& info) const;
48 [[nodiscard]] std::shared_ptr<Deck> part(const std::string& kind, std::int64_t id, std::int64_t massId = 0) const;
49 [[nodiscard]] std::vector<model::PartInfo> parts() const;
50 void applyDefaults() const;
51 [[nodiscard]] std::vector<DiagnosticText> checkReferences() const;
52 [[nodiscard]] std::vector<std::string> documentNames() const;
53 [[nodiscard]] std::optional<std::string> document(const std::string& name) const;
54 void setDocument(std::string name, std::string text) const;
55 bool removeDocument(const std::string& name) const;
56 // Detects a native archive by content; otherwise reads model records and their Include files.
57 // Throws IoError when the file cannot be read, DeckError in strict mode.
58 [[nodiscard]] static std::shared_ptr<Deck> readModel(const std::string& path,
59 const DeckReadSettings& settings = {});
60 // Writes a model file. Returns any content that could not be carried, one description per item.
61 std::vector<std::string> writeModel(const std::string& path, const DeckWriteSettings& settings = {}) const;
62 // The model file text (one file, the Include structure flattened).
63 [[nodiscard]] std::string toModelText(const DeckWriteSettings& settings = {}) const;
64 // Writes an archive containing this model alone (no result tables).
65 results::ResultWriteReport writeArchive(const std::string& path,
66 const results::ArchiveWriteOptions& options = {}) const;
67
68 // The number of cards of each type the deck holds, by card name, in alphabetical order.
69 [[nodiscard]] std::vector<std::pair<std::string, std::size_t>> cardCounts() const;
70 [[nodiscard]] std::size_t cardCount() const;
71 [[nodiscard]] std::vector<DiagnosticText> diagnostics() const;
72 [[nodiscard]] const std::shared_ptr<model::Model>& model() const noexcept { return m_model; }
73
74private:
75 friend class Results;
76 explicit Deck(std::shared_ptr<model::Model> model) : m_model(std::move(model)) {}
77
78 std::shared_ptr<model::Model> m_model;
79};
80
81// The text of a diagnostic of the library.
82[[nodiscard]] DiagnosticText diagnosticText(const base::Diagnostic& diagnostic);
83
84} // namespace oor::api
CardTables.hpp¶
1#pragma once
2
3#include "oor/api/Deck.hpp"
4#include "oor/query/table/QueryTable.hpp"
5
6#include <cstdint>
7#include <memory>
8#include <string>
9#include <vector>
10
11// The card tables of a model: the columns of the cards themselves (every field of a ShellQuad4, ShellProp, IsoMat, ...)
12// and the computed columns the cards have (the rows of their grid points and property: nodesRows, propIdRow, propType;
13// the positions of the grid points: xyzGlobal), with the exact Arrow layout of the library. This is what a program that
14// computes on the model (the O_o_Solver module) reads, where the named queries give views made for people.
15namespace oor::api
16{
17
18// The columns a card table can give: the stored ones (the fields of the card, given by default) and the computed ones
19// (given when asked for).
20struct CardTableColumns
21{
22 std::vector<std::string> stored;
23 std::vector<std::string> computed;
24};
25
26// What a card table is made of. `source` names the cards: a card type ("ShellQuad4", "ShellProp",
27// "LanczosEigenMethod"), "nodes" for the grid points or "points" for the other points (ScalarPoint, ExtraPoint, ...).
28// Throws QueryError for an unknown name.
29[[nodiscard]] CardTableColumns cardTableColumns(const std::string& source);
30
31// The table of the live cards of `source`, sorted by ID: the columns asked for, or every stored column when `columns`
32// is empty. The rows are those the row-index columns of other card tables point at (nodesRows indexes the rows of the
33// "nodes" table). Throws QueryError for an unknown source or column.
34[[nodiscard]] std::shared_ptr<const query::QueryTable> cardTable(const Deck& deck, const std::string& source,
35 const std::vector<std::string>& columns);
36
37// The card types of the deck that have live cards, by category: "elements", "properties", "materials", "methods",
38// "loads", "points", "nodes", "coordinates", "constraints" (the other categories are not listed). Sorted by name.
39[[nodiscard]] std::vector<std::string> cardTypesOf(const Deck& deck, const std::string& category);
40
41// For every grid point, in the rows of the "nodes" table, the rotation from its displacement system CD to the basic
42// system: 9 values per grid point, a 3 x 3 matrix row-major whose columns are the directions 1, 2, 3 of CD in the basic
43// system at the grid point (the identity for CD = 0).
44[[nodiscard]] std::vector<double> displacementRotations(const Deck& deck);
45
46// Independent revision counters: connectivity and identifiers, card content, and analysis controls. A client
47// compares the relevant counter before reusing derived geometry, card tables or case selections.
48struct ModelVersions
49{
50 std::uint64_t structure = 0;
51 std::uint64_t content = 0;
52 std::uint64_t control = 0;
53};
54[[nodiscard]] ModelVersions modelVersions(const Deck& deck);
55
56} // namespace oor::api
CardEdits.hpp¶
1#pragma once
2
3#include "oor/api/Deck.hpp"
4#include "oor/base/ids/EntityId.hpp"
5#include "oor/model/format/FieldValue.hpp"
6
7#include <functional>
8#include <limits>
9#include <optional>
10#include <span>
11#include <string>
12#include <utility>
13#include <vector>
14
15// The cards of a deck one by one: found by ID, read as named values, edited, added and removed. Works the same way for
16// every card type, through what every card type has: its stored columns (the names of its fields, registered in
17// src/query/providers/columns/) and its format (how it is read from and written to fields).
18//
19// Where a card is looked for (`source`): a category of cards that share an ID space ("nodes", "elements", "properties",
20// "materials", "coordinates"), or a card type ("ShellQuad4", "ShellProp", "SinglePointConstrList"). A card type whose
21// cards share an ID (the set cards: several SinglePointConstrList of SID 7) gives the first card of that ID, in the
22// order of the deck.
23namespace oor::api
24{
25
26// The value of one named field of a card.
27struct FieldValue
28{
29 enum class Kind
30 {
31 Missing, // the card leaves it blank and it has no default (a null)
32 Number,
33 Numbers, // a list or a vector (the grid points of an element, the position of a grid point)
34 Text,
35 Texts
36 };
37 Kind kind = Kind::Missing;
38 bool integer = false; // the numbers are whole
39 double number = std::numeric_limits<double>::quiet_NaN();
40 std::vector<double> numbers;
41 std::string text;
42 std::vector<std::string> texts;
43};
44
45// A card, read.
46struct CardView
47{
48 std::string type; // "Node"
49 base::EntityId id = 0;
50 std::uint32_t key = 0;
51 // The named values: every stored field of the card type, then the computed columns asked for ("xyzGlobal").
52 std::vector<std::pair<std::string, FieldValue>> values;
53 // The fields of the card as it is written, field 1 first (the card name is not a field). A blank field is "".
54 std::vector<std::string> fields;
55 std::string text; // the card as one model record
56 std::string comment; // the comment lines above the card in the deck, joined with '\n'
57};
58
59// The card of `source` that has `id`; nothing when there is none. `computed` adds computed columns of the card type
60// ("xyzGlobal" for a grid point, "area" or "mass" for an element, ...). Throws QueryError for an unknown source or
61// column.
62[[nodiscard]] std::optional<CardView> findCard(const Deck& deck, const std::string& source, base::EntityId id,
63 const std::vector<std::string>& computed = {});
64
65// The IDs of the live cards of `source`, increasing, each once.
66[[nodiscard]] std::vector<base::EntityId> cardIds(const Deck& deck, const std::string& source);
67
68// The fields of a card as it is written, field 1 first (as CardView::fields). Throws UsageError when there is no such
69// card.
70[[nodiscard]] std::vector<std::string> cardFields(const Deck& deck, const std::string& source, base::EntityId id);
71
72// Editing. An edited card keeps its place in the deck, its comment and its link to attached results (its card key);
73// its new fields are read and checked as the model reader checks them. Each function changes nothing when it throws:
74// UsageError for fields the card cannot hold (with the reasons), DuplicateIdError for an ID another card has.
75
76// Sets field `field` (from 1, the numbering of the card's fields: field 1 is the first after the name) to the text
77// `value` ("" for blank), and reads the card again.
78void setCardField(const Deck& deck, const std::string& source, base::EntityId id, int field, const std::string& value);
79// The compact fields of the model record, in order, each name once: {3, "thickness"} of a ShellProp,
80// {3, "position1"} of a Node. Section markers and list counts have no field name.
81[[nodiscard]] std::vector<std::pair<int, std::string>> cardFieldNames(const Deck& deck, const std::string& source,
82 base::EntityId id);
83// Sets the field named `name` (one of cardFieldNames, exactly) to the text `value`. Throws
84// UsageError, listing the named fields, when the card has no field of that name.
85void setCardValue(const Deck& deck, const std::string& source, base::EntityId id, const std::string& name,
86 const std::string& value);
87// Gives the card all its fields at once (as CardView::fields).
88void setCardFields(const Deck& deck, const std::string& source, base::EntityId id,
89 const std::vector<std::string>& fields);
90// Replaces the card by the model record written in `text`, of the same type.
91void replaceCard(const Deck& deck, const std::string& source, base::EntityId id, const std::string& text);
92
93// A card added: its type and ID.
94struct AddedCard
95{
96 std::string type;
97 base::EntityId id = 0;
98 std::uint32_t key = 0;
99};
100
101// Compact field values, as in the layout catalogue. Typed fixed-layout input reaches the card reader without
102// decimal formatting. Complex layouts use the same layout mapping and validation as file input.
103struct CardInput
104{
105 std::string type;
106 std::vector<model::FieldValue> fields;
107 std::optional<std::string> comment; // absent preserves the existing comment on replacement
108 std::string form{}; // optional selected form, checked against the record discriminant
109};
110
111// Singular construction refuses records that expand to multiple entities, without changing live data.
112AddedCard insertCard(const Deck& deck, const CardInput& card);
113std::vector<AddedCard> insertCards(const Deck& deck, std::span<const CardInput> cards);
114// A homogeneous batch, visited one row at a time. The caller keeps its column buffers; records are not accumulated.
115std::vector<AddedCard> insertCardBatch(const Deck& deck, const std::string& type, std::size_t count,
116 const std::function<CardInput(std::size_t)>& row);
117[[nodiscard]] std::optional<CardView> findCardByKey(const Deck& deck, const std::string& type, std::uint32_t key,
118 const std::vector<std::string>& computed = {});
119void updateCardByKey(const Deck& deck, const std::string& type, std::uint32_t key, const CardInput& card);
120bool removeCardByKey(const Deck& deck, const std::string& type, std::uint32_t key);
121void setCardValueByKey(const Deck& deck, const std::string& type, std::uint32_t key, const std::string& name,
122 const std::string& value);
123void setCardValuesByKey(const Deck& deck, const std::string& type, std::uint32_t key,
124 std::span<const std::pair<std::string, model::FieldValue>> values);
125void setCardCommentByKey(const Deck& deck, const std::string& type, std::uint32_t key, const std::string& comment);
126// Appends a separate model source and its cards, retaining Include boundaries for split model output.
127std::vector<AddedCard> appendInclude(const Deck& deck, const std::string& path, std::span<const CardInput> cards);
128// Adds the model records written in `text` (one card per line), at the end of the model,
129// all or none. Throws UsageError for a card the library does not know or cannot read, DuplicateIdError for a taken ID.
130std::vector<AddedCard> addCards(const Deck& deck, const std::string& text);
131
132// Removes the card; false when there is none.
133bool removeCard(const Deck& deck, const std::string& source, base::EntityId id);
134
135} // namespace oor::api
ControlEdits.hpp¶
1#pragma once
2
3#include "oor/api/Deck.hpp"
4
5#include <span>
6
7namespace oor::api
8{
9
10// A catalogue command and its separate fields. No delimiter escaping or model-file sections cross this interface.
11struct ControlRecord
12{
13 std::string name;
14 std::vector<std::string> fields;
15 std::string comment;
16};
17
18// Replaces executive statements and external file assignments together, after validating every record.
19void setExecutive(const Deck& deck, std::span<const ControlRecord> records);
20[[nodiscard]] std::vector<ControlRecord> executiveRecords(const Deck& deck);
21void setSolution(const Deck& deck, const std::string& solution);
22// Complete structured Case Control, including section and output-block headers. Replacing invalidates old keys.
23void setCaseControl(const Deck& deck, std::span<const ControlRecord> records);
24[[nodiscard]] std::vector<ControlRecord> caseRecords(const Deck& deck);
25
26[[nodiscard]] const model::Subcase& caseSection(const Deck& deck, std::uint32_t key);
27// parentKey is zero for a top-level section; step/substep keys are scoped to their parent. Global has its own key.
28std::uint32_t addCaseSection(const Deck& deck, const std::string& kind, std::int64_t id, std::uint32_t parentKey,
29 std::span<const ControlRecord> commands = {});
30void renumberCaseSection(const Deck& deck, std::uint32_t key, std::int64_t id);
31bool removeCaseSection(const Deck& deck, std::uint32_t key);
32// Upserts ordinary commands, output requests (name/options), sets (ID) and parameters (name), all or none.
33std::vector<std::uint32_t> setCaseCommands(const Deck& deck, std::uint32_t sectionKey,
34 std::span<const ControlRecord> commands);
35bool removeCaseEntry(const Deck& deck, std::uint32_t entryKey);
36
37} // namespace oor::api
Queries.hpp¶
1#pragma once
2
3#include "oor/api/Deck.hpp"
4#include "oor/api/Results.hpp"
5#include "oor/base/text/Json.hpp"
6#include "oor/base/threading/ThreadPool.hpp"
7#include "oor/query/QueryErrors.hpp"
8#include "oor/query/named/QueryInfo.hpp"
9#include "oor/query/named/QueryValue.hpp"
10#include "oor/query/table/QueryTable.hpp"
11
12#include <memory>
13#include <string>
14#include <vector>
15
16namespace oor::api
17{
18
19// A named query of the catalogue, as a caller sees it.
20struct QueryDescription
21{
22 std::string name;
23 std::string family; // "T1" ... (topology of the model), "R1" ... (results)
24 std::string description;
25 bool resultQuery = false; // reads results
26 bool needsModel = false; // cannot run on results alone
27 // The parameters, the query's own then the common ones (`columns`, `sort`, `limit`, ...).
28 std::vector<query::ParameterInfo> parameters;
29};
30
31// Every named query, in the order of the catalogue.
32[[nodiscard]] std::vector<QueryDescription> queryCatalogue();
33
34// The kind of value a parameter of a query takes; throws QueryError for an unknown query or parameter.
35[[nodiscard]] query::ParameterKind parameterKind(const std::string& queryName, const std::string& parameter);
36
37// Runs a named query on a deck and/or results (either may be null when the query does not need it). Throws QueryError
38// for an unknown query, parameter or column.
39[[nodiscard]] std::shared_ptr<const query::QueryTable> runQuery(const std::string& name,
40 const std::shared_ptr<Deck>& deck,
41 const std::shared_ptr<Results>& results,
42 const query::QueryArguments& arguments);
43
44// An embedding application can own worker lifetime and join its workers before unloading the library.
45[[nodiscard]] std::shared_ptr<const query::QueryTable> runQueryWithPool(
46 const std::string& name, const std::shared_ptr<Deck>& deck, const std::shared_ptr<Results>& results,
47 const query::QueryArguments& arguments, base::ThreadPool* pool);
48
49// The arguments of a query from a JSON object {"parameter": value, ...} (what the JavaScript side sends): each value is
50// converted to the kind its parameter takes (ParameterKind):
51// Bool true/false; Integer, Real a number; Text a text; IdList a number or an array of numbers (null: all);
52// IdListOrText, RealsOrText a text or numbers; TextList a text or an array of texts; Point, Reals an array of
53// numbers; Steps an array of step values, or {"start": 0, "stop": 10, "step": 2} for positions; Pairs an array of
54// [n1, n2]; Thresholds, Values an object {"name": number}; IdSets an object {"name": [IDs]} or an array of IdListSet1
55// IDs; Groups {"name": {"components": [IDs]}} or {"name": {"elements": [IDs]}}; Combinations {"name": {"1": 1.5}};
56// Cuts {"name": {"plane": [x, y, z, nx, ny, nz]}} or {"name": {"nodes": [IDs], "sideElements": [IDs]}}.
57// A parameter that takes another model (ParameterKind::Model) is not available from JSON. Throws UsageError for a value
58// of the wrong type, QueryError for an unknown query or parameter.
59[[nodiscard]] query::QueryArguments argumentsFromJson(const std::string& queryName, const std::string& json);
60
61// The table as CSV text.
62[[nodiscard]] std::string toCsv(const query::QueryTable& table);
63
64} // namespace oor::api
Results.hpp¶
1#pragma once
2
3#include "oor/api/Deck.hpp"
4#include "oor/query/results/ResultSets.hpp"
5#include "oor/results/archive/ArchiveWriter.hpp"
6#include "oor/results/core/MemoryResults.hpp"
7#include "oor/results/core/NamedResultBuilder.hpp"
8#include "oor/results/core/ResultFile.hpp"
9#include "oor/results/core/ResultTables.hpp"
10#include "oor/results/xlsx/XlsxWriter.hpp"
11
12#include <cstdint>
13#include <memory>
14#include <string>
15#include <vector>
16
17namespace oor::api
18{
19
20// What a result table is, without its values.
21struct TableDescription
22{
23 std::size_t index = 0; // the position of the table in `Results::tables()`: the handle to read it with
24 std::string kind; // "displacements", "stress", ...
25 std::string variant; // "" for the results of an analysis, "psd", "rms", ...
26 std::string elementType; // "ShellQuad4" for an element table, the variant of a grid point stress table; else empty
27 std::string layout; // "centre" or "corner" for the element types that have both; else empty
28 std::int32_t subcase = 0;
29 std::string analysis; // "static", "modes", "frequency", "transient", ...
30 std::string stepKind; // "none", "loadSet", "mode", "frequency", "time", "loadFactor"
31 std::vector<double> steps;
32 std::vector<double> eigenvalues;
33 std::vector<double> cycles;
34 std::size_t rowCount = 0;
35 std::vector<std::string> components;
36 std::string valueType; // "float32", "float64", "complex64", "complex128"
37 std::string tableName;
38 std::string title;
39 std::string subtitle;
40 std::string label;
41};
42
43// What to read of a table; an empty member keeps everything.
44struct TableSelection
45{
46 std::vector<std::int64_t> stepIndices; // positions of the steps, from 0
47 std::vector<std::string> components; // in the order wanted
48 std::vector<std::int32_t> ids; // grid points of a nodal table
49 std::vector<std::int32_t> elementIds; // elements of an element table
50};
51
52// The values of a table, read: shape (steps, rows, components), with a last dimension of 2 for complex values.
53struct TableValues
54{
55 std::vector<std::size_t> shape;
56 std::string valueType;
57 std::vector<std::string> components;
58 std::vector<double> steps;
59 std::vector<std::int32_t> ids;
60 std::vector<std::int32_t> nodeIds; // element tables: the grid point of the row, 0 at the centre
61 std::vector<std::int32_t> layers; // element tables: the fibre, ply or station of the row, from 1
62 std::vector<std::int32_t> elementIds; // grid point forces: the element of the row
63 // Text labels of the rows, by name ("elementName"), one text a row.
64 std::vector<std::pair<std::string, std::vector<std::string>>> texts;
65 // The values (it keeps them alive): read them with `values<float>()` or `values<double>()`.
66 std::shared_ptr<const results::ResultData> data;
67};
68
69// A result set: an HDF5 results archive opened, or tables made in memory by a program.
70class Results
71{
72public:
73 // Opens an archive by content. Model and result values are loaded only when requested.
74 [[nodiscard]] static std::shared_ptr<Results> open(const std::string& path);
75 // A result set of tables made in memory (a solver hands over its results): each input is checked against the result
76 // catalogue (makeMemoryTable). `label` names the set. Throws UsageError with every problem of an input.
77 [[nodiscard]] static std::shared_ptr<Results> fromTables(const std::string& label,
78 std::vector<results::MemoryTableInput> inputs);
79
80 [[nodiscard]] std::string format() const;
81 [[nodiscard]] const results::ResultFileMetadata& metadata() const;
82 [[nodiscard]] std::vector<DiagnosticText> diagnostics() const;
83
84 [[nodiscard]] std::vector<TableDescription> tables() const;
85 [[nodiscard]] std::vector<results::NamedResultMeta> named() const;
86 [[nodiscard]] std::shared_ptr<const results::NamedResultData> readNamed(std::size_t index) const;
87 // Validates and copies a complete named result before adding it. Existing results are unchanged on failure.
88 void addNamed(const std::string& kind, const results::NamedResultOrigin& origin,
89 const std::vector<results::NamedArrayInput>& arrays,
90 const std::vector<results::NamedTextInput>& texts);
91 // Reads a table (by its index in `tables()`). Throws UsageError for an index out of range, EmptySelectionError when
92 // the selection keeps nothing.
93 [[nodiscard]] TableValues read(std::size_t index, const TableSelection& selection = {}) const;
94 [[nodiscard]] bool hasModel() const;
95 // The attached or embedded model, or nullptr when absent. Loading also attaches it to the results for queries.
96 [[nodiscard]] std::shared_ptr<Deck> model();
97
98 // Links the results to the cards of a deck: what the queries that combine both need. Throws DeckError when the
99 // results name cards the deck does not have and `strict` is set.
100 void attach(const std::shared_ptr<Deck>& deck, bool strict = false);
101
102 results::ResultWriteReport writeArchive(const std::string& path,
103 const results::ArchiveWriteOptions& options = {}) const;
104 // An Excel workbook of the tables, for people (results/xlsx/XlsxWriter.hpp).
105 results::ResultWriteReport writeXlsx(const std::string& path, const results::XlsxWriteOptions& options = {}) const;
106
107 // The result set the query engine reads.
108 [[nodiscard]] query::ResultSet resultSet() const;
109
110private:
111 Results() = default;
112
113 std::shared_ptr<results::ResultFile> m_file;
114 std::shared_ptr<results::ResultTables> m_tables;
115 std::vector<std::shared_ptr<results::ResultTable>> m_list; // the tables in a stable order: the handles
116 std::shared_ptr<results::ResultAttachment> m_attachment;
117 std::shared_ptr<Deck> m_deck;
118 results::ResultFileMetadata m_metadata;
119};
120
121} // namespace oor::api
Design.hpp¶
1#pragma once
2
3#include "oor/api/Deck.hpp"
4#include "oor/model/design/DesignUpdate.hpp"
5
6namespace oor::api
7{
8// Card types supported by native design relations and applyDesignPoint. General card edits remain available for
9// every card in the construction catalogue; a consumer must distinguish editability from differentiability.
10[[nodiscard]] std::vector<std::string> designableCards();
11// Read on each operation: card edits cannot leave a cached design model behind.
12[[nodiscard]] model::DesignModel designModel(const Deck& deck);
13// IDs are explicit, so the solver's independent-variable order never gets confused with the reader's full order.
14// All validation happens before the atomic model update. Default: reject field limit violations and save XINIT.
15[[nodiscard]] model::DesignUpdate applyDesignPoint(Deck& deck, const std::vector<std::int32_t>& ids,
16 const std::vector<double>& values,
17 model::DesignLimitMode limits = model::DesignLimitMode::Error,
18 bool setInitialValues = true);
19} // namespace oor::api
Native archive interfaces¶
The The HDF5 model and results archive (format version 4) guide specifies archive version 4 and native model schema 1. These lower-level interfaces
write a model with optional result tables, stream result tables into an archive, and load native model data independently.
The Deck and Results facade above also exposes these operations to application code.
ArchiveWriter.hpp¶
1#pragma once
2
3#include "oor/model/core/Model.hpp"
4#include "oor/results/core/ResultTables.hpp"
5#include "oor/results/writers/ResultWriteReport.hpp"
6#include "oor/results/writers/ResultWriteSession.hpp"
7
8#include <filesystem>
9#include <memory>
10#include <string>
11
12namespace oor::results
13{
14
15// How an archive is written.
16struct ArchiveWriteOptions
17{
18 // The deflate level of the values and labels, 0 (no compression, contiguous datasets) to 9. 4 is a good balance:
19 // most of the gain of 9 at a fraction of its time.
20 int compressionLevel = 4;
21 // The shuffle filter before deflate: it groups the bytes of the numbers by rank, which compresses floating-point
22 // values much better.
23 bool shuffle = true;
24 // Raise (UsageError) instead of reporting when a table cannot be written.
25 bool strict = false;
26 // Written in the root attributes; the producer is "oor_reader <version>" when empty.
27 std::string producer;
28 std::string title;
29 std::string subtitle;
30 std::string label;
31 // Optional model, serialized as native typed columns. An unrepresentable control entry raises UsageError.
32 std::shared_ptr<const model::Model> model;
33};
34
35// Writes an archive by batches: `beginArchive`, then `push` tables and `pushNamed` named results as many times as
36// needed, then `finish`. Each push writes its tables at once to a temporary file next to the target and keeps nothing
37// of their values; `finish` writes the index and puts the file in place. `abort` (or the destruction of an unfinished
38// session) removes the temporary file, so a failure never leaves a half-written archive at the target.
39[[nodiscard]] std::unique_ptr<ResultWriteSession> beginArchive(const std::filesystem::path& target,
40 const ArchiveWriteOptions& options = {});
41
42// Writes every table and named result of `tables` to an archive in one call.
43ResultWriteReport writeArchive(const std::filesystem::path& target, const ResultTables& tables,
44 const ArchiveWriteOptions& options = {});
45
46} // namespace oor::results
ArchiveResultFile.hpp¶
1#pragma once
2
3#include "oor/model/core/Model.hpp"
4#include "oor/model/core/ModelReadOptions.hpp"
5#include "oor/results/core/NamedResult.hpp"
6#include "oor/results/core/ResultFile.hpp"
7#include "oor/results/core/ResultTable.hpp"
8#include "oor/results/core/ResultTables.hpp"
9
10#include <filesystem>
11#include <memory>
12#include <vector>
13
14namespace oor::results
15{
16
17// An HDF5 results archive (ArchiveFormat.hpp), opened. Opening reads the root attributes and the two index datasets;
18// the values of a table are read when the table is first asked for them, step by step: a table restricted to some
19// steps reads those steps only.
20class ArchiveResultFile final : public ResultFile, public std::enable_shared_from_this<ArchiveResultFile>
21{
22public:
23 // Throws IoError when the file cannot be read or is not an archive of a version this library reads.
24 [[nodiscard]] static std::shared_ptr<ArchiveResultFile> open(const std::filesystem::path& path);
25
26 // True when the file is an HDF5 file whose root says it is an archive (any version).
27 [[nodiscard]] static bool isArchive(const std::filesystem::path& path);
28
29 [[nodiscard]] std::string_view format() const noexcept override { return "archive"; }
30 [[nodiscard]] const ResultFileMetadata& metadata() const noexcept override { return m_metadata; }
31 [[nodiscard]] const std::vector<base::Diagnostic>& diagnostics() const noexcept override { return m_diagnostics; }
32 [[nodiscard]] ResultTables tables(const ResultFilter& filter) const override;
33
34 // The optional model is read only when requested. No Include record may access files outside the archive.
35 [[nodiscard]] bool hasModel() const noexcept { return m_hasModel; }
36 [[nodiscard]] std::shared_ptr<model::Model> readModel(const model::ModelReadOptions& options = {}) const;
37
38 // The format version written in the file.
39 [[nodiscard]] const std::string& formatVersion() const noexcept { return m_formatVersion; }
40
41private:
42 ArchiveResultFile() = default;
43 void readIndex();
44
45 ResultFileMetadata m_metadata;
46 std::vector<base::Diagnostic> m_diagnostics;
47 std::string m_formatVersion;
48 bool m_hasModel = false;
49 std::vector<std::shared_ptr<ResultTable>> m_tables;
50 std::vector<std::shared_ptr<NamedResult>> m_named;
51};
52
53} // namespace oor::results
ArchiveModel.hpp¶
1#pragma once
2
3#include "oor/model/core/Model.hpp"
4#include "oor/model/core/ModelReadOptions.hpp"
5
6#include <filesystem>
7#include <memory>
8
9namespace oor::results::archive
10{
11
12// Appends the native model to an archive's temporary file. Only the archive writer should call this function.
13void writeModel(const std::filesystem::path& path, const model::Model& model, int compressionLevel, bool shuffle);
14// Loads the model independently of result values; missing, invalid or unsupported model data raises IoError.
15[[nodiscard]] std::shared_ptr<model::Model> readModel(const std::filesystem::path& path,
16 const model::ModelReadOptions& options = {});
17
18} // namespace oor::results::archive