""" The statelist module. """
import logging
import shutil
from pathlib import Path
from eon import atoms
from eon import fileio as io
from eon.config import ConfigClass # Typing
logger = logging.getLogger('statelist')
def _ensure_state_table(path):
"""Create an empty state table when the file is absent.
The open is exclusive (``O_CREAT|O_EXCL``). A table that already
exists, including one written by another process, is left as it is.
"""
try:
with open(path, 'x'):
pass
except FileExistsError:
return
[docs]
class StateList:
""" The StateList class. Serves as an interface to State objects and StateList metadata. """
def __init__(self, StateClass, initial_state = None, config: ConfigClass = None):
''' Check to see if state_path exists and that state zero exists.
Initializes state zero when passed a initial_state only if state
zero doesn't already exist. '''
if config is None:
raise TypeError("statelist requires a ConfigClass instance")
self.config = config
self.path = self.config.path_states
self.epsilon_e = self.config.comp_eps_e
self.epsilon_r = self.config.comp_eps_r
self.use_identical = self.config.comp_use_identical
self.StateClass = StateClass
# Paths
root = Path(self.path)
self.state_table_path = str(root / "state_table")
# Create the statelist directory if it does not exist.
if not root.is_dir():
logger.warning("State list path does not exist; Creating: %s" % self.path)
root.mkdir(parents=True)
# The table used to be written only with that mkdir. A directory
# left without one still has to resume, and an existing table
# must not be truncated.
_ensure_state_table(self.state_table_path)
# Create the zero state directory if it does not exist.
if not (root / "0").is_dir():
if initial_state is None:
raise IOError("Missing zeroth state directory and no reactant provided")
self.StateClass(
statepath=str(root / "0"),
statenumber=0,
statelist=self,
previous_state_num=-1,
reactant_path=initial_state,
config=config,
)
# Other class variables.
self.states = {}
self.state_table = None
[docs]
def get_num_states(self):
""" Returns the number of lines in the state_table file. """
self.load_state_table(force=True)
return len(self.state_table)
[docs]
def get_product_state(self, state_number, process_id):
''' Returns a State object referenced by state_number and process_id. '''
# If the number of states in state_table is zero
#we need to add the zero state and energy to the state table.
if self.get_num_states() == 0:
zst = self.get_state(0)
self.append_state_table(zst.get_energy())
while self._settle_unlisted_state(self.get_num_states()):
pass
# Load the state object containing the process we want the product for.
st = self.get_state(state_number)
st.load_process_table()
# Get the state number for the product.
newstnr = st.procs[process_id]['product']
# If the product id is not initialized, make sure it is not a copy of an existing state.
# Otherwise, create it, connect it to st, and return it.
if newstnr == -1:
# Make a list of states for which we need to compare self.configurations.
enew = st.procs[process_id]['product_energy']
energetically_close = []
for id in range(self.get_num_states()):
if abs(self.get_state(id).get_energy() - enew) < self.epsilon_e:
energetically_close.append(id)
# Perform distance checks on the energetically close self.configurations.
if len(energetically_close) > 0:
pnew = st.get_process_product(process_id)
for id in energetically_close:
p = self.get_state(id).get_reactant()
if atoms.match(p, pnew, self.config.comp_eps_r, self.config.comp_neighbor_cutoff, True, check_rotation=self.config.comp_check_rotation, use_identical=self.config.comp_use_identical, remove_translation=self.config.comp_remove_translation):
if id == state_number:
logging.warning("State %i process %i leads back to initial state",
state_number, process_id)
self.register_process(st.number, id, process_id)
return self.get_state(id)
# The id for the new state is the number of states.
newstnr = self.get_num_states()
# Create the new state object.
newst = self.StateClass(
statepath=self.state_path(newstnr),
statenumber=newstnr,
statelist=self,
previous_state_num=state_number,
reactant_path=st.proc_product_path(process_id),
config=self.config,
)
self.register_process(st.number, newstnr, process_id)
# Append the new state to the state table.
self.append_state_table(st.procs[process_id]['product_energy'])
# The product state already exists, so get it.
else:
newst = self.get_state(newstnr)
# Return the product state.
return newst
def _settle_unlisted_state(self, number):
"""Finish or drop states/<number> when state_table has no row for it.
A new state is renamed into place, then a reactant process is
pointed at it, then its row is appended. A pass that stops before
the row leaves a directory that the next new state would reuse,
together with its reactant. When a process of any listed state
already points at it, the row is appended. When none does, the
directory contains only the staged copy of a product and is removed.
The "previous state" key in info is not used: PRState.set_energy
rewrites info without it.
Returns True when a row was appended.
"""
path = Path(self.state_path(number))
if number == 0 or not path.is_dir():
return False
for listed in range(number):
reactant = self.get_state(listed)
reactant.load_process_table(force=True)
for proc in reactant.procs.values():
if proc["product"] == number:
state = self.get_state(number)
if state.get_energy() is None:
state.set_energy(proc["product_energy"])
logger.warning("State %i was not in the state table; adding it", number)
self.append_state_table(proc["product_energy"])
return True
logger.warning("Removing state %i, which no process reaches", number)
shutil.rmtree(path)
return False
[docs]
def get_state(self, state_number):
''' Returns a state object. '''
if state_number in self.states:
return self.states[state_number]
st = self.StateClass(
statepath=str(Path(self.path) / str(state_number)),
statenumber=state_number,
statelist=self,
config=self.config,
)
self.states[state_number] = st
return st
[docs]
def load_state_table(self, force=False):
"""Load the state table from disk.
If already loaded and *force* is false, do nothing. When *force* is
true (used by :meth:`get_num_states`), re-read so states appended by
another process are seen; a stale count would mint a state number
that is already taken.
"""
if self.state_table is not None and not force:
return
lines = io.DurableTable(
self.state_table_path,
header_lines=0,
min_fields=2,
exact=True,
label="state_table %s" % self.state_table_path,
).lines()
self.state_table = []
for l in lines:
parts = l.split()
if not parts:
continue
self.state_table.append(float(parts[1]))
[docs]
def save_state_table(self):
if self.state_table != None:
with io.atomic_write(self.state_table_path) as f:
for i in range(len(self.state_table)):
f.write("% 7d %16.5f\n" % (i, self.state_table[i]))
[docs]
def append_state_table(self, energy):
"""Append one state row, then flush and sync it.
A torn final line is cut off first.
"""
number = self.get_num_states()
if energy is None:
raise IOError(
"State %i has no reactant energy in its info file; it cannot "
"be added to the state table" % number
)
line = "% 7d %16.5f\n" % (number, energy)
io.DurableTable(
self.state_table_path, header_lines=0, min_fields=2, exact=True
).append(line)
if self.state_table != None:
self.state_table.append(energy)
[docs]
def state_path(self, state_number):
""" Utility function to return the compiled path of a state, whether it exists or not. """
return str(Path(self.path) / str(state_number))
if __name__ == "__main__":
pass