Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Subclass routing solution was broken #619

Merged
merged 1 commit into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions autochem/rate/_00func.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Blending function models."""

import abc
from typing import Annotated, TypeVar
from typing import Annotated, TypeVar, ClassVar

import numpy
import pydantic
Expand Down Expand Up @@ -31,7 +31,7 @@ def __call__(self, t: ArrayLike, p_r: ArrayLike) -> numpy.ndarray:
class LindemannBlendingFunction(BlendingFunction):

# Private attributes
_type: str = "lindemann"
type_: ClassVar[str] = "lindemann"

def __call__(self, t: ArrayLike, p_r: ArrayLike) -> numpy.ndarray:
"""Evaluate blending function, f(t, p_r)."""
Expand All @@ -45,7 +45,7 @@ class TroeBlendingFunction(BlendingFunction):
t2: float | None = None

# Private attributes
_type: str = "troe"
type_: ClassVar[str] = "troe"

def __call__(self, t: ArrayLike, p_r: ArrayLike) -> numpy.ndarray:
"""Evaluate blending function, f(t, p_r)."""
Expand Down Expand Up @@ -84,7 +84,7 @@ class SriBlendingFunction(BlendingFunction):
e: float = 0.0

# Private attributes
_type: str = "sri"
type_: ClassVar[str] = "sri"

def __call__(self, t: ArrayLike, p_r: ArrayLike) -> numpy.ndarray:
"""Evaluate blending function, f(t, p_r)."""
Expand Down
20 changes: 14 additions & 6 deletions autochem/rate/_01const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Rate constant models."""

import abc
from collections.abc import Mapping
from typing import Annotated, ClassVar

import more_itertools as mit
Expand Down Expand Up @@ -87,7 +88,7 @@ class RawRateConstant(RateConstant):
# Private attributes
_t_key = "t"
_p_key = "p"
_type: str = "raw"
type_: ClassVar[str] = "raw"
_scalers: ClassVar[Scalers] = {"k_array": numpy.multiply}
_dimensions: ClassVar[dict[str, Dimension]] = {
"ts": Dimension.temperature,
Expand Down Expand Up @@ -128,14 +129,21 @@ def third_body(self) -> str | None:

return next((c for c, e in eff.items() if e == 1.0), None)

@pydantic.field_validator("efficiencies", mode="before")
@classmethod
def sanitize_efficiencies(cls, value: object) -> object:
if isinstance(value, Mapping):
return {k: v for k, v in value.items() if v is not None}
return value


class ArrheniusRateConstant(ParamRateConstant):
A: float = 1.0
b: float = 0.0
E: float = 0.0

# Private attributes
_type: str = "arrhenius"
type_: ClassVar[str] = "arrhenius"
_scalers: ClassVar[Scalers] = {"A": numpy.multiply}
_dimensions: ClassVar[dict[str, Dimension]] = {
"A": Dimension.rate_constant,
Expand Down Expand Up @@ -224,7 +232,7 @@ def effective_reduced_pressure(
class FalloffRateConstant(BlendedRateConstant):

# Private attributes
_type: str = "falloff"
type_: ClassVar[str] = "falloff"

@unit_.manage_units(
[Dimension.temperature, Dimension.pressure], Dimension.rate_constant
Expand All @@ -243,7 +251,7 @@ def __call__(
class ActivatedRateConstant(BlendedRateConstant):

# Private attributes
_type: str = "activated"
type_: ClassVar[str] = "activated"

@unit_.manage_units(
[Dimension.temperature, Dimension.pressure], Dimension.rate_constant
Expand All @@ -266,7 +274,7 @@ class PlogRateConstant(ParamRateConstant):
ps: list[float]

# Private attributes
_type: str = "plog"
type_: ClassVar[str] = "plog"
_scalers: ClassVar[Scalers] = {"As": numpy.multiply}
_dimensions: ClassVar[dict[str, Dimension]] = {
"As": Dimension.rate_constant,
Expand Down Expand Up @@ -371,7 +379,7 @@ class ChebRateConstant(ParamRateConstant):
p_range: tuple[float, float]

# Private attributes
_type: str = "cheb"
type_: ClassVar[str] = "cheb"
_scalers: ClassVar[Scalers] = {"coeffs": numpy.multiply}
_dimensions: ClassVar[dict[str, Dimension]] = {
"coeffs": Dimension.rate_constant,
Expand Down
24 changes: 17 additions & 7 deletions autochem/util/type_.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,29 +39,29 @@ class SubclassTyped(pydantic.BaseModel, abc.ABC):

Usage:
```
from typing import Final
from typing import ClassVar

class A(SubclassTyped):
x: int

class B(A):
_type: str = "b"
type: ClassVar[str] = "b"

class C(A):
_type: str = "c"
type: ClassVar[str] = "c"

A.from_data({"x": 1, "type": "b"})

# output: B(x=5)
```
"""

_type: str
type_: ClassVar[str] = ""

@pydantic.computed_field
def type(self) -> str:
"""Subclass type."""
return self._type
return self.__class__.type_

@classmethod
def model_validate(
Expand All @@ -76,8 +76,8 @@ def model_validate(
if isinstance(obj, Mapping) and "type" in obj:
assert "type" in obj, f"Missing type field: {obj}"
obj = dict(obj).copy()
_type = obj.pop("type")
sub = next((s for s in cls.__subclasses__() if s._type == _type), None)
typ = obj.pop("type")
sub = next((s for s in subclasses(cls) if s.type_ == typ), None)
if sub is not None:
return sub.model_validate(
obj, strict=strict, from_attributes=from_attributes, context=context
Expand All @@ -88,6 +88,16 @@ def model_validate(
)


def subclasses(cls: type[SubclassTyped]) -> list[type[SubclassTyped]]:
subs = []

for sub in cls.__subclasses__():
subs.append(sub)
subs.extend(subclasses(sub))

return subs


class Scalable(pydantic.BaseModel, abc.ABC):
"""Abstract base class for models with scalar multiplication.

Expand Down