Skip to content

Commit

Permalink
Make Engines contextmanagers and add to_dict methods
Browse files Browse the repository at this point in the history
  • Loading branch information
domdfcoding committed Jun 29, 2023
1 parent 0209829 commit d57837e
Show file tree
Hide file tree
Showing 15 changed files with 235 additions and 133 deletions.
3 changes: 3 additions & 0 deletions doc-source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ API Reference
:no-members:

.. autoclass:: pyms_nist_search.search_result.SearchResult
:exclude-members: __repr__


.. latex:vspace:: 40px
:mod:`~pyms_nist_search.utils`
-----------------------------------

Expand Down
25 changes: 17 additions & 8 deletions src/pyms_nist_search/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,24 @@ def from_dict(cls, dictionary: Dict[str, Any]):

return cls(**dictionary)

def to_dict(self) -> Dict[str, Any]:
"""
Convert the object to a dictionary.
.. versionadded:: 0.6.0
"""

return dict(
name=self._name,
cas=self.cas,
)

def to_json(self) -> str:
"""
Convert the object to json.
"""

return sdjson.dumps(dict(self))
return sdjson.dumps(self.to_dict())

@classmethod
def from_pynist(cls, pynist_dict: Dict[str, Any]):
Expand All @@ -135,26 +147,23 @@ def from_pynist(cls, pynist_dict: Dict[str, Any]):

@property
def __dict__(self):
return dict(
name=self._name,
cas=self.cas,
)
return self.to_dict()

def __getstate__(self) -> Dict[str, Any]:
return self.__dict__
return self.to_dict()

def __setstate__(self, state):
self.__init__(**state) # type: ignore

def __iter__(self):
yield from self.__dict__.items()
yield from self.to_dict().items()

def __str__(self) -> str:
return self.__repr__()

def __eq__(self, other) -> bool:
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return self.to_dict() == other.to_dict()

return NotImplemented

Expand Down
21 changes: 21 additions & 0 deletions src/pyms_nist_search/docker_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,21 @@ class Engine:
docker pull domdfcoding/pywine-pyms-nist
The engine must be uninitialized when no longer required to shut down the underlying docker container.
This is achieved with the :meth:`uninit() <pyms_nist_search.docker_engine.Engine.uninit>` method.
Alternatively, this class can be used as a contextmanager to automatically uninitialize the engine
upon leaving the :keyword:`with` block:
.. code-block:: python3
with pyms_nist_search.Engine(
FULL_PATH_TO_MAIN_LIBRARY,
pyms_nist_search.NISTMS_MAIN_LIB,
FULL_PATH_TO_WORK_DIR,
) as search:
search.full_spectrum_search(ms, n_hits=5)
.. versionchanged:: 0.6.0 Added context manager support.
"""

initialised: bool
Expand Down Expand Up @@ -176,6 +191,12 @@ def __launch_container(self, lib_path, lib_type) -> None:
environment=[f"LIBTYPE={lib_type}"],
)

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.uninit()

def uninit(self) -> None:
"""
Uninitialize the Search Engine.
Expand Down
15 changes: 12 additions & 3 deletions src/pyms_nist_search/reference_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,13 @@ def from_pynist(cls, pynist_dict: Dict[str, Any]) -> "ReferenceData":
def __repr__(self) -> str:
return f"Reference Data: {self.name} \t({self.cas})"

@property
def __dict__(self):
def to_dict(self) -> Dict[str, Any]:
"""
Convert the object to a dictionary.
.. versionadded:: 0.6.0
"""

return dict(
name=self.name,
cas=self.cas,
Expand All @@ -223,6 +228,10 @@ def __dict__(self):
mass_spec=self.mass_spec,
)

@property
def __dict__(self):
return self.to_dict()

@classmethod
def from_jcamp(cls, file_name: PathLike, ignore_warnings: bool = True) -> "ReferenceData":
"""
Expand Down Expand Up @@ -293,7 +302,7 @@ def to_json(self) -> str:
Convert the object to JSON.
"""

return sdjson.dumps(self.__dict__)
return sdjson.dumps(self.to_dict())

