Skip to content

Commit

Permalink
Merge branch 'master' into molextras
Browse files Browse the repository at this point in the history
  • Loading branch information
loriab committed Sep 3, 2019
2 parents 35bbd94 + 7cb0fc8 commit e4f2cc9
Show file tree
Hide file tree
Showing 20 changed files with 255 additions and 163 deletions.
13 changes: 10 additions & 3 deletions qcelemental/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,23 @@
"""

from . import models, molparse, molutil, util
from .covalent_radii import CovalentRadii, covalentradii
from .datum import Datum
from .exceptions import ChoicesError, DataUnavailableError, MoleculeFormatError, NotAnElementError, ValidationError
# Handle versioneer
from .extras import get_information
# Handle singletons, not their classes or modules
from .periodic_table import periodictable
from .physical_constants import PhysicalConstantsContext, constants
from . import covalent_radii, periodic_table, physical_constants
# from .physical_constants import PhysicalConstantsContext, constants
from .testing import compare, compare_recursive, compare_values

# Expose singletons from the modules
periodictable = periodic_table.periodictable
PhysicalConstantsContext = physical_constants.PhysicalConstantsContext
constants = physical_constants.constants
CovalentRadii = covalent_radii.CovalentRadii
covalentradii = covalent_radii.covalentradii

# Remove singleton-providing modules from known imported objects
del periodic_table
del physical_constants
del covalent_radii
Expand Down
10 changes: 6 additions & 4 deletions qcelemental/covalent_radii.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import collections
from decimal import Decimal
from typing import Union
from typing import Union, Dict

from .datum import Datum, print_variables
from .exceptions import DataUnavailableError
Expand Down Expand Up @@ -38,21 +38,22 @@ class CovalentRadii:
"""
def __init__(self, context: str = "ALVAREZ2008"):
self.cr = collections.OrderedDict()
self.cr: Dict[str, Datum] = collections.OrderedDict()

from .data import alvarez_2008_covalent_radii

if context == "ALVAREZ2008":
self.doi = alvarez_2008_covalent_radii["doi"]
self.native_units = alvarez_2008_covalent_radii["units"]

for cr in alvarez_2008_covalent_radii["covalent_radii"]:
# TypedDict wont be in until 3.8, have to ignore heterogeneous dicts for now
for cr in alvarez_2008_covalent_radii["covalent_radii"]: # type: ignore
self.cr[cr[0]] = Datum(cr[0], self.native_units, Decimal(cr[1]), comment=cr[2], doi=self.doi)
else:
raise KeyError("Context set as '{}', only contexts {'ALVAREZ2008', } are currently supported")

self.name = context
self.year = int(alvarez_2008_covalent_radii["date"][:4])
self.year = int(alvarez_2008_covalent_radii["date"][:4]) # type: ignore

