Changelog¶
Unreleased¶
Added¶
Documentation, built with Sphinx (
docs/) and published to GitHub Pages from main: installation, a quick start, explanations of connecting, studies, storage, Ray, embedding and extending, and the API reference. The build fails on any warning, broken cross-references included.Ready to embed in a host application:
A long-lived local Acquirium:
flex-orch [--data-dir D] acquirium start [--config acquirium.toml] [--port P] | status | stop(flexorchestrator.service). It runsacquirium serverdetached on loopback, optionally with your own config and its drivers, so it outlives every script; while it runs,Orchestrator(data_dir=)attaches to it and never stops it.FLEXORCH_START_ACQUIRIUM=0makes the orchestrator fail rather than start a short-lived managed server.FLEXORCH_ACQUIRIUM_URLconnectsOrchestrator()andconnect()to that Acquirium (mode 3). While it’s set, passingdata_dir,dbor anotheracquirium_urlraises, so the store is chosen in one place.Study handles:
select_study,create_studyandget_or_create_studystill select the study, and now return a handle fixed to it that shares the connection, so callers in several threads never see each other’s selection.orch.user(or a handle’s) sets who runs and stores are recorded as.Spec files as bytes:
store_model_spec(tag, spec, files={path: bytes})stores a spec’s files without reading the disk, exactly as the same files read from disk (the samespec_hash), andmodel_spec(tag, with_files=True)returns them (SpecRecordWithFiles).flex-orch verify [--study S ...] [--samples N] [--against FILE](flexorchestrator.verify): per study and kind, run counts, tags and hashes of a sample of values, and problems (a tag stored twice, runs left running, unreadable values, a study that doesn’t exist).--againstan earlier report exits 1 on any difference in succeeded runs, tags or values; a copy (an import, a move) matches its original.python -m flexorchestratorruns the CLI.
Design studies, built on flex-pse’s
flexdesign: size equipment once across every modeled year and representative month. Add adesign:section to a study config, or store a wholeDesignSpecas a model spec (formatflex-pse.design, with the files in itsbaseandchangesstored too). Sweeps, Ray, retries and resume work as usual, and a study withoutdesignis unchanged.A design study stores a summary by default, read with
orch.design_results(tag); export patterns add per-horizon series.The exporter takes the time Sets of several blocks, each with its own timestamps.
model_inputscan’t be combined with a design yet (#5).
Changed¶
The import package is renamed
flexorchestrator, matching flex-pse’sflexcore,flexdesignand the rest:from flexorchestrator import Orchestrator. The distribution is stillflex-orchestrator, the CLI stillflex-orch, and the plugin entry-point group is nowflexorchestrator.plugins.select_study,create_studyandget_or_create_studyreturn a study handle instead of the study’s name;.studyon it is the name.The memory backend locks every method, and the file backend locks its reads too, so both are safe to share between threads.
The Acquirium backend’s stream lookups (
stream_info,find_streams,stream_rows) use Acquirium’s query API instead of SPARQL, so they don’t depend on its graph layout. Stream values now come in the unitstream_inforeports: the point’s unit, converted by Acquirium if the stream is stored in another. Only thesparqlselector still runs SPARQL, the query its user writes.Acquirium is pinned to
mainatb7f6fc8(thev0.4.0a9release commit).flex-pse is pinned to v0.3.0. Flowsheet specs are now schema
0.1.1;0.1.0specs still load, and BatteryModel’scapacitymigrates toenergy_capacity.Validating normalises a
0.1.0spec to different JSON, so storing it again under an existing tag, or resuming a study from before this bump, can raiseTagExistsErroror re-run the task. Useon_existing: replaceor a new tag.solve_optionsfor the flex-pse hook are nowprefer,tee,warmstart,mip_gap,time_limitandoptions. Others, such asload_solutions, give anerroroutcome.An infeasible HiGHS solve is now stored as
failedrather thanerror, soretriesno longer applies to it.A model with inline
energy_pricesnow solves with HiGHS instead of IPOPT.Run metadata still records
flexpse_versionas0.1.0, because the v0.3.0 tag’s package metadata says so.
Fixed¶
[in an export or result pattern is literal, as in a Pyomo path, sohorizon[2030,*].pump.*matches. Patterns can no longer use[...]character classes.The flex-pse spec validators dump with
by_alias=True, so a$sourcereference is stored as{"$source": ...}, not{"source": ...}.A study run in-process (
max_workers: 1) whose config names registered hooks no longer fails every task with “No hooks are registered”.Cancelling
execute_studynow also cancels the fits it runs first.create_orchestrator(and soflex-orch run) honoursFLEXORCH_RAY_ADDRESS.With
on_error: stop, two tasks timing out at once no longer raiseKeyError.A model key named
timeis refused wherever it appears, not only when it is the first key on its time axis.A numeric pandas
time_columnraisesStorageErrorinstead of being read as nanoseconds since 1970.Deleting the same run id twice in one call deletes it once (both backends).
Acquirium
has_studyturns connection errors intoStorageError;runs()sorts a run with no start time last.A
constant_intensitysurrogate with the wrong number of coefficients raisesFitError.An export’s final folder rename retries briefly on a Windows
PermissionError(a just-written file held by antivirus or the indexer).
Changed¶
retriesnow covers only the model work (build, solve, export, or a dead Ray worker) on both paths. A task whose spec can’t be prepared or whose result can’t be stored is an error result at once; in-process this used to be retried.fit_surrogateon Ray finds Ray the same way studies do: the call’s address, then the fit’s, thenOrchestrator(ray_address=)/FLEXORCH_RAY_ADDRESS, then local Ray.An unknown registered hook name in a study config raises
HookErrorbefore the study runs, on both paths.Code review: shared helpers replace duplicated code (
backend.recording,SolveOutcome.from_stored,results.ResultReads,results.layout,backend.base.align/qudt_key, task error results), and docstrings were filled in or corrected across the package.The package root also exports
ConfigureFn,StudyConfigError,FitError,CommandError,CommandCancelled,PluginErrorandArchiveError.A root
README.md.
Added¶
GitHub Actions CI (
.github/workflows/ci.yml):lint, thenunitandcomponenton Linux and Windows andintegrationon Linux, each built fromenvironment-dev.yml; also weekly, to catch upstream drift.Model inputs from stored data: a study’s
model_inputs, a case’smodel_inputs, amodel_inputssweep, andorch.apply_model_inputs(model, inputs)on a built model (newapply_valueshook) set model variables from a dataset, a result or general-store streams, selected as fit data is. The data is lined up with the model’s time steps (the newtime_gridhook) in the facility’stimezone, resampled, gap-filled (interpolateby default,ffill,zeroorerror) or reduced to one number, and shifted byoffset. Each result records where its inputs came from (ResultHandle.model_inputs, kept through export and import).orch.resolve_model_inputsreturns the values without building. Example:examples/ro_study/model_inputs.py.A
streamsfit selector names general-store streams bysource_idandref_name, as their driver registered them, instead of by reference URI.A file backend:
FileBackend(path)keeps every study in a folder on disk, with no Acquirium. It passes the same contract tests as the memory and Acquirium backends, and every orchestrator feature works on it (fits, sweeps, Ray, export, import). Each value is written as it’s recorded, with an atomic rename, so a crash loses only the run in progress; deletion is real. Storing a result takes about 45 ms against about 580 ms on a local Acquirium.flex-orch --files DIRselects it, andexamples/ro_study/store_on_disk.pyshows it.examples/ro_study/compare_ray.pytimes a month-long nested sweep in-process and on Ray with half the machine’s cores.Parallel execution on Ray. With
max_workers > 1,execute_studyruns its tasks on Ray (flexorchestrator.parallel):Workers build, solve and export; the main process stores each result as it arrives (a
ray.waitloop), so workers hold no credentials. Results are the same as withmax_workers=1.A task’s spec and files go to Ray once per spec (
ray.put).The loop enforces
task_timeout_s, two hours by default (nullfor no limit):ray.cancel(force=True), and the task is stored as a failed result,termination: timeout. It also retries a dead worker or a raising build/solve withinretries, and cancels running tasks onon_error: stopor a cancelled command.Workers get
OMP/MKL/OPENBLAS_NUM_THREADS=1;num_cpus,memoryandmax_callsare configurable.Hooks must be importable by name, checked before anything runs.
fit_surrogatevariants also fit on Ray: data is prepared once in the main process and shared withray.put.New config fields:
execution.ray_address,execution.resources(num_cpus,memory) andexecution.max_calls. Also new:FitParams.ray_address,Orchestrator(ray_address=)(defaultFLEXORCH_RAY_ADDRESS),execute_study(ray_address=)andflex-orch run --ray-address.Local Ray starts with
namespace="flexorch"and no dashboard.TaskResultreportsseconds(build, solve, export, store) and the worker’srss_mb.The task is now three steps,
prepare/execute/finish, instudy.task.deploy/ray/has per-tenant Ray cluster templates (compose and KubeRay) and the opt-in benchmarkstudy/tests/test_benchmark_ray.py.New optional dependency extra
ray.
Result runs record the hooks a task actually used (
flexorch_hooks), including a study’s build hook.Study export and import:
flexorchestrator.archivewithexport_study/export_result(aflexorch-export/1folder of JSON files, written to a temporary folder and renamed into place, withchecksums.sha256and optional gzip),load_result(no database) andimport_study(checks schemas and checksums, re-creates the study through the store paths, keeps tags, spec hashes and hooks, recordsflexorch_imported_from).Orchestrator.export_study,.export_result,.import_study. JSON Schemas indocs/schemas/(python -m flexorchestrator.schemas). NewArchiveError.Commands, plugins and events:
flexorchestrator.extwith@command,Command,CommandRegistry,Progress,Plugin(PLUGIN_API_VERSION1.0.0, theflexorchestrator.pluginsentry-point group, theFLEXORCH_PLUGINSallowlist, collision checks),create_orchestrator, and lifecycle events.Orchestrator(plugins=...),.run_command,.register_command,.on, and the stable methodsbuild_hooks,default_export_selection,before_store,after_store,on_task_result,on_study_created. Every command call is recorded inflexorch::commands. Testing helpersmemory_orchestratorandrun_command_in_test. NewCommandError,CommandCancelled,PluginError.Regression: the built-in
fit_surrogatecommand (Orchestrator.fit_surrogate,flexorchestrator.fitting): dataset, other-study, result,ref_uris,resolveand read-onlysparqlselectors; alignment, resampling and gap handling; variants; holdout validation; flex-pse’smultilinearandconstant_intensityregressors or any class by import string. Each fit stores its surrogate spec and a fit run in<s>::fitswith the training data’s provenance anddata_hash. The Acquirium backend reads general-store streams (stream_rows,sparql_select,stream_info,find_streams). flex-pse hooksget_regressorandpredict_surrogate;export.units.qudt_to_pyomoandpyomo_unit_of. NewFitError.Declarative studies:
flexorchestrator.studywithStudyConfig(fits;surrogate,variable,configuration_option,spec_listandcasessweeps, combined as a product or zipped;output_name,on_existing,export,execution),expand,TaskSpec/TaskResult/run_task, and the built-inexecute_studycommand (Orchestrator.execute_study, withdry_run). NewStudyConfigError.output_namefields take Python format specs ({price:.2f}); values are otherwise written exactly, withe+written ase.A
configurehook slot and its flex-pse defaultflexorchestrator.flexpse.configure(spec, path, value): sets a unit’s construction option or another element’s field, named by the element’s path and the option (dict options whole or one key at a time). The flex-pse build hook also editscostingelement fields named by an override.The
flex-orchCLI:run,cmd(options from the command’s params model),commands,exportandimport. New dependencypyyaml.examples/ro_study/: thero_surrogatesmodel as study configs, one script per sweep (surrogates, variables, configuration options, nested with a full-model export, cases), and the sample pluginexamples/plugins/ro_tools/.User-replaceable build and solve hooks:
BuildFn,SolveFn,ApplySurrogateFnandSwapSurrogateFnprotocols,SolveOutcome,HookSet,HookRegistry(callables, registered names and import strings), andrun_solve.Default flex-pse hooks in
flexorchestrator.flexpse, targeting flex-pse v0.2.0 (flowsheet spec schema 0.1.0):build(overrides becomefixelements),solve(honours the spec’ssolver),apply_surrogateandswap_surrogate(surrogateelements, optionalrelation).Specs as data:
flexorchestrator.specswithto_json_spec, canonicalspec_hash/run_hash,detect_format,validate_spec(normalises flex-pse specs through their validators),check_tagandSpecRecord; flex-pse validators inflexorchestrator.flexpse.Model data exporter:
flexorchestrator.exportwithexport_model_data(identity-based time detection, time / time x custom / custom / scalar classification,ModelData/ExportedSeries), andUnitMapper, which generates QUDT keys from pint’s unit parts (L/day->L-PER-DAY) and verifies them through an optional resolver, plusconversion_factor. NewExportErrorandUnitError; newpyomoextra.A
time_setshook kind (TimeSetsFn); the flex-pse default (flexorchestrator.flexpse.time_sets) registers the TimeBlock’s time set plus thestartup/shutdownindex sets, so those export as timeseries.Explicit results API:
Orchestratorwithcreate_study/select_study/get_or_create_study(with guards),store_model_results(tag, model, outcome, keys, include, exclude),solve_and_store(tag, model, ...)andmodel_results(tag), returningStoredResult. A tag is stored once; a result whose solve wasn’tokis afailedrun holding only its outcome, so the tag can be retried.Storage backends: the
StorageBackendcontract,MemoryBackendandAcquiriumBackend, and the results writer (flexorchestrator.results): only verified QUDT units are declared, the Pyomo unit, component and index go in variable metadata, and later runs are converted to a label’s declared unit. NewStorageError,StudyExistsError,StudyNotFoundError,TagExistsErrorandTagNotFoundError; newacquiriumextra.Data API:
Orchestrator.store_data(name, df, units=, time_column=)andget_data(name, columns=, start=, end=, column=, frame=); one dataset is one run of<s>::data, one timeseries per column. Units given as text (m3/day) or QUDT keys. NewAmbiguousColumnError,StoredData, theframe=default onOrchestrator, andflexorchestrator.frames(polars/pandas in and out). polars and pandas are now dependencies.Orchestrator.store_model_data(tag, data, outcome)stores values that are already exported.Results are stored as a snapshot: a
model_valuestable (Parquet, through Acquirium’stablekind) and amodel_manifestJSON.streams=onstore_model_results/store_model_data/solve_and_storealso stores chosen keys as native variables, andmodel_results(tag, units=)converts with pint.StoredResult.streams.Storage contract: the
tablekind; a timeseries sample must have a value (missing values are left out). The Acquirium backend declares units as QUDT URIs.Acquirium pin moved to PR #78
9a70a1f.Orchestrator.acquirium: the raw Acquirium client; there are no query wrappers.Result handles:
Orchestrator.result(tag)andstored_model_results(tags=)returnResultHandles withto_frame(),to_polars(),to_pandas(),data(units=),scalars(),unitsandoutcome, read lazily from the snapshot.Deletion and uniqueness:
Orchestrator.delete(kind, tag),delete_study(name),replace=Trueonstore_model_results,store_model_data,solve_and_storeandstore_data(writes first, then deletes the old item),allow_delete=, a per-study lock, and a post-write check that removes a racing duplicate. Storage contract:delete_runsanddelete_study, using Acquirium PR #78’s deletion.Storage contract:
variables(study)andrecords(..., labels=).Spec storage:
store_model_spec(withparent=,base_dir=,assets=),store_surrogate_spec,model_spec,surrogate_spec,stored_specs,apply_surrogate,materialize_specandbuild(tag, **overrides), in<s>::specs. Files a spec references (flex-pse tariff and events files,$sourcedata, or explicit JSON pointers) are stored with it (flexorchestrator.assets:AssetRef,find_assets,flexpse_assets,collect_assets,materialize_spec), andSpecRecord.assets/record_hashmake the hash cover them. Results recordmodel_spec_refandoverridesinputs andspec_tag/spec_hash/run_hashmetadata;ResultHandle.spec_tag,.overridesand.spec().Storage contract: the
filekind (FileValue) andstudies();Orchestrator.studies()andregister_hooks().examples/ro_surrogates/: one short script that stores synthetic RO data, emits and stores a tariff-priced flex-pse model’s spec, fits an average energy intensity and a linear power surrogate, and compares the two; run as an integration test (test_examples.py). An opt-in real-Postgres preflight test (FLEXORCH_TEST_PG).Connection modes:
flexorchestrator.connectionwithconnect(),Connection,DBCredentials,credentials_from_env,postgres_dsn,redactandpreflight.Orchestrator()connects by itself (local DuckDB in.flexorch,db=+data_dir=for Postgres, oracquirium_url=), withorch.connection,close()andwithsupport. Postgres logins come fromFLEXORCH_DB_PASSWORD_FILE,FLEXORCH_DB_USER/FLEXORCH_DB_PASSWORDor libpq, never from code; the password reaches the server only asPGPASSWORDin its environment. NewDBAuthError.Run provenance: run metadata records the flex-pse and Acquirium versions, the user, the hooks (results) and the redacted connection.
An opt-in
benchmarktier (pytest -m benchmark -s) with the storage benchmark.The flex-pse
time_setshook returns[]for a model without exactly one TimeBlock, so user models store through the default hooks.flexorchestrator.testing: fake hooks for tests without a solver, and the shared flex-pse specs tests build models from:DEMO_SPEC, plusLOGIC_SPEC,SURROGATE_DISPATCH_SPECandNETWORK_SPECemitted from flex-pse’s round-trip corpus (repo-widedemo_spec/demo_modelfixtures).Project scaffold:
pyproject.toml, black/ruff/import-linter config and pre-commit hooks matching flex-pse, pytest tier markers.