Stage 4 · Connect your engine
Build an adapter step by step
Seven steps from an empty module to the first run of DeltaRecon with your engine. For each part of the protocol you see what you program: what you are given, what you give back and what you report. A part to unfold shows beside it how the connection of the reference model does it.
-
Step 1 of 7
Write the class and what the engine says about itself
Your connection, the adapter, is a class in a Python module. The module lies in a folder of your choice; it need not be a part of DeltaRecon. The protocol is the file
degelmann/deltarecon/protocol.py. It needs the standard library of Python alone, so your module can import the types of the protocol from there:StageDeclaration,DomainReference,RevisionandHistory, the errorsRejection,UsageErrorandModelPointFailure, and the constantSCRATCH_PREFIX.Your module needs two classes: that of the engine, with four statements and seven operations (steps 1 to 3 and 5), and a small one for an opened release (step 4).
This page goes through each part on its own. For each part you see its signature from the protocol, what DeltaRecon hands to you, what you give back and which errors you report. A part to unfold shows how the connection of the reference model does it, with lines of
degelmann/deltarecon/engines/reference_model.py.- protocol.py the protocol
- engines/reference_model.py the connection of the reference model
The two files this page reads from: what each part has to do, and how the reference model does it.
Begin with this skeleton. It holds both classes with every part of the protocol; each operation is still to be written and raises
NotImplementedErroruntil then. Save it asmy_engine.pyin a folder of your choice; in step 6 you then namemy_engine:MyEngine. The names of the two classes and of the file are a free choice."""The connection of my engine to DeltaRecon.""" import tempfile from contextlib import contextmanager from pathlib import Path from degelmann.deltarecon.protocol import (SCRATCH_PREFIX, DomainReference, History, ModelPointFailure, Rejection, Revision, StageDeclaration, UsageError) class MySession: """One opened release: one state of the model (step 4).""" time_basis = "" # the name of the time basis quantities = [] # (name, unit) of each quantity, in the order of the result columns def model_point_ids(self): raise NotImplementedError # the id of every model point def project(self, model_point_id): raise NotImplementedError # the periods of one model point, with one value per quantity def parameters(self): raise NotImplementedError # the parameters of the release # Optional: project_many(self, model_point_ids) and # project_target(self, model_point_ids, quantities, periods). class MyEngine: """The engine (steps 1 to 3 and 5).""" stages = {} # each stage with its domain reference and its quantities realisations = frozenset() # the kinds of change the engine can apply determines = frozenset() # the kinds of reference one revision fixes holdable = {} # the kinds the engine can hold, each with the classes of its paths def __init__(self, workers=None): self.workers = workers # the number of worker processes, or None def repositories_folder(self, given): raise NotImplementedError # the folder given, else the default of the engine def describe(self, stage, label, revision, options, repositories, input_revision=None): raise NotImplementedError # the release identity of a revision def resolve(self, stage, release, repositories): raise NotImplementedError # check that the release can be restored; give nothing back def input_revision(self, release): raise NotImplementedError # the revision the release takes its input data from @contextmanager def open(self, stage, release, enabled, manifest_dir, repositories, hold=frozenset()): # restore the state in a new folder of the temporary folder whose # name begins with SCRATCH_PREFIX, apply the enabled changes, # and hand out the opened release raise NotImplementedError with tempfile.TemporaryDirectory(prefix=SCRATCH_PREFIX) as scratch: yield MySession() def history(self, older, newer, repositories): raise NotImplementedError # the revisions between two releases, as a History def state_release(self, base, revision, hold, repositories): raise NotImplementedError # the release identity of the state after a revisionThe cards below go through the parts in the order of the steps. The class
MySessionat the top of the skeleton belongs to step 4.Call the class
__init__def __init__(self, workers: int | None = None):DeltaRecon calls your class with the number of worker processes as its one, optional argument. The signature is that of the reference model; your class takes the same argument.
You are given
workers: no argument when the command names no--workers, so give the parameter a default such asNone; the numberNwith--workers N; and 1 forrequestandderive, which project no model point.
You program
Keep the number when your engine can project model points in several processes. Without an argument your engine decides itself; DeltaRecon does not read the variable
DELTARECON_WORKERS. An engine that has no use for worker processes accepts the argument and ignores it.How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 1007 to 1009 · v0.2.0def __init__(self, workers: int | None = None): """``workers`` is the number of worker processes of a session, see :func:`worker_count`.""" self.workers = worker_count(workers)The reference model keeps the number. Without an argument
worker_counttakes the number that the variableDELTARECON_WORKERSnames, else one process per processor.The stages your engine offers
stagesstages: Mapping[str, StageDeclaration]An attribute of the class: one entry per stage, under the name of the stage. A stage is one kind of result that your engine computes, with fixed quantities.
You set
- The key is the name of the stage, which the request and the option
--stagename. - The value is a
StageDeclaration(domain_reference, quantities). domain_referenceis aDomainReference(id, version): the reference to the domain reference of the stage, the text that says what its quantities, their units and signs, and the time basis mean. Both members are strings of your choice that are not empty;versionchanges only when the text changes meaning.quantitiesare the names of the quantities in the order of that text.
What DeltaRecon does with it
DeltaRecon accepts a request only for a stage named here. It checks the names of the quantities that an opened release declares (step 4) against the names here, and it writes the reference into every response of the stage.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 997 to 1005 · v0.2.0class ReferenceModel: """The engine of the stage ``liability_cashflow``: modelx with the model ``RLV_DE_S``, computed through its export or through modelx, as the engine version names.""" # The stage of the domain reference of the pack, under the pair the pack reserves for it. stages = {STAGE: StageDeclaration(LIABILITY_CASHFLOW, tuple(STAGE_QUANTITIES[STAGE]))} realisations = frozenset({changes_contract.TEXT_PATCH, changes_contract.REVISION}) determines = DETERMINED_KINDS holdable = {"input_data": frozenset({"data"})} # the model point table, the class ``data``The four statements of the reference model: one stage with its domain reference and its quantities; two kinds of change, a text patch and a revision; the three kinds of reference that one revision fixes, namely code, parameters and input data; and the input data as the one kind it can hold.
The reference model offers one stage,
liability_cashflow. Its domain reference is the filecontracts/v3/domain/liability_cashflow.mdof the repository.The kinds of change it can apply
realisationsrealisations: frozenset[str] # the realisation types of a change the engine can applyAn attribute of the class: a set of names.
You set
revision, when your engine can apply a revision of its own history.walkandsearchneed it: they compute each state as a release with enabled revisions.text_patch, when it can apply a text patch that a change manifest brings along as a file.
What DeltaRecon does with it
Every enabled change that
openis given (step 3) is of a kind that stands here.How the reference model does it
The reference model names both kinds,
text_patchandrevision. The line stands in the excerpt atstages.What one revision fixes
determinesdetermines: frozenset[str] # the kinds of release reference one revision fixesAn attribute of the class: the kinds of reference of a release that one revision of your history determines.
You set
The names of the kinds, as they stand in a release identity (step 2,
describe). For the reference model one revision fixes the code (code_state), the parameters (parameter_set) and the input data (input_data).How the reference model does it
The reference model names the three kinds
code_state,parameter_setandinput_data. The line stands in the excerpt atstages.What it can hold while revisions are applied
holdableholdable: Mapping[str, frozenset[str]]An attribute of the class: the kinds of reference that can stay as the request names them while revisions are applied.
You set
- The key is a kind of reference, for example
input_data. - The value is the set of the classes of the paths that carry this kind, for example
data.
What DeltaRecon does with it
A regression computes the newer revision on the input data of the recorded run. For that DeltaRecon names in
holdthe kinds that are held (steps 3 and 5); each stands here.How the reference model does it
The reference model can hold the input data:
input_datawith the classdata, the model point table. The line stands in the excerpt atstages. -
Step 2 of 7
Find, check and describe a release
DeltaRecon knows no file and no repository of your engine. It names a release by its release identity: a label and a set of references that only your connection reads. In the signatures it is called
releaseand is adictof Python. Four operations belong to it. None of them restores or writes anything.The reference model keeps its history in a Git repository. From such a history a connection needs four things: name a revision, read the files of a revision, list the revisions between two releases on the main line, and say what each of them touches. This step needs the first two, step 5 the other two.
The connection of the reference model reads the repository with a library,
dulwich, and starts no Git program; so none has to be installed. An engine whose history is not in Git answers the same four questions in its own way.- repositories/ the folder of the histories
- delib-history/ the Git repository of the model
What the reference model looks for: the folder of its histories, with its repository in it.
Find the folder of the histories
repositories_folderdef repositories_folder(self, given: Path | str | None) -> Path:Every command that reads a release first asks for the folder that holds what your engine restores a release from, and hands the result as
repositoriesto the other operations.You are given
given: the folder that the option--repositoriesnames, orNonewhen the command names none.
You give back
A
Path: the folder given, else the default of your engine. You read nothing beyond the lookup, and the folder need not exist.How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 411 to 420 · v0.2.0if repositories is not None: return Path(repositories) named = os.environ.get(REPOSITORIES_VARIABLE) if named: return Path(named) here = Path.cwd() for folder in (here, *here.parents): if (folder / REPOSITORIES_FOLDER / CLONE_NAME).is_dir(): return folder / REPOSITORIES_FOLDER return here / REPOSITORIES_FOLDERHow the reference model finds its folder: the one given, else the one a variable names, else the nearest folder
repositories/that holds its repository, in the working directory or in one of the folders above it, and when there is none,repositories/in the working directory.Describe a release by its revision
describedef describe(self, stage: str, label: str, revision: str, options: Mapping[str, str], repositories: Path, input_revision: str | None = None) -> dict:requestcalls this operation and writes its result into the request. It turns a revision, as a person names it, into the complete release identity.You are given
stage: the stage of the request, one ofstages.label: the label that the command is given with--label, for exampleN.revision: the revision as the command is given it with--revision. How a revision is named is your engine’s matter, for example by a hash, a branch or a tag.options: the options of the engine from--engine-option, by key; empty when the command names none.repositories: the folder fromrepositories_folder.input_revision:None, or the identifier of a revision asinput_revisiongives it. The input data are then those of that revision. You take the identifier as it is and do not resolve it again.
You give back
A
dictwith two keys:label, the label given, andreferences, a list of references. Each reference is adictwithkindandvalue, a value that only your connection reads. The list names the state completely: so thatresolveandopenfind it again from it.You report
UsageErrorfor an option that your engine does not take, a key or a value, before you read the revision.Rejection("unknown_reference", …)whenrevisionnames nothing.
How the reference model does it
The reference model writes four references: one each for code, parameters and input data, all with the full hash of the revision, and one for the version of the core of the engine. With
input_revisiononly the reference of the input data names the other revision; that is how a regression describes the state N+1 on the input data of release N.degelmann/deltarecon/engines/reference_model.py lines 1095 to 1097 · v0.2.0path = path_option(options) commit = resolve_revision(revision, repositories) return {"label": label, "references": release_references(commit, input_revision, path)}The three lines of
describe: check the options, find the full hash of the revision, and build the references from it.Check that a release can be restored
resolvedef resolve(self, stage: str, release: dict, repositories: Path) -> None:requestchecks the release identity with it before it writes the request.replay,walkandsearchcheck a recorded release with it before they compute.You are given
stage: the stage of the request, one ofstages.release: a release identity, in the form thatdescribegives back.repositories: the folder fromrepositories_folder.
You give back
Nothing. The operation ends without an error when the release identity names a state of the stage that your engine can restore.
You report
Rejection("unknown_reference", …)when the references cannot be resolved.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 1103 to 1105 · v0.2.0def resolve(self, stage: str, release: dict, repositories: Path) -> None: # One stage: the run admits only a stage of ``stages``, so ``stage`` selects nothing here. self._locate(release, repositories)resolveof the reference model calls_locateand gives nothing back.degelmann/deltarecon/engines/reference_model.py lines 1050 to 1058 · v0.2.0def _locate(self, release: dict, repositories: Path) -> tuple[Path, dict[str, str]]: """The clone and the files of the release state: path and blob id. The files are those of the state commit, with the model point table of the input-data commit in place of its own. """ revision, input_revision = parse_identity(release) clone = find_clone(repositories) return clone, self._files(clone, revision, input_revision)The check of a release. The reference model reads the two revisions from the release identity, finds the repository and reads which files the revision holds.
Name the revision of the input data
input_revisiondef input_revision(self, release: dict) -> str:regressionasks with it on which input data a recorded run was computed, and then has the newer revision described with those input data.You are given
release: a recorded release identity. It may come from another version of the core of your engine.
You give back
A string: the identifier of the revision that the release takes its input data from, in the form that
describetakes asinput_revision.You report
Rejection("unknown_reference", …)whenreleasenames no state that your engine can read.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 1099 to 1101 · v0.2.0def input_revision(self, release: dict) -> str: """The input-data revision of a recorded identity of any engine version, see :func:`recorded_identity`.""" return recorded_identity(release)[1]The reference model reads the revision from the reference of the input data.
If you know Git
The same questions as Git commands
The connection of the reference model runs none of these commands. Each line names the command that answers the same question, and where the connection differs from it.
git rev-parse --verify <name>^{commit}Name a revision: the full hash of the commit that a hash, a branch, a tag orHEADnames. The connection takes no suffix such asHEAD~1.git ls-tree -r <commit>List the files of a revision. The connection refuses a revision that holds anything but regular files.git show <commit>:<path>Read one file of a revision. The connection writes every file of the revision into a new folder, byte for byte; it uses no archive and no working tree of the repository.git log --first-parent --reverse <older>..<newer>List the revisions between two releases on the main line, the oldest first. The connection refuses two revisions of which the older one does not lie on the main line of the newer one.git diff --name-only --no-renames <parent> <commit>Say which paths a revision touches, against the revision before it.git fetch --unshallowComplete a clone whose history is cut off. From such a clone the connection does not read the history, and it names this command. -
Step 3 of 7
Open a release for a run
opendoes the work of a run. It restores the state of the release in a scratch folder, applies the enabled changes there and gives back the opened release. DeltaRecon uses the result in awithstatement of Python and reads the opened release inside it.What the folder of the histories holds is never altered. The scratch folder is created in the temporary folder of the system, and its name begins with
deltarecon-, the value ofSCRATCH_PREFIX.- deltarecon-…/ in the temporary folder
- delib-history/ the restored state
Where the reference model restores a release. The folder is removed when the run is over.
Open a release for a run
opendef open(self, stage: str, release: dict, enabled: list[dict], manifest_dir: Path | None, repositories: Path, hold: frozenset[str] = frozenset()) -> ContextManager[Session]:The operation is a context manager: it hands out the opened release and clears the scratch folder away when the
withstatement ends. The simplest way to write it is a generator with@contextmanagerofcontextlib.You are given
stage: the stage of the request, one ofstages.release: the release identity of the request, in the form ofdescribe.enabled: the enabled changes in the order in which they are applied; empty for a run without changes. Each is an entry of a change manifest, and itsrealisation.typeis a kind ofrealisations.manifest_dir: the folder of the change manifest, which the paths of its files are relative to;Nonewhen no change is enabled.repositories: the folder fromrepositories_folder.hold: the kinds of reference that you take fromreleaseinstead of from the last enabled revision; each is a kind ofholdable. Empty when nothing is held.
You program
- Without enabled changes you restore the state that
releasenames. - For changes of the kind
revisionyou restore the state after the last enabled revision. The kinds inholdyou take fromrelease. - Restore the state in a new folder in the temporary folder of the system whose name begins with
SCRATCH_PREFIX. - You are given a text patch only when your engine names
text_patchunderrealisations. What an entry ofenabledholds and how a text patch is applied is described incontracts/v3/changes.mdof the repository.
You give back
The opened release: an object of your second class (step 4).
You report
Rejection("unsupported_realisation", …)for a revision whosesourceis not the history of your engine, before you restore anything.Rejection("invalid_manifest", …)for a change that does not apply.- Any other error ends the run with the outcome
error.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 1131 to 1135 · v0.2.0foreign = [c["id"] for c in enabled if c["realisation"]["type"] == changes_contract.REVISION and c["realisation"]["source"] != SOURCE] if foreign: raise Rejection("unsupported_realisation", f"The change {foreign[0]} is a revision of another history " f"source than {SOURCE}, which the reference model cannot realise.", change_ids=foreign)First the reference model refuses a revision of another history.
degelmann/deltarecon/engines/reference_model.py lines 1136 to 1147 · v0.2.0clone, files = self._locate(release, repositories) path = release_path(release) revisions = [c["realisation"]["revision"] for c in enabled if c["realisation"]["type"] == changes_contract.REVISION] patches = [c for c in enabled if c["realisation"]["type"] != changes_contract.REVISION] if revisions: # the state after the last enabled revision; the request's state is the base _, input_revision = parse_identity(release) last = revisions[-1] try: files = self._files(clone, last, input_revision if "input_data" in hold else last) except Rejection as rejection: # the request is accepted; the state cannot be restored raise RuntimeError(rejection.message) from NoneThen it determines the files of the state: those of the release of the request, or those of the last enabled revision, with the model point table of the release when the input data are held.
degelmann/deltarecon/engines/reference_model.py lines 1148 to 1158 · v0.2.0with tempfile.TemporaryDirectory(prefix=SCRATCH_PREFIX) as scratch: state = Path(scratch) / CLONE_NAME state.mkdir() # The model point table of the input-data commit lies over the restored tree. export_tree(clone, files, state) if patches: changes_contract.apply_changes(state, patches, manifest_dir) model = _read_model(state / PRODUCT_FOLDER) try: if path == "modelx": yield ReferenceModelSession(model, workers=self.workers, state=state)The reference model creates the scratch folder, writes the files of the revision into it, applies the text patches there, reads the model from it and hands the opened release to the run. The excerpt shows one of the two computation paths of the reference model.
-
Step 4 of 7
Answer the questions of an opened release
The opened release is a second, small class. It stands for one state of the model and answers what a run asks: which model points there are, and the projection of each, with one value per quantity and period. It also gives the parameters of the release, which the record of a run holds.
It has two attributes and three operations. Two further operations are optional.
- results.csv ids, periods, values
- run-record.json the parameters
Two of the files of a run and what they take from the opened release.
The time basis
time_basistime_basis: strAn attribute: the name of the time basis, that is of what a period counts.
You set
A name that the domain reference of the stage explains.
What DeltaRecon does with it
A comparison first puts both runs on projection periods. For the time basis
policy_month, whose periods count from the issue of the contract, it subtracts from every period of a model point the first period that the run gives for it. For any other name it takes the periods as your engine gives them.How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 812 to 814 · v0.2.0class ReferenceModelSession: time_basis = TIME_BASIS quantities = [(name, unit) for name, unit, _, _ in QUANTITIES]The two attributes of the opened release of the reference model.
The quantities
quantitiesquantities: list[tuple[str, str]] # name and unit, in export column orderAn attribute: name and unit of each quantity, in the order of the result columns.
You set
A list of pairs
(name, unit). Each name must be one of the names that your engine names in step 1 understagesfor the stage; DeltaRecon checks that. The order is that of the values thatprojectgives per period, and that of the columns ofresults.csv.How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 210 to 221 · v0.2.0QUANTITIES = ( ("Anzahl Verträge", "policies", "pols_if", ("pols_if",)), ("Bruttobeitrag", "EUR", "prem_gross", ("prem_gross",)), ("Zahlbeitrag", "EUR", "premiums", ("premiums",)), ("Beitragsverrechnung", "EUR", "prem_rebate", ("prem_rebate",)), ("garantierte Todesfallleistung", "EUR", "claims_death", ("claims", "DEATH")), ("garantierter Rückkaufswert", "EUR", "claims_lapse", ("claims", "LAPSE")), ("garantierte Erlebensfallleistung", "EUR", "claims_maturity", ("claims", "MATURITY")), ("Kosten 2. Ordnung ohne Provisionen", "EUR", "expenses", ("expenses",)), ("Provisionen", "EUR", "commissions", ("commissions",)), ("Netto-Cashflow", "EUR", "net_cf", ("net_cf",)), )The quantities of the reference model: name, unit, and where the connection reads each from the model. Names and units become
quantitiesof the opened release, in this order.Give the ids of the model points
model_point_idsdef model_point_ids(self) -> list[str]:Every run first asks which model points the release holds.
You give back
A list of strings: the public id of every model point of the release, in the order of your engine. An id that the release holds several times you give several times; DeltaRecon lets such a model point fail and does not project it.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 871 to 876 · v0.2.0def model_point_ids(self) -> list[str]: with _readable_formula_errors(): return [str(value) for value in self._points()[MODEL_POINT_ID_COLUMN]] def project(self, model_point_id: str) -> list[tuple[int, list[float]]]: return self._project_index(self._index(model_point_id))The ids come from the model point table of the model; the projection of a model point is looked up by its id.
Project one model point
projectdef project(self, model_point_id: str) -> list[tuple[int, list[float]]]:The calculation itself: DeltaRecon calls the operation for every selected model point.
You are given
model_point_id: an id ofmodel_point_ids.
You give back
A list with one entry per period of the model point. Each entry is a pair: the number of the period as an integer, and a list with one value per quantity, in the order of
quantities. The periods follow one another without a gap, there is at least one, and every value is a finite number; otherwise DeltaRecon lets the model point fail.You report
ModelPointFailure(…)when the model point cannot be calculated. The run then ends with the outcomefailed.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 945 to 966 · v0.2.0def _project_index(self, index: int) -> list[tuple[int, list[float]]]: """The periods of the point of row ``index``. Raises :class:`ModelPointFailure`.""" with self._projection(index, "result_cf") as projection: try: frame = projection.result_cf() except Exception as exc: # a modelx FormulaError wraps the cause raise ModelPointFailure(self._failure("result_cf", exc, projection, index)) from None problems = [] for check in CHECKS: try: if not bool(getattr(projection, check)()): problems.append(f"{check} is false") except Exception as exc: problems.append(self._failure(check, exc, projection, index)) if problems: raise ModelPointFailure("; ".join(problems)) try: columns = [[float(value) for value in frame[column]] for _, _, column, _ in QUANTITIES] periods = [int(period) for period in frame.index] except Exception as exc: raise _form_failure("result_cf", exc) from None return [(period, [column[row] for column in columns]) for row, period in enumerate(periods)]The projection of one model point in the reference model: compute the result of the model, evaluate the built-in checks of the model, and put together the values of each period in the order of the quantities. An error, or a check that is false, becomes a
ModelPointFailure.Give the parameters
parametersdef parameters(self) -> list[dict]:Every run writes the parameters of the release into its record.
You give back
A list with one
dictper parameter of the release, in the form in which the record of a run holds them. The order of the parameters and of the rows of a table carries no meaning.- A single value:
name,typewith the valuescalar, andvalue. - A table:
name,typewith the valuekeyed_table,key_columns,value_columnsandrows; each row haskeyandvalues.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 972 to 994 · v0.2.0def _parameters(self) -> list[dict]: inventory: dict[str, dict] = {} def add(parameter: dict) -> None: if parameter["name"] in inventory: raise RuntimeError(f"two parameters of the model have the name {parameter['name']}") inventory[parameter["name"]] = parameter for space in (self._model.Projection, self._model.Data): for name, value in space.refs.items(): if not name.startswith("_") and name not in NOT_A_PARAMETER and _is_scalar(value): add({"name": name, "type": "scalar", "value": _plain(value)}) for name in PARAMETER_TABLES: frame = getattr(self._model.Data, name)() value_columns = [str(c) for c in frame.columns if c not in NOT_A_VALUE_COLUMN] rows = [] for key, values in zip(frame.index, frame[value_columns].itertuples(index=False, name=None)): key = list(key) if isinstance(key, tuple) else [key] rows.append({"key": [_plain(k) for k in key], "values": [_plain(v) for v in values]}) add({"name": name, "type": "keyed_table", "key_columns": [str(c) for c in frame.index.names], "value_columns": value_columns, "rows": rows}) return [inventory[name] for name in sorted(inventory)]The reference model collects the single values of the model and its tables and gives them back sorted by name.
Project several model points at once
project_manyoptionaldef project_many(self, model_point_ids: list[str]) -> list:Without this operation DeltaRecon projects model point by model point with
project. With it your engine can spread the work itself, for example over several processes. The protocol describes it in a comment; the signature is that of the reference model.You are given
model_point_ids: the ids of the model points to compute.
You give back
A list with one entry per id, in the order given: the periods as
projectgives them, or theModelPointFailurethatprojectwould raise, as an object in the list. Any other error is raised.How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 878 to 884 · v0.2.0def project_many(self, model_point_ids: list[str]) -> list: """The outcome of each id in the given order: its periods or its :class:`ModelPointFailure`. The parent maps each id to its row; the workers project by row and return the periods or the message of a failure, so a message is the same on every worker count. """ return self._project_rows(model_point_ids, "_project_index")project_manyof the reference model spreads the model points over the worker processes.Project a target only
project_targetoptionaldef project_target(self, model_point_ids: list[str], quantities: list[str], periods: tuple[int, int] | None) -> list:Without this operation your engine cannot compute a run on a target alone, which a search with
--target-onlyneeds. The protocol describes it in a comment; the signature is that of the reference model.You are given
model_point_ids: the ids of the model points to compute.quantities: names of quantities that the opened release declares, in its order.periods: a pair(first, last)in projection periods, orNonefor every period. Projection period 0 is the period of the valuation date of the model point.
You give back
A list with one entry per id, in the order given: a
ModelPointFailure, or the periods of the window, with one value per name ofquantities. The window reaches from the period of the valuation date plusfirstto that period pluslast, at most to the last period of the model point. A model point whose window is empty has no period.You program
Evaluate no check of the model here: a model point fails only when a value of the target cannot be calculated.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 886 to 891 · v0.2.0def project_target(self, model_point_ids: list[str], quantities: list[str], periods: tuple[int, int] | None) -> list: """The outcome of each id in the given order: the periods of its target window, with one value per name of ``quantities``, or its :class:`ModelPointFailure`; see "Target-only runs".""" return self._project_rows(model_point_ids, "_project_target_index", tuple(quantities), None if periods is None else tuple(periods))project_targetof the reference model spreads the model points over the worker processes asproject_manydoes, and computes for each model point the values of the target alone. -
Step 5 of 7
List the history between two releases
walkandsearchcompute the states between two releases one after the other. For that they need the history between the two as single revisions, and a name for the state after each.derivewrites the change manifest from the same history.What the main line is, your engine defines; in Git it is the chain of first parents.
- model_point_table.csv data
- mort_table.csv parameter
- RLV_DE_S/ code
Three paths in the repository of the reference model. A revision carries the classes of all paths it touches.
List the revisions between two releases
historydef history(self, older: dict, newer: dict, repositories: Path) -> History:derive,walkandsearchcall this operation. It also reads release identities that another version of the core of your engine recorded.You are given
olderandnewer: the release identities of two releases, the older one first. Which references name the revision is your engine’s matter.repositories: the folder fromrepositories_folder.
You give back
A
History(source, older, newer, revisions):source: the kind of history, a name in small letters:git, or a name that your engine chooses. Withgitthe main line is the chain of first parents.olderandnewer: the identifiers of the two revisions.revisions: every revision on the main line after the older one, up to and including the newer one, the oldest first. Empty when both releases name the same revision.
Each revision is a
Revision(id, message, classes): its full identifier; its message as it was written, with the line breaks at its end; and the classes of the paths it touches against the revision before it, a set ofdata,parameterandcode. The set is empty when the revision touches none of these.You report
Rejection("unknown_reference", …)when a release identity names no revision that your engine can read.Rejection("unrelated_revisions", …)when the older revision does not lie on the main line of the newer one.UsageErrorwhen the history at hand is cut off.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 1119 to 1125 · v0.2.0between = line[:line.index(old)][::-1] # after the older commit, oldest first messages = log_messages(clone, between) revisions = [] for parent, revision, message in zip([old] + between, between, messages): classes = {path_class(path) for path in touched_paths(clone, parent, revision)} - {None} revisions.append(Revision(revision, message, frozenset(classes))) return History(SOURCE, old, new, tuple(revisions))The end of
historyof the reference model: the revisions after the older one, the oldest first, each with its message and with the classes of the paths it touches against the revision before it.degelmann/deltarecon/engines/reference_model.py lines 528 to 537 · v0.2.0def path_class(path: str) -> str | None: """The class of a path of the repository: ``data``, ``parameter``, ``code``, or none.""" if path == MODEL_POINT_PATH: return "data" if path.startswith(f"{PRODUCT_FOLDER}/{MODEL_NAME}/"): return "code" folder, _, name = path.rpartition("/") if folder == PRODUCT_FOLDER and name.endswith(".csv"): return "parameter" return NoneHow the reference model classes a path: the model point table is data, a file of the model is code, another CSV file of the product folder is a parameter, and every other path has no class.
Name the state after a revision
state_releasedef state_release(self, base: dict, revision: str | None, hold: frozenset[str], repositories: Path) -> dict:walkandsearchwrite with the result the request for each state they compute.You are given
base: a recorded release identity; it may come from another version of the core of your engine.revision: the identifier of a revision ofhistory, orNonefor the state ofbaseitself.hold: the kinds of reference that come frombaseinstead of from the revision; each is a kind ofholdable.repositories: the folder fromrepositories_folder.
You give back
The release identity of the state after
revision, in the form ofdescribe, as your engine would record it today: with the label ofbase, the kinds ofholdfrombaseand the others from the revision. Nothing is restored and nothing is written.You report
Rejection("unknown_reference", …)whenbasenames no state that your engine can read.
How the reference model does it
degelmann/deltarecon/engines/reference_model.py lines 1082 to 1086 · v0.2.0state, input_revision = recorded_identity(base) if revision is not None: state, input_revision = revision, (input_revision if "input_data" in hold else revision) return {"label": base["label"], "references": release_references(state, input_revision, release_path(base))}The lines of
state_release: the state is that of the revision, and the input data stay those of the recorded release when they are held. -
Step 6 of 7
Let DeltaRecon find your class
Seven commands load an engine:
request,run,replay,regression,derive,walkandsearch. Each takes the engine from the first of three places that names one, and looks for its module in a folder that you name.When a selection cannot be loaded, the command says in one line what is wrong, writes nothing and ends with exit status 2. This holds for a folder that is no folder, a selection that is not of the form
<module>:<class>, a module that is not found, a name in the module that is no class, and a class that does not take the number of worker processes as its argument.- <folder>/ named by --engine-path
- <module>.py the module of --engine
The folder and the module of your connection. Your class stands in the module.
-
The option of the command
--engine <module>:<class>Names the module and, in it, the class of your connection. The name of the module is absolute: it does not begin with a dot.
-
The environment variable
DELTARECON_ENGINEUsed when the command names no engine. An empty variable counts as not set.
-
Neither
DeltaRecon takes the reference model.
-
The folder of your module
--engine-path <folder>DeltaRecon puts this folder first on the import path of Python before it loads the module, so that a module in it can be named.
-
The variable for that folder
DELTARECON_ENGINE_PATHRead only when the command gives no
--engine. With--engine, only--engine-pathadds a folder.
Known limits
Four faults that end in a traceback
In this release DeltaRecon answers four faults of a connection with a traceback of Python and exit status 1, not with a message of its own. That is a limit of this release, not an error in how you call the command. The last line of the traceback names the cause.
The module of your connection raises another error than a failed import while it is loaded, for example a syntax error.
Your class raises an error of its own when it is called with the number of worker processes.
Your class lacks a member of the protocol.
The history that your connection gives breaks the protocol: its kind is not a name in small letters, its revisions do not lead from the older to the newer release, or a revision carries a class other than data, parameter and code.
-
Step 7 of 7
Run DeltaRecon with your engine for the first time
Now DeltaRecon computes one release with your engine.
requestwrites down what is to be computed, andruncomputes it. Both name your engine with the two options of step 6.Windows
Open PowerShell in the package folder.
Linux
Open a terminal and change into the package folder.
Put your own words in the places between
<and>:Windows PowerShell
.\deltarecon.cmd request --revision <revision> --stage <stage> --label <label> --run-id <run-id> --output <output>\request.json --engine <module>:<class> --engine-path <folder> .\deltarecon.cmd run <output>\request.json --engine <module>:<class> --engine-path <folder>Linux
./deltarecon request --revision <revision> --stage <stage> --label <label> --run-id <run-id> --output <output>/request.json --engine <module>:<class> --engine-path <folder> ./deltarecon run <output>/request.json --engine <module>:<class> --engine-path <folder><revision>is a revision as your engine names it.<stage>is a stage that your engine supports; you may leave--stageout when it supports one stage only.<label>and<run-id>are names that you give to this release and to this run.<output>is a folder for the files of the run. When your engine does not find the folder of its histories by itself, add--repositorieswith that folder to both commands.- request.json what is to be computed
- response.json how the run ended
- results.csv the results
- run-record.json the record
What the two commands write.
requestprints the path of the request it wrote.runprintsoutcome: succeeded, the number of model points, the number of rows of the results and their SHA-256, and the paths of the three files it wrote. Both commands end with exit status 0. When a command ends with a traceback, look at the known limits in step 6.With a second run, of another revision, you can compare two results.
regression,replay,walkandsearchwrite their compare requests themselves and run them. You write a compare request yourself only forcompare, the comparison of two runs by hand. It is a JSON file with these members:-
The kind of document
documentis alwayscompare_request. -
The version of the contracts
contract_version: the version the request is written for,3.3in this release. -
The stage
stage: the stage of both runs. -
An id
compare_id: a name that you give to this comparison. -
The two responses
left.responseandright.response: for each run the path of itsresponse.jsonand the SHA-256 of that file in small hexadecimal digits. The path is relative to the folder of the request, with forward slashes and without... By convention the left run is the older one. -
The tolerance
tolerance.per_quantity: the tolerance profile. It may be empty; every quantity is then compared exactly.
The smallest compare request:
{ "document": "compare_request", "contract_version": "3.3", "stage": "<stage>", "compare_id": "<id>", "left": { "response": { "path": "<older>/response.json", "sha256": "<sha256>" } }, "right": { "response": { "path": "<newer>/response.json", "sha256": "<sha256>" } }, "tolerance": { "per_quantity": {} } }comparetakes the path of this file and nothing else. “Single commands” describes what it writes.
With the first run of your own engine, stage 4 is complete.