# Extra relationships
aliases = [
Expand Down Expand Up @@ -116,6 +117,7 @@ def get(self, atom: Union[int, str], *, return_tuple: bool = False, units: str =
identifier = periodictable.to_E(atom)

try:
assert isinstance(identifier, str) # Should be string by now
qca = self.cr[identifier]
except KeyError as e:
if missing is not None and return_tuple is False:
Expand Down
6 changes: 3 additions & 3 deletions qcelemental/models/align.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ class AlignmentMill(ProtoModel):
then molecular system can be substantively changed by procedure.
"""
shift: Array[float]
rotation: Array[float]
atommap: Array[int]
shift: Array[float] # type: ignore
rotation: Array[float] # type: ignore
atommap: Array[int] # type: ignore
mirror: bool = False

@validator('shift', whole=True)
Expand Down
21 changes: 11 additions & 10 deletions qcelemental/models/basemodels.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ class Config:
allow_mutation = False
extra = "forbid"
json_encoders = {np.ndarray: lambda v: v.flatten().tolist()}
serialize_default_excludes = set()
serialize_default_excludes: Set = set()
serialize_skip_defaults = False
force_skip_defaults = False
canonical_repr = False

@classmethod
def parse_raw(cls, data: Union[bytes, str], *, encoding: str = None) -> 'Model':
def parse_raw(cls, data: Union[bytes, str], *, encoding: str = None) -> 'ProtoModel': # type: ignore
"""
Parses raw string or bytes into a Model object.
Expand Down Expand Up @@ -65,7 +65,7 @@ def parse_raw(cls, data: Union[bytes, str], *, encoding: str = None) -> 'Model':
return cls.parse_obj(obj)

@classmethod
def parse_file(cls, path: Union[str, Path], *, encoding: str = None) -> 'Model':
def parse_file(cls, path: Union[str, Path], *, encoding: str = None) -> 'ProtoModel': # type: ignore
"""Parses a file into a Model object.
Parameters
Expand Down Expand Up @@ -95,15 +95,16 @@ def parse_file(cls, path: Union[str, Path], *, encoding: str = None) -> 'Model':

return cls.parse_raw(path.read_bytes(), encoding=encoding)

def dict(self, *args, **kwargs) -> Dict[str, Any]:
def dict(self, **kwargs) -> Dict[str, Any]:
encoding = kwargs.pop("encoding", None)

kwargs["exclude"] = (kwargs.get("exclude", None) or set()) | self.__config__.serialize_default_excludes
kwargs.setdefault("skip_defaults", self.__config__.serialize_skip_defaults)
if self.__config__.force_skip_defaults:
kwargs["exclude"] = (
(kwargs.get("exclude", None) or set()) | self.__config__.serialize_default_excludes) # type: ignore
kwargs.setdefault("skip_defaults", self.__config__.serialize_skip_defaults) # type: ignore
if self.__config__.force_skip_defaults: # type: ignore
kwargs["skip_defaults"] = True

data = super().dict(*args, **kwargs)
data = super().dict(**kwargs)

if encoding is None:
return data
Expand Down Expand Up @@ -140,7 +141,7 @@ def serialize(self,

return serialize(data, encoding=encoding)

def compare(self, other: 'Model', **kwargs) -> bool:
def compare(self, other: Union['ProtoModel', BaseModel], **kwargs) -> bool:
"""Compares the current object to the provided object recursively.
Parameters
Expand All @@ -158,7 +159,7 @@ def compare(self, other: 'Model', **kwargs) -> bool:
return compare_recursive(self, other, **kwargs)

def __str__(self) -> str: # lgtm: [py/inheritance/incorrect-overridden-signature]
if self.__config__.canonical_repr:
if self.__config__.canonical_repr: # type: ignore
return super().to_string()
else:
return f"{self.__class__.__name__}(ProtoModel)"
Expand Down
25 changes: 13 additions & 12 deletions qcelemental/models/common_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ class Model(ProtoModel):
"""
The quantum chemistry model specification for a given operation to compute against
"""
method: str = Schema(..., description="The quantum chemistry method to evaluate (e.g., B3LYP, PBE, ...).")
basis: Optional[str] = Schema(
method: str = Schema( # type: ignore
..., description="The quantum chemistry method to evaluate (e.g., B3LYP, PBE, ...).")
basis: Optional[str] = Schema( # type: ignore
None,
description="The quantum chemistry basis set to evaluate (e.g., 6-31g, cc-pVDZ, ...). Can be ``None`` for "
"methods without basis sets.")
Expand Down Expand Up @@ -53,15 +54,15 @@ def derivative_int(self):

class ComputeError(ProtoModel):
"""The type of error message raised"""
error_type: str = Schema( # Error enumeration not yet strict
...,
error_type: str = Schema( # type: ignore
..., # Error enumeration not yet strict
description="The type of error which was thrown. Restrict this field short classifiers e.g. 'input_error'.")
error_message: str = Schema(
error_message: str = Schema( # type: ignore
...,
description="Text associated with the thrown error, often the backtrace, but can contain additional "
"information as well.")
extras: Optional[Dict[str, Any]] = Schema(None,
description="Additional data to ship with the ComputeError object.")
extras: Optional[Dict[str, Any]] = Schema( # type: ignore
None, description="Additional data to ship with the ComputeError object.")

def __str__(self) -> str:
return f"{self.__class__.__name__}(error_type={self.error_type} error_message:\n{self.error_message}\n)"
Expand All @@ -73,25 +74,25 @@ class FailedOperation(ProtoModel):
input data which generated the failure.
"""
id: str = Schema(
id: str = Schema( # type: ignore
None,
description="A unique identifier which links this FailedOperation, often of the same Id of the operation "
"should it have been successful. This will often be set programmatically by a database such as "
"Fractal.")
input_data: Any = Schema(
input_data: Any = Schema( # type: ignore
None,
description="The input data which was passed in that generated this failure. This should be the complete "
"input which when attempted to be run, caused the operation to fail.")
success: bool = Schema(
success: bool = Schema( # type: ignore
False,
description="A boolean indicator that the operation failed consistent with the model of successful operations. "
"Should always be False. Allows programmatic assessment of all operations regardless of if they failed or "
"succeeded")
error: ComputeError = Schema(
error: ComputeError = Schema( # type: ignore
...,
description="A container which has details of the error that failed this operation. See the "
":class:`ComputeError` for more details.")
extras: Optional[Dict[str, Any]] = Schema(
extras: Optional[Dict[str, Any]] = Schema( # type: ignore
None,
description="Additional information to bundle with this Failed Operation. Details which pertain specifically "
"to a thrown error should be contained in the `error` field. See :class:`ComputeError` for details.")
Expand Down
Loading

0 comments on commit e4f2cc9

Please sign in to comment.