# -*- coding: utf-8 -*-
"""
Created on 2020-05-11
@author: Vincent Michaud-Rioux
"""
from nanotools.io.calculators import read as read_calc
from nanotools.utils import (
convert_quantity,
list_methods,
Quantity,
)
from nanotools.jsonio import json_write
import attr
import copy
[docs]
@attr.s
class Base:
"""The ``Base`` class is used to define universal methods and parameters common to `nanotools` classes."""
# input is dictionary with default constructor
# attr = attr.ib(default=None)
# def __attrs_post_init__(self):
# return
[docs]
@classmethod
def read(cls, filename, units="si"):
"""Initialize an object from a JSON file."""
return read_calc(cls, filename, units=units)
[docs]
def asdict(self):
"""
Returns the object as a dictionary.
Args:
Returns:
"""
return attr.asdict(
self,
recurse=True,
filter=lambda attr, value: attr.name != "inpDict",
)
[docs]
def copy(self):
"""Returns a deep copy of the object."""
return copy.deepcopy(self)
[docs]
def set_units(self, units):
"""Converts all units to the prescribed unit system (recursive).
Args:
units (str):
Unit system ('atomic' or 'si')
"""
set_units_core(self, units)
def write(self, filename, units="atomic"):
self.set_units(units)
adict = self.asdict()
json_write(filename, adict)
def _update(self, filename):
tmp = self.__class__.read(filename)
self.__dict__.update(tmp.__dict__)
[docs]
def set_units_core(self, units):
"""
Convert all units to the prescribed unit system (recursive).
Args:
units (str): Unit system ('atomic' or 'si')
Returns:
"""
units = units.lower()
if units not in ["atomic", "si"]:
raise Exception("Unit system " + units + " not recognized.")
for key in self.__dict__.keys():
atr = getattr(self, key)
object_methods = list_methods(atr)
if "set_units" in object_methods:
atr.set_units(units)
setattr(self, key, atr)
continue
if isinstance(atr, Quantity):
atr = convert_quantity(atr, units)
continue