@classmethod
def from_json(cls, json_data: str):
Expand Down
15 changes: 13 additions & 2 deletions src/pyms_nist_search/search_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ class SearchResult(NISTBase):
:param reverse_match_factor:
:param hit_prob:
:param spec_loc: The location of the reference spectrum in the library.
.. latex:vspace:: 20px
"""

def __init__(
Expand Down Expand Up @@ -135,8 +137,13 @@ def from_pynist(cls, pynist_dict: Dict[str, Any]) -> "SearchResult":
def __repr__(self) -> str:
return f"Search Result: {self.name} \t({self.match_factor})"

@property
def __dict__(self):
def to_dict(self) -> Dict[str, Any]:
"""
Convert the object to a dictionary.
.. versionadded:: 0.6.0
"""

return dict(
name=self._name,
cas=self.cas,
Expand All @@ -146,6 +153,10 @@ def __dict__(self):
hit_prob=self.hit_prob,
)

@property
def __dict__(self):
return self.to_dict()


@register_encoder(SearchResult)
def encode_search_result(obj: SearchResult) -> Dict[str, Any]:
Expand Down
8 changes: 7 additions & 1 deletion src/pyms_nist_search/win_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class Engine:
:param lib_type: The type of library. One of ``NISTMS_MAIN_LIB``, ``NISTMS_USER_LIB``, ``NISTMS_REP_LIB``.
:param work_dir: The path to the working directory.
.. latex:vspace:: 60px
.. latex:vspace:: 50px
"""

def __init__(
Expand Down Expand Up @@ -181,3 +181,9 @@ def get_reference_data(spec_loc: int) -> ReferenceData:
reference_data = _core._get_reference_data(spec_loc)

return ReferenceData.from_pynist(reference_data)

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.uninit()
2 changes: 1 addition & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
sys.path.remove(os.getcwd())

# this package
from .engines import search # noqa: E402,F401
# from .engines import search # noqa: E402,F401
from .spectra import spectra # noqa: E402,F401
18 changes: 18 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# 3rd party
import pytest

# this package
import pyms_nist_search

# this package
from .engines import FULL_PATH_TO_USER_LIBRARY, FULL_PATH_TO_WORK_DIR


@pytest.fixture(scope="session")
def search():
with pyms_nist_search.Engine(
FULL_PATH_TO_USER_LIBRARY,
pyms_nist_search.NISTMS_USER_LIB, # type: ignore # TODO
FULL_PATH_TO_WORK_DIR, # debug=True,
) as engine:
yield engine
10 changes: 5 additions & 5 deletions tests/engines.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
# debug=True,
# )

search = pyms_nist_search.Engine(
FULL_PATH_TO_USER_LIBRARY,
pyms_nist_search.NISTMS_USER_LIB, # type: ignore # TODO
FULL_PATH_TO_WORK_DIR, # debug=True,
)
# search = pyms_nist_search.Engine(
# FULL_PATH_TO_USER_LIBRARY,
# pyms_nist_search.NISTMS_USER_LIB, # type: ignore # TODO
# FULL_PATH_TO_WORK_DIR, # debug=True,
# )
6 changes: 3 additions & 3 deletions tests/test_full_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
from pyms_nist_search import SearchResult

# this package
from .engines import search
# from .engines import search
from .spectra import spectra


def test_full_search():
def test_full_search(search):
print()

for name, spectrum in spectra.items():
Expand All @@ -23,7 +23,7 @@ def test_full_search():
# assert hit_list[0].cas == cas


def test_different_n_hits():
def test_different_n_hits(search):
print()

spectrum = spectra["Diphenylamine"]
Expand Down
6 changes: 3 additions & 3 deletions tests/test_full_search_ref_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from pyms_nist_search import ReferenceData, SearchResult

# this package
from .engines import search
# from .engines import search
from .spectra import spectra


def test_full_search():
def test_full_search(search):
print()

for name, spectrum in spectra.items():
Expand All @@ -32,7 +32,7 @@ def test_full_search():
assert hit_list[0][1].name.lower() == name.lower()


def test_different_n_hits():
def test_different_n_hits(search):
print()

spectrum = spectra["Diphenylamine"]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_get_ref_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
from pyms_nist_search import ReferenceData, SearchResult

# this package
from .engines import search
# from .engines import search
from .spectra import spectra


def test_get_ref_data():
def test_get_ref_data(search):
print()

# To avoid duplicates for speed
Expand Down
6 changes: 3 additions & 3 deletions tests/test_quick_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
from pyms_nist_search import SearchResult

# this package
from .engines import search
# from .engines import search
from .spectra import spectra


def test_quick_search():
def test_quick_search(search):
print()

for name, spectrum in spectra.items():
Expand All @@ -32,7 +32,7 @@ def test_quick_search():
# assert hit_list[0].cas == cas


def test_different_n_hits():
def test_different_n_hits(search):
print()

spectrum = spectra["Diphenylamine"]
Expand Down
Loading

0 comments on commit d57837e

Please sign in to comment.