httk.optimade.backend¶
Submodules¶
Classes¶
A single query under construction, and its results once iterated. |
|
Base class for protocol classes. |
|
A queryable field of a search variable. |
|
One match: the declared output values, and the names they were declared under. |
|
A query variable bound to a target type; attribute access yields fields. |
|
Base class for protocol classes. |
|
Binds a store to the OPTIMADE entry endpoints it serves. |
|
One queryable source (table/type) behind an OPTIMADE entry endpoint. |
|
Results of a query over one or more searchers. |
|
A store over dict rows: |
|
One list axis of a |
|
A property value provided lazily, one slice at a time. |
|
The callback seam through which the request engine runs queries on a backend. |
|
The results of a query against a backend, as consumed by the entry endpoints. |
Functions¶
|
|
|
Build a filter handler table for an entry type from a property-key map. |
Build a |
|
|
Return the registered entry-provider factories keyed by their registered name. |
|
Build one searcher per entry source, with the filter applied to each. |
|
Translate one filter node against an OPTIMADE entry-info property mapping. |
Package Contents¶
- class httk.optimade.backend.Searcher[source]¶
Bases:
ProtocolA single query under construction, and its results once iterated.
Iteration yields one
SearchResultper match, soitem[0][0]is the first declared output of the match (typically the matched row object). The expressions received byaddare always ones produced by this same backend’s search variables, so implementations may type them as their own expression class; a backend that needs a second (post-filter) evaluation position decides that from the expression itself, not from the caller.
- class httk.optimade.backend.SearchExpression[source]¶
Bases:
ProtocolBase class for protocol classes.
Protocol classes are defined as:
class Proto(Protocol): def meth(self) -> int: ...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).
For example:
class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:
class GenProto[T](Protocol): def meth(self) -> T: ...
- class httk.optimade.backend.SearchField[source]¶
Bases:
ProtocolA queryable field of a search variable.
In addition to the methods below, fields support the rich comparison operators (
==,!=,<,<=,>,>=), returningSearchExpression. The handlers invoke those viagetattr(field, '__eq__')(value)since the comparison dunders cannot be typed as expression-returning.The three string-matching methods take literal text: no wildcard or pattern syntax whatsoever crosses this contract, so
%and_(and any other metacharacter) match themselves. A backend is therefore free to implement them with SQLLIKEover an escaped pattern, with a regular expression, or with a full-text index — the choice is invisible here.- has_any(*values: Any) SearchExpression[source]¶
- has_only(*values: Any) SearchExpression[source]¶
- contains(text: str) SearchExpression[source]¶
Match values containing
textas a literal substring.
- startswith(prefix: str) SearchExpression[source]¶
Match values beginning with the literal
prefix.
- endswith(suffix: str) SearchExpression[source]¶
Match values ending with the literal
suffix.
- class httk.optimade.backend.SearchResult[source]¶
Bases:
NamedTupleOne match: the declared output values, and the names they were declared under.
valuesholds one entry perSearcher.output()call in declaration order; it is a tuple, sovalues, names = resultandresult[0][0]both work.
- class httk.optimade.backend.SearchVariable[source]¶
Bases:
ProtocolA query variable bound to a target type; attribute access yields fields.
always_true/always_falseare reserved names: they are real methods of the variable, never stored fields resolved through__getattr__. They exist so a translation layer can express a constant truth value without inventing a probe field. Afield == fieldprobe is NULL-unsound, since it yields NULL (not true) for a NULL field.- always_true() SearchExpression[source]¶
An expression that matches every row.
- always_false() SearchExpression[source]¶
An expression that matches no row.
- class httk.optimade.backend.Store[source]¶
Bases:
ProtocolBase class for protocol classes.
Protocol classes are defined as:
class Proto(Protocol): def meth(self) -> int: ...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).
For example:
class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:
class GenProto[T](Protocol): def meth(self) -> T: ...
- class httk.optimade.backend.BackendAdapter[source]¶
Binds a store to the OPTIMADE entry endpoints it serves.
sourcesmaps entry endpoint names (e.g.'structures') to the sources queried for that endpoint; an endpoint with several sources (e.g. several calculation result types) is queried across all of them.schemais required: it declares the served entry types and properties.field_handlersmaps each entry type to its filter-handler table. When omitted (left empty) it is derived fromschemaviasimple_property_handlers(), using an identity property-key map (each property is filtered against a backend field of the same name); a backend whose field names differ, or that wants finer control, supplies its own tables instead.- store: httk.data.query.Store¶
- field_handlers: collections.abc.Mapping[str, httk.data.optimade_query.HandlerTable]¶
- query_function() httk.optimade.model.results.QueryFunction[source]¶
- class httk.optimade.backend.EntrySource[source]¶
One queryable source (table/type) behind an OPTIMADE entry endpoint.
targetis what gets passed tosearcher.variable();fieldsmaps OPTIMADE response-field names to extractors applied to matched row objects.relationships, when set, is an extractor mapping a matched row to a dictionary keyed by related entry type, each value a list of{'id': str, 'description': str?, 'role': str?}dictionaries.sort_keysmaps response-field names to the backend field names to sort on.property_metadatamaps response-field names to extractors returning the per-property metadata dictionary for a matched row (orNonewhen there is no metadata for that row).- target: Any¶
- fields: collections.abc.Mapping[str, FieldExtractor]¶
- sort_keys: collections.abc.Mapping[str, str]¶
- relationships: FieldExtractor | None = None¶
- property_metadata: collections.abc.Mapping[str, FieldExtractor]¶
- class httk.optimade.backend.StoreResults(pairs: list[tuple[httk.optimade.backend.adapter.EntrySource, httk.data.query.Searcher]], response_fields: list[str], unknown_response_fields: list[str], limit: int | None, offset: int, recognized_prefixes: tuple[str, Ellipsis])[source]¶
Results of a query over one or more searchers.
Implements the
QueryResultsprotocol. Iteration yields oneResultRowper entry, whose values map response-field names to values extracted from the matched row objects.- pairs¶
- recognized_prefixes¶
- limit¶
- response_fields¶
- unknown_response_fields¶
- offset¶
- more_data_available = True¶
- httk.optimade.backend.execute_query(adapter: httk.optimade.backend.adapter.BackendAdapter, entries: list[str], response_fields: list[str], unknown_response_fields: list[str], response_limit: int | None, response_offset: int | None, filter_ast: httk.core.FilterAst | None = None, *, sort: collections.abc.Sequence[tuple[str, bool]] | None = None, debug: bool = False) StoreResults[source]¶
- httk.optimade.backend.simple_property_handlers(entry_type: str, property_keys: collections.abc.Mapping[str, str], property_fulltypes: collections.abc.Mapping[str, str]) dict[str, collections.abc.Mapping[str, collections.abc.Callable[Ellipsis, Any]]][source]¶
Build a filter handler table for an entry type from a property-key map.
Always provides the standard
id(matched against the__idfield) andtype(a constant equal toentry_type) handlers. For every property named inproperty_keys(which maps property names to backend field names), handlers are generated from the property’s fulltype inproperty_fulltypes(default"string"): string properties get comparison and stringmatching handlers; integer and float properties get a numeric comparison handler;list of ...properties get a HAS (set membership) handler. Every generated property also gets aknownunknown handler.
- class httk.optimade.backend.InMemoryStore(tables: dict[str, list[Row]])[source]¶
A store over dict rows:
InMemoryStore({'structures': [ {...}, ... ]}).- tables¶
- searcher() MemorySearcher[source]¶
- class httk.optimade.backend.PartialDimension[source]¶
One list axis of a
PartialValue.lengthis the number of items along the axis (Nonewhen unknown or entry-dependent and not declared).sliceableindicates whether the server can honour a slice request for this axis.
- class httk.optimade.backend.PartialValue[source]¶
A property value provided lazily, one slice at a time.
fetchtakes a tuple of Python slices (one per dimension, with the usual exclusive stop) and returns the corresponding nested lists.- dimensions: tuple[PartialDimension, Ellipsis]¶
- fetch: collections.abc.Callable[[tuple[slice, Ellipsis]], Any]¶
- class httk.optimade.backend.QueryFunction[source]¶
Bases:
ProtocolThe callback seam through which the request engine runs queries on a backend.
- class httk.optimade.backend.QueryResults[source]¶
Bases:
ProtocolThe results of a query against a backend, as consumed by the entry endpoints.
Iteration yields one
ResultRowper entry; itsvaluesmap OPTIMADE response-field names to values, and theidandtypekeys are always present.
- httk.optimade.backend.adapter_from_providers(providers: collections.abc.Iterable[httk.core.EntryProvider], **options: Any) httk.optimade.backend.adapter.BackendAdapter[source]¶
Build a
BackendAdapterserving the given entry providers.Every provider’s
entry_types()become served entry types (described by theirEntryTypeDefinition), itsproperty_keys()name the served subset and drive both the filter handlers (viasimple_property_handlers()) and the response-field extractors, and itsrecords()are loaded into anInMemoryStore. Every served property MUST be described by the entry type’s definition (a custom property must therefore live in anextended()definition); aValueErrornames any offender. All served properties beyondid/typeare marked default-response. Extra keywordoptions(e.g.sortable,recognized_prefixes) are forwarded tobuild_served_schema(); every served property is sortable-capable, since the provider’s property-key map is passed through as the source’ssort_keys.Declared relationships (
relationships()) are fully auto-wired for serving and filtering: for each entry type with declared relationships, a synthetic__rel_<related_type>id-list field is materialized on EVERY row of that entry type (an empty list when the row has no related entries of that type, so inverse set semantics are well-defined), and a'<related_type>.id'entry built withrelationship_id_handler()is merged into the entry type’s derived filter-handler table (never overwriting an entry already present, mirroring howBackendAdapterrespects explicitly supplied handler tables).<related_type>.id HAS ...filters — and, through the related-property resolver oftranslate_filter(), depth-1 relationship-property filters such asreferences.doi CONTAINS "10.1"— therefore work without any hand-wiring.
- httk.optimade.backend.providers_from_registry() dict[str, collections.abc.Callable[Ellipsis, httk.core.EntryProvider]][source]¶
Return the registered entry-provider factories keyed by their registered name.
Resolves each factory registered via
httk.core.register_entry_provider()(throughhttk.handlers.*self-registration) into a callable. Providers need data, so applications instantiate them:providers_from_registry()["atomistic-structures"](data).
- httk.optimade.backend.translate_filter(filter_ast: httk.core.FilterAst | None, entries: list[str], adapter: httk.optimade.backend.adapter.BackendAdapter, sort: collections.abc.Sequence[tuple[str, bool]] | None = None) list[tuple[httk.optimade.backend.adapter.EntrySource, httk.data.query.Searcher]][source]¶
Build one searcher per entry source, with the filter applied to each.
Relationship-property filters (dotted identifiers over served entry types) are resolved through the adapter’s related-property resolver (built by
_related_property_resolver), so filteringreferences.doibehaves exactly like filtering/referencesdirectly.
- httk.optimade.backend.translate_filter_node(node: httk.core.FilterAst, search_variable: httk.data.query.SearchVariable, entry: str, entry_info: collections.abc.Mapping[str, Any], handlers: httk.data.optimade_query.HandlerTable, recognized_prefixes: tuple[str, Ellipsis], served_entries: tuple[str, Ellipsis] = ()) httk.data.query.SearchExpression[source]¶
Translate one filter node against an OPTIMADE entry-info property mapping.
An OPTIMADE-side adaptation of
translate_filter_ast():entry_infomaps property names to their property dictionaries (only their'fulltype'keys are read) rather than straight to fulltypes,served_entriesnames the relationship targets, and failures surface asTranslatorErrorinstead of the upstream neutralFilterTranslationError.No related-property resolver is threaded through, so relationship-property filters other than
<type>.id HAS ...raise a not-implemented (501) error. Usetranslate_filter()(which builds the resolver from its adapter) for full relationship-property filtering.