httk.core

Submodules

Attributes

DecodeObjectCallback

Callback invoked as (dict_obj, jsonld_url) that returns the value to use in place of

BytestreamLike

TextstreamLike

STORAGE_INFO_ATTRIBUTE

Class attribute name where a storable class may attach its StorageInfo.

DedupPolicy

How a storage layer deduplicates saved instances of a class.

NumericVector

VectorLike

subpackages

Classes

DataLoader

Lazy loader for httk dataset files, resolved only when data is first accessed.

DataRecord

Read-only attribute and mapping view over a dict[str, Any].

DatasetMeta

Header metadata extracted from a structured JSON-LD dataset document.

BytestreamBackend

Abstract base class for all backends of streaming byte data.

BytestreamBytes

Backend for streaming byte data backed by an actual bytes object.

BytestreamBytesView

A view presenting underlying streaming byte data as bytes.

BytestreamCommon

Common superclass for many of the implementations of backends for streaming byte data.

BytestreamFile

Backend for file-based (io.IOBase-conforming) streaming byte data.

BytestreamFilename

Backend for streaming byte data via operations on a file specified by a filename.

BytestreamFilenameView

A view presenting an underlying data streaming backend via a filename.

BytestreamFileView

A view presenting an underlying data streaming backend via an io.IOBase-like API.

BytestreamRequest

Backend for streaming byte data fetched via a urllib.request.Request.

BytestreamRequestView

A view presenting an underlying data streaming backend via a urllib.request.Request.

BytestreamURL

Backend for streaming byte data fetched from a URL string.

BytestreamURLView

A view presenting an underlying data streaming backend via a URL string.

BytestreamView

Abstract base class for all views of streaming byte data.

CompressionCodec

A decompression codec for a single container format.

TextstreamBackend

Abstract base class for all backends of streaming text data.

TextstreamCommon

Common superclass for many of the implementations of backends for streaming text data.

TextstreamFile

Backend for file-based (io.TextIOBase-conforming) streaming text data

TextstreamFilename

Backend for streaming text via operations on a file specfied by a filename

TextstreamFilenameView

A view presenting an underlying data streaming backend via a filename.

TextstreamFileView

A view presenting an underlying data streaming backend via the full io.TextIOBase API, which is a superset of TextstreamAPI.

TextstreamRequest

Backend for streaming text fetched via a urllib.request.Request.

TextstreamRequestView

A view presenting an underlying data streaming backend via a urllib.request.Request.

TextstreamString

Backend for streaming text backed by an actual string

TextstreamStringView

A view presenting an underlying data streaming as a string.

TextstreamURL

Backend for streaming text fetched from a URL string.

TextstreamURLView

A view presenting an underlying data streaming backend via a URL string.

TextstreamView

Abstract base class for all views of streaming text data.

EntryProvider

Supplies described, queryable entry types as plain JSON-able records.

Calculation

One OPTIMADE calculations record.

File

One OPTIMADE files record.

Reference

One OPTIMADE references record (a bibliographic reference).

EntryTypeDefinition

An immutable OPTIMADE entry-type definition.

PropertyDefinition

An immutable wrapper around one full OPTIMADE property definition.

Indexed

Field marker: request a single-column index on this field's column(s).

Shape

Field marker: fixed or variable shape for a vector-valued field.

Skip

Field marker: the field exists on the dataclass but is not stored.

StorageInfo

Optional class-level storage declaration for a storable dataclass.

Unique

Field marker: request a unique index on this field's column(s).

stored_property

A derived property that a storage layer stores and makes queryable.

FracScalar

Represents the fractional number nom/denom. This is a subclass of FracVector with the

FracVector

FracVector is a general immutable N-dimensional vector (tensor) class for performing

LeafCodec

A leaf codec: a documented conversion of one exact fractions.Fraction leaf into a

MutableFracVector

Same as FracVector, only this version allows

SurdScalar

A scalar SurdVector (shape ()): a single field element

SurdVector

An immutable exact tensor over the squarefree-radical field

VectorAPI

Abstract base class for the canonical vector interface.

VectorBackend

Abstract base class for all backends of vector (tensor) data.

VectorFrac

Backend for a vector backed by an actual FracVector

VectorFracView

A view presenting an underlying vector backend as an exact

VectorNative

Backend for a vector backed by plain nested sequences.

VectorNativeView

A view presenting an underlying vector backend as nested tuples, with a selectable leaf codec.

VectorSurd

Backend for a vector backed by an exact SurdVector

VectorSurdView

A view presenting an underlying vector backend as an exact

VectorView

Abstract base class for all views of vector (tensor) data.

Backend

Abstract base class to be subclassed into classes that keep track of alternative

View

A set of views allow manipulating data and state of a backend through different interfaces.

Functions

known_compressions(→ list[str])

Return the registered codec names, in registration order.

register_compression(→ None)

Register (or replace) a codec under its name (case-insensitive).

load(→ Any)

Load filename via the loader registered for its type.

known_definition_prefixes(→ tuple[str, Ellipsis])

Return the registered database-specific property-name prefixes.

load_entry_type_definition(→ EntryTypeDefinition)

Load a vendored OPTIMADE entry-type definition JSON from a package.

register_definition_prefix(→ None)

Register a database-specific OPTIMADE property-name prefix.

standard_entry_type(→ EntryTypeDefinition)

Return one of httk-core's vendored standard OPTIMADE entry types.

known_entry_providers(→ list[str])

register_entry_provider(→ None)

Register an EntryProvider factory under name.

known_leaf_codecs(→ list[str])

Return the registered leaf-codec names, in registration order.

numpy_available(→ bool)

Return whether the optional numpy dependency is available for the numeric helpers.

register_leaf_codec(→ None)

Register (or replace) a codec under its name.

to_numeric(→ NumericVector)

Present obj as plain numpy numbers: a numpy.ndarray for a tensor, a float for a

to_numeric_scalar(→ float)

Convert a single scalar value to a plain float, deterministically.

unwrap(→ Any)

Given a Backend or a View, return the most raw representation possible, i.e., if the backend has an internal representaion -

Package Contents

class httk.core.DataLoader(identifier: str, source: httk.core.datastream.TextstreamLike, decode_object: DecodeObjectCallback | None = None, **hints: Any)[source]

Lazy loader for httk dataset files, resolved only when data is first accessed.

A DataLoader is a declare-time placeholder: constructing it records its arguments and performs no I/O. The source is read the first time data, meta, or index is accessed. Files are either plain JSON (any JSON value is exposed as data with meta/index set to None) or a structured JSON-LD document (with @context, header fields, data, and optional indicies) whose header is exposed via meta, datasets via data.<name>, and lookup indices via index.<name>.

Loaders that share an identifier deduplicate through a class-level registry: the first load wins, and later loaders reusing that identifier return the same result while their source and decode_object arguments 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 .json name (e.g. data.json or data.json.gz) is parsed as JSON; any other recognizable suffix raises ValueError; a source with no determinable name is treated as JSON. Compression is handled transparently by the stream layer, so .json.gz and similar load directly. A str/Path source is interpreted as a filename unless its scheme marks it as a URL (http, https, ftp, file); pass kind="content" for literal content or kind="filename"/kind="url" to force an interpretation.

Example

symmetry_basics = DataLoader(“symmetry_basics”, “data/spacegroup_symbols.json”) spacegroups = symmetry_basics.data.spacegroups # first access triggers the load

property data: Any
property meta: DatasetMeta | None
property index: DataRecord | None
class httk.core.DataRecord(data: dict[str, Any])[source]

