ABQflow package¶
Subpackages¶
- ABQflow.core package
- Submodules
- ABQflow.core.abaqus_automation module
- ABQflow.core.context module
- ABQflow.core.registry module
- ABQflow.core.runner module
- ABQflow.core.spec module
- ABQflow.core.status module
JobStatusJobStatus.CREATEDJobStatus.COMPLETEDJobStatus.PREPARINGJobStatus.PREPARATION_FAILEDJobStatus.PREPARATION_SUCCESSJobStatus.PREFLIGHT_FAILEDJobStatus.SIMULATINGJobStatus.SIMULATION_FAILEDJobStatus.SIMULATION_SUCCESSJobStatus.EXTRACTINGJobStatus.EXTRACTION_FAILEDJobStatus.EXTRACTION_SUCCESSJobStatus.MONOLITHIC_SCRIPT_FAILEDJobStatus.JSON_DECODE_ERRORJobStatus.SCRIPT_ERRORJobStatus.SUBROUTINE_COMPILE_FAILEDJobStatus.UNKNOWN_ERRORJobStatus.UNKNOWN
PhaseRecordJobStatusManagerJobStatusManager.error_messageJobStatusManager.current_statusJobStatusManager.phase_historyJobStatusManager.mark_compiling()JobStatusManager.mark_preparing()JobStatusManager.mark_preflight()JobStatusManager.mark_simulating()JobStatusManager.mark_extracting()JobStatusManager.record_compile()JobStatusManager.record_preparation()JobStatusManager.record_preflight()JobStatusManager.record_simulation()JobStatusManager.record_extraction()JobStatusManager.get_final_status()
- ABQflow.core.strategies module
- Module contents
- ABQflow.helpers package
Module contents¶
Key modules¶
AbaqusCalculation
BatchAbaqusProcessor
JobSpec
PreparationSpec
HookSpec
Key Methods¶
degenerate_from_array
generate_from_array
generate_from_inp_files
outcomes_to_dict
outcomes_to_list
- class ABQflow.AbaqusCalculation(job_name, output_dir, workflow_strategy, cpus_per_job, abaqus_exe='abaqus', timeout=None, user_subroutine=None)[source]¶
Bases:
objectThin wrapper: assembles JobContext + AbaqusRunner, delegates to strategy.
No side effects in
__init__(only creates the output directory and builds the immutable JobContext). The logger is created lazily on the first call toexecute().Attributes¶
- job_namestr
Unique job identifier.
- output_dirstr
Working directory for this job.
- workflow_strategyJobWorkflowStrategy
The assembled workflow to execute.
- cpus_per_jobint
Number of CPUs requested for the solver.
- abaqus_exestr
Path to the Abaqus executable.
- timeoutfloat or None
Per-subprocess timeout in seconds.
- ctxJobContext
Immutable context built from the constructor arguments.
- execute(phase='full')[source]¶
Run the workflow (or a single phase of it) and return the result dict.
Creates the logger and the
AbaqusRunneron first call, then delegates toself.workflow_strategy.execute()(phase='full') or to the matching<phase>_onlymethod on the strategy.Parameters¶
- phasestr
'full'(default) runs the complete workflow.'prepare','simulate', or'extract'run only that phase via the strategy’sprepare_only/simulate_only/extract_onlymethod (seeJobWorkflowStrategy’s optional phase-separated protocol).
Returns¶
- dict
Must contain at least
'status'. May include extracted values.
Raises¶
- NotImplementedError
If
phase != 'full'andself.workflow_strategydoes not implement the corresponding<phase>_onlymethod (e.g.MonolithicWorkflowStrategy).
- class ABQflow.AbaqusRunner(ctx, logger, timeout=None, record_only=False)[source]¶
Bases:
objectEncapsulates every subprocess call a strategy may need.
Detects the execution environment and routes commands accordingly:
abqpy installed — uses plain
python(abqpy wraps the Abaqus API).Needs CAE kernel (
mdb) — usesabaqus cae noGUI=<script>.Only needs odbAccess — uses
abaqus python <script>.
Attributes¶
- ctxJobContext
Frozen context providing job name, paths, CPU count, and Abaqus exe.
- loggerlogging.Logger
Logger instance for this runner.
- timeoutfloat or None
Per-command timeout in seconds;
Nonemeans no limit.
- static build_make_command(ctx, subroutine)[source]¶
Build the
abaqus make library=<source> [explicit|cfd]command line.Pure function shared by
run_compile()and dry-run planning.solver='standard'needs no extra flag;'explicit'/'cfd'are appended as bare flags — mirrors the convention documented inreference/abaqus-cli(verify against the installed Abaqus version before relying on this in production).- Parameters:
ctx (JobContext)
subroutine (SubroutineSpec)
- Return type:
- static build_preflight_command(ctx, mode)[source]¶
Build the
abaqus <mode> job=<job>_chk input=... [user=...]command line.Returns¶
- tuple[list[str], str]
(cmd, chk_name)— chk_name is the temporary job name used so preflight output never overwrites the real job’s files.
- static build_script_command(script, needs_cae_kernel, abaqus_exe, has_abqpy)[source]¶
Select the correct interpreter and Abaqus entry-point for script.
Pure function — no instance state required — so both the real execution path (
_base_command()) and dry-run planning (_dry_run_plan()) can share one definition instead of maintaining separate copies.Decision logic (first match wins):
abqpyavailable —['python', script].needs_cae_kernelis True —[exe, 'cae', 'noGUI=<script>', '--']. The'--'separator prevents custom args from being consumed by the Abaqus CLI.Otherwise —
[exe, 'python', script](odbAccess-only scripts).
Parameters¶
- scriptstr
Path to the Python script to execute.
- needs_cae_kernelbool
Whether the script requires the CAE kernel (
mdbaccess).- abaqus_exestr
Path or command name for the Abaqus executable.
- has_abqpybool
Whether the
abqpypackage is importable in this environment.
Returns¶
- list[str]
Command line as a list of tokens ready for
subprocess.run.
- static build_solver_command(ctx)[source]¶
Build the
abaqus job=... input=... cpus=... [user=...] interactivecommand line.Pure function of ctx — shared by
run_solver()and dry-run planning so the two never drift apart.user=<ctx.user_subroutine>is inserted (beforeinteractive) when a subroutine is configured.- Parameters:
ctx (JobContext)
- Return type:
- run_compile(subroutine)[source]¶
Run
abaqus maketo compile subroutine.No regex parsing of compiler errors is performed — stdout/stderr are captured and returned as-is for the caller to log (matches the reference tool’s approach: compiler-error classification is left to a human/LLM reading the raw output, not this library).
Parameters¶
- subroutineSubroutineSpec
Subroutine to compile.
Returns¶
- tuple[bool, str, str]
(success, stdout, stderr).
- Parameters:
subroutine (SubroutineSpec)
- Return type:
- run_hook(script_path, tasks, common_args, needs_cae_kernel)[source]¶
Execute a hook script with a JSON task list, return per-task results.
Writes tasks to a temporary JSON file, launches the script via
_base_command()(so the correct environment is used), appendscommon_args,--job_name, and--tasks_json, then extracts the JSON result payload from stdout.Before execution,
_stage_hookkit()copieshookkit.pyinto the job output directory so hooks canimport hookkit.After execution, every sidecar envelope in the results dict passes through
_validate_envelope()for path-safety, existence, and metadata-augmentation checks.Parameters¶
- script_pathstr
Path to the hook script.
- taskslist[dict]
List of task descriptors, each expected to contain a
result_namekey.- common_argsdict[str, str]
Extra CLI arguments forwarded to every task (e.g.
--odb_path).- needs_cae_kernelbool
Passed through to
_base_command()for environment selection.
Returns¶
- dict
Mapping
{result_name: value, ...}. Tasks that could not run map toNone. Returns an empty dict whentasksis empty.
- run_preflight(mode)[source]¶
Run an Abaqus syntax/datacheck on the INP before the real solve.
Uses a temporary job name
<job>_chkso preflight output files (.dat,.odb) never overwrite the real job’s files.Parameters¶
- modestr
'syntaxcheck'or'datacheck'.
Returns¶
- tuple[bool, list[str]]
(passed, errors)— errors are harvested from the temporary.datfile viaharvest_errors()(IMP-01/04 synergy).
- run_solver()[source]¶
Submit the INP file to the Abaqus solver and wait for completion.
Uses
Popenwith process-group isolation so that the terminate escalation ladder can reach solver child processes (standard.exe/explicit.exe) — somethingsubprocess.runcannot do.Escalation ladder (IMP-03):
Normal wait up to
self.timeout.Graceful:
abaqus terminate job=<name>.Grace period G = clamp(0.05 × T, 30, 300) s.
Force-kill the process tree (
taskkill /Toros.killpg).Remove
<job>.lckso the job can be re-run.
After the solver process exits (by any means),
diagnose()is called and the truth table applied.Returns¶
- SolverResult
Success/failure judgment with diagnostics.
- Return type:
- subroutine_needs_recompile(subroutine)[source]¶
Return
Trueif subroutine has changed since the last successful compile.Compares the sha256 of
subroutine.source_pathagainst a sidecar hash file written by_record_compile_hash()after a successful compile (same hash-compare-and-skip pattern as_stage_hookkit()). AlwaysTrueif no prior compile record exists.- Parameters:
subroutine (SubroutineSpec)
- Return type:
- Parameters:
ctx (JobContext)
logger (logging.Logger)
timeout (float | None)
record_only (bool)
- class ABQflow.BatchAbaqusProcessor(batch_data, base_output_dir, cpus_per_job, abaqus_exe='abaqus', duplicate_mode='fail', prompt_fn=<built-in function input>, timeout=None, preflight_only=False)[source]¶
Bases:
objectOrchestrate a batch of Abaqus jobs through a three-phase lifecycle.
plan()— inspect for directory conflicts, compute decisions. Pure computation; no side effects.prepare()— apply decisions (delete, rename, skip) and build theAbaqusCalculationlist.run_batch()— execute viaProcessPoolExecutor; one failure never affects sibling jobs.
Attributes¶
- specslist[JobSpec]
Normalised list of job specifications.
- calculationslist[AbaqusCalculation] or None
Built calculations (populated by
prepare()).- loggerlogging.Logger
Logger writing to
batch_processor.login the output directory.
- __init__(batch_data, base_output_dir, cpus_per_job, abaqus_exe='abaqus', duplicate_mode='fail', prompt_fn=<built-in function input>, timeout=None, preflight_only=False)[source]¶
Parameters¶
- batch_datalist[dict] or list[JobSpec]
Job configs as dicts or
JobSpecobjects. Dicts are converted viaJobSpec.from_dict().- base_output_dirstr
Absolute directory where all job subdirectories will be created.
- cpus_per_jobint
Number of CPUs to request for each Abaqus job.
- abaqus_exestr
Absolute path to the Abaqus executable (default
'abaqus').- duplicate_modestr
How to handle existing job directories (default
'fail'):'fail'— raiseFileExistsErroron any conflict.'skip'— skip jobs whose directory already exists.'overwrite'— delete the existing directory and re-run.'interactive'— prompt the user for each conflict.
- prompt_fncallable
Function for interactive prompts (default
input()).- timeoutfloat or None
Per-subprocess timeout in seconds;
Nonemeans no limit.- preflight_onlybool
If
True, only run preparation + preflight, skip solver & extraction (IMP-04 batch inspection mode).
- dry_run(level='plan')[source]¶
Inspect what the batch would do without executing it.
Two levels (see IMP-05):
'plan'(default)Zero side effects. Inspects each spec and builds a command plan without touching the filesystem.
'stage'Runs the real preparation phase, but substitutes a
record_onlyrunner so solver and hook commands are logged, not executed. Has filesystem side effects (output_diris created, INPs are staged).
Parameters¶
- levelstr
'plan'(L1, default) or'stage'(L2).
Returns¶
- list[JobPlan]
One plan per job.
- plan()[source]¶
Inspect output directory for existing job subdirectories.
Pure read-only check — no directories are created, deleted, or renamed. The decision for each job is one of:
'run','skip','overwrite', or a new name string (rename).Returns¶
- dict[str, str]
{job_name: decision}mapping.
Raises¶
- FileExistsError
If
duplicate_mode='fail'and any job directory already exists.
- prepare(decisions=None)[source]¶
Apply plan decisions and build the
AbaqusCalculationlist.Side effects: directories may be deleted (
'overwrite') or specs may be renamed ('rename'). Results are stored inself.calculations.Parameters¶
- run_batch(num_parallel_jobs, license_tokens=None)[source]¶
Execute all prepared calculations via
ProcessPoolExecutor.If
prepare()has not been called yet it is invoked with a fresh call toplan().Parameters¶
- num_parallel_jobsint
Desired maximum concurrent jobs.
- license_tokensint or None
Total license tokens available;
Nonemeans no license limit.
Returns¶
- list[JobOutcome]
One outcome per executed job. Failed jobs are included with their error state — they do not halt the batch.
- Parameters:
- Return type:
- run_extraction(num_parallel_jobs=1, license_tokens=None)[source]¶
Run only the post-extraction phase for every spec.
Assumes
ctx.odb_pathalready exists for every job (e.g. from a priorrun_simulation()call). Onlyworkflow='modular'specs are supported.Parameters¶
- num_parallel_jobsint
Desired maximum concurrent jobs (default
1).- license_tokensint or None
Total license tokens available;
Nonemeans no license limit.
Returns¶
- list[JobOutcome]
One outcome per job.
- Parameters:
- Return type:
- run_preparation(num_parallel_jobs=1, license_tokens=None)[source]¶
Run only the preparation phase (produce INPs, and compile a subroutine if configured) for every spec in
self.specs.Builds
AbaqusCalculations directly fromself.specs(see_build_calc()) rather than throughplan()/prepare()’s duplicate-directory handling — callplan()/prepare()first if you need overwrite/rename/skip semantics. Onlyworkflow='modular'specs are supported; amonolithicspec raisesNotImplementedError(it has no separable preparation phase).Parameters¶
- num_parallel_jobsint
Desired maximum concurrent jobs (default
1).- license_tokensint or None
Total license tokens available;
Nonemeans no license limit.
Returns¶
- list[JobOutcome]
One outcome per job.
- Parameters:
- Return type:
- run_simulation(num_parallel_jobs=1, license_tokens=None)[source]¶
Run only the solver phase (pre-extraction + solve) for every spec.
Assumes
ctx.inp_pathalready exists for every job (e.g. from a priorrun_preparation()call — possibly in an earlier process/session; reconstruct theBatchAbaqusProcessorwith the samebatch_data/base_output_dirto resume). Onlyworkflow='modular'specs are supported.Parameters¶
- num_parallel_jobsint
Desired maximum concurrent jobs (default
1).- license_tokensint or None
Total license tokens available;
Nonemeans no license limit.
Returns¶
- list[JobOutcome]
One outcome per job.
- Parameters:
- Return type:
- class ABQflow.CommandRecord(stage, cmd, cwd)[source]¶
Bases:
objectOne command that was (or would be) executed.
- class ABQflow.ExistingInpStrategy(source_inp_path, staging_mode='copy', resolve_includes=True)[source]¶
Bases:
PreparationStrategyUse a pre-existing INP file directly — no generation or modification.
This strategy satisfies the preparation contract (“ensure an INP at
ctx.inp_path”) by copying an already-complete INP file. It is the entry point for the UC-03 “pre-existing INP batch” use case.Key features beyond a plain file copy:
INCLUDE resolution: scans for
*INCLUDE, INPUT=...lines and rewrites relative paths to absolute paths so Abaqus can find referenced files regardless of the working directory.Template detection: rejects INPs that still contain
{{...}}placeholders, steering the user towardkind='inp_based'instead.STEP presence check: confirms the file contains at least one
*STEPkeyword.
Attributes¶
- source_inp_pathstr
Absolute or relative path to the existing INP file.
- staging_modestr
'copy'(default) — copy the INP (with resolved paths) to output_dir.- resolve_includesbool
If
True(default), rewrite*INCLUDE, INPUT=rel_pathto use absolute paths resolved against the source INP’s directory.
- prepare(ctx, runner, logger)[source]¶
Produce the INP file.
Parameters¶
- ctxJobContext
Job context providing
inp_pathandoutput_dir.- runnerAbaqusRunner
Subprocess runner (may not be used by every strategy).
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- bool
Trueif the INP was produced,Falseotherwise.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.ExtractionStrategy[source]¶
Bases:
ABCInterface for extraction: read results from model or ODB files.
Subclasses¶
- OdbExtractionStrategy
Post-simulation extraction from ODB (requires
odbAccess).- ModelPropertiesExtractionStrategy
Pre-simulation extraction from INP (requires
mdb/ CAE kernel).
- abstractmethod extract(ctx, runner, logger)[source]¶
Extract results.
Parameters¶
- ctxJobContext
Job context providing file paths.
- runnerAbaqusRunner
Subprocess runner for launching hook scripts.
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- dict
{result_name: value, ...}. Failed tasks map toNone.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.HookSpec(script_path, tasks=<factory>)[source]¶
Bases:
objectDescription of one extraction/pre-extraction hook script and its tasks.
Attributes¶
- script_pathstr
Path to the Python script that processes the hook.
- taskslist[dict]
List of task descriptors; each dict typically contains
result_name,script_path, and task-specific parameters.
- class ABQflow.InpModifyStrategy(base_inp_path, data_params)[source]¶
Bases:
PreparationStrategyReplace
{{placeholder}}tokens in a base INP template file.Performs coverage validation: if the INP references a placeholder that is missing from data_params, preparation fails. If data_params contains keys that are not used in the INP, a warning is emitted.
Attributes¶
- base_inp_pathstr
Path to the template INP file containing
{{key}}placeholders.- data_paramsdict
Mapping of placeholder names to substitution values.
- prepare(ctx, runner, logger)[source]¶
Produce the INP file.
Parameters¶
- ctxJobContext
Job context providing
inp_pathandoutput_dir.- runnerAbaqusRunner
Subprocess runner (may not be used by every strategy).
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- bool
Trueif the INP was produced,Falseotherwise.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.JobContext(job_name, output_dir, cpus, abaqus_exe='abaqus', user_subroutine=None)[source]¶
Bases:
objectImmutable data contract holding all information a strategy can observe.
Strategies depend on this object but cannot mutate it, preventing accidental cross-strategy side effects. Every field is read-only after construction.
Attributes¶
- job_namestr
Unique identifier for this job (also used as directory name).
- output_dirstr
Absolute path to the job’s working directory.
- cpusint
Number of CPUs requested for the Abaqus solver run.
- abaqus_exestr
Path or command name for the Abaqus executable (default
"abaqus").
- property exec_log_path: str¶
Absolute path to ABQflow’s own execution log (
<output_dir>/<job_name>_abqflow.log).Deliberately distinct from
log_path(Abaqus’s native job log) so the two writers never collide on the same file.
- property log_path: str¶
Absolute path to Abaqus’s own native job log (
<output_dir>/<job_name>.log).This file is owned and written by the Abaqus solver process itself (
abaqus job=... interactivewrites it as a side effect). ABQflow never opens this path for writing — seeexec_log_pathfor ABQflow’s own execution log, which uses a distinct filename to avoid colliding with this one.
- class ABQflow.JobOutcome(job_name, status, results=None, error=None, diagnostics=None, output_dir=None, phases=None, duration_s=None)[source]¶
Bases:
objectUnified result envelope returned from every job, pass or fail.
Status is normalised to a plain string (
JobStatus.value) so it serialises cleanly across process boundaries.Attributes¶
- job_namestr
Name of the job.
- statusstr
String status, e.g.
"COMPLETED"or"SIMULATION_FAILED".- resultsdict or None
Extracted result values, or
Noneif the job did not reach extraction.- errorstr or None
Error message if the job failed,
Noneotherwise.- diagnosticsdict or None
Solver diagnostics snapshot (IMP-02). Populated on failure and on the
rc≠0 + COMPLETEDedge case.Nonefor clean success or jobs that never reached the solver phase.- phaseslist[dict] or None
Phase-by-phase history (name/status/duration/error) collected from
JobStatusManager.Nonefor strategies that don’t populate it (e.g. monolithic workflows).- duration_sfloat or None
Wall-clock seconds spent in
AbaqusCalculation.execute()for this job.
- class ABQflow.JobPlan(job_name, commands=<factory>, paths=<factory>, resource_summary=<factory>)[source]¶
Bases:
objectDry-run output for a single job — commands, paths, and resource summary.
Attributes¶
- job_namestr
Job identifier.
- commandslist
List of
CommandRecordinstances.- pathsdict[str, str]
Expected file paths (
inp,odb,output_dir).- resource_summarydict
Planned CPUs, token estimate, and parallelism info.
- class ABQflow.JobSpec(job_name, workflow='modular', preparation=None, preflight=None, monolithic_script=None, monolithic_params=<factory>, pre_extraction=<factory>, post_extraction=<factory>, subroutine=None, meta=<factory>)[source]¶
Bases:
objectSingle-job configuration validated at construction time.
Fails fast — validation runs in
__post_init__so invalid configs are rejected before any Abaqus process is launched.Attributes¶
- job_namestr
Unique name for this job (also used as the working directory name).
- workflowstr
'modular'(default, 4-phase pipeline) or'monolithic'(single-script).- preparationPreparationSpec or None
Preparation spec; required when
workflow='modular', ignored for monolithic.- preflightstr, default=None
Preflight mode for modular workflows. - None: No preflight checks (default) - ‘syntaxcheck’: Run abaqus syntax check - ‘datacheck’: Run abaqus datacheck
- monolithic_scriptstr or None
Path to the monolithic script; required when
workflow='monolithic'.- monolithic_paramsdict
Parameters forwarded to the monolithic script as
--key valueargs.- pre_extractionlist[HookSpec]
Hooks run before the solver (e.g. model property extraction).
- post_extractionlist[HookSpec]
Hooks run after the solver (e.g. ODB result extraction).
- subroutineSubroutineSpec or None
User subroutine to compile and pass via
user=to the solver (modular workflow only; ignored forworkflow='monolithic').- metadict
Arbitrary user metadata
- classmethod from_dict(d)[source]¶
Migration bridge: construct a
JobSpecfrom a legacy dict.Deep-copies the input dict so the returned spec owns all of its mutable data (no shared references with the caller).
Parameters¶
- ddict
Legacy configuration dict. Recognised keys:
job_name,workflow,type,base_inp_path,model_script_path,script_path,params,pre_extraction,post_extraction.
Returns¶
- JobSpec
Fully validated spec.
- preparation: PreparationSpec | None = None¶
- subroutine: SubroutineSpec | None = None¶
- class ABQflow.JobStatus(value)[source]¶
Bases:
EnumLifecycle state for a single batch job.
Key values¶
- CREATED
Initial state — job has been constructed but not yet started.
- COMPLETED
Terminal success — the full workflow finished without error.
- PREPARATION_FAILED
Terminal failure — the preparation phase could not produce an INP.
- SIMULATION_FAILED
Terminal failure — the Abaqus solver exited with an error.
- EXTRACTION_FAILED
Terminal failure — one or more post-extraction tasks returned
None.- MONOLITHIC_SCRIPT_FAILED
Terminal failure — the monolithic script exited with a non-zero code.
- JSON_DECODE_ERROR
Terminal failure — monolithic or hook script output could not be parsed as JSON.
- SCRIPT_ERROR
Terminal failure — an unhandled exception occurred in a hook or monolithic script.
- SUBROUTINE_COMPILE_FAILED
Terminal failure —
abaqus make(user subroutine compilation) exited with an error.- UNKNOWN_ERROR
Terminal failure — an exception escaped the worker process.
- UNKNOWN
Fallback value used when no explicit status is available.
- CREATED = 'CREATED'¶
- COMPLETED = 'COMPLETED'¶
- PREPARING = 'PREPARING'¶
- PREPARATION_FAILED = 'PREPARATION_FAILED'¶
- PREPARATION_SUCCESS = 'PREPARATION_SUCCESS'¶
- PREFLIGHT_FAILED = 'PREFLIGHT_FAILED'¶
- SIMULATING = 'SIMULATING'¶
- SIMULATION_FAILED = 'SIMULATION_FAILED'¶
- SIMULATION_SUCCESS = 'SIMULATION_SUCCESS'¶
- EXTRACTING = 'EXTRACTING'¶
- EXTRACTION_FAILED = 'EXTRACTION_FAILED'¶
- EXTRACTION_SUCCESS = 'EXTRACTION_SUCCESS'¶
- MONOLITHIC_SCRIPT_FAILED = 'MONOLITHIC_SCRIPT_FAILED'¶
- JSON_DECODE_ERROR = 'JSON_DECODE_ERROR'¶
- SCRIPT_ERROR = 'SCRIPT_ERROR'¶
- SUBROUTINE_COMPILE_FAILED = 'SUBROUTINE_COMPILE_FAILED'¶
- UNKNOWN_ERROR = 'UNKNOWN_ERROR'¶
- UNKNOWN = 'UNKNOWN'¶
- class ABQflow.JobStatusManager[source]¶
Bases:
objectState machine for a single job with terminal-state protection.
Calling
record_preparation(),record_simulation(), orrecord_extraction()advances the state. Once a terminal failure state is reached, all subsequent transitions are silently ignored — the first failure is the one that is kept.The
mark_*methods set the live in-progress status (PREPARING/SIMULATING/EXTRACTING) and open aPhaseRecord; the pairedrecord_*method closes it.mark_*calls are optional — callers that only care about the final outcome (as before) can skip them and just callrecord_*directly.Attributes¶
- error_messagestr or None
Error message from the first terminal failure, or
None.
- property current_status: JobStatus¶
Read-only access to the live status (updated at phase start, not just at the end).
- get_final_status()[source]¶
Return the current state or
COMPLETEDif no failure was recorded.Returns¶
- JobStatus
The terminal failure state if one was reached, otherwise
JobStatus.COMPLETED.
- Return type:
- mark_extracting(label='extraction')[source]¶
Mark the start of an extraction phase.
Parameters¶
- labelstr
'pre_extraction'or'post_extraction'— distinguishes the two extraction phases inphase_history.
- Parameters:
label (str)
- property phase_history: list[dict]¶
Closed phases so far, as plain dicts (picklable across process boundaries).
- record_compile(success, error=None)[source]¶
Record the outcome of user-subroutine compilation.
Parameters¶
- successbool
Trueifabaqus make(or an equivalent compile step) succeeded.- errorstr or None
Error message on failure; a default is used if omitted.
- record_extraction(results)[source]¶
Record extraction results; fails if any task returned
None.On success this now sets
current_statustoJobStatus.EXTRACTION_SUCCESS(previously a no-op — the final status reported byget_final_status()is unaffected, sinceEXTRACTION_SUCCESSis not a terminal state).Parameters¶
- resultsdict
{result_name: value}mapping. AnyNonevalue triggersEXTRACTION_FAILED.
- Parameters:
results (dict)
- record_preflight(success, error=None)[source]¶
Record the outcome of the preflight phase (IMP-04).
Parameters¶
- successbool
Trueif syntax/datacheck passed.- errorstr or None
Error message on failure; a default is used if omitted.
- class ABQflow.JobWorkflowStrategy[source]¶
Bases:
ABCInterface for a complete job workflow.
Subclasses¶
- MonolithicWorkflowStrategy
Single-script workflow that handles everything itself.
- ModularWorkflowStrategy
Multi-phase pipeline: optional subroutine compile, preparation, optional preflight, pre-extraction, simulation, post-extraction.
Optional phase-separated protocol¶
Subclasses may additionally implement
prepare_only(ctx, runner, logger, status_manager=None) -> tuple[dict, JobStatusManager],simulate_only(...) -> tuple[dict, JobStatusManager, bool](theboolsignals whether the pipeline should stop), andextract_only(...) -> tuple[dict, JobStatusManager]so thatAbaqusCalculationcan invoke a single phase (see itsexecute(phase=...)parameter). This is not required by the ABC —MonolithicWorkflowStrategyand user-defined strategies that don’t implement it simply raiseNotImplementedErrorwhen a phase-only call is attempted.- abstractmethod execute(ctx, runner, logger)[source]¶
Run the full workflow and return a result dict.
Parameters¶
- ctxJobContext
Job context.
- runnerAbaqusRunner
Subprocess runner for all subprocess calls.
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- dict
Must contain at least a
'status'key (aJobStatusor its string value). May include extracted results.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.ModelGenerationStrategy(model_script_path, script_params)[source]¶
Bases:
PreparationStrategyRun a model-generation script (requires CAE kernel /
mdbaccess).The script is launched via
abaqus cae noGUI=<script>and is expected to produce an INP file atctx.inp_path. Common arguments (--job_name, user params) are forwarded as CLI flags.Attributes¶
- model_script_pathstr
Path to the model-generation script.
- script_paramsdict
Key-value pairs forwarded as
--key valuearguments.
- prepare(ctx, runner, logger)[source]¶
Produce the INP file.
Parameters¶
- ctxJobContext
Job context providing
inp_pathandoutput_dir.- runnerAbaqusRunner
Subprocess runner (may not be used by every strategy).
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- bool
Trueif the INP was produced,Falseotherwise.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.ModelPropertiesExtractionStrategy(hooks)[source]¶
Bases:
ExtractionStrategyExtract material/property data from the INP before simulation.
Runs in the CAE kernel environment (
abaqus cae noGUI) because it needsmdbaccess. Each hook script receives--inp_pathas a common argument and a JSON task list via--tasks_json.Attributes¶
- hookslist[HookSpec]
List of hook descriptors, each with
script_pathandtasks.
- extract(ctx, runner, logger)[source]¶
Extract results.
Parameters¶
- ctxJobContext
Job context providing file paths.
- runnerAbaqusRunner
Subprocess runner for launching hook scripts.
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- dict
{result_name: value, ...}. Failed tasks map toNone.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.ModularWorkflowStrategy(preparation_strategy, pre_extraction_strategies, post_extraction_strategies, preflight_mode=None, preflight_only=False, compile_strategy=None)[source]¶
Bases:
JobWorkflowStrategyMulti-phase pipeline: [compile], preparation, [preflight], pre-extraction, simulation, post-extraction.
Uses a
JobStatusManagerinternally to track the job through each phase. If any phase fails the pipeline stops and returns the terminal status immediately.execute()composes three independently callable phase methods —prepare_only(),simulate_only(),extract_only()— so thatAbaqusCalculation(andBatchAbaqusProcessor’srun_preparation/run_simulation/run_extraction) can invoke a single phase without running the rest of the pipeline. The external contract ofexecute()— return-dict shape and terminal-status semantics — is unchanged by this split.Attributes¶
- preparation_strategyPreparationStrategy
Strategy that produces the INP file.
- preflight_modestr or None
'syntaxcheck','datacheck', orNone(IMP-04).- pre_extraction_strategieslist[ExtractionStrategy]
Strategies run before the solver (e.g. property extraction from INP).
- post_extraction_strategieslist[ExtractionStrategy]
Strategies run after the solver (e.g. result extraction from ODB).
- compile_strategySubroutineCompileStrategy or None
Optional user-subroutine compile step, run before preparation.
- execute(ctx, runner, logger)[source]¶
Run the full modular workflow by composing the three phase methods.
Returns a dict with at least a
'status'key plus any results from pre- and post-extraction hooks. Failing early means later phases are skipped — return-dict shape and terminal-status semantics are unchanged from before the phase-separation refactor.- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- extract_only(ctx, runner, logger, status_manager=None)[source]¶
Phase 3: post-extraction hooks only.
Assumes
ctx.odb_pathalready exists. No existence guard is needed —OdbExtractionStrategyalready reports every task asNonewhen the ODB is missing, andJobStatusManager.record_extraction()already turns that intoEXTRACTION_FAILED.Returns¶
- tuple[dict, JobStatusManager]
(results, status_manager).
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
status_manager (JobStatusManager | None)
- Return type:
- prepare_only(ctx, runner, logger, status_manager=None)[source]¶
Phase 1: optional subroutine compile, preparation, optional preflight.
Standalone entry point for “produce an INP (and compiled subroutine) only”. Does not run pre-extraction, the solver, or post-extraction — those live in
simulate_only()/extract_only().Returns¶
- tuple[dict, JobStatusManager]
(results, status_manager)— results has at least'status'and'_phase_history'; the manager is returned soexecute()can thread it into the next phase.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
status_manager (JobStatusManager | None)
- Return type:
- simulate_only(ctx, runner, logger, status_manager=None)[source]¶
Phase 2: pre-extraction hooks, then the solver run.
Assumes
ctx.inp_pathalready exists (produced by a priorprepare_only()call — possibly in an earlier process/session, e.g. viaBatchAbaqusProcessor.run_simulation()). Mirrors the original monolithic behavior: a pre-extraction failure does not stop the solver from running, but a solver failure does stop the pipeline.Returns¶
- tuple[dict, JobStatusManager, bool]
(results, status_manager, stop)— stop isTruewhen the caller (e.g.execute()) should not proceed toextract_only()(INP missing or solver failed).
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
status_manager (JobStatusManager | None)
- Return type:
- Parameters:
preparation_strategy (PreparationStrategy)
pre_extraction_strategies (List[ExtractionStrategy])
post_extraction_strategies (List[ExtractionStrategy])
preflight_mode (str | None)
preflight_only (bool)
compile_strategy (SubroutineCompileStrategy | None)
- class ABQflow.MonolithicWorkflowStrategy(script_path, params)[source]¶
Bases:
JobWorkflowStrategySingle-script workflow: one script does everything.
The script is launched via the CAE kernel (
abaqus cae noGUI) and must print its JSON results wrapped in the sentinel markers===ABQ_RESULT_BEGIN===/===ABQ_RESULT_END===. The result dict is expected to contain at least a'status'key.Attributes¶
- script_pathstr
Path to the monolithic script.
- paramsdict
Key-value parameters forwarded as
--key valueCLI arguments.
- execute(ctx, runner, logger)[source]¶
Run the full workflow and return a result dict.
Parameters¶
- ctxJobContext
Job context.
- runnerAbaqusRunner
Subprocess runner for all subprocess calls.
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- dict
Must contain at least a
'status'key (aJobStatusor its string value). May include extracted results.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.OdbExtractionStrategy(hooks)[source]¶
Bases:
ExtractionStrategyExtract results from the ODB file via hook scripts.
Runs in the
odbAccessenvironment (abaqus python), NOT the CAE kernel. Each hook script receives--odb_pathas a common argument and a JSON task list via--tasks_json.Attributes¶
- hookslist[HookSpec]
List of hook descriptors, each with
script_pathandtasks.
- extract(ctx, runner, logger)[source]¶
Extract results.
Parameters¶
- ctxJobContext
Job context providing file paths.
- runnerAbaqusRunner
Subprocess runner for launching hook scripts.
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- dict
{result_name: value, ...}. Failed tasks map toNone.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.PreparationSpec(kind, source_path, params=<factory>, options=<factory>)[source]¶
Bases:
objectSpecification for the preparation phase of a modular workflow.
Attributes¶
- kindstr
Preparation strategy identifier. Currently
'inp_based','existing_inp', or'model_generation'.- source_pathstr
Path to the base INP file (for
inp_based) or model-generation script (formodel_generation).- paramsdict
Key-value parameters forwarded to the preparation strategy (e.g. placeholder replacements for
inp_based).- optionsdict
Additional options for the preparation strategy (Currently only used by
existing_inp): - ‘staging_mode’ (str):'copy'(default) - ‘resolve_includes’ (bool): Whether to resolve*INCLUDEdirectives in the INP file (default: True).
- class ABQflow.PreparationStrategy[source]¶
Bases:
ABCInterface for preparation: produce an INP file at
ctx.inp_path.Subclasses¶
- InpModifyStrategy
Template-based INP generation (
{{placeholder}}substitution).- ModelGenerationStrategy
Run an external script that produces the INP (requires CAE kernel).
- abstractmethod prepare(ctx, runner, logger)[source]¶
Produce the INP file.
Parameters¶
- ctxJobContext
Job context providing
inp_pathandoutput_dir.- runnerAbaqusRunner
Subprocess runner (may not be used by every strategy).
- loggerlogging.Logger
Logger for progress and error messages.
Returns¶
- bool
Trueif the INP was produced,Falseotherwise.
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- class ABQflow.SolverDiagnostics(sta_verdict='INDETERMINATE', errors=None, error_total=0, warning_total=0, increments=0, source_files=None, solver_type='unknown')[source]¶
Bases:
objectDiagnostic snapshot harvested after a solver run.
Attributes¶
- sta_verdictstr
Raw verdict from .sta parsing:
'COMPLETED'|'NOT_COMPLETED'|'ABORTED'|'INDETERMINATE'.- errorslist[str]
Deduplicated, truncated error lines (at most k_errors entries).
- error_totalint
Total ERROR lines found before dedup/truncation.
- warning_totalint
Total WARNING lines found.
- incrementsint
Completed increment count from .sta (best-effort).
- source_filesdict[str, str]
Map of kind (
'sta','msg','dat','log') to absolute path for every file that was actually read.- solver_typestr
'standard'|'explicit'|'unknown'.
- class ABQflow.SolverResult(success, error=None, diagnostics=None)[source]¶
Bases:
objectReturned by
AbaqusRunner.run_solver().Wraps the raw diagnostics with the combined truth-table success determination so callers get a single authoritative answer.
- Parameters:
success (bool)
error (str | None)
diagnostics (SolverDiagnostics | None)
- diagnostics: SolverDiagnostics | None = None¶
- class ABQflow.SubroutineCompileStrategy(subroutine, cache=True)[source]¶
Bases:
objectCompiles a user subroutine via
abaqus makebefore preparation.Not part of the
PreparationStrategy/ExtractionStrategyABC hierarchies — compilation is its own concern with a single implementation today (YAGNI; add a registry likePREPARATION_REGISTRYif multiple compile backends are ever needed).Attributes¶
- subroutineSubroutineSpec
Subroutine to compile.
- cachebool
If
True(default), skip recompilation when the source file’s content hash matches the last successful compile (seesubroutine_needs_recompile()).
- compile(ctx, runner, logger)[source]¶
Compile the subroutine, or skip if precompiled/cached.
Returns¶
- tuple[bool, str]
(success, message)— message is empty on success (or a skip note), or the compiler’s raw stdout+stderr on failure. No regex parsing of compiler errors is performed (seerun_compile()).
- Parameters:
ctx (JobContext)
runner (AbaqusRunner)
logger (Logger)
- Return type:
- Parameters:
subroutine (SubroutineSpec)
cache (bool)
- class ABQflow.SubroutineSpec(source_path, language='fortran', solver='standard', precompiled=False)[source]¶
Bases:
objectSpecification for an Abaqus user subroutine (UMAT/VUMAT/UEL/…).
Attributes¶
- source_pathstr
Path to the subroutine source file (or, when
precompiled=True, to the already-compiled object/library).- languagestr
'fortran'(default),'c', or'cpp'.- solverstr
Target solver:
'standard'(default),'explicit', or'cfd'. Controls the flag passed toabaqus make(seebuild_make_command()).- precompiledbool
If
True, skip the compile phase entirely and passsource_pathstraight through touser=on the solver/preflight commands. DefaultFalse.
- ABQflow.apply_truth_table(returncode, sta_verdict)[source]¶
Combine subprocess return code and .sta verdict into a single judgment.
The principle: .sta’s ``COMPLETED`` marker is the only success certificate; the return code is merely corroborating evidence.
Truth table¶ returncode
sta_verdict
result
0
COMPLETED
success
0
NOT_COMPLETED / ABORTED
failure
0
INDETERMINATE
failure (rc=0 but no .sta marker)
!=0
COMPLETED
success (warning: cleanup error)
!=0
any other
failure
Parameters¶
- returncodeint
Subprocess exit code (0 = clean exit).
- sta_verdictstr
Verdict from
parse_sta().
Returns¶
- tuple[bool, str | None]
(is_success, warning_message). warning_message is only populated for therc≠0 + COMPLETEDedge case.
- ABQflow.build_workflow(spec, preflight_only=False)[source]¶
Assemble a concrete
JobWorkflowStrategyfrom a spec.Monolithic specs produce a
MonolithicWorkflowStrategy.Modular specs look up the preparation kind in
PREPARATION_REGISTRY, wrap pre/post-extraction hooks, and return aModularWorkflowStrategy.
Parameters¶
- specJobSpec
Validated job configuration.
- preflight_onlybool
If
True, the workflow stops after preflight (IMP-04).
Returns¶
- JobWorkflowStrategy
Ready-to-execute strategy chain.
Raises¶
- ValueError
If
spec.preparation.kindis not registered.
- Parameters:
- Return type:
- ABQflow.degenerate_from_array(outcomes, output_names, default_value=nan, require_completed=True)[source]¶
Extract a 2D NumPy array of output values from a list of outcomes.
Outcomes are sorted by natural key on
job_nameso rows appear in the order the jobs were generated. Jobs that are notCOMPLETEDare filled with default_value and trigger a warning.Parameters¶
- outcomeslist[JobOutcome]
Outcomes from
BatchAbaqusProcessor.run_batch().- output_nameslist[str]
Keys to extract from each outcome’s
resultsdict.- default_valuefloat
Value to use for missing or non-completed results (default
NaN).- require_completedbool
If
True(default), warn when non-COMPLETEDjobs are encountered.
Returns¶
- np.ndarray
Shape
(len(outcomes), len(output_names))float array.
- ABQflow.diagnose(job_name, work_dir)[source]¶
Run full diagnostics on a completed (or failed) Abaqus job.
Reads files in the following order of importance:
1.
.dat— pre-processing errors (INP syntax, mesh, materials). If the job died before the analysis phase the .sta may not exist; .dat is the only clue. 2..msg— Standard solver errors & warnings (convergence, increments). 3..sta— authoritative completion marker + increment progress. Explicit solver errors also appear in the .sta tail. 4..log— fallback: the one-lineCOMPLETED/exited with errorsconclusion.Parameters¶
- job_namestr
Abaqus job name (used to derive file names).
- work_dirstr
Job output directory containing the result files.
Returns¶
- SolverDiagnostics
Populated diagnostic snapshot.
- Parameters:
- Return type:
- ABQflow.extract_json(text)[source]¶
Extract a JSON object from subprocess stdout.
Protocol: the script wraps its JSON payload between sentinel markers
===ABQ_RESULT_BEGIN===and===ABQ_RESULT_END===. If both are present the payload between them is parsed directly. Otherwise falls back to a legacy brace-scan that searches from the end of the output (useful when Abaqus prints a banner before user code runs).Parameters¶
- textstr
Raw stdout captured from a subprocess call.
Returns¶
- dict
Parsed JSON payload.
Raises¶
- ValueError
If no JSON object can be found or parsed.
- ABQflow.generate_from_array(samples_array, param_names, base_spec)[source]¶
Create N
JobSpecobjects from an (N, D) parameter array.Each row of samples_array becomes a new spec via
copy.deepcopy()of base_spec, so every spec owns independent mutable state.Parameters¶
- samples_arrayndarray or Tensor
Shape
(N, D)parameter matrix. Torch tensors are converted to NumPy internally.- param_nameslist[str]
Length-D list of parameter names.
- base_specJobSpec or dict
Template spec. Dicts are upgraded via
JobSpec.from_dict().
Returns¶
- list[JobSpec]
N specs with zero-padded names (e.g.
job_0001,job_0002).
Raises¶
- ValueError
If the array column count does not match
len(param_names).
- ABQflow.generate_from_inp_files(inp_files, base_spec, naming='stem', sort=True)[source]¶
Create N
JobSpecobjects from a list (or glob) of existing INP files.This is the batch-spec generator for the UC-03 “pre-existing INP batch” use case. Each INP file becomes a spec with
kind='existing_inp'.Parameters¶
- inp_fileslist[str] or str
List of INP paths, or a glob pattern (e.g.
'./legacy/*.inp').- base_specJobSpec or dict
Template spec whose
workflow, extraction hooks, and other non-preparation fields are copied. Thepreparationfield is overwritten for each generated spec.- namingstr
Job-name generation rule:
'stem'(default) - use the INP filename without extension,
sanitised via
sanitize_job_name(). *'indexed'-{base_spec.job_name}_{i:04d}.- sortbool
If
True(default), sort files by natural key order.
Returns¶
- list[JobSpec]
One spec per INP file, ready for
BatchAbaqusProcessor.
Raises¶
- ValueError
If glob expands to zero files, or if sanitised stem names collide.
- ABQflow.harvest_errors(msg_path, dat_path, k_errors=5, k_chars=500)[source]¶
Stream-scan .msg and .dat files for ERROR / WARNING lines.
Reads files line-by-line so multi-GB .msg files never blow memory. Consecutive identical errors are folded into one entry with a repeat count. Results are truncated to at most k_errors entries, each clipped to k_chars characters.
Parameters¶
- msg_pathstr or None
Path to the
.msgfile (may beNoneor missing).- dat_pathstr or None
Path to the
.datfile (may beNoneor missing).- k_errorsint
Maximum number of error lines to retain (default 5).
- k_charsint
Maximum characters per retained error line (default 500).
Returns¶
- tuple[list[str], int, int]
(errors, error_total, warning_total).
- ABQflow.is_sidecar(value)[source]¶
Return
Trueif value is a sidecar envelope (dict with__file__).Parameters¶
- valueany
Value to test.
Returns¶
bool
- Return type:
- ABQflow.iter_fields(outcomes, result_name, on_missing='skip')[source]¶
Yield
(job_name, ndarray)pairs for a named field across a batch.Outcomes are sorted by
_natural_key()onjob_nameso the iteration order is deterministic and matches the row order ofdegenerate_from_array()(row-order contract).Parameters¶
- outcomeslist[JobOutcome]
Outcomes from
BatchAbaqusProcessor.run_batch().- result_namestr
Key in
outcome.resultsto load.- on_missingstr
How to handle jobs where
load_field()returnsNone:'skip'(default) — omit the job; a single summary warning lists all skipped job names at generator exit.'none'— yield(job_name, None)so the caller can align rows withdegenerate_from_array().'raise'— raiseValueErroron the first missing field.
Yields¶
- tuple[str, numpy.ndarray or None]
(job_name, ndarray)pairs.ndarrayisNoneonly whenon_missing='none'.
- ABQflow.load_field(outcome, result_name, numeric_only=True)[source]¶
Load a single named field from a
JobOutcome.Normalises inline values and sidecar CSV envelopes into a uniform
numpy.ndarray. This is the single-job entry point for consuming sidecar results; for batch consumption useiter_fields().Parameters¶
- outcomeJobOutcome
Outcome from
BatchAbaqusProcessor.run_batch().- result_namestr
Key in
outcome.resultsto load.- numeric_onlybool
If
True(default), non-numeric CSV columns are dropped with a warning. IfFalse, return an object array preserving string columns (for callers that need label columns).
Returns¶
- numpy.ndarray or None
Nonewhen the result is missing, the extraction failed, the sidecar file is gone, or the path is unsafe.
- ABQflow.outcomes_to_dict(outcomes)[source]¶
Convert a list of
JobOutcomeobjects to a{job_name: {...}}dict.Parameters¶
- outcomeslist[JobOutcome]
Outcomes from
BatchAbaqusProcessor.run_batch().
Returns¶
- dict[str, dict]
Each value dict contains
'status', flattened results, and optionally'error'.
Raises¶
- ValueError
If two outcomes share the same
job_name.
- ABQflow.outcomes_to_list(outcomes)[source]¶
Convert a list of
JobOutcomeobjects to a list of plain dicts.Convenience for callers that prefer the legacy list-of-dicts shape.
Parameters¶
- outcomeslist[JobOutcome]
Outcomes from
BatchAbaqusProcessor.run_batch().
Returns¶
- list[dict]
Each dict contains
'job_name','status', flattened results, and optionally'error'.
- ABQflow.parse_sta(path)[source]¶
Parse an Abaqus .sta file for verdict, increment count, and solver type.
Parameters¶
- pathstr
Absolute path to the
.stafile.
Returns¶
- tuple[str, int, str]
(verdict, increments, solver_type)where verdict is one of'COMPLETED','NOT_COMPLETED','ABORTED', or'INDETERMINATE'.
- ABQflow.plan_parallelism(requested, cpus_per_job, license_tokens=None, reserve_cores=1)[source]¶
Compute the actual number of concurrent jobs given license limits.
License tokens (if provided) are a hard cap — Abaqus will refuse to start a job it cannot license. CPU cores are informational only: requesting more parallel jobs than physical cores support is allowed (CPU oversubscription), since small jobs rarely saturate a full core, but it is flagged with a warning so the user can see the allocation.
Parameters¶
- requestedint
Desired number of parallel jobs.
- cpus_per_jobint
CPUs each job will request.
- license_tokensint or None
Total license tokens available.
Nonemeans unconstrained.- reserve_coresint
Cores to reserve for the OS and other processes (default 1).
Returns¶
- int
Feasible parallelism level (at least 1).
- ABQflow.register_preparation(kind, factory)[source]¶
Register a custom preparation strategy for use in modular workflows.
After registration, users can set
PreparationSpec.kindto kind andbuild_workflow()will dispatch to factory automatically — no framework source changes required.Parameters¶
- kindstr
Unique key for the preparation strategy (referenced in
PreparationSpec.kind).- factorycallable
Callable that receives a
PreparationSpecand returns aPreparationStrategy.
- Parameters:
kind (str)
factory (callable)
- ABQflow.resolve_sidecar(value, output_dir, load=False)[source]¶
Resolve a sidecar envelope to an absolute path and optional data.
Parameters¶
- valuedict
Sidecar envelope:
{'__file__': path, 'format': 'csv', ...}.- output_dirstr
Directory that
__file__is relative to.- loadbool
If
True, load the file and return anumpy.ndarray. DefaultFalse(lazy — returns the absolute path).
Returns¶
- tuple[str, dict] or tuple[numpy.ndarray, dict]
(absolute_path, metadata)whenload=False;(ndarray, metadata)whenload=True.
Raises¶
- ValueError
If the envelope is missing
__file__or the file doesn’t exist.
- ABQflow.sanitize_job_name(name, max_len=80)[source]¶
Clean name so it is a valid Abaqus job name.
Replaces any character outside
[A-Za-z0-9_-]with'_', collapses consecutive underscores, strips leading/trailing underscores, ensures the result starts with a letter, and truncates to max_len.Returns name unchanged if it is already valid.