Skip to content

Commit

Permalink
Convert os.path to pathlib based Paths (#646)
Browse files Browse the repository at this point in the history
* Convert os.path to pathlib based Paths

* Actually use name set/get

* Add custom JSONEncoder to handle Paths
  • Loading branch information
oerc0122 authored Feb 5, 2025
1 parent 3a32499 commit 3f1535c
Show file tree
Hide file tree
Showing 46 changed files with 411 additions and 542 deletions.
12 changes: 6 additions & 6 deletions MDANSE/Src/MDANSE/Chemistry/ChemicalSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, name: str = "", trajectory=None):
:type name: str
"""

self._name = name
self.name = str(name)
self._database = ATOMS_DATABASE
if trajectory is not None:
self._database = trajectory
Expand All @@ -55,7 +55,7 @@ def __init__(self, name: str = "", trajectory=None):
self._unique_elements = set()

def __str__(self):
return f"ChemicalSystem {self._name} consisting of {len(self._atom_types)} atoms in {len(self._clusters)} molecules"
return f"ChemicalSystem {self.name} consisting of {len(self._atom_types)} atoms in {len(self._clusters)} molecules"

def initialise_atoms(self, element_list: List[str], name_list: List[str] = None):
self._atom_indices = [
Expand Down Expand Up @@ -191,7 +191,7 @@ def copy(self) -> "ChemicalSystem":
:return: Copy of the ChemicalSystem instance
:rtype: MDANSE.Chemistry.ChemicalSystem.ChemicalSystem
"""
cs = ChemicalSystem(self._name)
cs = ChemicalSystem(self.name)

for attribute_name, attribute_value in self.__dict__.items():
if attribute_name in ["rdkit_mol", "_configuration"]:
Expand Down Expand Up @@ -248,7 +248,7 @@ def serialize(self, h5_file: h5py.File) -> None:
string_dt = h5py.special_dtype(vlen=str)

grp = h5_file.create_group("/composition")
grp.attrs["name"] = self._name
grp.attrs["name"] = self.name

try:
grp.create_dataset("atom_types", data=self._atom_types, dtype=string_dt)
Expand Down Expand Up @@ -292,7 +292,7 @@ def load(self, trajectory: str):
self.rdkit_mol = Chem.RWMol()

grp = source["/composition"]
self._name = grp.attrs["name"]
self.name = grp.attrs["name"]

atom_types = [binary.decode("utf-8") for binary in grp["atom_types"][:]]
atom_names = None
Expand Down Expand Up @@ -326,7 +326,7 @@ def legacy_load(self, trajectory: str):
self.rdkit_mol = Chem.RWMol()

grp = source["/chemical_system"]
self._name = grp.attrs["name"]
self.name = grp.attrs["name"]
atoms = grp["atoms"]
element_list = [line[0].decode("utf-8").strip("'") for line in atoms]
self.initialise_atoms(element_list)
Expand Down
22 changes: 15 additions & 7 deletions MDANSE/Src/MDANSE/Chemistry/Databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
#

import copy
import os
from typing import Union, ItemsView, Dict, Any
from pathlib import Path

import json

Expand All @@ -30,8 +30,8 @@ class _Database(metaclass=Singleton):
Base class for all the databases.
"""

_DEFAULT_DATABASE: str
_USER_DATABASE: str
_DEFAULT_DATABASE: Path
_USER_DATABASE: Path

def __init__(self):
"""
Expand Down Expand Up @@ -65,7 +65,11 @@ def __iter__(self):
for v in self._data.values():
yield copy.deepcopy(v)

def _load(self, user_database: str = None, default_database: str = None) -> None:
def _load(
self,
user_database: Union[Path, str, None] = None,
default_database: Union[Path, str, None] = None,
) -> None:
"""
Load the database. This method should never be called elsewhere than __init__ or unit testing.
Expand All @@ -77,10 +81,14 @@ def _load(self, user_database: str = None, default_database: str = None) -> None
"""
if user_database is None:
user_database = self._USER_DATABASE
else:
user_database = Path(user_database)
if default_database is None:
default_database = self._DEFAULT_DATABASE
else:
default_database = Path(default_database)

if os.path.exists(user_database):
if user_database.exists():
database_path = user_database
else:
database_path = default_database
Expand Down Expand Up @@ -164,10 +172,10 @@ class AtomsDatabase(_Database):
>>> atoms = ATOMS_DATABASE.atoms()
"""

_DEFAULT_DATABASE = os.path.join(os.path.dirname(__file__), "atoms.json")
_DEFAULT_DATABASE = Path(__file__).parent / "atoms.json"

# The user path
_USER_DATABASE = os.path.join(PLATFORM.application_directory(), "atoms.json")
_USER_DATABASE = PLATFORM.application_directory() / "atoms.json"

# The python types supported by the database
_TYPES = {"str": str, "int": int, "float": float, "list": list}
Expand Down
Loading

0 comments on commit 3f1535c

Please sign in to comment.