Read-only attribute and mapping view over a dict[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, and keys().

keys() collections.abc.KeysView[str][source]
class httk.core.DatasetMeta[source]

Header metadata extracted from a structured JSON-LD dataset document.

context: dict[str, Any]

The raw @context object.

id: str | None

The document @id, or None if absent.

type_: str | None

The document @type, or None if absent (trailing underscore avoids the builtin type).

header: dict[str, Any]

All remaining top-level keys except data, indicies, and @-keys (titles, creator, license, provenance, …).

dataset_ids: dict[str, str]

Mapping of dataset name to its @id.

fields: dict[str, dict[str, str]]

Mapping of dataset name to a mapping of field name to its property URL.

type httk.core.DecodeObjectCallback = Callable[[dict[str, Any], str], Any][source]

Callback invoked as (dict_obj, jsonld_url) that returns the value to use in place of dict_obj (return the input unchanged to decline).

class httk.core.BytestreamBackend(backend, **hints)[source]

Bases: httk.core.views.Backend[BytestreamBackend], httk.core.datastream.bytestream_api.BytestreamAPI

Abstract base class for all backends of streaming byte data.

backend_classes: ClassVar[list[type[httk.core.views.Backend[Any]]]]
class httk.core.BytestreamBytes(content: bytes | bytearray, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_common.BytestreamCommon, httk.core.datastream.bytestream_backend.BytestreamBackend

Backend for streaming byte data backed by an actual bytes object.

b: bytes
property name: str | None
property closed: bool
class httk.core.BytestreamBytesView(obj: httk.core.datastream.bytestream_like.BytestreamLike, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_view.BytestreamView, bytes

A view presenting underlying streaming byte data as bytes. This view can be used both to pass bytes in place of streaming data, and for reading streaming data into bytes. Note: this view is not lazy (this is impossible for views inheriting bytes, since bytes is immutable), hence all streaming data is read immediately upon creating this view.

unwrap() Any[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.

class httk.core.BytestreamCommon[source]

Bases: abc.ABC

Common superclass for many of the implementations of backends for streaming byte data.

unwrap() io.IOBase[source]
read(size: int = -1) bytes[source]
close() None[source]
seek(offset: int, whence: int = os.SEEK_SET) int[source]
tell() int[source]
class httk.core.BytestreamFile(obj: io.IOBase, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_common.BytestreamCommon, httk.core.datastream.bytestream_backend.BytestreamBackend

Backend for file-based (io.IOBase-conforming) streaming byte data.

property name: str | None
property closed: bool
class httk.core.BytestreamFilename(filename: str | pathlib.Path, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_common.BytestreamCommon, httk.core.datastream.bytestream_backend.BytestreamBackend

Backend for streaming byte data via operations on a file specified by a filename.

property name: str | None
property closed: bool
class httk.core.BytestreamFilenameView(obj: httk.core.datastream.bytestream_like.BytestreamLike, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_view.BytestreamView, str

A view presenting an underlying data streaming backend via a filename. This view is mostly useful for providing filenames to functions that will open them. 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 name.

unwrap() Any[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.

class httk.core.BytestreamFileView(obj: httk.core.datastream.bytestream_like.BytestreamLike, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_view.BytestreamView, io.IOBase, httk.core.datastream.bytestream_api.BytestreamAPI

A view presenting an underlying data streaming backend via an io.IOBase-like API.

unwrap() Any[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.

property name: str | None
property closed: bool
close() None[source]

Flush and close the IO object.

This method has no effect if the file is already closed.

readable() bool[source]

Return whether object was opened for reading.

If False, read() will raise OSError.

writable() bool[source]

Return whether object was opened for writing.

If False, write() will raise OSError.

seekable() bool[source]

Return whether object supports random access.

If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().

flush() None[source]

Flush write buffers, if applicable.

This is not implemented for read-only and non-blocking streams.

read(size: int | None = -1) bytes[source]
readline(size: int | None = -1) bytes[source]

Read and return a line from the stream.

If size is specified, at most size bytes will be read.

The line terminator is always b’n’ for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.

readlines(hint: int = -1) list[bytes][source]

Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

seek(offset: int, whence: int = io.SEEK_SET) int[source]

Change the stream position to the given byte offset.

offset

The stream position, relative to ‘whence’.

whence

The relative position to seek from.

The offset is interpreted relative to the position indicated by whence. Values for whence are:

  • os.SEEK_SET or 0 – start of stream (the default); offset should be zero or positive

  • os.SEEK_CUR or 1 – current stream position; offset may be negative

  • os.SEEK_END or 2 – end of stream; offset is usually negative

Return the new absolute position.

tell() int[source]

Return current stream position.

detach() NoReturn[source]
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.BytestreamRequest(request: urllib.request.Request, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_common.BytestreamCommon, httk.core.datastream.bytestream_backend.BytestreamBackend

Backend for streaming byte data fetched via a urllib.request.Request.

property name: str | None
property url: str
property request: urllib.request.Request
property closed: bool
class httk.core.BytestreamRequestView(obj: httk.core.datastream.bytestream_like.BytestreamLike, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_view.BytestreamView, urllib.request.Request

A view presenting an underlying data streaming backend via a urllib.request.Request. This view is mostly useful for providing a Request to functions that will open it. Note: this view is not lazy (it does not fetch); it only mirrors the underlying request/URL.

Raises TypeError if created with a streaming data source that does not come with a URL.

unwrap() Any[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.

class httk.core.BytestreamURL(url: str, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_common.BytestreamCommon, httk.core.datastream.bytestream_backend.BytestreamBackend

Backend for streaming byte data fetched from a URL string. A bare string is interpreted as a URL when its scheme is one of http, https, ftp, or file, or when an explicit kind=”url” hint is given.

property name: str | None
property url: str
property closed: bool
class httk.core.BytestreamURLView(obj: httk.core.datastream.bytestream_like.BytestreamLike, **hints: Any)[source]

Bases: httk.core.datastream.bytestream_view.BytestreamView, str

A 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.

unwrap() Any[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.

class httk.core.BytestreamView[source]

Bases: httk.core.views.View[httk.core.datastream.bytestream_backend.BytestreamBackend]

Abstract base class for all views of streaming byte data.

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).

name: str

Canonical, lower-case codec name (e.g. "gzip"); also how an explicit hint selects it.

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.

class httk.core.TextstreamBackend(backend, **hints)[source]

Bases: httk.core.views.Backend[TextstreamBackend], httk.core.datastream.textstream_api.TextstreamAPI

Abstract base class for all backends of streaming text data.

backend_classes: ClassVar[list[type[httk.core.views.Backend[Any]]]]
class httk.core.TextstreamCommon[source]

Bases: abc.ABC

Common superclass for many of the implementations of backends for streaming text data.

unwrap() io.TextIOBase[source]
read(size: int = -1) str[source]
close() None[source]
seek(offset: int, whence: int = os.SEEK_SET) int[source]
tell() int[source]
class httk.core.TextstreamFile(obj: io.TextIOBase, **hints: Any)[source]

Bases: httk.core.datastream.textstream_common.TextstreamCommon, httk.core.datastream.textstream_backend.TextstreamBackend

Backend for file-based (io.TextIOBase-conforming) streaming text data

property name: str | None
property closed: bool
class httk.core.TextstreamFilename(filename: str | pathlib.Path, **hints: Any)[source]

Bases: httk.core.datastream.textstream_common.TextstreamCommon, httk.core.datastream.textstream_backend.TextstreamBackend

Backend for streaming text via operations on a file specfied by a filename

property name: str | None
property closed: bool
class httk.core.TextstreamFilenameView(obj: httk.core.datastream.textstream_like.TextstreamLike, **hints: Any)[source]

Bases: httk.core.datastream.textstream_view.TextstreamView, str

A view presenting an underlying data streaming backend via a filename. This view is probably mostly useful for providing filenames to functions that will open them. Note: this view is not lazy (this is impossible for views inherting str, since str is immutable)

Raises TypeError if created with a streaming data source that do not come with a name, in the future we may consider creating a temporary file to place the data in.

unwrap() Any[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.

class httk.core.TextstreamFileView(obj: httk.core.datastream.textstream_like.TextstreamLike, **hints: Any)[source]

Bases: httk.core.datastream.textstream_view.TextstreamView, io.TextIOBase, httk.core.datastream.textstream_api.TextstreamAPI

A view presenting an underlying data streaming backend via the full io.TextIOBase API, which is a superset of TextstreamAPI.

unwrap() Any[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.

property name: str | None
property closed: bool
close() None[source]

Flush and close the IO object.

This method has no effect if the file is already closed.

readable() bool[source]

Return whether object was opened for reading.

If False, read() will raise OSError.

writable() bool[source]

Return whether object was opened for writing.

If False, write() will raise OSError.

seekable() bool[source]

Return whether object supports random access.

If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().

flush() None[source]

Flush write buffers, if applicable.

This is not implemented for read-only and non-blocking streams.

read(size: int | None = -1) str[source]

Read at most size characters from stream.

Read from underlying buffer until we have size characters or we hit EOF. If size is negative or omitted, read until EOF.

readline(size: int | None = -1) str[source]

Read until newline or EOF.

Return an empty string if EOF is hit immediately. If size is specified, at most size characters will be read.

readlines(hint: int = -1) list[str][source]

Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

seek(offset: int, whence: int = io.SEEK_SET) int[source]

Change the stream position to the given byte offset.

offset

The stream position, relative to ‘whence’.

whence

The relative position to seek from.

The offset is interpreted relative to the position indicated by whence. Values for whence are:

  • os.SEEK_SET or 0 – start of stream (the default); offset should be zero or positive

  • os.SEEK_CUR or 1 – current stream position; offset may be negative

  • os.SEEK_END or 2 – end of stream; offset is usually negative

Return the new absolute position.

tell() int[source]

Return current stream position.

detach() NoReturn[source]

Separate the underlying buffer from the TextIOBase and return it.

After the underlying buffer has been detached, the TextIO is in an unusable state.

property encoding: str | None

Encoding of the text stream.

Subclasses should override.

property errors: str | None

The error setting of the decoder or encoder.

Subclasses should override.

property newlines: str | tuple[str, Ellipsis] | None

Line endings translated so far.

Only line endings translated during reading are considered.

Subclasses should override.

type httk.core.TextstreamLike = textstream_backend.TextstreamBackend | textstream_view.TextstreamView | io.TextIOBase | io.StringIO | str | pathlib.Path | urllib.request.Request[source]
class httk.core.TextstreamRequest(request: urllib.request.Request, **hints: Any)[source]

Bases: httk.core.datastream.textstream_common.TextstreamCommon, httk.core.datastream.textstream_backend.TextstreamBackend

Backend for streaming text fetched via a urllib.request.Request.

property name: str | None
property url: str
property request: urllib.request.Request
property closed: bool
class httk.core.TextstreamRequestView(obj: httk.core.datastream.textstream_like.TextstreamLike, **hints: Any)[source]

Bases: httk.core.datastream.textstream_view.TextstreamView, urllib.request.Request

A view presenting an underlying data streaming backend via a urllib.request.Request. This view is mostly useful for providing a Request to functions that will open it. Note: this view is not lazy (it does not fetch); it only mirrors the underlying request/URL.

Raises TypeError if created with a streaming data source that does not come with a URL.

unwrap() Any[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.

class httk.core.TextstreamString(content: str, **hints: Any)[source]

Bases: httk.core.datastream.textstream_common.TextstreamCommon, httk.core.datastream.textstream_backend.TextstreamBackend

Backend for streaming text backed by an actual string

s: str
property name: str | None
property closed: bool
class httk.core.TextstreamStringView(obj: httk.core.datastream.textstream_like.TextstreamLike, **hints: Any)[source]

Bases: httk.core.datastream.textstream_view.TextstreamView, str

A view presenting an underlying data streaming as a string. This view can be used both to pass a string in place of streaming data, and for reading streaming data into a string. Note: this view is not lazy (this is impossible for views inherting str, since str is immutable), hence all the streaming data is read immedately upon creating this view.

unwrap() Any[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.

class httk.core.TextstreamURL(url: str, **hints: Any)[source]

Bases: httk.core.datastream.textstream_common.TextstreamCommon, httk.core.datastream.textstream_backend.TextstreamBackend

Backend for streaming text fetched from a URL string. A bare string is interpreted as a URL when its scheme is one of http, https, ftp, or file, or when an explicit kind=”url” hint is given.

property name: str | None
property url: str
property closed: bool
class httk.core.TextstreamURLView(obj: httk.core.datastream.textstream_like.TextstreamLike, **hints: Any)[source]

Bases: httk.core.datastream.textstream_view.TextstreamView, str

A 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.

unwrap() Any[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.

class httk.core.TextstreamView[source]

Bases: httk.core.views.View[httk.core.datastream.textstream_backend.TextstreamBackend]

Abstract base class for all views of streaming text data.

httk.core.known_compressions() list[str][source]

Return the registered codec names, in registration order.

httk.core.register_compression(codec: CompressionCodec) None[source]

Register (or replace) a codec under its name (case-insensitive).

class httk.core.EntryProvider[source]

Bases: abc.ABC

Supplies 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 column, and yields the records themselves.

Three notions define the contract:

  • Definitions (entry_types()) are first-class EntryTypeDefinition objects — the OPTIMADE property-definition model shared across httk₂ modules. A provider obtains them from the vendored standards (via standard_entry_type() or load_entry_type_definition()) or builds them from from_optimade() and from_simple(). A standard definition typically describes more properties than a provider serves; the served subset is exactly the property names in columns().

  • Columns (columns()) map each served property name to the key under which that property’s value is found in a record. Every entry type’s column map MUST cover at least id and type, and every served name MUST be described by the entry type’s definition (custom properties must therefore live in an extended() definition).

  • Records (records()) are plain JSON-able mappings keyed by the column keys named in columns() (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 columns drive both response-field extraction and filter handling, and the records are loaded into a store the consumer queries.

abstractmethod entry_types() collections.abc.Mapping[str, httk.core.property_definitions.EntryTypeDefinition][source]

Return the served entry types keyed by name.

Each value is an EntryTypeDefinition describing the entry type and its properties. The subset a provider actually serves is named by columns(); a definition may describe more properties than are served.

abstractmethod columns(entry_type: str) collections.abc.Mapping[str, str][source]

Return the served-property-name to record-column-key map for entry_type.

The mapping MUST include entries for at least id and type. Every key names a property described by entry_types(); every value names the key under which that property’s value is found in a record from records().

abstractmethod records(entry_type: str) collections.abc.Iterable[collections.abc.Mapping[str, Any]][source]

Yield the records for entry_type as plain JSON-able mappings.

Each record is a mapping keyed by the record-column keys named in columns(); values are JSON-able (strings, numbers, booleans, None, or nested lists/dicts of the same).

relationships(entry_type: str) collections.abc.Mapping[str, collections.abc.Mapping[str, tuple[str, Ellipsis]]][source]

Return the related entries for each record of entry_type.

The result maps an entry id to a mapping of related entry type to the tuple of related entry ids, e.g. {"struct-1": {"references": ("ref-1", "ref-2")}}. This is the neutral source of an OPTIMADE relationships block: a consumer turns each related id into a resource identifier under the named related type, and an include=<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.

class httk.core.Calculation[source]

One OPTIMADE calculations record.

Every field is optional and defaults to None; id is supplied by the provider’s mapping key and type is the constant "calculations". The standard calculations entry type carries only the shared core properties; database-specific results are added by extending the definition.

immutable_id: str | None = None
last_modified: str | None = None
classmethod create(obj: Calculation | Mapping[str, Any]) Self[source]
class httk.core.File[source]

One OPTIMADE files record.

Every field is optional and defaults to None; id is supplied by the provider’s mapping key and type is the constant "files". Timestamps are ISO-8601 strings and checksums is a mapping of algorithm name to hex digest.

immutable_id: str | None = None
last_modified: str | None = None
url: str | None = None
url_stable_until: str | None = None
name: str | None = None
size: int | None = None
media_type: str | None = None
version: str | None = None
modification_timestamp: str | None = None
description: str | None = None
checksums: collections.abc.Mapping[str, str] | None = None
atime: str | None = None
ctime: str | None = None
mtime: str | None = None
classmethod create(obj: File | Mapping[str, Any]) Self[source]
class httk.core.Reference[source]

One OPTIMADE references record (a bibliographic reference).

Every field is optional and defaults to None; id is supplied by the provider’s mapping key and type is the constant "references". Author and editor lists are tuples of plain name dictionaries.

immutable_id: str | None = None
last_modified: str | None = None
address: str | None = None
annote: str | None = None
booktitle: str | None = None
chapter: str | None = None
crossref: str | None = None
edition: str | None = None
howpublished: str | None = None
institution: str | None = None
journal: str | None = None
key: str | None = None
month: str | None = None
note: str | None = None
number: str | None = None
organization: str | None = None
pages: str | None = None
publisher: str | None = None
school: str | None = None
series: str | None = None
title: str | None = None
volume: str | None = None
year: str | None = None
bib_type: str | None = None
authors: tuple[collections.abc.Mapping[str, Any], Ellipsis] | None = None
editors: tuple[collections.abc.Mapping[str, Any], Ellipsis] | None = None
doi: str | None = None
url: str | None = None
classmethod create(obj: Reference | Mapping[str, Any]) Self[source]
httk.core.load(filename: str, **kwargs: Any) Any[source]

Load filename via the loader registered for its type.

Dispatch strips at most one recognized compression suffix (.gz, .bz2, …) to obtain an inner name, then selects a loader by that inner name’s extension (.cif, .poscar, …) or, failing that, by its exact basename (POSCAR, CONTCAR; case-insensitive). The selected loader always receives the original filename; loaders open it through the datastream layer, which transparently decompresses.

class httk.core.EntryTypeDefinition(name: str, description: str, properties: collections.abc.Mapping[str, PropertyDefinition])[source]

An immutable OPTIMADE entry-type definition.

Bundles the entry type’s name and description with an insertion-ordered mapping of PropertyDefinition objects (one per described property). A standard definition typically describes more properties than any given deployment serves; the served subset is chosen separately (an EntryProvider names it through its columns()).

classmethod from_optimade(name: str, entrytype: collections.abc.Mapping[str, Any]) Self[source]

Build an entry-type definition from a vendored OPTIMADE entry type.

entrytype is the vendored document shape: a description string and a properties mapping of property name to full property definition. A clear ValueError is raised when either is missing.

property name: str
property description: str
property properties: collections.abc.Mapping[str, PropertyDefinition]
extended(extra: collections.abc.Mapping[str, PropertyDefinition], *, allow_unprefixed: bool = False) Self[source]

Return a copy with extra custom property definitions merged in.

Each name in extra MUST be new (a collision with an existing property raises ValueError naming it) and, unless allow_unprefixed is set, MUST carry a registered database-specific prefix (see register_definition_prefix() / known_definition_prefixes()); a custom property that does not is rejected with a ValueError explaining the OPTIMADE prefix rule.

as_optimade() dict[str, Any][source]

Return the entry type as a vendored-shape OPTIMADE document.

class httk.core.PropertyDefinition(name: str, payload: collections.abc.Mapping[str, Any])[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.

classmethod from_optimade(name: str, definition: collections.abc.Mapping[str, Any]) Self[source]

Wrap a full vendored OPTIMADE property definition.

definition must at least carry $id, description, x-optimade-type, and type; a clear ValueError is raised otherwise. The document is deep-copied.

classmethod from_simple(name: str, *, description: str, fulltype: str = 'string', unit: str | None = None, dimensions: collections.abc.Mapping[str, Any] | None = None, dict_properties: collections.abc.Mapping[str, str] | None = None, metadata_definition: collections.abc.Mapping[str, Any] | None = None, required_response: bool = False, definition_id: str | None = None) Self[source]

Generate a property definition from a compact description.

This mirrors the OPTIMADE property-definition generator: it emits the $schema meta-schema reference, a synthesized $id (under the base registered for a matching prefix via register_definition_prefix() — e.g. httk.org for _httk_ / _omdb_ — under schemas.optimade.org otherwise, unless definition_id overrides it), a title, the description, the OPTIMADE type derived from fulltype ("string", "integer", "float", "boolean", "timestamp", "dict", or "list of ..."), the x-optimade-unit (with an ångström unit definition when unit == "angstrom"), the x-optimade-definition stamp (format "1.2"; see the module docstring), the JSON type with nullability derived from required_response, items for lists, a date-time format for timestamps, inner properties for dicts (from dict_properties), x-optimade-dimensions from dimensions, and an x-optimade-metadata-definition (explicit, or a generated list_axes definition when dimensions is given).

The result is implementation-neutral: per-deployment sortable and response-default flags are layered on later via with_implementation().

property name: str
property definition_id: str
property title: str | None
property description: str
property optimade_type: str
property json_type: Any
property nullable: bool
property unit: str | None
property format_version: str | None
property requirements: collections.abc.Mapping[str, Any]
property dimensions: collections.abc.Mapping[str, Any] | None
property metadata_definition: collections.abc.Mapping[str, Any] | None
with_implementation(*, sortable: bool | None = None, response_default: bool | None = None) Self[source]

Return a copy carrying this deployment’s implementation flags.

Adds an x-optimade-implementation object with the sortable and response-default keys that are provided (a None argument leaves that key unset), and — when sortable is given — mirrors it in a top-level sortable field. The original instance is untouched.

as_optimade() dict[str, Any][source]

Return a deep copy of the wrapped property-definition document.

httk.core.known_definition_prefixes() tuple[str, Ellipsis][source]

Return the registered database-specific property-name prefixes.

The tuple reflects the current state of the prefix registry (see register_definition_prefix()); _httk_ and _omdb_ are pre-registered.

httk.core.load_entry_type_definition(package: str, name: str) EntryTypeDefinition[source]

Load a vendored OPTIMADE entry-type definition JSON from a package.

Reads optimade_defs/<name>.json from package (via importlib.resources) and models it as an EntryTypeDefinition. Results are cached per (package, name).

httk.core.register_definition_prefix(prefix: str, id_base: str) None[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 prefix gets its $id synthesized under id_base by PropertyDefinition.from_simple(), and EntryTypeDefinition.extended() accepts it as a custom property.

prefix must be a lower-case alphanumeric token wrapped in single underscores (matching _[a-z0-9]+_); anything else raises a clear ValueError. Re-registering an existing prefix overwrites its base.

httk.core.standard_entry_type(name: str) EntryTypeDefinition[source]

Return one of httk-core’s vendored standard OPTIMADE entry types.

Supported names are "references", "files", and "calculations"; an unknown name raises a ValueError listing the known ones. The structures standard is vendored by httk-atomistic, not httk-core.

httk.core.known_entry_providers() list[str][source]
httk.core.register_entry_provider(*, name: str, factory: str) None[source]

Register an EntryProvider factory under name.

factory is 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 mirrors register_loader.

httk.core.STORAGE_INFO_ATTRIBUTE: Final = '__httk_storage__'[source]

Class attribute name where a storable class may attach its StorageInfo.

type httk.core.DedupPolicy = Literal['content_id', 'by_value', 'none'][source]

How a storage layer deduplicates saved instances of a class.

  • "content_id": reuse an existing row whose stored content identity matches (the default; suited to immutable value objects).

  • "by_value": reuse an existing row whose stored columns all match (suited to join-objects such as tags and references, whose identity is their value).

  • "none": always insert a new row.

class httk.core.Indexed[source]

Field marker: request a single-column index on this field’s column(s).

class httk.core.Shape[source]

Field marker: fixed or variable shape for a vector-valued field.

rows >= 1 declares a fixed-shape value stored inline (flattened row-major into columns). rows == 0 declares a variable number of rows with cols fixed columns each, stored out-of-line (one row per entry, in insertion order).

Parameters:
  • rows – Number of rows; 0 means variable-length.

  • cols – Number of columns per row; must be at least 1.

rows: int
cols: int = 1
class httk.core.Skip[source]

Field marker: the field exists on the dataclass but is not stored.

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__), annotated ClassVar[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:
  • table_name – Storage table name; None derives one from the class name.

  • indexes – Composite indexes, each a tuple of field names.

  • dedup – Deduplication policy applied when saving; see DedupPolicy.

table_name: str | None = None
indexes: tuple[tuple[str, Ellipsis], Ellipsis] = ()
dedup: DedupPolicy = 'content_id'
class httk.core.Unique[source]

Field marker: request a unique index on this field’s column(s).

class httk.core.stored_property[source]

Bases: property

A 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__.

class httk.core.FracScalar(nom: int, denom: int)[source]

Bases: FracVector

Represents 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.

noms
denom
classmethod create(noms: Any, denom: int | None = None, simplify: bool = True, chain: bool = False, min_accuracy: fractions.Fraction | None = fractions.Fraction(1, 10000)) Self[source]

Create a FracScalar.

FracScalar.create(something) where something may be any object that can be used in the constructor of the Python Fraction class (also works with strings!).

Note: for signature-compatibility with FracVector.create(), this accepts chain and min_accuracy, but (as in the legacy implementation) it ignores them and converts strings exactly via the Fraction constructor.

class httk.core.FracVector(noms: Noms, denom: int = 1)[source]

FracVector is a general immutable N-dimensional vector (tensor) class for performing linear algebra with fractional numbers.

A FracVector consists of a multidimensional tuple of integer nominators, and a single shared integer denominator.

Since FracVectors are immutable, every operation on a FracVector returns a new FracVector with the result of the operation. A created FracVector never changes. Hence, they are safe to use as keys in dictionaries, to use in sets, etc.

Note: most methods return FracVector results that are not simplified (i.e., the FracVector returned does not have the smallest possible integer denominator). To return a FracVector with the smallest possible denominator, just call simplify() at the last step.

nested_map: ClassVar[collections.abc.Callable[Ellipsis, Any]]
nested_map_fractions: ClassVar[collections.abc.Callable[Ellipsis, Any]]
noms: Noms
denom: int
classmethod use(old: Any) FracVector[source]

Make sure the variable is a FracVector, and if not, convert it.

classmethod create(noms: Any, denom: int | None = None, simplify: bool = True, chain: bool = False, min_accuracy: fractions.Fraction | None = fractions.Fraction(1, 10000)) Self[source]

Create a FracVector from various types of sequences.

Simplest use:

FracVector.create(some_kind_of_sequence)

where ‘some_kind_of_sequence’ can be any nested list or tuple of objects that can be used in the constructor of the Python Fraction class (also works with strings!). If any object found while traveling the items has a .to_fractions() method, it will be called and is expected to return a fraction or list or tuple of fractions.

Parameters:
  • noms – any nested sequence of Fraction-constructible objects.

  • denom – an optional common denominator to divide all nominators with.

  • simplify – if True, return a FracVector with the smallest possible denominator.

  • chain – if True, remove the outermost dimension and chain the sub-sequences. I.e., if input=[[1, 2, 3], [4, 5, 6]] then FracVector.create(input) gives [1, 2, 3, 4, 5, 6].

  • min_accuracy – the minimum accuracy assumed in string input. The default is 1/10000, i.e. 0.33 = 0.3300 = 33/100, whereas 0.3333 = 1/3. Set it to None to assume infinite accuracy, i.e. convert exactly whatever string is given (unless a standard deviation is given as a parenthesis after the string).

Note: FracVector itself implements .to_fractions(), and hence the same constructor allows stacking several FracVector objects like this:

vertical_fracvector = FracVector.create([[fracvector1], [fracvector2]])
horizontal_fracvector = FracVector.create([fracvector1, fracvector2], chain=True)
classmethod create_fast(noms: Any, common_denom: int = 1, max_denom: int | None = None, denom: int | None = None, simplify: bool = True, chain: bool = False) Self[source]

Optimized version of create() that takes advantage of the fact that the type of noms is a nested list of ints (of depth 2 or 3) over a single common_denom.

get_append(other: Any) Self[source]
get_extend(other: Any) Self[source]
get_insert(pos: int, other: Any) Self[source]
get_prepend(other: Any) Self[source]
get_prextend(other: Any) Self[source]
get_stacked(other: Any) Self[source]

Return a new FracVector with other stacked after self along a new leading axis.

self and other must have the same shape; the result gains one extra outermost dimension of size two (numpy stack-like). E.g. stacking the row [1, 2, 3] with [4, 5, 6] gives [[1, 2, 3], [4, 5, 6]]. (The legacy version wrapped other in a redundant extra list, producing a ragged, non-rectangular result.)

get_prestacked(other: Any) Self[source]

Return a new FracVector with other stacked before self along a new leading axis.

The mirror of get_stacked(): stacking [1, 2, 3] in front with [4, 5, 6] gives [[4, 5, 6], [1, 2, 3]].

get_stackedinsert(pos: int, other: Any) Self[source]
classmethod chain_vecs(vecs: Any) Self[source]

Optimized chaining of FracVectors.

Parameters:

vecs – a list (or tuple) of fracvectors that all share the same denominator.

Returns the same thing as FracVector.create(vecs, chain=True), i.e., removes the outermost dimension and chains the sub-sequences. If input=[[1, 2, 3], [4, 5, 6]] then it gives [1, 2, 3, 4, 5, 6], but this method assumes all vectors share the same denominator (it raises an exception if this is not true).

classmethod stack_vecs(vecs: Any) Self[source]

Optimized stacking of FracVectors.

Parameters:

vecs – a list (or tuple) of fracvectors that all share the same denominator.

Returns the same thing as FracVector.create(vecs), but only works if all vectors share the same denominator (raises an exception if this is not true).

classmethod eye(dims: tuple[int, Ellipsis]) Self[source]

Create a diagonal one-matrix with the given dimensions.

classmethod zeros(dims: tuple[int, Ellipsis]) Self[source]

Create a zero matrix with the given dimensions.

classmethod random(dims: tuple[int, Ellipsis], minnom: int = -100, maxnom: int = 100, denom: int = 100) Self[source]

Create a matrix with the given dimensions filled with random rational numbers.

classmethod from_tuple(t: tuple[int, Noms]) Self[source]

Return a FracVector created from the tuple representation (denom, noms), as returned by the to_tuple() method. from_tuple(v.to_tuple()) reconstructs v exactly.

classmethod from_floats(data: Any, resolution: int = 2**32) Self[source]

Create a FracVector from a (nested) list or tuple of floats. You can convert a numpy array with this method if you use A.tolist().

Parameters:
  • l – the (nested) list or tuple of floats.

  • resolution – the resolution used for interpreting the given floating point numbers. Default is 2**32.

classmethod create_cos(data: Any, degrees: bool = False, limit: bool = False, find_best_rational: bool = True, prec: fractions.Fraction = fractions.Fraction(1, 1000000)) Self[source]

Create a FracVector as the cosine of the argument data. If data is composed of strings, the standard deviation of the numbers is taken into account, and the best possible fractional approximation to the cosines of the data is returned within the standard deviation.

This is not the same as FracVector.create(data).cos(), which creates the best possible fractional approximations of data and then takes cos on that.

classmethod create_sin(data: Any, degrees: bool = False, limit: bool = False, prec: fractions.Fraction = fractions.Fraction(1, 1000000)) Self[source]

Create a FracVector as the sine of the argument data. If data is composed of strings, the standard deviation of the numbers is taken into account, and the best possible fractional approximation to the sines of the data is returned within the standard deviation.

This is not the same as FracVector.create(data).sin(), which creates the best possible fractional approximations of data and then takes sin on that.

classmethod create_exp(data: Any, prec: fractions.Fraction = fractions.Fraction(1, 1000000), limit: bool = False) Self[source]

Create a FracVector as the exponent of the argument data. If data is composed of strings, the standard deviation of the numbers is taken into account, and the best possible fractional approximation to the exponents of the data is returned within the standard deviation.

This is not the same as FracVector.create(data).exp(), which creates the best possible fractional approximations of data and then takes exp on that.

classmethod pi(prec: fractions.Fraction = fractions.Fraction(1, 1000000), limit: bool = False) Self[source]

Create a scalar FracVector with a rational approximation of pi to precision prec.

property dim: tuple[int, Ellipsis]

A tuple with the dimensionality of each dimension of the FracVector (the noms are assumed to be a nested list of rectangular shape).

property nom: int

Return the integer nominator of a scalar FracVector.

validate() bool[source]
to_tuple() tuple[int, Noms][source]

Return the FracVector on tuple representation (denom, ...noms...).

to_floats() Any[source]

Convert the FracVector to a (nested) list of floats.

to_float() float[source]

Convert a scalar FracVector to a single float.

to_fractions() Any[source]

Convert the FracVector to a (nested) list of fractions.

to_ints() Any[source]

Convert the FracVector to a (nested) list of integers, rounded off as best possible.

to_strings(accuracy: int = 8) Any[source]

Convert the FracVector to a (nested) list of strings.

to_string(accuracy: int = 8) str[source]

Convert a scalar FracVector to a single string.

to_fraction() fractions.Fraction[source]

Convert a scalar FracVector to a fraction.

to_int() int[source]

Convert a scalar FracVector to an integer (truncating as necessary).

flatten() Self[source]

Return a FracVector that has been flattened out to a single row vector.

classmethod set_common_denom(A: Any, B: Any) tuple[Self, Self, int][source]

Used internally to combine two different FracVectors.

Returns a tuple (A2, B2, denom) where A2 is numerically equal to A, and B2 is numerically equal to B, but A2 and B2 are both set on the same shared denominator denom, which is the product of the denominators of A and B.

sign() int[source]

Return the sign of the scalar FracVector: -1, 0 or 1.

T() Self[source]

Return the transpose, A^T.

det() Self[source]

Return the determinant of the FracVector as a scalar FracVector.

inv() Self[source]

Return the matrix inverse, A^-1.

simplify() Self[source]

Return a reduced FracVector. I.e., each element has the same numerical value but the new FracVector represents them using the smallest possible shared denominator.

simplify_fast(depth: int) Self[source]

Return a reduced FracVector, taking advantage of a known nesting depth. I.e., each element has the same numerical value but the new FracVector represents them using the smallest possible shared denominator.

set_denominator(set_denom: int = 1000000000) Self[source]

Return a FracVector of reduced resolution where every element is the closest numerical approximation using this denominator.

limit_denominator(max_denom: int = 1000000000) Self[source]

Return a FracVector of reduced resolution.

Each element in the returned FracVector is the closest numerical approximation that is allowed by a fraction with maximally this denominator. Note: since all elements must be put on a common denominator, the result may have a larger denominator than max_denom.

floor() int[source]

Return the integer that is equal to or just below the value stored in a scalar FracVector.

modf() tuple[FracVector, FracVector][source]

Return the fractional and integer parts of each element as the pair (fractional, integer) of exact FracVectors sharing this vector’s denominator.

Both parts carry the sign of the element and the integer part truncates toward zero, matching the conventions of math.modf() (e.g. the value -5/2 splits into -1/2 and -2).

ceil() int[source]

Return the integer that is equal to or just above the value stored in a scalar FracVector.

normalize() Self[source]

Add/remove an integer +/-N to each element to place it in the range [0, 1).

normalize_half() Self[source]

Add/remove an integer +/-N to each element to place it in the range [-1/2, 1/2).

This is useful to find the shortest vector C between two points A, B in a space with periodic boundary conditions [0, 1):

C = (A - B).normalize_half()
mul(other: Any) Self[source]

Return the result of multiplying the vector with other using matrix multiplication.

Note that for two 1D FracVectors, A.dot(B) is not the same as A.mul(B), but rather A.mul(B.T()).

dot(other: FracVector) Self[source]

Return the vector dot product of the 1D vector with the 1D vector other, i.e., A . B. The same as A * B.T().

lengthsqr() Self[source]

Return the square of the length of the vector. The same as A * A.T().

cross(other: FracVector) Self[source]

Return the vector cross product of the 3-element 1D vector with the 3-element 1D vector other, i.e., A x B.

reciprocal() Self[source]

Return the reciprocal matrix of a 3x3 matrix (the rows are the reciprocal vectors, without the 2*pi factor).

metric_product(vecA: FracVector, vecB: FracVector) Self[source]

Return the result of the metric product using the present square FracVector as the metric matrix. The same as vecA * self * vecB.T().

cos(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

Return a FracVector where every element is the cosine of the element in the source FracVector.

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, interpret the elements in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

sin(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

Return a FracVector where every element is the sine of the element in the source FracVector.

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, interpret the elements in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

acos(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

Return a FracVector where every element is the arccos of the element in the source FracVector.

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, return the result in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

asin(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

Return a FracVector where every element is the arcsin of the element in the source FracVector.

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, return the result in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

exp(prec: fractions.Fraction | None = None, limit: bool = False) Self[source]

Return a FracVector where every element is the exponent of the element in the source FracVector.

Parameters:
  • prec – the precision (should be set as a fraction).

  • limit – if True, require the denominator to be smaller than or equal to the precision.

sqrt(prec: fractions.Fraction | None = None, limit: bool = False) Self[source]

Return a FracVector where every element is the sqrt of the element in the source FracVector.

Parameters:
  • prec – the precision (should be set as a fraction).

  • limit – if True, require the denominator to be smaller than or equal to the precision.

max() Self[source]

Return the maximum element across all dimensions in the FracVector. max(fracvector) works for a 1D vector.

nargmax() list[Any][source]

Return a list of indices of all maximum elements across all dimensions in the FracVector.

argmax() Any[source]

Return the index of the maximum element across all dimensions in the FracVector.

min() Self[source]

Return the minimum element across all dimensions in the FracVector. min(fracvector) works for a 1D vector.

nargmin() list[Any][source]

Return a list of indices for all minimum elements across all dimensions in the FracVector.

argmin() Any[source]

Return the index of the minimum element across all dimensions in the FracVector.

class httk.core.LeafCodec[source]

A leaf codec: a documented conversion of one exact fractions.Fraction leaf into a presentation leaf.

A codec is an orthogonal layer beside the vector backends: given a value already reduced to the canonical Fraction hub, it produces the requested element type. Its from_fraction documents both its exactness contract (when the result is exact) and its default conversion (what it does when an exact result is impossible); on data it never raises.

name: str

Canonical codec name (e.g. "int"); also how an explicit leaf= hint selects it.

from_fraction: collections.abc.Callable[Ellipsis, Any]

Convert (value: fractions.Fraction, **options) -> leaf from the canonical Fraction hub.

check_options: collections.abc.Callable[[dict[str, Any]], None]

Validate an options mapping eagerly, raising ValueError on any invalid option.

class httk.core.MutableFracVector(noms: Any, denom: int = 1)[source]

Bases: httk.core.vectors.fracvector.FracVector

Same 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.

However, methods have also been added named with set_* prefixes which 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
classmethod use(old: Any) httk.core.vectors.fracvector.FracVector[source]

Make sure the variable is a MutableFracVector, and if not, convert it.

to_FracVector() httk.core.vectors.fracvector.FracVector[source]

Return a FracVector with the values of this MutableFracVector.

classmethod from_FracVector(other: httk.core.vectors.fracvector.FracVector) MutableFracVector[source]

Create a MutableFracVector from a FracVector.

validate() bool[source]
invalidate() None[source]

Internal method to call when the MutableFracVector is changed in such a way that cached properties are invalidated (e.g., _dim).

set_negative() None[source]

Change the MutableFracVector inline into its own negative: self -> -self.

set_T() None[source]

Change the MutableFracVector inline into its own transpose: self -> self.T.

set_inv() Any[source]

Change the MutableFracVector inline into its own inverse: self -> self^-1.

set_simplify() None[source]

Change the MutableFracVector; reduces any common factor between the denominator and all nominators.

set_set_denominator(resolution: int = 1000000000) None[source]

Change the MutableFracVector; reduces resolution.

Parameters:

resolution – the new denominator; each element becomes the closest numerical approximation using this denominator.

set_normalize() None[source]

Add/remove an integer +/-N to each element to place it in the range [0, 1).

set_normalize_half() None[source]

Add/remove an integer +/-N to each element to place it in the range [-1/2, 1/2).

This is useful to find the shortest vector C between two points A, B in a space with periodic boundary conditions [0, 1):

C = (A - B).normalize_half()
type httk.core.NumericVector = float | numpy.ndarray[source]
class httk.core.SurdScalar(components: dict[int, httk.core.vectors.fracvector.FracVector], dim: tuple[int, Ellipsis])[source]

Bases: SurdVector

A 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.

inverse() SurdScalar[source]

The multiplicative inverse 1/self (raises ZeroDivisionError on zero).

sign() int[source]

Return the exact sign of the value: -1, 0 or 1.

For an irrational value the sign is decided by refining rational lower/upper bounds on each sqrt(r) (from integer_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.

classmethod cos_degrees(q: Any) SurdScalar | None[source]

Return cos(q degrees) as an exact SurdScalar, 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\). q may be an int, Fraction, or numeric string (parsed via any_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 None result is therefore a proof that the exact cosine lies outside \(\mathbb{Q}[\sqrt n]\) — use cos() with degrees=True for a deterministic rational approximation in that case.

classmethod sin_degrees(q: Any) SurdScalar | None[source]

Return sin(q degrees) as an exact SurdScalar, or None when it is irrational.

Computed as cos(90 - q) degrees, so exactness follows the same classification as cos_degrees() applied to 90 - q: exact for all multiples of 15 degrees, otherwise None (a proof that the exact sine is outside the field). Note the asymmetry with cos_degrees() for the 36° family: \(\cos 36°\) is an exact surd but \(\sin 36° = \cos 54°\) is not (54 is a multiple of neither 15 nor 36).

acos_degrees() fractions.Fraction | None[source]

Return the exact arccos of 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). Raises ValueError — decided exactly via sign() — when the value lies outside \([-1, 1]\).

to_float(prec: fractions.Fraction = fractions.Fraction(1, 10**30)) float[source]

The value as a float (via a high-precision exact rational approximation).

to_decimal(digits: int | None = None, rounding: str = 'half_even', max_refinements: int | None = None) Any[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") and max_refinements match sqrt() in Decimal mode.

class httk.core.SurdVector(components: dict[int, httk.core.vectors.fracvector.FracVector], dim: tuple[int, Ellipsis])[source]

An 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 one dim); radicand 1 is the rational part. It is stored canonically — coefficients simplified, all-zero coefficients dropped — so the representation is unique and equality/zero-detection are exact. Like FracVector it 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.

classmethod create(obj: Any) SurdVector[source]

Create a SurdVector from a FracVector, nested rationals, or another SurdVector.

A SurdVector is returned unchanged; anything else is built through create() and embedded exactly at radicand 1 (so every rational value is representable, and a rational input stays rational).

classmethod from_radicand_map(mapping: dict[int, Any]) SurdVector[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: Any) SurdScalar[source]

Return the exact square root of a nonnegative rational q as a SurdScalar.

The result is a plain rational when q is 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 as sqrt(p*q)/q so the stored radicand is always a positive squarefree integer (sqrt_of(1/2) == sqrt(2)/2). Raises ValueError on a negative argument — there is no exact square root of a surd (no nested radicals), only of a rational.

classmethod zero(dim: tuple[int, Ellipsis] = ()) SurdVector[source]

The zero SurdVector of shape dim (a SurdScalar for the default ()).

classmethod one() SurdScalar[source]

The scalar 1.

property dim: tuple[int, Ellipsis]

The shape tuple, as for dim.

property is_rational: bool

True iff the value is purely rational (only the radicand-1 term is present).

is_zero() bool[source]

True iff the value is exactly zero (empty canonical form).

property radicands: tuple[int, Ellipsis]

The sorted squarefree radicands present in the canonical form.

coefficient(radicand: int) httk.core.vectors.fracvector.FracVector[source]

The FracVector coefficient of sqrt(radicand) (a zero tensor when absent).

T() SurdVector[source]

Return the transpose, transposing each radicand’s coefficient tensor.

dot(other: Any) SurdScalar[source]

Vector dot product of two 1-D SurdVectors (sum a_i b_i).

lengthsqr() SurdScalar[source]

Return the squared length A * A^T as a SurdScalar.

length() SurdScalar[source]

Return the exact length sqrt(lengthsqr) as a SurdScalar.

Exact precisely when lengthsqr is rational — which canonical arithmetic guarantees for a difference of Cartesian sites under a rational metric (the crystallographic case). When lengthsqr is itself irrational the length would be a nested radical (sqrt(a + b*sqrt(c))), which is outside the field, so this raises ValueError.

det() SurdScalar[source]

Return the determinant of a 3x3 SurdVector as a SurdScalar.

inv() SurdVector[source]

Return the inverse of a 3x3 SurdVector via the adjugate and the scalar field inverse.

to_fractions_approx(prec: fractions.Fraction = fractions.Fraction(1, 10**30)) Any[source]

A deterministic nested list of fractions.Fraction within prec of the true value.

Exact (not merely within prec) whenever the value is rational. This is the compute(prec)-shaped rational approximation reused by the Decimal rendering.

to_floats(prec: fractions.Fraction = fractions.Fraction(1, 10**30)) Any[source]

A nested list of floats (via a high-precision exact rational approximation).

class httk.core.VectorAPI[source]

Bases: abc.ABC

Abstract base class for the canonical vector interface.

It declares the exactness-preserving fractions accessor (a nested tuple of fractions.Fraction, or a bare Fraction for a scalar) that every vector backend produces from its own native representation and every vector view builds its presentation from, together with the dim shape tuple. This is the single interchange format; there is no pairwise conversion between backends.

On top of the two abstract accessors it provides the guaranteed float renderings to_floats() and to_float(), derived from the fractions hub — so whatever object the family hands you, .to_floats() works. (The exact value types FracVector and SurdVector honor the same contract with their own implementations.)

property fractions: Fractions
Abstractmethod:

property dim: tuple[int, Ellipsis]
Abstractmethod:

to_floats() Any[source]

The value as (possibly nested) plain lists of float — a bare float for a scalar.

Derived from the exact fractions hub; nested lists match the numpy.ndarray.tolist() convention and are directly JSON-serializable.

to_float() float[source]

The scalar value as a plain float; raises TypeError on a non-scalar.

class httk.core.VectorBackend(backend, **hints)[source]

Bases: httk.core.views.Backend[VectorBackend], httk.core.vectors.vector_api.VectorAPI

Abstract base class for all backends of vector (tensor) data.

Concrete backends carry a native representation (an exact FracVector, plain nested sequences, or a numpy array) and produce the canonical exactness-preserving fractions interchange declared by VectorAPI from it.

backend_classes: ClassVar[list[type[httk.core.views.Backend[Any]]]]
class httk.core.VectorFrac(obj: httk.core.vectors.fracvector.FracVector, **hints: Any)[source]

Bases: httk.core.vectors.vector_backend.VectorBackend

Backend for a vector backed by an actual FracVector (or FracScalar).

Its fractions accessor produces the exact nested tuple of Fraction, and unwrap returns the wrapped FracVector.

property fractions: httk.core.vectors.vector_api.Fractions
property dim: tuple[int, Ellipsis]
unwrap() Any[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.

class httk.core.VectorFracView(obj: httk.core.vectors.vector_like.VectorLike, denom: Any = _NO_DENOM, **hints: Any)[source]

Bases: httk.core.vectors.vector_view.VectorView, httk.core.vectors.fracvector.FracVector

A view presenting an underlying vector backend as an exact FracVector.

This view is a genuine FracVector, so it can be passed anywhere a FracVector is accepted, and it exposes the full exact-rational algebra (det/inv/*/…). It is built eagerly from the backend’s exact fractions interchange on construction, so the round-trip is exactness-preserving for the frac and native backends. (numpy values are binary rationals, so a numpy source round-trips to the exact float64 rational, not necessarily the original decimal fraction.)

Because inherited FracVector algebra builds its results with the low-level self.__class__(noms, denom) constructor, this class also accepts that two-argument form; results built that way are plain (backend-less) FracVector values presented through this class.

unwrap() Any[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.

type httk.core.VectorLike = vector_backend.VectorBackend | vector_view.VectorView | fracvector.FracVector | surdvector.SurdVector | tuple[Any, ...] | list[Any] | 'numpy.ndarray'[source]
class httk.core.VectorNative(obj: Any, **hints: Any)[source]

Bases: httk.core.vectors.vector_backend.VectorBackend

Backend for a vector backed by plain nested sequences.

The native representation is a (possibly nested) rectangular list or tuple whose leaves are int, float, decimal.Decimal, fractions.Fraction, or str. Conversion into the exact fractions interchange goes through create(), so string-uncertainty parsing (e.g. "0.33342(10)") works here too. unwrap returns the original raw object.

property native: Any

The original nested list/tuple this backend wraps, leaves untouched.

This is the same object returned by unwrap(), exposed as a named accessor so the native view can present a natively-held vector’s leaves verbatim (its preserve-original default) without reaching into private state.

property fractions: httk.core.vectors.vector_api.Fractions
property dim: tuple[int, Ellipsis]
unwrap() Any[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.

class httk.core.VectorNativeView(obj: httk.core.vectors.vector_like.VectorLike, **hints: Any)[source]

Bases: httk.core.vectors.vector_view.VectorView, tuple

A view presenting an underlying vector backend as nested tuples, with a selectable leaf codec.

The leaf codec is the element-domain axis (see httk.core.vectors.leaf_codecs); it is chosen with the leaf= hint plus any codec options (rounding=, digits=, …). There are three modes:

  • preserve-original (leaf=None, and the source is natively-held data): the backend’s original nested leaves are presented verbatim — the same objects, only containers tuple-ized (Decimals in, the same Decimals out). This fixes silent Fraction-ization of natively-held data.

  • exact default (leaf=None, source crossing from a frac/numpy backend): the "exact" codec — int when integral, else fractions.Fraction, never a float (the historical behavior).

  • explicit codec (leaf="int"/"float"/"decimal"/"fraction"/…): every element is converted from the backend’s exact fractions interchange through that codec.

The codec name and its options are validated eagerly at construction (an unknown codec name or invalid option raises ValueError); a codec never raises on the data — a value it cannot represent exactly takes the codec’s documented default conversion, because the backend keeps the exact original. A scalar source is presented as a single-element tuple.

unwrap() Any[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.

class httk.core.VectorSurd(obj: httk.core.vectors.surdvector.SurdVector, **hints: Any)[source]

Bases: httk.core.vectors.vector_backend.VectorBackend

Backend for a vector backed by an exact SurdVector (or SurdScalar), kind "surd".

unwrap returns the exact SurdVector. The canonical fractions hub is exact whenever the value is rational (a surd whose canonical form has only the radicand-1 term), matching the established backend-keeps-the-original principle; when the value is genuinely irrational it is reduced to a deterministic rational approximation at the active decimal context precision plus a small guard (lossy but reproducible), and the exact original remains recoverable via unwrap.

property fractions: httk.core.vectors.vector_api.Fractions
property dim: tuple[int, Ellipsis]
unwrap() Any[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.

class httk.core.VectorSurdView(obj: httk.core.vectors.vector_like.VectorLike, **hints: Any)[source]

Bases: httk.core.vectors.vector_view.VectorView, httk.core.vectors.surdvector.SurdVector

A view presenting an underlying vector backend as an exact SurdVector.

This view is a genuine SurdVector, so it exposes the full exact surd algebra (det/inv/*/length/…). It is built eagerly on construction, following the eager immutable-subclass pattern of VectorFracView: from a surd backend it adopts the exact SurdVector directly, and from a frac/native/numpy backend it embeds the backend’s exact rational fractions at radicand 1 — exactly, since every rational is a surd.

(numpy values are binary rationals, so a numpy source embeds the exact float64 rational, not necessarily the original decimal fraction — the same caveat as VectorFracView.)

unwrap() Any[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.

class httk.core.VectorView[source]

Bases: httk.core.views.View[httk.core.vectors.vector_backend.VectorBackend]

Abstract base class for all views of vector (tensor) data.

httk.core.known_leaf_codecs() list[str][source]

Return the registered leaf-codec names, in registration order.

httk.core.numpy_available() bool[source]

Return whether the optional numpy dependency is available for the numeric helpers.

This reads the vectors package’s _numpy_available flag freshly on each call (the flag set when httk.core.vectors conditionally imports/registers the numpy backend), so tests may monkeypatch httk.core.vectors._numpy_available to exercise the numpy-absent path.

httk.core.register_leaf_codec(codec: LeafCodec) None[source]

Register (or replace) a codec under its name.

httk.core.to_numeric(obj: httk.core.vectors.vector_like.VectorLike) NumericVector[source]

Present obj as plain numpy numbers: a numpy.ndarray for a tensor, a float for a scalar.

A tensor becomes a base-class float64 numpy.ndarray (never a view subclass) via VectorNumpyView; a scalar input (shape ()) returns a plain float via to_numeric_scalar() (never a 0-d array).

The numeric presentation is numpy-backed, so this always requires numpy: it raises ImportError (naming the httk-core[numpy] extra) when numpy is not installed, uniformly, so the contract is predictable regardless of the input shape. Use to_numeric_scalar() directly for a single float without a numpy requirement.

httk.core.to_numeric_scalar(obj: Any) float[source]

Convert a single scalar value to a plain float, deterministically.

A SurdScalar (or scalar SurdVector) and a scalar FracVector render through their own exact to_float(); a Fraction, int, float, or numeric str render via any_to_fraction(). A non-scalar shape raises TypeError.

Unlike to_numeric(), this needs no numpy: a plain float conversion 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.ABC

Abstract 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.

backend_classes: ClassVar[list[type[Backend[Any]]]]
classmethod create(obj: Any, **hints: Any) Self[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 __new__ does not return None. 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.

unwrap() Any[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.

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 excpectation should be that the original X object is now 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.

unwrap() Any[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.

httk.core.unwrap(obj: Any) Any[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.

httk.core.subpackages[source]