httk.core¶
Public core APIs for loading, reporting, project anchors, and registration.
Importing this package discovers installed capability modules and exposes their registered readers, writers, adapters, and related public APIs.
The deliberate public surface contains 90 names.
Submodules¶
- httk.core.building
- httk.core.citations
- httk.core.cli
- httk.core.converting
- httk.core.crypto
- httk.core.data_records
- httk.core.dataset_loader
- httk.core.datasets
- httk.core.datastream
- httk.core.digests
- httk.core.docs
- httk.core.entry_provider
- httk.core.entry_types
- httk.core.exactmath
- httk.core.fetching
- httk.core.files
- httk.core.loading
- httk.core.memguard
- httk.core.optimade
- httk.core.plugins
- httk.core.precision
- httk.core.project
- httk.core.property_definitions
- httk.core.provenance
- httk.core.register
- httk.core.report
- httk.core.saving
- httk.core.schema_check
- httk.core.services
- httk.core.storage
- httk.core.userdirs
- httk.core.validation
- httk.core.vectors
- httk.core.views
Attributes¶
Classes¶
Carry invocation context to a registered top-level command. |
|
Store one canonical JSON value of one declared property. |
|
Logical entry family for served |
|
Lazy loader for httk dataset files, resolved only when data is first accessed. |
|
Read-only attribute and mapping view over a |
|
Describe header metadata extracted from a structured JSON-LD document. |
|
Describe one published dataset independently of a transport or provider. |
|
Describe one retrievable representation of a dataset. |
|
Store one |
|
A view presenting an underlying data streaming backend via an io.IOBase-like API. |
|
A view presenting an underlying data streaming backend via a URL string. |
|
A decompression codec for a single container format. |
|
An explicit network-consent value carrying a URL and optional timeout for lazy consumers, which resolve it through the existing |
|
A view presenting an underlying data streaming backend via the full io.TextIOBase API, which is a superset of TextstreamAPI. |
|
A view presenting an underlying data streaming backend via a URL string. |
|
Supplies described, queryable entry types as plain JSON-able records. |
|
One related entry of a record, as reported by |
|
The |
|
The |
|
The |
|
Logical entry family for served |
|
Store one OPTIMADE |
|
An immutable OPTIMADE entry-type definition. |
|
An immutable wrapper around one full OPTIMADE property definition. |
|
A curation |
|
One workflow execution with loose provenance edges. |
|
Store one loose labeled reference from a run to another entry. |
|
Logical entry family for served |
|
Describe one service independently of its publication transport. |
|
Store one |
|
Field marker: exclude the field from content identity. |
|
Field marker: request a single-column index on this field's column(s). |
|
Field marker: relationship metadata for a reference or list-of-storable field. |
|
Class-level relationship declaration: each stored row expresses one FROM→TO relationship. |
|
Field marker: fixed or variable shape for a vector-valued field. |
|
Field marker: the field exists on the dataclass but is not stored. |
|
Optional class-level storage declaration for a storable dataclass. |
|
Field marker: request a unique index on this field's column(s). |
|
A derived property that a storage layer stores and makes queryable. |
|
Represents the fractional number |
|
Immutable exact-rational vector that is also its own vector backend. |
|
Same as |
|
A scalar |
|
An immutable exact tensor over the squarefree-radical field |
|
Abstract base class to be subclassed into classes that keep track of alternative |
|
A set of views allow manipulating data and state of a backend through different interfaces. |
Functions¶
|
Register one or more references under a human-readable explanation. |
Return the registered codec names, in registration order. |
|
|
Register (or replace) a codec under its |
|
Fetch a URL as an OPTIMADE entry or a registered file format. |
|
Return whether |
|
Load |
|
Load multiple sources lazily, preserving input order. |
|
Load |
|
Return the precision of a set of values taken together: the coarsest of them. |
|
Return the absolute precision implied by how a number was written, or |
Return the registered database-specific property-name prefixes. |
|
|
Register a database-specific OPTIMADE property-name |
|
Return one of httk-core's vendored standard OPTIMADE entry types. |
|
Register a lazy top-level httk command. |
Return registered entry-provider names. |
|
|
Register a lazy entry-family class reference without importing it. |
|
Register an |
|
Register a lazy record-class reference and optional family and definition IRI. |
|
Register one lazy typed binding, selected only by exact definition IRI. |
|
Register one lazy adapter for each neutral payload format in |
|
Register one lazy serializer for a neutral payload format tag. |
|
Register a reader under one or more file |
|
Register a writer under one or more extensions and/or exact basenames. |
|
Load and verify a registered entry-type definition resource. |
|
Load and verify a registered property definition resource. |
|
Register one resource for an entry-type definition IRI. |
|
Register one resource for a property definition IRI. |
|
Return whether |
|
Save |
|
Return the lowercase SHA-256 content identity of |
Return whether the optional numpy dependency is available for the numeric helpers. |
|
|
Present |
|
Convert a single scalar value to a plain |
|
Coerce |
|
Coerce |
|
Shed the httk View wrapper from |
|
Given a Backend or a View, return the most raw representation possible, i.e., if the backend has an internal representaion - |
Package Contents¶
- httk.core.register_citation(*, applies_to, references)[source]¶
Register one or more references under a human-readable explanation.
References are normalized on registration and duplicate references under the same explanation are retained only once. The registration is visible through
credits, allowing imported modules to contribute their citation requirements as they are loaded.- Parameters:
applies_to (str) – Human-readable explanation of when the references apply.
references (httk.core.entry_types.Reference | collections.abc.Mapping[str, Any] | collections.abc.Sequence[httk.core.entry_types.Reference | collections.abc.Mapping[str, Any]]) – One reference, mapping, or sequence of references to register.
- Raises:
TypeError – If
referencesis not a reference, mapping, or sequence of references.ValueError – If
applies_tois invalid orreferencesis empty.
- class httk.core.CLIContext[source]¶
Carry invocation context to a registered top-level command.
- Parameters:
program – Program name used in command output and help.
cwd – Working directory selected for the command invocation.
- cwd: pathlib.Path¶
- class httk.core.DataRecord[source]¶
Store one canonical JSON value of one declared property.
value_jsonis canonical JSON, with sorted object keys, compact separators, and no non-finite numeric values.valuedecodes it on access;value_numberexposes finite numeric values for numeric queries. The immutable and timestamp metadata fields are excluded from content identity.- Parameters:
definition_id – The property definition IRI for the value.
name – The property name.
value_json – The canonical JSON representation of the value.
immutable_id – An optional provider-specific immutable identifier.
last_modified – The optional timezone-aware metadata timestamp.
- immutable_id: Annotated[str | None, IdentitySkip()] = None¶
- last_modified: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- property value: Any¶
Decode and return the stored property value.
- property value_number: float | None¶
The decoded numeric value, stored as a numeric SQL query column.
- classmethod from_value(definition_id, name, value, *, immutable_id=None, last_modified=None)[source]¶
Encode a value canonically and construct its data record.
- Parameters:
definition_id (str) – The property definition IRI for the value.
name (str) – The property name.
value (Any) – The JSON value to encode.
immutable_id (str | None) – An optional provider-specific immutable identifier.
last_modified (datetime.datetime | None) – The optional timezone-aware metadata timestamp.
- Returns:
A data record containing the canonical JSON value.
- Raises:
TypeError – If the value contains an unsupported object.
ValueError – If the value is circular or contains a non-finite number, or if
definition_idornameis invalid orlast_modifiedis not timezone-aware.
- Return type:
Self
- classmethod create(obj)[source]¶
Coerce a mapping or existing record into a
DataRecord.- Parameters:
obj (DataRecord | Mapping[str, Any]) – A data record instance or field mapping.
- Returns:
The existing or newly constructed data record.
- Raises:
TypeError – If
objis neither a data record nor a mapping.ValueError – If the mapping has unknown or invalid fields.
- Return type:
Self
- class httk.core.DataRecordEntry[source]¶
Logical entry family for served
DataRecordrecords.This family is not itself storable; store a
DataRecorddirectly.- type = '_httk_records'¶
- definition_id = 'https://schemas.httk.org/defs/v0.1/entrytypes/records'¶
- class httk.core.DatasetLoader(identifier, source, decode_object=None, **hints)[source]¶
Lazy loader for httk dataset files, resolved only when data is first accessed.
A
DatasetLoaderis a declare-time placeholder: constructing it records its arguments and performs no I/O. The source is read the first timedata,meta, orindexis accessed. Files are either plain JSON (any JSON value is exposed asdatawithmeta/indexset toNone) or a structured JSON-LD document (with@context, header fields,data, and optionalindicies) whose header is exposed viameta, datasets viadata.<name>, and lookup indices viaindex.<name>.Loaders that share an
identifierdeduplicate through a class-level registry: the first load wins, and later loaders reusing that identifier return the same result while theirsourceanddecode_objectarguments are ignored. Keeping identifiers unique is the caller’s responsibility. Not thread-safe.Format is resolved from the source name after stripping any compression suffix: a
.jsonname (e.g.data.jsonordata.json.gz) is parsed as JSON; any other recognizable suffix raisesValueError; a source with no determinable name is treated as JSON. Compression is handled transparently by the stream layer, so.json.gzand similar load directly. A plain.sqlarfile is an alternative structured JSON-LD representation. It containsheader.json, optionalindicies.json, scalardata/{D}.jsonmembers, and list members atdata/{D}/{i:05d}.jsonordata/{D}/{i:05d}/{field}.json. Sqlar sources require a real filename because their immutable SQLite connection is retained for the lifetime of the cached load; they cannot be compressed, streamed, or loaded from content. Empty list datasets and empty dictionary records cannot be represented and are rejected by the writer; individual members are limited to 256 MiB. Sqlar-backed record/sequence/data views (andDatasetLoaderRecord) pickle by materializing to plain containers; live iterators over them are not picklable. Astr/Pathsource is interpreted as a filename unless its scheme marks it as a URL (http,https,ftp,file); bare network URLs are refused at read time, so passkind="url"or aurllib.request.Request. Passkind="content"for literal content orkind="filename"to force a filename interpretation.Example
symmetry_basics = DatasetLoader(“symmetry_basics”, “data/spacegroup_symbols.json”) spacegroups = symmetry_basics.data.spacegroups # first access triggers the load
- Parameters:
identifier (str) – The deduplication key for this load.
source (httk.core.datastream.TextstreamLike) – The filename, URL-like stream, request, or literal content to read.
decode_object (DecodeObjectCallback | None) – An optional callback for JSON-LD objects identified by context URLs.
**hints (Any) – Stream interpretation hints such as
kind.
- property data: Any¶
Return the lazily loaded dataset value.
- property meta: DatasetMeta | None¶
Return structured-document metadata, or
Nonefor plain JSON.
- property index: DatasetLoaderRecord | None¶
Return structured-document lookup indices, or
Nonewhen absent.
- class httk.core.DatasetLoaderRecord(data)[source]¶
Bases:
collections.abc.Mapping[str,Any]Read-only attribute and mapping view over a
Mapping[str, Any].Top-level keys are reachable both as attributes (
record.name) and as items (record["name"]); the wrapped values are the plain parsed JSON and are not themselves wrapped. Supports iteration over keys,len(),in, andkeys().- Parameters:
data (collections.abc.Mapping[str, Any]) – The parsed top-level object exposed by this view.
- class httk.core.DatasetMeta[source]¶
Describe header metadata extracted from a structured JSON-LD document.
- Parameters:
context – The raw document context.
id – The document identifier, if present.
type – The document type, if present.
header – Remaining top-level header fields.
dataset_ids – Dataset names mapped to their identifiers.
fields – Dataset names mapped to their field property URLs.
- type_: str | None¶
The document
@type, orNoneif absent (trailing underscore avoids the builtintype).
- class httk.core.Dataset[source]¶
Describe one published dataset independently of a transport or provider.
idandpublisher_idare absolute IRIs. The remaining fields are human-readable metadata and retain their supplied text exactly.- Parameters:
id – The dataset’s absolute IRI.
title – The dataset’s human-readable title.
description – A non-empty description of the dataset.
publisher_id – The publisher’s absolute IRI.
publisher_name – The publisher’s human-readable name.
distributions – The dataset’s retrievable representations.
- distributions: tuple[DatasetDistribution, Ellipsis] = ()¶
- classmethod create(obj)[source]¶
Coerce a mapping or existing dataset into a
Dataset.- Parameters:
obj (Dataset | Mapping[str, Any]) – A dataset instance or a mapping with exactly the dataset fields.
- Returns:
The existing or newly constructed dataset.
- Raises:
TypeError – If
objis neither a dataset nor a mapping.ValueError – If the mapping has missing, unknown, or invalid fields.
- Return type:
Self
- class httk.core.DatasetDistribution[source]¶
Describe one retrievable representation of a dataset.
Identifier and vocabulary fields must be well-formed absolute IRIs.
access_urlmay instead be a root-relative URL for later resolution by a serving application.byte_sizeis a non-negative integer, andsha256is a lowercase hexadecimal digest.- Parameters:
id – An optional identifier for this representation.
access_url – An optional URL from which the representation can be retrieved.
media_type_iri – An optional IRI identifying the media type.
format_iri – An optional IRI identifying the representation format.
byte_size – The optional representation size in bytes.
sha256 – The optional lowercase SHA-256 digest.
- classmethod create(obj)[source]¶
Coerce a distribution instance or exact-field mapping.
- Parameters:
obj (DatasetDistribution | Mapping[str, Any]) – A distribution instance or a mapping of distribution fields.
- Returns:
The existing or newly constructed distribution.
- Raises:
TypeError – If
objis neither a distribution nor a mapping.ValueError – If the mapping has unknown or invalid fields.
- Return type:
Self
- class httk.core.DatasetRecord[source]¶
Bases:
DatasetStore one
Datasetusing the core dataset storage contract.- Parameters:
id – The dataset’s absolute IRI.
title – The dataset’s human-readable title.
description – A non-empty description of the dataset.
publisher_id – The publisher’s absolute IRI.
publisher_name – The publisher’s human-readable name.
distributions – The dataset’s retrievable representations.
- classmethod create(obj)[source]¶
Coerce a dataset record, neutral dataset, or field mapping.
- Parameters:
obj (DatasetRecord | Dataset | Mapping[str, Any]) – A dataset record, neutral dataset, or exact-field mapping.
- Returns:
The existing or newly constructed dataset record.
- Raises:
TypeError – If
objis not a dataset or mapping.ValueError – If the mapping has unknown, missing, or invalid fields.
- Return type:
Self
- class httk.core.BytestreamFileView(obj, **hints)[source]¶
Bases:
httk.core.datastream.bytestream_view.BytestreamView,io.IOBase,httk.core.datastream.bytestream_api.BytestreamAPIA view presenting an underlying data streaming backend via an io.IOBase-like API.
- Parameters:
obj (httk.core.datastream.bytestream_like.BytestreamLike) – Byte-stream source to present through the file API.
**hints (Any) – Backend-selection and compression hints.
- unwrap()[source]¶
Return the raw representation of the wrapped backend.
- Returns:
The backend’s most raw available representation.
- Return type:
Any
- writable()[source]¶
Report that the view does not support writing.
- Returns:
Always
False.- Return type:
- seekable()[source]¶
Report whether the backend supports seeking and telling.
- Returns:
Whether both operations are available.
- Return type:
- flush()[source]¶
Flush the backend when it provides flushing.
- Raises:
ValueError – If the view is closed.
- read(size=-1)[source]¶
Read up to
sizebytes, or all remaining bytes whensizeis negative.- Parameters:
size (int | None) – Maximum number of bytes to read;
Nonealso means all remaining bytes.- Returns:
The bytes read from the stream.
- Raises:
ValueError – If the view is closed.
- Return type:
- readline(size=-1)[source]¶
Read one line, optionally limited to
sizebytes.- Parameters:
size (int | None) – Maximum number of bytes to read;
Nonemeans no limit.- Returns:
The line read, including its newline when present.
- Raises:
ValueError – If the view is closed.
- Return type:
- readlines(hint=-1)[source]¶
Read lines until EOF or until the accumulated size reaches
hint.- Parameters:
hint (int) – Approximate minimum number of bytes to collect, or a negative value for no limit.
- Returns:
The lines read from the stream.
- Raises:
ValueError – If the view is closed.
- Return type:
- seek(offset, whence=io.SEEK_SET)[source]¶
Move the stream position and discard buffered line data.
- Parameters:
- Returns:
The resulting absolute stream position.
- Raises:
ValueError – If the view is closed.
io.UnsupportedOperation – If the backend is not seekable.
- Return type:
- tell()[source]¶
Return the logical stream position before buffered line data.
- Returns:
The logical absolute stream position.
- Raises:
ValueError – If the view is closed.
io.UnsupportedOperation – If the backend does not support telling.
- Return type:
- detach()[source]¶
Reject detaching because the view owns its backend interface.
- Raises:
io.UnsupportedOperation – Always, because detaching is unsupported.
- type httk.core.BytestreamLike = bytestream_backend.BytestreamBackend | bytestream_view.BytestreamView | io.IOBase | io.BytesIO | bytes | bytearray | str | pathlib.Path | urllib.request.Request[source]¶
- class httk.core.BytestreamURLView(obj, **hints)[source]¶
Bases:
httk.core.datastream.bytestream_view.BytestreamView,strA view presenting an underlying data streaming backend via a URL string. This view is mostly useful for providing a URL to functions that will open it. Note: this view is not lazy (this is impossible for views inheriting str, since str is immutable).
Raises TypeError if created with a streaming data source that does not come with a URL.
- Parameters:
obj (httk.core.datastream.bytestream_like.BytestreamLike) – Byte-stream source whose URL should be presented.
**hints (Any) – Backend-selection, consent, timeout, and compression hints.
- Raises:
TypeError – If the source has no URL.
- class httk.core.CompressionCodec[source]¶
A decompression codec for a single container format.
A codec is an orthogonal layer below the datastream backends: it turns a compressed binary stream into an uncompressed binary stream, independently of where the compressed bytes come from (a filename, an open file, raw bytes, or a remote response).
- Parameters:
name – Canonical name used to select the codec explicitly.
extensions – Filename suffixes that identify the codec.
magics – Leading byte signatures used to detect the codec.
open_stream – Function that wraps compressed bytes for reading.
- extensions: tuple[str, Ellipsis]¶
Recognized filename suffixes including the leading dot (e.g.
(".gz",)).
- magics: tuple[bytes, Ellipsis]¶
Leading magic-byte signatures; an empty tuple means the format cannot be sniffed.
- open_stream: collections.abc.Callable[[io.IOBase], io.IOBase]¶
Wrap a compressed binary stream and return a readable, decompressed binary stream.
- type httk.core.DatastreamLike = BytestreamLike | TextstreamLike | DatastreamURL[source]¶
- class httk.core.DatastreamURL(url, *, timeout=None)[source]¶
An explicit network-consent value carrying a URL and optional timeout for lazy consumers, which resolve it through the existing fetch/loader machinery; constructing it performs no network I/O.
- Parameters:
- Raises:
ValueError – If the URL uses an unsupported scheme.
- class httk.core.TextstreamFileView(obj, **hints)[source]¶
Bases:
httk.core.datastream.textstream_view.TextstreamView,io.TextIOBase,httk.core.datastream.textstream_api.TextstreamAPIA view presenting an underlying data streaming backend via the full io.TextIOBase API, which is a superset of TextstreamAPI.
- Parameters:
obj (httk.core.datastream.textstream_like.TextstreamLike) – Text-stream source to present through the text file API.
**hints (Any) – Backend-selection, encoding, and compression hints.
- unwrap()[source]¶
Return the raw representation of the wrapped backend.
- Returns:
The backend’s most raw available representation.
- Return type:
Any
- writable()[source]¶
Report that the view does not support writing.
- Returns:
Always
False.- Return type:
- seekable()[source]¶
Report whether the backend supports seeking and telling.
- Returns:
Whether both operations are available.
- Return type:
- flush()[source]¶
Flush the backend when it provides flushing.
- Raises:
ValueError – If the view is closed.
- read(size=-1)[source]¶
Read up to
sizecharacters, or all remaining characters whensizeis negative.- Parameters:
size (int | None) – Maximum number of characters to read;
Nonealso means all remaining characters.- Returns:
The text read from the stream.
- Raises:
ValueError – If the view is closed.
- Return type:
- readline(size=-1)[source]¶
Read one line, optionally limited to
sizecharacters.- Parameters:
size (int | None) – Maximum number of characters to read;
Nonemeans no limit.- Returns:
The line read, including its newline when present.
- Raises:
ValueError – If the view is closed.
- Return type:
- readlines(hint=-1)[source]¶
Read lines until EOF or until the accumulated size reaches
hint.- Parameters:
hint (int) – Approximate minimum number of characters to collect, or a negative value for no limit.
- Returns:
The lines read from the stream.
- Raises:
ValueError – If the view is closed.
- Return type:
- seek(offset, whence=io.SEEK_SET)[source]¶
Move the stream position and discard buffered line data.
- Parameters:
- Returns:
The resulting absolute stream position.
- Raises:
ValueError – If the view is closed.
io.UnsupportedOperation – If the backend is not seekable.
- Return type:
- tell()[source]¶
Return the logical stream position before buffered line data.
- Returns:
The logical absolute stream position.
- Raises:
ValueError – If the view is closed.
io.UnsupportedOperation – If the backend does not support telling.
- Return type:
- detach()[source]¶
Reject detaching because the view owns its backend interface.
- Raises:
io.UnsupportedOperation – Always, because detaching is unsupported.
- type httk.core.TextstreamLike = textstream_backend.TextstreamBackend | textstream_view.TextstreamView | io.TextIOBase | io.StringIO | str | pathlib.Path | urllib.request.Request[source]¶
- class httk.core.TextstreamURLView(obj, **hints)[source]¶
Bases:
httk.core.datastream.textstream_view.TextstreamView,strA view presenting an underlying data streaming backend via a URL string. This view is mostly useful for providing a URL to functions that will open it. Note: this view is not lazy (this is impossible for views inheriting str, since str is immutable).
Raises TypeError if created with a streaming data source that does not come with a URL.
- Parameters:
obj (httk.core.datastream.textstream_like.TextstreamLike) – Text-stream source whose URL should be presented.
**hints (Any) – Backend-selection, consent, encoding, timeout, and compression hints.
- Raises:
TypeError – If the source has no URL.
- httk.core.register_compression(codec)[source]¶
Register (or replace) a codec under its
name(case-insensitive).- Parameters:
codec (CompressionCodec) – Codec to add to the registry.
- class httk.core.EntryProvider[source]¶
Bases:
abc.ABCSupplies described, queryable entry types as plain JSON-able records.
A provider serves one or more entry types, each identified by a name (e.g.
"structures"). For every entry type it describes the entry type and its properties, states how each served property maps to a record key, and yields the records themselves.Three notions define the contract:
Definitions (
entry_types()) are first-classEntryTypeDefinitionobjects — the OPTIMADE property-definition model shared across httk₂ modules. A provider obtains them from the vendored standards (viastandard_entry_type()orload_entry_type_definition()) or builds them fromfrom_optimade()andfrom_simple(). A standard definition typically describes more properties than a provider serves; the served subset is exactly the property names inproperty_keys().Property keys (
property_keys()) map each served property name to the key under which that property’s value is found in a record. Every entry type’s property-key map MUST cover at leastidandtype, and every served name MUST be described by the entry type’s definition (custom properties must therefore live in anextended()definition).Records (
records()) are plain JSON-able mappings keyed by the record keys named inproperty_keys()(values are strings, numbers, booleans,None, or nested lists/dicts of the same).
A consumer combines the three: the definitions become the served schema, the property keys drive both response-field extraction and filter handling, and the records are loaded into a store the consumer queries.
A provider may additionally declare relationships (
relationships()): a flat tuple ofRelatedEntryvalues per entry id, each naming a related entry (and optionally the relationship’sdescription/rolemetadata) that the consumer serves as the entry’s relationships block.- abstractmethod entry_types()[source]¶
Return the served entry types keyed by name.
Each value is an
EntryTypeDefinitiondescribing the entry type and its properties. The subset a provider actually serves is named byproperty_keys(); a definition may describe more properties than are served.- Returns:
The served entry-type definitions keyed by entry type name.
- Return type:
collections.abc.Mapping[str, httk.core.property_definitions.EntryTypeDefinition]
- abstractmethod property_keys(entry_type)[source]¶
Return the served-property-name to record-key map for
entry_type.The mapping MUST include entries for at least
idandtype. Every key names a property described byentry_types(); every value names the key under which that property’s value is found in a record fromrecords().- Parameters:
entry_type (str) – The entry type whose property mapping is requested.
- Returns:
The served property names mapped to record keys.
- Return type:
- abstractmethod records(entry_type)[source]¶
Yield the records for
entry_typeas plain JSON-able mappings.Each record is a mapping keyed by the record keys named in
property_keys(); values are JSON-able (strings, numbers, booleans,None, or nested lists/dicts of the same).- Parameters:
entry_type (str) – The entry type whose records are requested.
- Returns:
An iterable of JSON-able records.
- Return type:
- relationships(entry_type)[source]¶
Return the related entries for each record of
entry_type.The result maps an entry id to a flat tuple of
RelatedEntryvalues, e.g.{"struct-1": (RelatedEntry("references", "ref-1"), RelatedEntry("references", "ref-2", description="Cites the method"))}. Grouping the related entries by related entry type is the serving layer’s concern (JSON:API groups them at render time). This is the neutral source of an OPTIMADE relationships block: a consumer turns each related entry into a resource identifier under its entry type (carrying thedescription/rolemetadata when present), and aninclude=<type>request then embeds those related resources. The default implementation returns an empty mapping (no relationships); a provider overrides it to declare them. Ids referring to records this provider (or a sibling provider serving the related type) does not supply are simply not resolvable by the consumer.- Parameters:
entry_type (str) – The entry type whose relationships are requested.
- Returns:
Related entries keyed by the source record identifier.
- Return type:
collections.abc.Mapping[str, tuple[RelatedEntry, Ellipsis]]
- class httk.core.RelatedEntry[source]¶
One related entry of a record, as reported by
EntryProvider.relationships().Mirrors the OPTIMADE v1.3 relationships model: a related entry is named by its entry type and id, optionally carrying the per-identifier metadata the standard defines —
description(the human-readable relationship description introduced in OPTIMADE v1.2 asmeta.description) androle(the machine-readable relationship role introduced in OPTIMADE v1.3 asmeta.role, e.g."input"/"output"for the calculations↔files relationship). An absentrolemeans exactly that — no role is declared and no default is assumed.labelis the provenance edge label (the OPTIMADE relation-objectlabel); until relation-object serving exists, it is served on the OPTIMADE side as prefixed relationship metadata.- Parameters:
entry_type – The entry type of the related entry.
id – The identifier of the related entry.
description – The human-readable relationship description, if declared.
role – The machine-readable relationship role, if declared.
label – The provenance edge label, if declared.
- class httk.core.Calculation[source]¶
The
calculationsentry type.The calculations entry type describes calculations. Related files entries specified as relationships list files used or produced by a calculation. They MAY be defined as either input or output files by the role field inside the meta dictionary of the JSON:API resource identifier object. The allowed values are input for input files and output for output files. If the role field is not provided or the value is set to null, a default role SHOULD NOT be assumed. It is RECOMMENDED to order the output files in the list of calculation’s relationships in a way that prioritizes the files most likely to contain details which could be used to automatically analyze the performed calculation. Such an approach minimizes the number of calculation output files that need to be analyzed to possibly identify the code, type and parameters of the performed calculation.
Schema properties:
- Variables:
immutable_id –
The entry’s immutable ID (e.g., a UUID).
Requirements/Conventions:
This is important for databases having preferred IDs that point to “the latest version” of a record, but still offer access to older variants.
This ID maps to the version-specific record, in case it changes in the future.
last_modified – Date and time representing when the entry was last modified.
- last_modified: datetime.datetime | None = None¶
- class httk.core.File[source]¶
The
filesentry type.The files entry type describes a file with metadata and a URL to retrieve it
Schema properties:
- Variables:
immutable_id –
The entry’s immutable ID (e.g., a UUID).
Requirements/Conventions:
This is important for databases having preferred IDs that point to “the latest version” of a record, but still offer access to older variants.
This ID maps to the version-specific record, in case it changes in the future.
last_modified – Date and time representing when the entry was last modified.
url –
The URL to get the contents of a file.
Requirements/Conventions:
The URL MUST point to the actual contents of a file (i.e. byte stream), not an intermediate (preview) representation. For example, if referring to a file on GitHub, a link should point to raw contents.
url_stable_until –
Point in time until which the URL in url is guaranteed to stay stable.
Requirements/Conventions:
null means that there is no stability guarantee for the URL in url. Indefinite support could be communicated by providing a date sufficiently far in the future, for example, 9999-12-31.
name –
Base name of a file.
Requirements/Conventions:
File name extension is an integral part of a file name and, if available, MUST be included.
size –
Size of a file in bytes.
Requirements/Conventions:
If provided, it MUST be guaranteed that either exact size of a file is given or its upper bound. This way if a client reserves a static buffer or truncates the download stream after this many bytes the whole file would be received. Such provision is included to allow the providers to serve on-the-fly compressed files.
media_type – Media type identifier (also known as MIME type), for a file as per [RFC 6838 Media Type Specifications and Registration Procedures](https://datatracker.ietf.org/doc/html/rfc6838).
version –
Version information of a file (e.g., commit, revision, timestamp).
Requirements/Conventions:
If provided, it MUST be guaranteed that file contents pertaining to the same combination of id and version are the same.
modification_timestamp –
Timestamp of the last modification of file contents. A modification is understood as an addition, change or deletion of one or more bytes, resulting in file contents different from the previous.
Requirements/Conventions:
Timestamps of subsequent file modifications SHOULD be increasing (not earlier than previous timestamps).
description – Free-form description of a file.
checksums –
Dictionary providing checksums of file contents.
Requirements/Conventions:
The keys in the dictionary identify checksum functions and the values are strings containing the corresponding checksum.
Supported dictionary keys: md5, sha1, sha224, sha256, sha384, sha512. Checksums outside this list MAY be used, but their names MUST be prefixed by database-provider-specific namespace prefix.
atime – Time of last access of a file as per POSIX standard.
ctime – Time of last status change of a file as per POSIX standard.
mtime –
Time of last modification of a file as per POSIX standard.
Requirements/Conventions:
It should be noted that the values of last_modified, modification_timestamp and mtime do not necessary match. last_modified pertains to the modification of the OPTIMADE metadata, modification_timestamp pertains to file contents and mtime pertains to the modification of the file (not necessary changing its contents). For example, appending an empty string to a file would result in the change of mtime in some operating systems, but this would not be deemed as a modification of its contents.
- last_modified: datetime.datetime | None = None¶
- url_stable_until: datetime.datetime | None = None¶
- modification_timestamp: datetime.datetime | None = None¶
- checksums: collections.abc.Mapping[str, str] | None = None¶
- atime: datetime.datetime | None = None¶
- ctime: datetime.datetime | None = None¶
- mtime: datetime.datetime | None = None¶
- class httk.core.Reference[source]¶
The
referencesentry type.The references entry type describes a reference
Schema properties:
- Variables:
immutable_id –
The entry’s immutable ID (e.g., a UUID).
Requirements/Conventions:
This is important for databases having preferred IDs that point to “the latest version” of a record, but still offer access to older variants.
This ID maps to the version-specific record, in case it changes in the future.
last_modified – Date and time representing when the entry was last modified.
address – Typically the location of the publisher or institution (the address field in the BibTeX specification).
annote – Additional notes or comments on the reference (the annote field in the BibTeX specification).
booktitle – The title of a book being cited; for parts of a book, use the title field instead (the booktitle field in the BibTeX specification).
chapter – The chapter, section, or similar part number (the chapter field in the BibTeX specification).
crossref – The database key of the entry being cross referenced (the crossref field in the BibTeX specification).
edition – The edition of a book (the edition field in the BibTeX specification).
howpublished – The method of publication (the howpublished field in the BibTeX specification)
institution – The sponsoring institution of a technical report (the institution field in the BibTeX specification).
journal – The name of a journal (the journal field in the BibTeX specification).
key – Used for alphabetizing, cross-referencing, and creating a label (the key field in the BibTeX specification).
month – The three-letter abbreviation of the month of publication or writing (the month field in the BibTeX specification).
note – Additional information about the reference (the note field in the BibTeX specification).
number – The number of a journal, magazine, technical report, or work in a series (the number field in the BibTeX specification).
organization – The organization sponsoring a conference or publishing a manual (the organization field in the BibTeX specification)
pages – The page number(s) of the reference (the pages field in the BibTeX specification).
publisher – The name of the publisher (the publisher field in the BibTeX specification).
school – The name of the school where a thesis was written (the school field in the BibTeX specification).
series – The name of a series or set of books (the series field in the BibTeX specification).
title – The title of the work (the title field in the BibTeX specification).
volume – The volume number of a journal or multivolume book (the volume field in the BibTeX specification).
year – The year of publication or writing.
bib_type – Type of the reference (the type field in the BibTeX specification).
authors –
A list of dictionaries with names of the authors.
Requirements/Conventions:
Each list member MUST be a dictionary with the following keys:
name: Full name of the person, REQUIRED.
firstname, lastname: Parts of the person’s name, OPTIONAL.
editors –
A list of dictionaries with names of the editors.
Requirements/Conventions:
Each list member MUST be a dictionary with the following keys:
name: Full name of the person, REQUIRED.
firstname, lastname: Parts of the person’s name, OPTIONAL.
doi – The doi identifier of the object being referenced.
url – The URL of the object being referenced.
- last_modified: datetime.datetime | None = None¶
- authors: tuple[collections.abc.Mapping[str, Any], Ellipsis] | None = None¶
- editors: tuple[collections.abc.Mapping[str, Any], Ellipsis] | None = None¶
- httk.core.fetch(url, *, raw=False, timeout=None, kind=None, **kwargs)[source]¶
Fetch a URL as an OPTIMADE entry or a registered file format.
kind="optimade"forces OPTIMADE handling andkind="load"forces file-reader handling. With nokind, a reader-claimed extension wins over an OPTIMADE-shaped path; a reader-claimed basename is ambiguous and requires an explicitkind.file://URLs are supported in either branch. Redirects followurllibdefaults.As the explicit URL entry point, this function supplies the same network consent represented by
DatastreamURL; it does not use implicit bare-string network access for the reader branch.- Parameters:
url (str) – URL to fetch.
raw (bool) – Whether to return a neutral payload without a format adapter.
timeout (float | None) – Optional timeout for URL-backed reader access or OPTIMADE requests.
kind (str | None) – Optional branch selector:
"optimade"or"load".**kwargs (Any) – Additional options passed to the file reader.
- Returns:
The fetched OPTIMADE resource or loaded file value.
- Raises:
ValueError – If the URL,
kind, or automatic branch selection is invalid.- Return type:
Any
- class httk.core.FileEntry[source]¶
Logical entry family for served
FileRecordrecords.This family is not itself storable; store a
FileRecorddirectly.- type = 'files'¶
- definition_id = 'https://schemas.optimade.org/defs/v1.2/entrytypes/optimade/files'¶
- class httk.core.FileRecord[source]¶
Bases:
httk.core.entry_types.FileStore one OPTIMADE
filesentry with a content identity.URL and name remain required positional fields. The URL is included in identity so separate paths to identical bytes remain separate entries. Metadata timestamps and immutable identifiers are excluded from identity.
checksumsis skipped because mapping fields are not SQL-storable; store the flatsha256value when a storable digest is needed.- Parameters:
url – The URL to get the contents of the file.
name – The base name of the file.
immutable_id – An optional provider-specific immutable identifier.
last_modified – The optional timezone-aware metadata timestamp.
url_stable_until – The optional URL stability deadline.
size – The file size in bytes, if known.
media_type – The file MIME type, if known.
version – The file version, if known.
modification_timestamp – The optional content modification timestamp.
description – An optional free-form file description.
checksums – Optional checksums, kept out of SQL storage.
atime – The optional POSIX access timestamp.
ctime – The optional POSIX status-change timestamp.
mtime – The optional POSIX modification timestamp.
sha256 – The optional flat SHA-256 digest.
- immutable_id: Annotated[str | None, IdentitySkip()] = None¶
- last_modified: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- url_stable_until: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- modification_timestamp: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- atime: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- ctime: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- mtime: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- httk.core.load(filename, *, raw=False, **kwargs)[source]¶
Load
filenameand adapt its neutral payload to a domain object.Dispatch strips at most one recognized compression suffix (
.gz,.bz2, …) to obtain an inner name, then selects a reader by that inner name’s extension (.cif,.poscar, …) or, failing that, by its exact basename (POSCAR,CONTCAR; case-insensitive). The selected reader always receives the originalfilename; readers open it through the datastream layer, which transparently decompresses. By default, a mapping with a string"format"tag is passed to the registered domain adapter for that format.raw=Trueis the neutral-payload escape hatch. Payloads with unknown formats, and non-mapping reader results, pass through unchanged.- Parameters:
- Returns:
The loaded and optionally adapted value.
- Raises:
ValueError – If
filenameis a URL or no reader matches it.- Return type:
Any
- httk.core.load_many(sources, *, processes=None, errors='raise', **kwargs)[source]¶
Load multiple sources lazily, preserving input order.
processes=Noneuses the process-pool default.processes=0orprocesses=1loads in the current process, which is also the guaranteed path for readers registered at runtime. Parallel workers rediscover installed registration packages, but runtime registrations are not guaranteed to be present in a fresh worker. Parallel work uses bounded ordered futures rather thanmap()so worker failures and result-pickling failures can be returned per source.- Parameters:
sources (collections.abc.Iterable[Any]) – Sources accepted by
load().processes (int | None) – Number of worker processes, or
Nonefor the default.errors (Literal['raise', 'return']) – Whether to raise failures or yield them as exception values.
**kwargs (Any) – Options forwarded to every
load()call.
- Returns:
A lazy iterator of
(source, result)pairs in input order.- Raises:
ValueError – If
errorsis not"raise"or"return", or ifprocessesis negative.TypeError – If
processesis not an integer orNone.
- Return type:
collections.abc.Generator[tuple[Any, Any], None, None]
- httk.core.load_source(source, name, *, raw=False, **kwargs)[source]¶
Load
sourceusing the reader selected byname.- Parameters:
- Returns:
The reader result, optionally adapted to a domain value.
- Raises:
ValueError – If no reader matches the name; the error lists known extensions and basenames.
- Return type:
Any
- httk.core.combined_precision(values)[source]¶
Return the precision of a set of values taken together: the coarsest of them.
A structure is only as precisely stated as its least precisely stated number, so one sloppy
0.5among a table of six-decimal coordinates really does mean the table is good to1e-1. Taking the coarsest is the conservative reading and the one that keeps a derived tolerance from being too tight to match anything.Each value may be a literal to be interpreted by
decimal_precision(), or an already-computed precision, such as a standard uncertainty read from a file. Numeric values convert through their decimal spelling, so0.005lands on1/200rather than a binary approximation of it. Values that state no precision are skipped, andNoneis returned when none of them state one.- Parameters:
values (collections.abc.Iterable[object]) – Values or precision bounds to combine.
- Returns:
The largest absolute precision bound, or
Noneif none is stated.- Return type:
fractions.Fraction | None
- httk.core.decimal_precision(text)[source]¶
Return the absolute precision implied by how a number was written, or
None.Nonemeans the literal makes no precision claim, which is a different thing from claiming perfect precision. It is returned for an empty or missing value, for CIF’s?and.placeholders, for anything that is not a decimal literal, and — this one matters — for an exact rational such as"1/3", which states a value rather than a measurement and so should not drag a structure’s precision down to the width of its last digit.Examples, all exact:
"0.123"->1/1000— three digits after the point"-0.5"->1/10— the sign is not part of the claim".25"->1/100— a leading point is still two digits"5."->1— a trailing point states no fraction"10"->None— an integer literal states a value exactly, like a rational"1.2e-3"->1/10000— one digit, then scaled by the exponent"1/3"->None— exact, not measured"?"->None— no value at all
- Parameters:
text (object) – Value whose textual representation supplies the precision claim.
- Returns:
The absolute precision bound, or
Nonewhen the value makes no measured-precision claim.- Return type:
fractions.Fraction | None
- class httk.core.EntryTypeDefinition(name, description, properties, definition_id=None, extends_id=None)[source]¶
An immutable OPTIMADE entry-type definition.
Bundles the entry type’s
nameanddescriptionwith an insertion-ordered mapping ofPropertyDefinitionobjects (one per described property). A standard definition typically describes more properties than any given deployment serves; the served subset is chosen separately (anEntryProvidernames it through itsproperty_keys()).definition_ididentifies the source document when present. An extended definition is a new document, so it clears that identity and retains the original standard IRI inextends_idinstead.- Parameters:
name (str) – The entry type name.
description (str) – The human-readable entry type description.
properties (collections.abc.Mapping[str, PropertyDefinition]) – Property definitions keyed by property name.
definition_id (str | None) – The source document IRI, if one exists.
extends_id (str | None) – The standard document IRI extended by this definition, if any.
- classmethod from_optimade(name, entrytype)[source]¶
Build an entry-type definition from a vendored OPTIMADE entry type.
entrytypeis the vendored document shape: adescriptionstring, an optional top-level$id, and apropertiesmapping of property name to full property definition. A clearValueErroris raised when either required field is missing. The optional ID identifies the source document; ad-hoc definitions remain valid without one.- Parameters:
name (str) – The entry type name.
entrytype (collections.abc.Mapping[str, Any]) – The vendored entry-type definition document.
- Returns:
An entry-type definition built from the document.
- Raises:
ValueError – If
descriptionorpropertiesis missing.- Return type:
Self
- property definition_id: str | None¶
Return this definition’s document IRI, if it has a standard one.
- property extends_id: str | None¶
Return the original standard IRI extended to make this definition, if any.
- property properties: collections.abc.Mapping[str, PropertyDefinition]¶
Return a copy of the property definitions keyed by name.
- extended(extra, *, allow_unprefixed=False)[source]¶
Return a copy with
extracustom property definitions merged in.Each name in
extraMUST be new (a collision with an existing property raisesValueErrornaming it) and, unlessallow_unprefixedis set, MUST carry a registered database-specific prefix (seeregister_definition_prefix()/known_definition_prefixes()); a custom property that does not is rejected with aValueErrorexplaining the OPTIMADE prefix rule. The result deliberately has nodefinition_id: it is a new document, not the standard resource. Itsextends_idrecords the original standard ID so repeated extensions retain that provenance.- Parameters:
extra (collections.abc.Mapping[str, PropertyDefinition]) – New custom property definitions to add.
allow_unprefixed (bool) – Whether to allow custom names without a registered prefix.
- Returns:
A new definition containing the original and extra properties.
- Raises:
ValueError – If a property collides or violates the prefix rule.
- Return type:
Self
- class httk.core.PropertyDefinition(name, payload)[source]¶
An immutable wrapper around one full OPTIMADE property definition.
Instances are constructed from a vendored definition document (
from_optimade()) or generated from a compact description (from_simple()). The wrapped document is always deep-copied on the way in and out, so an instance never shares mutable state with its inputs or its callers.- Parameters:
name (str) – The canonical property name.
payload (collections.abc.Mapping[str, Any]) – The complete property-definition document.
- classmethod from_optimade(name, definition)[source]¶
Wrap a full vendored OPTIMADE property definition.
definitionmust at least carry$id,description,x-optimade-type, andtype; a clearValueErroris raised otherwise. The document is deep-copied.- Parameters:
name (str) – The canonical property name.
definition (collections.abc.Mapping[str, Any]) – The full property-definition document to wrap.
- Returns:
A validated property definition.
- Raises:
ValueError – If a required property-definition field is missing.
- Return type:
Self
- classmethod from_simple(name, *, description, fulltype='string', unit=None, dimensions=None, dict_properties=None, metadata_definition=None, required_response=False, definition_id=None)[source]¶
Generate a property definition from a compact description.
This mirrors the OPTIMADE property-definition generator: it emits the
$schemameta-schema reference, a synthesized$id(under the base registered for a matching prefix viaregister_definition_prefix()— e.g.httk.orgfor_httk_— underschemas.optimade.orgotherwise, unlessdefinition_idoverrides it), a title, thedescription, the OPTIMADE type derived fromfulltype("string","integer","float","boolean","timestamp","dict", or"list of ..."), thex-optimade-unit(with an ångström unit definition whenunit == "angstrom"), thex-optimade-definitionstamp (format"1.2"; see the module docstring), the JSONtypewith nullability derived fromrequired_response,itemsfor lists, adate-timeformat for timestamps, innerpropertiesfor dicts (fromdict_properties),x-optimade-dimensionsfromdimensions, and anx-optimade-metadata-definition(explicit, or a generatedlist_axesdefinition whendimensionsis given).The result is implementation-neutral: per-deployment
sortableandresponse-defaultflags are layered on later viawith_implementation().- Parameters:
name (str) – The canonical property name.
description (str) – The human-readable property description.
fulltype (str) – The OPTIMADE property type description.
unit (str | None) – The unit associated with numeric or list values.
dimensions (collections.abc.Mapping[str, Any] | None) – Dimension names and sizes for list values.
dict_properties (collections.abc.Mapping[str, str] | None) – Inner property names and type descriptions for dictionaries.
metadata_definition (collections.abc.Mapping[str, Any] | None) – An explicit metadata definition for the property.
required_response (bool) – Whether responses must contain a non-null value.
definition_id (str | None) – An explicit property-definition IRI.
- Returns:
A generated property definition.
- Return type:
Self
- property json_type: Any¶
Return the property’s JSON Schema type declaration.
- property requirements: collections.abc.Mapping[str, Any]¶
Return the property’s OPTIMADE requirements mapping.
- property dimensions: collections.abc.Mapping[str, Any] | None¶
Return the property’s dimensions declaration, if any.
- property metadata_definition: collections.abc.Mapping[str, Any] | None¶
Return the property’s metadata definition, if any.
- with_implementation(*, sortable=None, response_default=None)[source]¶
Return a copy carrying this deployment’s implementation flags.
Adds an
x-optimade-implementationobject with thesortableandresponse-defaultkeys that are provided (aNoneargument leaves that key unset), and — whensortableis given — mirrors it in a top-levelsortablefield. The original instance is untouched. The original$idandx-optimade-definitionare retained because the vendored v1.2Property Definitionsmeta-schema says definitions “SHOULD be regarded as the same if they only differ by” changes tox-optimade-implementation; the specification says a redefinition “MUST change the $id”. Top-levelsortableis the additional field required by theEntry Listing Info Endpointssection.
- httk.core.known_definition_prefixes()[source]¶
Return the registered database-specific property-name prefixes.
The tuple reflects the current state of the prefix registry (see
register_definition_prefix());_httk_is pre-registered.
- httk.core.register_definition_prefix(prefix, id_base)[source]¶
Register a database-specific OPTIMADE property-name
prefix.A custom property served by a database MUST use such a prefix (see the OPTIMADE specification, “Database-Specific Properties”). Once registered, a property name carrying
prefixgets its$idsynthesized underid_basebyPropertyDefinition.from_simple(), andEntryTypeDefinition.extended()accepts it as a custom property.prefixmust be a lower-case alphanumeric token wrapped in single underscores (matching_[a-z0-9]+_); anything else raises a clearValueError. Re-registering an existing prefix overwrites its base.- Parameters:
- Raises:
ValueError – If
prefixdoes not match_[a-z0-9]+_.
- httk.core.standard_entry_type(name)[source]¶
Return one of httk-core’s vendored standard OPTIMADE entry types.
Supported names are
"references","files", and"calculations"; an unknown name raises aValueErrorlisting the known ones. Thestructuresstandard is vendored by httk-atomistic, not httk-core.- Parameters:
name (str) – The standard entry type name to load.
- Returns:
The vendored entry-type definition.
- Raises:
ValueError – If
nameis not vendored by httk-core.- Return type:
- class httk.core.ProductLink[source]¶
A curation
has_product/is_productedge between data entries.A label is unique per source entry across links; that constraint is enforced at the serving projection rather than on each record.
- Parameters:
source_type – The source entry type name.
source_id – The source entry identifier.
target_type – The target entry type name.
target_id – The target entry identifier.
label – The relationship label, unique per source entry at serving time.
workflow_declaration_uri – The workflow declaration IRI, if declared.
- classmethod create(obj)[source]¶
Coerce a mapping or existing link into a
ProductLink.- Parameters:
obj (ProductLink | Mapping[str, Any]) – A product-link instance or field mapping.
- Returns:
The existing or newly constructed product link.
- Raises:
TypeError – If
objis neither a product link nor a mapping.ValueError – If the mapping has unknown or invalid fields.
- Return type:
Self
- class httk.core.Run[source]¶
One workflow execution with loose provenance edges.
inputsarehas_inputedges to consumed entries,artifactsarehas_artifactedges to created entries, andoutputsarehas_outputedges to returned entries. Artifact single-creator exclusivity across runs is documented here, not enforced per record.Every invariant is cheap and total, so there is deliberately no
__httk_validate__hook.Edges remain loose string triples by design, never object references. Labels are unique independently on each of
inputs,artifacts, andoutputs.- Parameters:
workflow_declaration_uri – The workflow declaration IRI, if declared.
inputs – The labeled entries consumed by the run.
artifacts – The labeled entries created by the run.
outputs – The labeled entries returned by the run.
immutable_id – An optional provider-specific immutable identifier.
last_modified – The optional timezone-aware metadata timestamp.
- immutable_id: Annotated[str | None, IdentitySkip()] = None¶
- last_modified: Annotated[datetime.datetime | None, IdentitySkip()] = None¶
- classmethod create(obj)[source]¶
Coerce a mapping or existing run into a
Run.- Parameters:
obj (Run | Mapping[str, Any]) – A run instance or field mapping.
- Returns:
The existing or newly constructed run.
- Raises:
TypeError – If
objis neither a run nor a mapping.ValueError – If the mapping has unknown or invalid fields.
- Return type:
Self
- class httk.core.RunEdge[source]¶
Store one loose labeled reference from a run to another entry.
Edges deliberately keep the related entry’s type and identifier as strings rather than object references, so a run can refer to entries served by another provider.
- Parameters:
label – The relationship label.
entry_type – The related entry type name.
entry_id – The related entry identifier.
- classmethod create(obj)[source]¶
Coerce a mapping or existing edge into a
RunEdge.- Parameters:
obj (RunEdge | Mapping[str, Any]) – A run edge instance or field mapping.
- Returns:
The existing or newly constructed run edge.
- Raises:
TypeError – If
objis neither a run edge nor a mapping.ValueError – If the mapping has unknown or invalid fields.
- Return type:
Self
- class httk.core.RunEntry[source]¶
Logical entry family for served
Runrecords.This family is not itself storable; store a
Rundirectly.- type = '_httk_runs'¶
- definition_id = 'https://schemas.httk.org/defs/v0.1/entrytypes/runs'¶
- httk.core.register_cli_command(name, handler, summary)[source]¶
Register a lazy top-level httk command.
A handler is either a callable or a lazy
"module:callable"reference with the contract(argv: Sequence[str], context: CLIContext) -> int. Names use lowercase, hyphen-separated command syntax. Registration is intentionally strict: reserved names and duplicate registrations are errors rather than order-dependent overrides.- Parameters:
name (str) – The lowercase hyphen-separated command name.
handler (str | collections.abc.Callable[Ellipsis, Any]) – The command callable or lazy
"module:callable"reference.summary (str) – The nonempty one-line command summary.
- Raises:
TypeError – If
handleris neither callable nor a lazy reference.ValueError – If the name, handler reference, summary, or registration is invalid.
- httk.core.register_entry_family(*, name, family, definition_id=None)[source]¶
Register a lazy entry-family class reference without importing it.
- Parameters:
- Raises:
ValueError – If validation fails or
nameis already registered.
- httk.core.register_entry_provider(*, name, factory)[source]¶
Register an
EntryProviderfactory undername.factoryis a lazy"module:callable"reference to a callable that constructs a provider (providers need data, so applications call the factory themselves; the registry only records how to reach it). This mirrorsregister_reader.
- httk.core.register_entry_record(*, name, record, family=None, definition_id=None)[source]¶
Register a lazy record-class reference and optional family and definition IRI.
- Parameters:
- Raises:
ValueError – If validation fails or
nameis already registered.
- httk.core.register_optimade_entry_binding(*, name, definition_id, backend, view, property_decoders=None, query_fields=None)[source]¶
Register one lazy typed binding, selected only by exact definition IRI.
- Parameters:
name (str) – The binding registry name.
definition_id (str) – The exact entry-type definition IRI selected by the binding.
backend (str) – The lazy backend class reference.
view (str) – The lazy view class reference.
property_decoders (collections.abc.Mapping[str, str] | None) – Property definition IRIs mapped to lazy decoder references.
query_fields (tuple[str, Ellipsis] | None) – Property definition IRIs supported for querying, if restricted.
- Raises:
ValueError – If the definition IRI is already registered or input is invalid.
- httk.core.register_format_adapter(*, name, adapter, formats)[source]¶
Register one lazy adapter for each neutral payload format in
formats.adaptermay be a callable or a lazy"module:callable"reference. A format tag has one owner: registering it again raises an error naming both the existing and attempted registrants.- Parameters:
name (str) – The registry name for the adapter.
adapter (str | collections.abc.Callable[Ellipsis, Any]) – The adapter callable or lazy
"module:callable"reference.formats (collections.abc.Sequence[str]) – Neutral payload format tags served by the adapter.
- Raises:
ValueError – If a format tag is invalid, duplicated, or already owned.
- httk.core.register_format_serializer(*, format, serializer)[source]¶
Register one lazy serializer for a neutral payload format tag.
- Parameters:
format (str) – The neutral payload format tag.
serializer (str | collections.abc.Callable[Ellipsis, Any]) – The serializer callable or lazy reference.
- Raises:
ValueError – If
formatis invalid or already has another serializer.
- httk.core.register_reader(*, name, reader, extensions=(), filenames=())[source]¶
Register a reader under one or more file
extensionsand/orfilenames.extensionsare matched (case-insensitively) against a file’s suffix, e.g.".cif".filenamesare exact basenames matched (case-insensitively) against a file’s name with any recognized compression suffix stripped, e.g."POSCAR"matchesPOSCAR,poscar, andPOSCAR.bz2.
- httk.core.register_writer(*, name, writer, format, extensions=(), filenames=())[source]¶
Register a writer under one or more extensions and/or exact basenames.
A format can have one writer owner; registering a conflicting writer raises an error. Extension and basename keys are matched case-insensitively.
- Parameters:
name (str) – The registry name for the writer.
writer (str | collections.abc.Callable[Ellipsis, Any]) – The writer callable or lazy
"module:callable"reference.format (str) – The neutral payload format emitted by the writer.
extensions (tuple[str, Ellipsis]) – File suffixes that select the writer.
filenames (tuple[str, Ellipsis]) – Exact basenames that select the writer.
- Raises:
ValueError – If
formatis invalid or conflicts with an existing writer.
- httk.core.load_entry_type_definition(definition_id)[source]¶
Load and verify a registered entry-type definition resource.
- Parameters:
definition_id (str) – The registered entry-type definition IRI.
- Returns:
The loaded and validated entry-type definition.
- Raises:
ValueError – If the IRI is unregistered or disagrees with the document.
- Return type:
- httk.core.load_property_definition(definition_id)[source]¶
Load and verify a registered property definition resource.
- Parameters:
definition_id (str) – The registered property definition IRI.
- Returns:
The loaded and validated property definition.
- Raises:
ValueError – If the IRI is unregistered or disagrees with the document.
- Return type:
- httk.core.register_entry_type_definition(*, definition_id, resource)[source]¶
Register one resource for an entry-type definition IRI.
- Parameters:
- Raises:
ValueError – If
definition_idis already registered.
- httk.core.register_property_definition(*, definition_id, resource)[source]¶
Register one resource for a property definition IRI.
- Parameters:
- Raises:
ValueError – If
definition_idis already registered.
- httk.core.save(obj, destination, *, format=None, **kwargs)[source]¶
Save
objto a local destination selected by its name orformathint.The writer registry selects by extension first and exact basename second, case-insensitively after stripping one recognized compression suffix, unless
formatselects a registered writer directly. The format-serializer registry converts non-neutral objects before writing, and a recognized compression suffix wraps the destination transparently.- Parameters:
obj (Any) – Object or neutral payload to serialize and write.
destination (str | os.PathLike[str]) – Local filename or path to write.
format (str | None) – Optional registered format name that selects the writer.
**kwargs (Any) – Additional options passed to the selected writer.
- Raises:
ValueError – If the destination or format has no writer, no serializer exists, or the destination is a URL.
- class httk.core.Service[source]¶
Describe one service independently of its publication transport.
The service and endpoint identifiers are absolute IRIs; this neutral core contract does not impose a particular scheme.
conforms_tonames one or more standards the service implements, and may be supplied as any ordered non-string iterable.- Parameters:
id – The service’s absolute IRI.
title – The service’s human-readable title.
endpoint_url – The service endpoint’s absolute IRI.
conforms_to – Non-empty unique absolute IRIs for implemented standards.
serves_dataset_ids – Optional non-empty unique absolute IRIs for served datasets.
endpoint_description – An optional absolute IRI describing the endpoint.
- classmethod create(obj)[source]¶
Coerce a mapping or existing service into a
Service.- Parameters:
obj (Service | Mapping[str, Any]) – A service instance or a mapping with service fields.
- Returns:
The existing or newly constructed service.
- Raises:
TypeError – If
objis neither a service nor a mapping.ValueError – If the mapping has missing, unknown, or invalid fields.
- Return type:
Self
- class httk.core.ServiceRecord[source]¶
Bases:
ServiceStore one
Serviceusing the core service storage contract.- Parameters:
id – The service’s absolute IRI.
title – The service’s human-readable title.
endpoint_url – The service endpoint’s absolute IRI.
conforms_to – Non-empty unique absolute IRIs for implemented standards.
serves_dataset_ids – Optional non-empty unique absolute IRIs for served datasets.
endpoint_description – An optional absolute IRI describing the endpoint.
- classmethod create(obj)[source]¶
Coerce a service record, neutral service, or field mapping.
- Parameters:
obj (ServiceRecord | Service | Mapping[str, Any]) – A service record, neutral service, or service field mapping.
- Returns:
The existing or newly constructed service record.
- Raises:
TypeError – If
objis not a service or mapping.ValueError – If the mapping has unknown, missing, or invalid fields.
- Return type:
Self
- httk.core.content_id(obj, *, as_record=None, projector=project_storage_record)[source]¶
Return the lowercase SHA-256 content identity of
obj.The digest covers
canonical_form(), including exact-type leaf encodings and excluding fields marked withIdentitySkip.- Parameters:
obj (Any) – The record or projected source to identify.
as_record (type[Any] | None) – An explicit record class override, if supplied.
projector (collections.abc.Callable[[type[Any], Any], collections.abc.Mapping[str, object]]) – The record-level projection function.
- Returns:
The lowercase SHA-256 hexadecimal digest.
- Raises:
TypeError – If a value or projection cannot be represented.
ValueError – If a projection is invalid or contains a cycle.
- Return type:
- class httk.core.Indexed[source]¶
Field marker: request a single-column index on this field’s column(s).
- class httk.core.Related[source]¶
Field marker: relationship metadata for a reference or list-of-storable field.
Applies to a field holding another storable class (a reference field) or a
list/tupleof storable classes. When the field’s target class is served alongside the declaring class, the storage layer surfaces the field as a relationship; this marker attaches the OPTIMADE per-identifier metadata that flows into each emittedRelatedEntry—role(machine readable, OPTIMADE v1.3meta.role) anddescription(human readable, OPTIMADE v1.2meta.description).serve=Falsesuppresses the field as a relationship entirely.- Parameters:
role – The machine-readable relationship role, if any.
description – The human-readable relationship description, if any.
serve – Whether the field is served as a relationship at all.
- class httk.core.RelationshipLink[source]¶
Class-level relationship declaration: each stored row expresses one FROM→TO relationship.
Declared in
StorageInfo.links.sourceandtargeteach name a reference field of the declaring class, or areNoneto meanthe declaring class's own entry: for every stored row, one relationship is declared from the entry the source side resolves to, to the entry the target side resolves to. The two canonical shapes:join-object:
RelationshipLink("structure", "reference")on aStructureRefjoin class — everyStructureRefrow relates itsstructureto itsreference(structures → references), without the join class itself being served.field-inverse:
RelationshipLink("structure", None, role="output")on aCalculationclass — everyCalculationrow relates itsstructureto the calculation itself (structures → calculations), i.e. the inverse of thestructurereference field.
roleanddescriptioncarry the same OPTIMADE per-identifier metadata asRelatedinto each relationship the link declares.- Parameters:
source – The reference field naming the FROM-side entry, or
Nonefor the declaring class’s own entry.target – The reference field naming the TO-side entry, or
Nonefor the declaring class’s own entry.role – The machine-readable relationship role, if any.
description – The human-readable relationship description, if any.
- Raises:
ValueError – If both endpoints are
None(which would relate every entry to itself), or if they name the same field.
- class httk.core.Shape[source]¶
Field marker: fixed or variable shape for a vector-valued field.
rows >= 1declares a fixed-shape value stored inline (flattened row-major into columns).rows == 0declares a variable number of rows withcolsfixed columns each, stored out-of-line (one row per entry, in insertion order).- Parameters:
rows – Number of rows;
0means variable-length.cols – Number of columns per row; must be at least
1.
- Raises:
ValueError – If
rowsis negative orcolsis less than1.
- class httk.core.StorageInfo[source]¶
Optional class-level storage declaration for a storable dataclass.
Attach as the class attribute named by
STORAGE_INFO_ATTRIBUTE(__httk_storage__), annotatedClassVar[StorageInfo]so dataclass processing ignores it. A storage layer may also accept an instance as an external override for classes that cannot be modified.- Parameters:
storage_name – The physical storage name;
Nonederives one from the class name. Relational backends use it as the table name, and document stores use it as the collection name.indexes – Composite indexes, each a tuple of field names.
dedup – The deduplication policy applied when saving; see
DedupPolicy.links – Class-level relationship declarations; see
RelationshipLink.identity_name – The logical name included in content identity;
Nonederives it from the declaring class and its bases.
- Raises:
ValueError – If
dedupor an identity name or index declaration is invalid.
- dedup: DedupPolicy = 'content_id'¶
- links: tuple[RelationshipLink, Ellipsis] = ()¶
- class httk.core.stored_property(fget=None, fset=None, fdel=None, doc=None)[source]¶
Bases:
propertyA derived property that a storage layer stores and makes queryable.
Use exactly like
property(getter only). The value type is read from the getter’s return annotation. On save, the storage layer evaluates and stores the value alongside the declared fields; on load, the value is recomputed by the property rather than passed to__init__. The getter must declare a return annotation when the property is created.- Parameters:
fget (collections.abc.Callable[Ellipsis, Any] | None) – The getter function whose derived value is stored.
fset (collections.abc.Callable[Ellipsis, Any] | None) – An optional setter, normally unused by storage declarations.
fdel (collections.abc.Callable[Ellipsis, Any] | None) – An optional deleter, normally unused by storage declarations.
doc (str | None) – An optional property documentation string.
- Raises:
TypeError – If
fgethas no return annotation.
- class httk.core.FracScalar(value, *, denom=None, simplify=True, chain=False, min_accuracy=fractions.Fraction(1, 10000))[source]¶
Bases:
FracVectorRepresents the fractional number
nom/denom. This is a subclass of FracVector with the purpose of making it clear when a scalar fracvector is needed/used.Convert a value into a FracScalar.
FracScalar(something)wheresomethingmay be any object that can be used in the constructor of the Python Fraction class (also works with strings!).For signature compatibility with the
FracVectorconstructor, this accepts but ignoreschainandmin_accuracy, and converts strings exactly via the Fraction constructor.- Parameters:
value (Any) – The scalar value or values to convert.
denom (int | None) – An optional additional denominator.
simplify (bool) – Whether to reduce the resulting denominator.
chain (bool) – An accepted compatibility parameter; it does not affect scalar creation.
min_accuracy (fractions.Fraction | None) – An accepted compatibility parameter; scalar strings are exact.
- class httk.core.FracVector(values, *, denom=None, simplify=True, chain=False, min_accuracy=fractions.Fraction(1, 10000))[source]¶
Bases:
FracVectorBase,httk.core.vectors.vector_backend.VectorBackendImmutable exact-rational vector that is also its own vector backend.
- property fractions: httk.core.vectors.vector_api.Fractions¶
Return this vector in the exact nested Fraction interchange format.
- class httk.core.MutableFracVector(values, *, denom=None, simplify=True, chain=False, min_accuracy=fractions.Fraction(1, 10000))[source]¶
Bases:
httk.core.vectors.fracvector.FracVectorBaseSame as
FracVector, only this version allows assignment of elements, e.g.:mfracvec[2, 7] = 5
and, e.g.:
mfracvec[:, 7] = [1, 2, 3, 4]
Other than this, the FracVector methods exist and do the same, i.e., they return copies of the fracvector, rather than modifying it.
- Parameters:
values (Any) – A rational value-like to convert, such as nested sequences or scalars.
denom (int | None) – An optional additional common denominator.
simplify (bool) – Whether to reduce the resulting denominator.
chain (bool) – Whether to flatten the outermost nested sequence.
min_accuracy (fractions.Fraction | None) – Minimum accuracy for decimal values, or
Nonefor exact conversion.
Methods with
set_*prefixes perform mutating operations, e.g.:A.set_T()
replaces A with its own transpose, whereas:
A.T()
just returns a new MutableFracVector that is the transpose of A, leaving A unmodified.
- nested_map: ClassVar[collections.abc.Callable[Ellipsis, Any]]¶
- nested_inmap: ClassVar[collections.abc.Callable[Ellipsis, Any]]¶
- nested_map_fractions: ClassVar[collections.abc.Callable[Ellipsis, Any]]¶
- noms: Any¶
- invalidate()[source]¶
Internal method to call when the MutableFracVector is changed in such a way that cached properties are invalidated (e.g.,
_dim).- Returns:
None.
- Return type:
None
- set_inv()[source]¶
Change the MutableFracVector inline into its own inverse:
self -> self^-1.- Returns:
The inverse scalar when
selfis scalar; otherwiseNoneafter mutation.- Return type:
Any
- set_simplify()[source]¶
Change the MutableFracVector; reduces any common factor between the denominator and all nominators.
- set_set_denominator(resolution=1000000000)[source]¶
Change the MutableFracVector; reduces resolution.
- Parameters:
resolution (int) – The new denominator; each element becomes the closest numerical approximation using this denominator.
- type httk.core.NumericVector = float | numpy.ndarray[source]¶
- type httk.core.ScalarLike = int | float | str | fractions.Fraction | decimal.Decimal | fracvector.FracScalar | surdvector.SurdScalar[source]¶
- class httk.core.SurdScalar(value)[source]¶
Bases:
SurdVectorA scalar
SurdVector(shape()): a single field element \(\sum_r q_r\sqrt r\).Adds the scalar-only operations — the field inverse, exact sign and ordering, and Decimal rendering — that need a single value rather than a tensor.
- Parameters:
value (Any) – A rational scalar/nested sequence accepted by
FracVector, or an existing SurdVector or SurdScalar, returned unchanged.
- inverse()[source]¶
Return the multiplicative inverse
1/self(raisesZeroDivisionErroron zero).- Returns:
The exact multiplicative inverse.
- Return type:
- sign()[source]¶
Return the exact sign of the value:
-1,0or1.For an irrational value the sign is decided by refining rational lower/upper bounds on each
sqrt(r)(frominteger_sqrt()at increasing precision) and summing the weighted intervals until the total interval excludes zero — which always happens in finitely many steps because a nonzero surd is bounded away from zero.- Returns:
-1,0, or1according to the exact sign.- Return type:
- classmethod cos_degrees(q)[source]¶
Return
cos(q degrees)as an exactSurdScalar, or None when it is not a surd.The value lies in the squarefree-radical field precisely when the angle, reduced modulo 360, is a multiple of 15 or of 36 degrees — e.g. \(\cos 30° = \tfrac{\sqrt3}2\), \(\cos 15° = \tfrac{\sqrt6+\sqrt2}4\), \(\cos 36° = \tfrac{1+\sqrt5}4\).
qmay be an int,Fraction, or numeric string (parsed viaany_to_fraction()).That list is complete: \(\cos(2\pi a/b)\) lies in a field generated by square roots of rationals iff the Galois group \((\mathbb{Z}/b)^\times/\{\pm1\}\) of \(\mathbb{Q}(\cos 2\pi/b)\) has exponent at most 2, which holds exactly for \(b \in \{1,2,3,4,5,6,8,10,12,24\}\) — the rational-degree angles that are multiples of 15° or 36°. (Niven’s theorem is the rational-value special case of this classification.) A
Noneresult is therefore a proof that the exact cosine lies outside \(\mathbb{Q}[\sqrt n]\) — usecos()withdegrees=Truefor a deterministic rational approximation in that case.- Parameters:
q (Any) – The angle in degrees.
- Returns:
The exact cosine, or
Noneoutside the surd field.- Return type:
SurdScalar | None
- classmethod sin_degrees(q)[source]¶
Return
sin(q degrees)as an exactSurdScalar, orNonewhen the value lies outside the supported surd field (when90 - qis not in the exact surd-cosine set).Computed as
cos(90 - q)degrees, so exactness follows the same classification ascos_degrees()applied to90 - q: exact when90 - qis a multiple of 15 or 36 degrees, andNoneotherwise (a proof that the exact sine is outside the field). For example,sin(54°)is exact because it iscos(36°).- Parameters:
q (Any) – The angle in degrees.
- Returns:
The exact sine, or
Noneoutside the surd field.- Return type:
SurdScalar | None
- acos_degrees()[source]¶
Return the exact
arccosof this value in degrees over \([0, 180]\), or None.This is the reverse table lookup: the result is an exact rational number of degrees precisely when the value equals the cosine of a multiple of 15° or 36° (the complete set of rational-degree angles with surd cosines — see
cos_degrees()), decided by exact surd equality; otherwise None (the exact angle is then irrational in degrees). RaisesValueError— decided exactly viasign()— when the value lies outside \([-1, 1]\).- Returns:
The exact angle in degrees, or
Nonewhen not represented by the table.- Return type:
fractions.Fraction | None
- to_float(prec=fractions.Fraction(1, 10**30))[source]¶
Return the value as a float via a high-precision exact rational approximation.
- Parameters:
prec (fractions.Fraction) – The maximum approximation error.
- Returns:
The value as a float.
- Return type:
- to_decimal(digits=None, rounding='half_even', max_refinements=None)[source]¶
Render the value as a correctly-rounded
decimal.Decimal.Reuses the exact-math module’s Ziv refinement loop (
_to_decimal): a rational value renders exactly (its finite expansion when it fits, else quantized), and an irrational surd — never on a rational rounding boundary — is rendered by refining the rational approximation until the rounding is determined.digits(significant digits; default: the active decimal context precision),rounding("half_even"/"down") andmax_refinementsmatchsqrt()in Decimal mode.- Parameters:
- Returns:
The correctly rounded decimal value.
- Return type:
Any
- class httk.core.SurdVector(value)[source]¶
Bases:
httk.core.vectors.vector_backend.VectorBackendAn immutable exact tensor over the squarefree-radical field \(\mathbb{Q}[\sqrt n : n\ \text{squarefree}]\).
A SurdVector is a map
{squarefree radicand -> FracVector coefficient}(all coefficients sharing onedim); radicand1is the rational part. It is stored canonically — coefficients simplified, all-zero coefficients dropped — so the representation is unique and equality/zero-detection are exact. LikeFracVectorit is immutable and hashable.See the module docstring for the field facts, the fractional-vs-Cartesian motivation, and the magnitude-vs-linear-structure purpose boundary.
- Parameters:
value (Any) – An existing SurdVector or SurdScalar, returned unchanged, or a rational scalar/nested sequence accepted by
FracVector; rational values become the radicand-1 component.
- classmethod from_components(components, dim)[source]¶
Build from trusted component vectors and a shared shape.
- classmethod from_radicand_map(mapping)[source]¶
Compose a SurdVector from a
{radicand -> coefficient}mapping.Radicands are positive integers and need not be squarefree — each is normalized via
square_part(sqrt(radicand) = s*sqrt(r)) and the coefficients (FracVector-like, all of one shape) folded together canonically.
- classmethod sqrt_of(q)[source]¶
Return the exact square root of a nonnegative rational
qas aSurdScalar.The result is a plain rational when
qis a perfect square (e.g.sqrt_of(4/9) == 2/3) and otherwise a single-radical surd (sqrt_of(8) == 2*sqrt(2)).sqrt(p/q)is normalized assqrt(p*q)/qso the stored radicand is always a positive squarefree integer (sqrt_of(1/2) == sqrt(2)/2). RaisesValueErroron a negative argument — there is no exact square root of a surd (no nested radicals), only of a rational.- Parameters:
q (Any) – A nonnegative rational value.
- Returns:
Its exact square root.
- Return type:
- classmethod zero(dim=())[source]¶
The zero SurdVector of shape
dim(aSurdScalarfor the default()).- Parameters:
- Returns:
The zero SurdVector or SurdScalar.
- Return type:
- property is_rational: bool¶
True iff the value is purely rational (only the radicand-1 term is present).
- property radicands: tuple[int, Ellipsis]¶
The sorted squarefree radicands present in the canonical form.
- coefficient(radicand)[source]¶
Return the FracVector coefficient of
sqrt(radicand)(a zero tensor when absent).- Parameters:
radicand (int) – The radicand whose coefficient to retrieve.
- Returns:
The coefficient, or a zero tensor when absent.
- Return type:
- T()[source]¶
Return the transpose, transposing each radicand’s coefficient tensor.
- Returns:
The transposed tensor.
- Return type:
- dot(other)[source]¶
Return the vector dot product of two 1-D SurdVectors (
sum a_i b_i).- Parameters:
other (Any) – The other 1-D SurdVector.
- Returns:
The exact scalar dot product.
- Return type:
- lengthsqr()[source]¶
Return the squared length
A * A^Tas aSurdScalar.- Returns:
The exact squared length.
- Return type:
- length()[source]¶
Return the exact length
sqrt(lengthsqr)as aSurdScalar.Exact precisely when
lengthsqris rational — which canonical arithmetic guarantees for a difference of Cartesian sites under a rational metric (the crystallographic case). Whenlengthsqris itself irrational the length would be a nested radical (sqrt(a + b*sqrt(c))), which is outside the field, so this raisesValueError.- Returns:
The exact length when the squared length is rational.
- Return type:
- det()[source]¶
Return the determinant of a 3x3 SurdVector as a
SurdScalar.- Returns:
The exact determinant.
- Return type:
- inv()[source]¶
Return the inverse of a 3x3 SurdVector via the adjugate and the scalar field inverse.
- Returns:
The exact inverse matrix.
- Return type:
- to_fractions_approx(prec=fractions.Fraction(1, 10**30))[source]¶
A deterministic nested list of
fractions.Fractionwithinprecof the true value.Exact (not merely within
prec) whenever the value is rational. This is thecompute(prec)-shaped rational approximation reused by the Decimal rendering.- Parameters:
prec (fractions.Fraction) – The maximum elementwise approximation error.
- Returns:
Nested rational approximations of the values.
- Return type:
Any
- to_floats(prec=fractions.Fraction(1, 10**30))[source]¶
Return a nested list of floats via a high-precision exact rational approximation.
- Parameters:
prec (fractions.Fraction) – The maximum elementwise approximation error.
- Returns:
Nested floating-point approximations of the values.
- Return type:
Any
- property fractions: httk.core.vectors.vector_api.Fractions¶
Return the exact or deterministic rational hub representation.
- type httk.core.VectorLike = vector_backend.VectorBackend | vector_view.VectorView | fracvector.FracVector | surdvector.SurdVector | tuple[Any, ...] | list[Any] | 'numpy.ndarray'[source]¶
- httk.core.numpy_available()[source]¶
Return whether the optional numpy dependency is available for the numeric helpers.
This reads the vectors package’s
_numpy_availableflag freshly on each call (the flag set whenhttk.core.vectorsconditionally imports/registers the numpy backend), so tests may monkeypatchhttk.core.vectors._numpy_availableto exercise the numpy-absent path.- Returns:
Truewhen numpy is available, otherwiseFalse.- Return type:
- httk.core.to_numeric(obj)[source]¶
Present
objas plain numpy numbers: anumpy.ndarrayfor a tensor, afloatfor a scalar.A tensor becomes a base-class
float64numpy.ndarray(never a view subclass) viaVectorNumpyView; a scalar input (shape()) returns a plainfloatviato_numeric_scalar()(never a 0-d array).The numeric presentation is numpy-backed, so this always requires numpy: it raises
ImportError(naming thehttk-core[numpy]extra) when numpy is not installed, uniformly, so the contract is predictable regardless of the input shape. Useto_numeric_scalar()directly for a single float without a numpy requirement.- Parameters:
obj (httk.core.vectors.vector_like.VectorLike | float | str | fractions.Fraction) – The vector-like value to present numerically.
- Returns:
The converted scalar or tensor value.
- Raises:
ImportError – If numpy is unavailable.
TypeError – If the value cannot be converted to the numeric presentation.
- Return type:
- httk.core.to_numeric_scalar(obj)[source]¶
Convert a single scalar value to a plain
float, deterministically.A
SurdScalar(or scalarSurdVector) and a scalarFracVectorrender through their own exactto_float(); aFraction,int,float, or numericstrrender viaany_to_fraction(). A non-scalar shape raisesTypeError.Unlike
to_numeric(), this needs no numpy: a plainfloatconversion has no numpy dependency, so it works unconditionally and never raises for a missing numpy.
- class httk.core.Backend[BackendT: Backend](backend, **hints)[source]¶
Bases:
abc.ABCAbstract base class to be subclassed into classes that keep track of alternative representations of certain types of data, all adhering to a common API interface.
The class variable backend_classes is a list of all classes that can carry the kind of data the subclass represents.
A system of “hints” are used primarily to disambiguate between multiple valid interpretations of the same input object. Unless otherwise documented for a specific backend, extra hints that do not affect this interpretation are ignored.
A set of backends are meant to be combined with a set of Views.
Concrete backends implement
_backend_adoptto accept an object and return an initialized backend instance, orNoneto decline it. Thekindhint convention is used to disambiguate between multiple valid interpretations.- Parameters:
backend (Any) – Source value or backend being adopted by the concrete backend.
**hints (Any) – Backend-specific initialization hints.
- classmethod create(obj, **hints)[source]¶
Given a source data (obj) and a set of hints, create a backend from one of the alternatives in the class variable backend_classes.
By design this creation depends heavily on order of the classes in backend_classes. Each class is tried in the order they appear until one of them is successful, in the sense that their _backend_adopt returns an initialized instance. Sometimes multiple backend classes can handle the same input type. In that case, dispatch is guided by keyword arguments
**hints, with the convention that:if a hint named kind is given, a backend class should accept the object only if it matches that kind;
when kind matches, additional unrecognized hints may be ignored.
- Parameters:
obj (Any) – Source object to represent with a registered backend.
**hints (Any) – Backend-selection and disambiguation hints.
- Returns:
A backend that represents
obj.- Raises:
TypeError – If no registered backend accepts
objand the hints.- Return type:
Self
- unwrap()[source]¶
Return the most raw representation possible of this backend, i.e., if it uses a backend with an internal representaion - or if it can (possibly lossly) convert itself into a more raw representation that still would be recognized as a <Something>Like type, that representation will be returned. If this is not possible, the instance itself is returned.
- Returns:
The backend’s most raw available representation.
- Return type:
Any
- class httk.core.View[BackendT: httk.core.views.backend.Backend][source]¶
A set of views allow manipulating data and state of a backend through different interfaces. Hence, creating a View from a Backend, or from another View, allows to read and operate on the data through the interface of that view, even if it is not the natural representation of the underlying data.
Important: views are always meant to reference the data and state of the same underlying object, hence, e.g.:
If a function is given an X object, and the function applies an Xvariant1View and then calls, e.g., close() via that view, the expectation should be that the original X object is also closed.
When, e.g., a TextstreamStringView is created on an already partially read stream, only the unread data will appear through that string interface.
All backends and views of the same kind of data (X) should be combined into a type union XLike that functions use to declare they support this kind of data. Such functions should start with creating a View on the passed data, giving them access to the data in a single desired format.
Views are lazy by default: construction stores only the backend, while
cached_propertyshadows and group fills materialize presentation state on first access. Size fills to the subset served by each backend call; validate before assigning, never read a shadowed attribute from a fill, and document why a view must remain eager. The explicitcoerce_view()/coerce()paths materialize via_ensure_materialized(); laziness is for pass-through use.- unwrap()[source]¶
Return the most raw representation possible of this view, i.e., if it uses a backend with an internal representaion - or if it can (possibly lossly) convert itself into a more raw representation that still would be recognized as a <Something>Like type, that representation will be returned. If this is not possible, the instance itself is returned.
- Returns:
The backend’s most raw available representation.
- Return type:
Any
- unview()[source]¶
Return the view’s presented representation as a plain, non-View instance.
Concrete views that mimic a value type override this to shed the httk wrapper; the result may alias the view’s storage (no copy is promised). The default raises
TypeError, which is the correct behavior for views that only adapt an interface and have no faithful standalone value.- Returns:
The presented value as a plain, non-View instance.
- Raises:
TypeError – If this interface-only view has no standalone plain value.
- Return type:
Any
- httk.core.coerce(value, target)[source]¶
Coerce
valuestrictly: return a non-View instance of the requested target or raise.The exact string
"natural"returnsvalueunchanged (no coercion, even for a View). Otherwise the resolution ofcoerce_view()applies, and then: an httk View result is shed viaunview()unless the requested target is itself a View class; a View result that cannot shed raisesunview’s ownTypeError; and the final result must satisfyisinstance(result, target)— a lossless fallback of another type (available throughcoerce_view()) makes strict coercion fail withTypeError. An existing non-View subtype of the target is an identity result.- Parameters:
value (Any) – Value to convert.
target (Any) – Target class, prototype instance, or the
"natural"sentinel.
- Returns:
A non-View instance matching the requested target.
- Raises:
TypeError – If strict conversion cannot produce the requested target.
- Return type:
Any
- httk.core.coerce_view(value, target)[source]¶
Coerce
valueto a target class or prototype instance, backend-aware and best-effort.The exact string
"natural"is a documented sentinel that returnsvalueunchanged. Otherwise, a class target is used directly and an instance target is treated as a prototype, using its type. Values already matching the target are returned unchanged — including httk Views that subclass the target, so the exact backend is retained. A target that is aViewsubclass is then tried directly as a view conversion ofvalue, so any view family works without a registered coercer. Failing that, registered coercers whose declared targets match are tried in registration order, and the first non-Noneresult wins. If none succeeds,TypeErroris raised naming the value type and target. Coercion is best effort and favors lossless view wrapping; a coercer may return a lossless fallback of another type (e.g.Fraction(1, 2)for targetint), and individual coercers document any deliberately lossy conversion. Callers that need a plain, exactly-typed result usecoerce()instead.- Parameters:
value (Any) – Value to convert.
target (Any) – Target class, prototype instance, or the
"natural"sentinel.
- Returns:
The best available backend-aware conversion.
- Raises:
TypeError – If no registered or direct conversion succeeds.
- Return type:
Any
- httk.core.unview(obj)[source]¶
Shed the httk View wrapper from
obj, returning a plain instance of the presented type.Unlike
unwrap(), which goes down to the backend’s raw source representation,unviewgoes sideways: it removes the httk wrapper while keeping the presentation the view exposes. The result is not promised to be a copy — it may alias the view’s (or the original input’s) storage; use the target representation’s normal copy operation when independent mutation is required. A non-View input is returned unchanged. Views that only adapt an interface and have no faithful standalone value raiseTypeError.- Parameters:
obj (Any) – Value or view to shed.
- Returns:
The presented value without its httk view wrapper.
- Raises:
TypeError – If a view has no faithful standalone value.
- Return type:
Any
- httk.core.unwrap(obj)[source]¶
Given a Backend or a View, return the most raw representation possible, i.e., if the backend has an internal representaion - or if it can (possibly lossly) convert itself into a more raw representation that still would be recognized as a <Something>Like type, that representation will be returned. If this is not possible, the instance itself is returned.
- Parameters:
obj (Any) – Value, backend, or view to unwrap.
- Returns:
The most raw available representation.
- Return type:
Any