pyretis.inout.formats package

This sub-package handles data formats for PyRETIS.

The methods and classes defined in this package will format the data created by PyRETIS and also enable the reading of such output data.

Further, this package includes some methods for interacting with other simulation packages.

Package structure

Modules

formatter.py (pyretis.inout.formats.formatter)

Generic methods for formatting output from PyRETIS. Defines the base class for all formatters.

cp2k.py (pyretis.inout.formats.cp2k)

A module defining input/output methods for use with CP2k.

cross.py (pyretis.inout.formats.cross)

Formatting of crossing data from PyRETIS.

energy.py (pyretis.inout.formats.energy)

Formatting of energy data from PyRETIS.

gromacs.py (pyretis.inout.formats.gromacs)

A module defining input/output methods for use with GROMACS.

__init__.py

This file.

order.py (pyretis.inout.formats.order)

Formatting of order parameter data from PyRETIS.

path.py (pyretis.inout.formats.path)

Formatting of path/trajectory data from PyRETIS.

pathensemble.py (pyretis.inout.formats.pathensemble)

Formatting of path ensemble data from PyRETIS.

snapshot.py (pyretis.inout.formats.snapshot)

Formatting of snapshot data from PyRETIS.

txt_table.py (pyretis.inout.formats.txt_table)

Definition of a table-like format.

xyz.py (pyretis.inout.formats.xyz)

A module defining input/output methods for use with a XYZ format.

Important classes defined in this package

CrossFormatter (CrossFormatter)

A class for formatting crossing data from flux simulations.

EnergyFormatter (EnergyFormatter)

A class for formatting energy data from PyRETIS.

EnergyPathFormatter

A class for formatting energy data for paths. See pyretis.inout.formats.energy.EnergyPathFormatter.

OrderFormatter (OrderFormatter)

A class for formatting order parameter data.

OrderPathFormatter

A class for formatting order parameter data for paths. See pyretis.inout.formats.order.OrderPathFormatter.

PathExtFormatter

A class for formatting external trajectories. See pyretis.inout.formats.path.PathExtFormatter.

PathIntFormatter (PathIntFormatter)

A class for formatting internal trajectories.

PathEnsembleFormatter (PathEnsembleFormatter)

A class for formatting path ensemble data.

SnapshotFormatter (SnapshotFormatter)

Generic class for formatting system snapshots (coordinates).

TxtTableFormatter (TxtTableFormatter)

A class for creating a table-like format.

List of submodules

pyretis.inout.formats.formatter module

Module for defining the generic formatting of output data from PyRETIS.

Important classes defined here

OutputFormatter (OutputFormatter)

A generic class for formatting output from PyRETIS.

PyretisLogFormatter (PyretisLogFormatter)

A class representing a formatter for the PyRETIS log file.

Important methods defined here

apply_format (apply_format())

Apply a format string to a given float value. This method can be used for formatting text for tables (i.e. if we want a fixed width).

format_number (format_number())

Format a number based on its size.

get_log_formatter (get_log_formatter())

Select a formatter for logging based on a given message level.

class pyretis.inout.formats.formatter.ColoredLogFormatter(fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', **kwargs)

Bases: TimestampedFormatter

Colored formatter for console output.

Maps logging levels to ANSI colors via colorama for colored console output via the standard logger.

COLORS = {10: '\x1b[36m', 20: '\x1b[34m', 25: '\x1b[32m', 26: '\x1b[36m', 27: '\x1b[37m', 28: '\x1b[34m', 29: '\x1b[37m', 30: '\x1b[33m', 40: '\x1b[31m', 50: '\x1b[31m\x1b[1m'}
_format_report_message(message)

Color report headings cyan and keep dense tables white.

pyretisanalyse emits generated text reports as one log record so file logs keep a readable multi-line block. The console view is more scannable if RST headings stand out, while the grid tables stay plain white and separated from the next heading.

static _is_heading_underline(line, heading)

Return True if line is an RST-style heading underline.

format(record)

Apply color based on the log level.

class pyretis.inout.formats.formatter.OutputFormatter(name, header=None)

Bases: object

A generic class for formatting output from PyRETIS.

Variables:
  • name (string) – A string which identifies the formatter.

  • header (string) – A header (or table heading) with information about the output data.

  • print_header (boolean) – Determines if we are to print the header or not. This is useful for classes making use of the formatter to determine if they should write out the header or not.

__init__(name, header=None)

Initialise the formatter.

Parameters:
  • name (string) – A string which identifies the output type of this formatter.

  • header (dict, optional) – The header for the output data

__str__()

Return basic info about the formatter.

format(step, data)

Use the formatter to generate output.

Parameters:
  • step (integer) – This is assumed to be the current step number for generating the output.

  • data (list, dict or similar) – This is the data we are to format. Here we assume that this is something we can iterate over.

property header

Define the header as a property.

load(filename)

Read generic data from a file.

Since this class defines how the data is formatted it is also convenient to have methods for reading the data defined here. This method will read entire blocks of data from a file into memory. This will be slow for large files.

Parameters:

filename (string) – The path/file name of the file we want to open.

Yields:

data_dict (dict) – One block of the file: data_dict['comment'] holds its comment lines and data_dict['data'] its rows, each parsed by parse().

static parse(line)

Parse formatted data.

This method is intended to be the “inverse” of the format() method. In this particular case, we read an integer from the first column and floats from the other columns of a file. One input line corresponds to a “row” of data.

Parameters:

line (string) – The string we will parse.

Returns:

out (list of int and floats) – The parsed input data: the integer of the first column and the floats of the other columns.

class pyretis.inout.formats.formatter.PyretisLogFormatter(fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', **kwargs)

Bases: TimestampedFormatter

Hard-coded formatter for the PyRETIS log file.

A multi-line message repeats the record heading (timestamp + level) on every non-empty line, so each line of the log carries its own time and reads/greps as a self-contained entry. Empty lines are kept empty, so records stay visually grouped and the output remains clean.

format(record)

Apply the PyRETIS log format.

class pyretis.inout.formats.formatter.TimestampedFormatter(fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', **kwargs)

Bases: Formatter

A logging.Formatter carrying the PyRETIS date style.

Defining the timestamped default once, here, keeps every PyRETIS log formatter in sync without repeating the datefmt at each construction site, so all records share the same %(asctime)s.

__init__(fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', **kwargs)

Initialise with the shared date format as the default.

pyretis.inout.formats.formatter.apply_format(value, fmt)

Apply a format string to a given float value.

Here we check the formatting of a float. We are forcing a maximum length on the resulting string. This is to avoid problems like: ‘{:7.2f}’.format(12345.7) which returns ‘12345.70’ with a length 8 > 7. The intended use of this function is to avoid such problems when we are formatting numbers for tables. Here it is done by switching to an exponential notation. But note however that this will have implications for how many decimal places we can show.

Parameters:
  • value (float) – The float to format.

  • fmt (string) – The format to use.

Note

This function converts numbers to have a fixed length. In some cases this may reduce the number of significant digits. Remember to also output your numbers without this format in case a specific number of significant digits is important!

pyretis.inout.formats.formatter.format_number(number, minf, maxf, fmtf='{0:<16.9f}', fmte='{0:<16.9e}')

Format a number based on its size.

Parameters:
  • number (float) – The number to format.

  • minf (float) – If the number is smaller than minf then apply the format with scientific notation.

  • maxf (float) – If the number is greater than maxf then apply the format with scientific notation.

  • fmtf (string, optional) – Format to use for floats.

  • fmte (string, optional) – Format to use for scientific notation.

Returns:

out (string) – The formatted number.

pyretis.inout.formats.formatter.get_log_formatter(level)

Select a log format based on a given level.

Here, it is just for getting a slightly more verbose format for the debug level.

Parameters:

level (integer) – This integer defines the log level.

Returns:

out (object like logging.Formatter) – An object that can be used as a formatter for a logger.

pyretis.inout.formats.formatter.setup_console_logging(level: int = None)

Set up the root logger with a colored console handler.

This configures the root logger at DEBUG level (so all messages are passed to handlers) and attaches a colored StreamHandler to stdout that displays only PROGRESS (25) and above on the console. INFO and DEBUG messages are suppressed on the console and are intended for file handlers added separately.

Parameters:

level (int, optional) – The minimum log level for the console handler. Defaults to PROGRESS (25) if not specified.

Returns:

root_logger (logging.Logger) – The configured root logger.

pyretis.inout.formats.cp2k module

Some method for interacting with input/output from CP2K.

Important methods defined here

update_cp2k_input (update_cp2k_input())

A method for updating a CP2K input file and creating a new one.

read_cp2k_input (read_cp2k_input())

A method to read a CP2K input file.

read_cp2k_template (read_cp2k_template())

A method to read a CP2K input file with its preprocessor directives resolved.

pyretis.inout.formats.cp2k.CP2K_CELL_KEYWORDS = {'A': ('A', 'real', 'ANGSTROM'), 'ABC': ('ABC', 'real', 'ANGSTROM'), 'ALPHA_BETA_GAMMA': ('ALPHA_BETA_GAMMA', 'real', 'DEG'), 'ANGLES': ('ALPHA_BETA_GAMMA', 'real', 'DEG'), 'B': ('B', 'real', 'ANGSTROM'), 'C': ('C', 'real', 'ANGSTROM'), 'MULTIPLE_UNIT_CELL': ('MULTIPLE_UNIT_CELL', 'integer', None), 'PERIODIC': ('PERIODIC', 'keyword', None)}

The keywords of the CELL section of a CP2K input that give the box, under each name CP2K accepts: the name read_box_data() stores the value under, the type of the values, and the unit CP2K reads them in without a unit tag (None for a keyword without one).

pyretis.inout.formats.cp2k.CP2K_CELL_UNREAD = {'CELL_FILE_NAME': None, 'SYMMETRY': 'NONE'}

The keywords of the CELL section of a CP2K input that make CP2K build a box that read_box_data() does not read: a cell read from a file, and a symmetry imposed on the cell vectors. The value of each keyword that CP2K builds the box of the section with.

pyretis.inout.formats.cp2k.CP2K_INTEGER = re.compile('[+-]?\\d+')

An integer as CP2K reads it.

pyretis.inout.formats.cp2k.CP2K_REAL = re.compile('[+-]?(\\d+\\.?\\d*|\\.\\d+)([eEdD][+-]?\\d+)?')

an exponent may start with D.

Type:

A real number as CP2K reads it, with Fortran rules

pyretis.inout.formats.cp2k.CP2K_VARIABLE = re.compile('\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?:-([^}]*))?\\}|\\$([A-Za-z_][A-Za-z0-9_]*)')

${NAME}, ${NAME-default} or $NAME.

Type:

A reference to a variable of the CP2K preprocessor

class pyretis.inout.formats.cp2k.SectionNode(title, parent, settings, data=None)

Bases: object

A class representing a section in the CP2K input.

Variables:
  • title (string) – The title of the section

  • parent (string) – The parent section if this node represents a sub-section.

  • settings (list of strings) – The setting(s) for this particular node.

  • data (string) – A section of settings if the node defines several settings.

  • children (set of objects like SectionNode) – A set with the sub-sections of this section.

  • level (integer) – An integer to remember how far down this node is. E.g. if the level is 2, this node is a sub-sub-section. This is used for printing.

  • parents (list of strings or None) – A list representing the path from the node to the top section.

__init__(title, parent, settings, data=None)

Initialise a node.

Parameters:
  • title (string) – The title of the section.

  • parent (object like SectionNode) – The parent if this section is a sub-section.

  • settings (list of strings) – The settings defined in this section.

  • data (list of strings, optional) – A section of settings.

add_child(child)

Add a sub-section to the current section.

get_all_parents()

Find the path to the top of the tree.

pyretis.inout.formats.cp2k._add_node(target, settings, data, nodes, node_ref)

Just add a new node.

pyretis.inout.formats.cp2k._cp2k_include_path(argument, variables, folder, included, source)

Return the file of an @INCLUDE directive.

Parameters:
  • argument (string) – The text after @INCLUDE.

  • variables (dict of strings) – The variables, by name.

  • folder (string) – The folder that a relative file name starts from.

  • included (list of strings) – The absolute paths of the files that include the directive.

  • source (string) – The file and line of the directive, as the error messages name it.

Returns:

out (string) – The path of the file, without the quotes that enclose its name.

Raises:

ValueError – If the directive names no file, a file that does not exist or a file in included, and as expand_cp2k_variables() raises it for the name.

pyretis.inout.formats.cp2k._cp2k_set_variable(argument, variables, source)

Define the variable of an @SET directive.

Parameters:
  • argument (string) – The text after @SET.

  • variables (dict of strings) – The variables, by name, updated in place.

  • source (string) – The file and line of the directive, as the error messages name it.

Raises:

ValueError – If the directive is not of the form @SET NAME value, and as expand_cp2k_variables() raises it for the value.

pyretis.inout.formats.cp2k._engine_template(settings, input_path)

Return the CP2K input that the engine of [engine] reads.

A CP2K engine class names the input it reads (CP2KEngineSteps.cp2k_template()): class = "cp2k" reads cp2k.inp whatever [engine] template sets, and class = "cp2k_steps" reads [engine] template, cp2k.inp when the section sets none. That input is looked up in input_path with pyretis.inout.settings.look_for_input_files(), as the engine looks it up when it is created and as the run set-up reads it (CP2KEngineSteps.read_input_temperatures()). For settings that name no CP2K engine class (pyretis.engines.run_temperature.known_engine_class()), the input is the template of the input_files of [engine].

Parameters:
  • settings (dict) – The current input settings, with the input_files of [engine] set.

  • input_path (string) – The CP2K input path, the directory the engine reads its input from.

Returns:

out (string) – The CP2K input that the engine reads.

Raises:

ValueError – If the settings name a CP2K engine class and input_path holds no input that the engine reads (pyretis.inout.settings.look_for_input_files()).

pyretis.inout.formats.cp2k._preprocess_cp2k_file(filename, folder, variables, included)

Return the lines of a CP2K input file with its directives resolved.

Parameters:
  • filename (string) – The file to read.

  • folder (string) – The folder that relative @INCLUDE file names start from.

  • variables (dict of strings) – The variables that @SET defines, updated in place.

  • included (list of strings) – The absolute paths of filename and of the files that include it.

Returns:

out (list of strings) – The lines, as preprocess_cp2k_input() returns them.

Raises:
pyretis.inout.formats.cp2k._resolve_cp2k_directive(text, folder, variables, included, source)

Return the lines that a CP2K preprocessor directive stands for.

Parameters:
  • text (string) – The line of the directive, without a comment.

  • folder (string) – The folder that relative @INCLUDE file names start from.

  • variables (dict of strings) – The variables that @SET defines, updated in place.

  • included (list of strings) – The absolute paths of the file of the directive and of the files that include it.

  • source (string) – The file and line of the directive, as the error messages name it.

Returns:

out (list of strings) – The lines of an @INCLUDE file, resolved; none for @SET.

Raises:
pyretis.inout.formats.cp2k._system_temperature_advice(stated, cp2k_temp)

Return the advice of a refusal of [system] temperature.

Parameters:
  • stated (float) – The [system] temperature of the settings.

  • cp2k_temp (float) – The temperature the CP2K input of the engine states.

Returns:

out (string) – For the settings of an input, to set [system] temperature to the temperature of the CP2K input, or to remove it; for the settings of a run file a run resumes (pyretis.inout.settings.reading_run_file()), how the run it records continues.

pyretis.inout.formats.cp2k.cp2k_keyword_line(keyword, value)

Return the line of a CP2K input that sets a keyword.

Parameters:
  • keyword (string) – The keyword.

  • value (object) – The value of the keyword. None gives the keyword without a value.

Returns:

out (string) – The line.

pyretis.inout.formats.cp2k.cp2k_settings(settings, input_path)

Read and process cp2k settings.

The CP2K input that the engine of [engine] reads (_engine_template()) states the temperature of the engine, MOTION/MD TEMPERATURE (read_cp2k_temperatures(), the reader the CP2K engines use). A [system] temperature the settings hold must equal it within the tolerance of pyretis.engines.run_temperature.temperatures_agree(). Settings without one are given the temperature of the CP2K input when the run is set up (pyretis.engines.run_temperature.resolve_run_temperature()). Before a refusal of the temperature (the temperatures differ, or read_cp2k_temperatures() refuses the CP2K input), the input of every engine section of the settings of a path-sampling task is checked for an integrator, a thermostat or a barostat a path-sampling run cannot use (pyretis.engines.run_temperature.refuse_path_sampling_task_inputs()), so its refusal comes first; settings whose temperatures agree pass on to the set-up of a run, which checks their inputs. The refusal of the settings of a run file a run resumes (pyretis.inout.settings.reading_run_file()) says how the run it records continues. The settings of a file the analysis reads (a run file, an input, or the settings an MD run stores: pyretis.inout.settings.ANALYSIS_READERS) are not compared with the CP2K input here: a run file records the temperature of its run, and the analysis compares the settings of a file without a state with the CP2K input itself, refusing none (pyretis.engines.run_temperature.compare_analysed_engine_inputs()).

Parameters:
  • settings (dict) – The current input settings.

  • input_path (string) – The CP2K input path

Raises:

ValueError – If [system] temperature differs from the temperature of the CP2K input by more than the tolerance, read_cp2k_temperatures() refuses the CP2K input, or the engine finds no CP2K input in input_path (_engine_template()); and as refuse_path_sampling_task_inputs() raises it.

pyretis.inout.formats.cp2k.dfs_print(node, visited)

Walk through the nodes and print out text.

Parameters:
  • node (object like SectionNode) – The object representing a CP2K section.

  • visited (set of objects like SectionNode) – The set contains the nodes we have already visited.

Returns:

out (list of strings) – These strings represent the CP2K input file.

pyretis.inout.formats.cp2k.expand_cp2k_variables(text, variables, source)

Replace the references to CP2K preprocessor variables in a text.

Parameters:
  • text (string) – The text, without a comment.

  • variables (dict of strings) – The values of the variables that @SET defines, by name. CP2K matches the names with their case.

  • source (string) – The file and line of the text, as the error messages name it.

Returns:

out (string) – The text with each ${NAME} and $NAME replaced by the value of NAME, and each ${NAME-default} by the value of NAME or, for a name without a value, by default.

Raises:

ValueError – For a $ that starts no reference, and for a reference to a variable without a value or a default.

pyretis.inout.formats.cp2k.parse_cp2k_lines(lines)

Read the sections of the lines of a CP2K input.

Parameters:

lines (iterable of strings) – The lines of the input.

Returns:

nodes (list of objects like SectionNode) – The root section nodes of the lines.

pyretis.inout.formats.cp2k.preprocess_cp2k_input(filename)

Return the lines of a CP2K input with its directives resolved.

The lines of an @INCLUDE file replace the directive, @SET NAME value defines a variable from that line on, and the references ${NAME}, ${NAME-default} and $NAME outside the comments are replaced by the values, as the CP2K preprocessor does. CP2K reads a relative @INCLUDE file name from its working directory, which for the PyRETIS engines is the directory that the input files are copied to; here, it is read from the folder of filename. A line without a directive and without a reference is returned as it is.

Parameters:

filename (string) – The CP2K input file.

Returns:

out (list of strings) – The lines of the input, without directives.

Raises:
  • ValueError – For an @INCLUDE file that does not exist or includes itself, an @SET that is not of the form @SET NAME value, and a reference to a variable without a value (expand_cp2k_variables()).

  • NotImplementedError – For any other directive, such as @IF and @ENDIF, which can hide sections of the input.

pyretis.inout.formats.cp2k.read_box_data(box_data, source='The CP2K input')

Read the box data.

The lines are read as CP2K reads them: a comment starts at # or !, the keywords are matched in any case and under each name of CP2K_CELL_KEYWORDS, and the values are read by read_cell_values(). CP2K multiplies each vector of the cell by the matching number of MULTIPLE_UNIT_CELL (default 1 1 1), and so does this function.

Parameters:
  • box_data (list of strings) – The settings for the SUBSYS->CELL section.

  • source (string, optional) – The CP2K file, for the error messages.

Returns:

  • out[0] (numpy.ndarray, 1D) – The box vectors, in the correct order. None when the section contains neither an A/B/C triplet nor an ABC entry.

  • out[1] (list of booleans) – The periodic boundary setting for each dimension.

Raises:

ValueError – If the section sets a keyword more than once, under one name or under two, which CP2K refuses, and as read_cell_values() raises it.

pyretis.inout.formats.cp2k.read_cell_values(words, keyword, source)

Return the values of a keyword of the CELL section.

Parameters:
  • words (list of strings) – The words of the line after the keyword, without the comment.

  • keyword (string) – The keyword, in upper case, a key of CP2K_CELL_KEYWORDS.

  • source (string) – The CP2K file, for the error messages.

Returns:

out (string or list of numbers) – The value of PERIODIC, in upper case; the three numbers of the other keywords, in the unit CP2K reads them in without a unit tag.

Raises:

ValueError – If a unit tag names another unit than that one, a keyword other than PERIODIC has another number of values than three, or a value is not a number of the type of the keyword.

pyretis.inout.formats.cp2k.read_cp2k_box(inputfile)

Read the box from a CP2K file.

Parameters:

inputfile (string) – The CP2K input we will read from, with its preprocessor directives resolved (read_cp2k_template()).

Returns:

  • out[0] (numpy.array) – The box vectors.

  • out[1] (list of booleans) – For each dimension, the list entry is True if periodic boundaries should be applied.

Raises:

ValueError – As read_box_data() and refuse_unread_cp2k_cell() raise it.

pyretis.inout.formats.cp2k.read_cp2k_energy(energy_file)

Read and return CP2K energies.

Parameters:

energy_file (string) – The input file to read.

Returns:

out (dict) – This dict contains the energy terms read from the CP2K energy file.

pyretis.inout.formats.cp2k.read_cp2k_input(filename)

Read a CP2K input file.

Parameters:

filename (string) – The file to open and read.

Returns:

nodes (list of objects like SectionNode) – The root section nodes found in the file.

pyretis.inout.formats.cp2k.read_cp2k_restart(restart_file)

Read some info from a CP2K restart file.

Parameters:

restart_file (string) – The file to read.

Returns:

  • pos (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • box_size (numpy.array) – The box vectors.

  • periodic (list of booleans) – For each dimension, the list entry is True if periodic boundaries should be applied.

Raises:

ValueError – As read_box_data() raises it.

pyretis.inout.formats.cp2k.read_cp2k_template(filename)

Read a CP2K input file with its preprocessor directives resolved.

Parameters:

filename (string) – The CP2K input file.

Returns:

nodes (list of objects like SectionNode) – The root section nodes of the input, as preprocess_cp2k_input() resolves it. For an input without directives and variables, the nodes are those of read_cp2k_input().

Raises:
pyretis.inout.formats.cp2k.refuse_unread_cp2k_cell(nodes, source)

Stop for a CP2K cell whose box PyRETIS does not read as CP2K does.

CP2K builds the box from the file of CELL_FILE_NAME and imposes the SYMMETRY of the CELL section on the cell vectors, which read_box_data() does not do, so the box PyRETIS would use could differ from the box of CP2K. A SYMMETRY NONE line, the default of CP2K, is accepted.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections of the CP2K input, as read_cp2k_template() returns them.

  • source (string) – The CP2K input, for the error message.

Raises:

ValueError – If a FORCE_EVAL%SUBSYS%CELL section sets a keyword of CP2K_CELL_UNREAD to another value than the one CP2K builds the box of the section with.

pyretis.inout.formats.cp2k.remove_keyword_lines(keywords, node_ref)

Remove the lines of nodes that set keywords.

Parameters:
  • keywords (list of tuples of strings) – Pairs of a node, on form root->section->subsection, and a keyword in upper case. A line of the node sets the keyword when its first word, in upper case, is the keyword. A node that is not in node_ref is left out.

  • node_ref (dict) – A dict with all the nodes.

pyretis.inout.formats.cp2k.remove_node(target, node_ref, root_nodes)

Remove a node (and its children) from the tree.

Parameters:
  • target (string) – The target node, on form root->section->subsection.

  • node_ref (dict) – A dict with all the nodes.

  • root_nodes (list of objects like SectionNode) – The root nodes.

pyretis.inout.formats.cp2k.set_parents(listofnodes)

Set parents for all nodes.

pyretis.inout.formats.cp2k.split_cp2k_comment(line)

Split a line of a CP2K input at the start of its comment.

Parameters:

line (string) – The line.

Returns:

  • text (string) – The line up to the first # or !.

  • comment (string) – The rest of the line, from that character; empty for a line without a comment.

pyretis.inout.formats.cp2k.update_cp2k_input(template, output, update=None, remove=None, remove_keywords=None)

Read a template input and create a new CP2K input.

The template is read with read_cp2k_template(), so the created input holds the sections of its @INCLUDE files and the values of its variables, and no preprocessor directive.

Parameters:
  • template (string) – The CP2K input file we use as a template.

  • output (string) – The CP2K input file we will create.

  • update (dict, optional) – The settings we will update: for each node, on the form root->section->subsection, a dict with the data of update_node(), and optionally its settings, its replace flag, and requires, a node of the same form: the update of a node with requires applies only when the template has that node.

  • remove (list of strings, optional) – The nodes we will remove.

  • remove_keywords (list of tuples of strings, optional) – Pairs of a node, on the form root->section, and a keyword in upper case: the lines of the node that set the keyword, in any case, are removed before the updates.

pyretis.inout.formats.cp2k.update_node(target, settings, data, node_ref, nodes, replace=False)

Update the given target node.

If the node does not exist, it will be created, with the lines of data: for a dict, one line for each keyword and its value (cp2k_keyword_line()).

Parameters:
  • target (string) – The target node, on form root->section->subsection

  • settings (list of strings) – The settings for the node.

  • data (list of strings or dict) – The data for the node: formatted lines, or the values of keywords.

  • node_ref (dict of SectionNode) – A dict of all nodes in the tree.

  • nodes (list of SectionNode) – The root nodes.

  • replace (boolean, optional) – If this is True and if the nodes have some data, the already existing data will be ignored. We also assume that the data is already formatted. If it is False, data is a dict, and each of its keywords replaces the lines of the node that set it, in any case (CP2K keywords are case-insensitive); the other lines are kept.

pyretis.inout.formats.cp2k.write_cp2k_nodes(nodes, output)

Write the sections of a CP2K input to a file.

Parameters:
  • nodes (list of objects like SectionNode) – The root sections.

  • output (string) – The CP2K input file we will create.

pyretis.inout.formats.cross module

Module for formatting crossing data from PyRETIS.

Important classes defined here

CrossFormatter (CrossFormatter)

A class for formatting crossing data from flux simulations.

CrossFile (CrossFile)

A class for handling PyRETIS crossing files.

class pyretis.inout.formats.cross.CrossFile(filename, file_mode, backup=True)

Bases: FileIO

A class for handling PyRETIS crossing files.

__init__(filename, file_mode, backup=True)

Create the cross file with correct formatter.

class pyretis.inout.formats.cross.CrossFormatter

Bases: OutputFormatter

A class for formatting crossing data from flux simulations.

This class handles formatting of crossing data. The format for the crossing file is three columns:

  1. The first column is the step number (an integer).

  2. The second column is the interface number (an integer). These are numbered from 1 (_NOT_ from 0).

  3. The direction we are moving in - + for the positive direction or - for the negative direction. Internally this is converted to an integer (+1 or -1).

CROSS_FMT = '{:>10d} {:>4d} {:>3s}'
__init__()

Initialise the crossing formatter.

format(step, data)

Generate output data to be written to a file or screen.

This will format the crossing data in a space delimited form.

Parameters:
  • step (int) – This is the current step number. It is only used here for debugging, and it gives a common interface for all formatters.

  • data (list of tuples) – The tuples are crossing with interfaces (if any) on the form (timestep, interface, direction) where the direction is ‘-’ or ‘+’.

Yields:

out (string) – The line(s) to be written.

See also

check_crossing(), calculates

Note

We add 1 to the interface number here: the crossing file numbers the interfaces from 1, and check_crossing() numbers them from 0.

static parse(line)

Parse crossing data.

The format is described in format(), this method will parse this format for a _single_ row of data.

Parameters:

line (string) – A line to parse.

Returns:

  • out[0] (integer) – The step number.

  • out[1] (integer) – The interface number.

  • out[2] (integer) – The direction, left (-1) or right (1).

Note

The interface number is returned as the file holds it, counted from 1. The flux analysis subtracts 1 from it.

pyretis.inout.formats.energy module

Module for formatting energy data from PyRETIS.

Important classes defined here

EnergyFormatter (EnergyFormatter)

A class for formatting energy data from PyRETIS.

EnergyPathFormatter (EnergyPathFormatter)

A class for formatting energy data for paths.

EnergyFile (EnergyFile)

A class for handling PyRETIS energy files.

EnergyPathFile (EnergyPathFile)

A class for handling PyRETIS energy path files.

class pyretis.inout.formats.energy.EnergyFile(filename, file_mode, backup=True)

Bases: FileIO

A class for handling PyRETIS energy files.

__init__(filename, file_mode, backup=True)

Create the file object and attach the energy formatter.

class pyretis.inout.formats.energy.EnergyFormatter(name='EnergyFormatter')

Bases: OutputFormatter

A class for formatting energy data from PyRETIS.

This class handles formatting of energy data. The data is formatted in 5 columns:

  1. Time, i.e. the step number.

  2. Potential energy.

  3. Kinetic energy.

  4. Total energy, should equal the sum of the two previous columns.

  5. Temperature.

ENERGY_FMT = ['{:>10d}', '{:>14.6f}', '{:>14.6f}', '{:>14.6f}', '{:>14.6f}', '{:>14.6f}']
ENERGY_TERMS = ('vpot', 'ekin', 'etot', 'temp')
HEADER = {'labels': ['Time', 'Potential', 'Kinetic', 'Total', 'Temperature'], 'width': [10, 14]}
__init__(name='EnergyFormatter')

Initialise the formatter for energy.

apply_format(step, energy)

Apply the energy format.

Parameters:
  • step (int) – The current simulation step.

  • energy (dict) – A dict with energy terms to format.

Returns:

out (string) – A string with the formatted energy data.

format(step, data)

Yield formatted energy data. See apply_format().

load(filename)

Load entire energy blocks into memory.

Parameters:

filename (string) – The path/file name of the file we want to open.

Yields:

data_dict (dict) – This is the energy data read from the file, stored in a dict. This is for convenience so that each energy term can be accessed by data_dict[‘data’][key].

class pyretis.inout.formats.energy.EnergyPathFile(filename, file_mode, backup=True)

Bases: FileIO

A class for handling PyRETIS energy path files.

__init__(filename, file_mode, backup=True)

Create the file object and attach the energy formatter.

class pyretis.inout.formats.energy.EnergyPathFormatter

Bases: EnergyFormatter

A class for formatting energy data for paths.

The path energy file carries the same four energy terms as the per-step energy file – potential, kinetic, total and temperature (inherited EnergyFormatter.ENERGY_TERMS / EnergyFormatter.HEADER). Engines that report only potential and kinetic energies leave etot/temp unset; _reconstruct() fills a missing etot with vpot + ekin and a missing temp from the cached _dof_kb, and a term that stays unset is written as nan. The reader (EnergyFormatter.load()) is column-count tolerant, so a path energy file with the potential and kinetic energies only loads too.

__init__()

Initialise.

_reconstruct(energies)

Fill missing total energy / temperature from the stored vpot/ekin.

Reconstructs the derived terms so the path energy file stays reproducible across frame reuse and restart (see _dof_kb). Only genuinely-missing terms are filled; engine-reported values are left untouched.

format(step, data)

Format the energy data from a path.

Parameters:
  • step (int) – The cycle number we are creating output for.

  • data (tuple) – Here we assume that data[0] contains an object like PathBase and that data[1] is a string with the status for the path.

Yields:

out (string) – The strings to be written.

pyretis.inout.formats.gromacs module

Module for handling GROMACS input/output.

Important methods defined here

read_gromacs_generic (read_gromacs_generic())

A method for reading snapshots from any GROMACS file.

read_gromacs_file (read_gromacs_file())

A method for reading snapshots from a GROMACS GRO file.

read_gromacs_gro_file (read_gromacs_gro_file())

Read a single snapshot from a GROMACS GRO file.

write_gromacs_gro_file (write_gromacs_gro_file())

Write configuration in GROMACS GRO format.

read_gromos96_file (read_gromos96_file())

Read a single configuration GROMACS .g96 file.

write_gromos96_file (write_gromos96_file())

Write configuration in GROMACS g96 format.

read_xvg_file (read_xvg_file())

For reading .xvg files from GROMACS.

read_trr_header (read_trr_header())

Read a header from an open TRR file.

read_trr_data (read_trr_data())

Read data from an open TRR file.

skip_trr_data (skip_trr_data())

Skip reading data from an open TRR file and move on to the next header.

read_trr_file (read_trr_file())

Yield frames from a TRR file.

trr_frame_to_g96 (trr_frame_to_g96())

Dump a specific frame from a TRR file to a .g96 file.

write_trr_frame (write_trr_frame())

A simple method to write to a TRR file.

pyretis.inout.formats.gromacs.read_gromacs_file(filename)

Read GROMACS GRO files.

This method will read a GROMACS file and yield the different snapshots found in the file. This function is intended to be used if we want to read all snapshots present in a file.

Parameters:

filename (string) – The file to open.

Yields:

out (dict) – This dict contains the snapshot.

Examples

>>> from pyretis.inout.formats.gromacs import read_gromacs_file
>>> for snapshot in read_gromacs_file('traj.gro'):
...     print(snapshot['x'][0])
pyretis.inout.formats.gromacs.read_gromacs_generic(filename)

Read GROMACS files.

This method will read a GROMACS file and yield the different snapshots found in the file. This function is intended to be used to just count the n of snapshots stored in a file.

Parameters:

filename (string) – The file to check.

Yields:

out (None.)

pyretis.inout.formats.gromacs.read_gromacs_gro_file(filename)

Read a single configuration GROMACS GRO file.

This method will read the first configuration from the GROMACS GRO file and return the data as given by read_gromacs_lines(). It will also explicitly return the matrices with positions, velocities and box size.

Parameters:

filename (string) – The file to read.

Returns:

  • frame (dict) – This dict contains all the data read from the file.

  • xyz (numpy.array) – The positions. The array is (N, 3) where N is the number of particles.

  • vel (numpy.array) – The velocities. The array is (N, 3) where N is the number of particles.

  • box (numpy.array) – The box dimensions.

pyretis.inout.formats.gromacs.read_gromos96_file(filename)

Read a single configuration GROMACS .g96 file.

Parameters:

filename (string) – The file to read.

Returns:

  • rawdata (dict of list of strings) – This is the raw data read from the file grouped into sections. Note that this does not include the actual positions and velocities as these are returned separately.

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • box (numpy.array) – The simulation box.

pyretis.inout.formats.gromacs.read_trr_data(fileh, header)

Read box, coordinates etc. from a TRR file.

Parameters:
  • fileh (file object) – The file handle for the file we are reading.

  • header (dict) – The header read from the file.

Returns:

data (dict) – The data we read from the file. It may contain the following keys if the data was found in the frame:

  • box : the box matrix,

  • vir : the virial matrix,

  • pres : the pressure matrix,

  • x : the coordinates,

  • v : the velocities, and

  • f : the forces

pyretis.inout.formats.gromacs.read_trr_file(filename, read_data=True)

Yield frames from a TRR file.

pyretis.inout.formats.gromacs.read_trr_header(fileh)

Read a header from a TRR file.

Parameters:

fileh (file object) – The file handle for the file we are reading.

Returns:

header (dict) – The header read from the file.

pyretis.inout.formats.gromacs.read_xvg_file(filename)

Return data in xvg file as numpy array.

pyretis.inout.formats.gromacs.skip_trr_data(fileh, header)

Skip coordinates/box data etc.

This method is used when we want to skip a data section in the TRR file. Rather than reading the data, it will use the size read in the header to skip ahead to the next frame.

Parameters:
  • fileh (file object) – The file handle for the file we are reading.

  • header (dict) – The header read from the TRR file.

pyretis.inout.formats.gromacs.trr_frame_to_g96(trr_file, index, outfile)

Dump a TRR frame to a GROMOS96 (.g96) file.

Parameters:
  • trr_file (string) – The TRR file to read from.

  • index (integer) – The index for the frame to dump from trr_file.

  • outfile (string) – The g96 file to write.

pyretis.inout.formats.gromacs.write_gromacs_gro_file(outfile, txt, xyz, vel=None, box=None)

Write configuration in GROMACS GRO format.

Parameters:
  • outfile (string) – The name of the file to create.

  • txt (dict of lists of strings) – This dict contains the information on residue-numbers, names, etc. required to write the GRO file.

  • xyz (numpy.array) – The positions to write.

  • vel (numpy.array, optional) – The velocities to write.

  • box (numpy.array, optional) – The box matrix.

pyretis.inout.formats.gromacs.write_gromos96_file(filename, raw, xyz, vel, box=None)

Write configuration in GROMACS .g96 format.

Parameters:
  • filename (string) – The name of the file to create.

  • raw (dict of lists of strings) – This contains the raw data read from a .g96 file.

  • xyz (numpy.array) – The positions to write.

  • vel (numpy.array) – The velocities to write.

  • box (numpy.array, optional) – The box matrix.

pyretis.inout.formats.gromacs.write_trr_frame(filename, data, endian=None, double=False, append=False)

Write data in TRR format to a file.

Parameters:
  • filename (string) – The name/path of the file to write to.

  • data (dict) – The data we will write to the file.

  • endian (string, optional) – The byte order, '>' (big-endian) or '<' (little-endian). If not specified, big-endian, the byte order of the XDR files GROMACS reads and writes.

  • double (boolean, optional) – If True, we will write in double precision.

  • append (boolean, optional) – If True, we will append to the file, otherwise, the file will be overwritten.

pyretis.inout.formats.order module

Module for formatting order parameter data from PyRETIS.

Important classes defined here

OrderFormatter (OrderFormatter)

A class for formatting order parameter data.

OrderPathFormatter (OrderPathFormatter)

A class for formatting order parameter data for paths.

OrderFile (OrderFile)

A class for handling PyRETIS order parameter files.

OrderPathFile (OrderPathFile)

A class for handling PyRETIS order parameter files for paths.

class pyretis.inout.formats.order.OrderFile(filename, file_mode, backup=True)

Bases: FileIO

A class for handling PyRETIS order parameter files.

__init__(filename, file_mode, backup=True)

Create the order file with correct formatter.

class pyretis.inout.formats.order.OrderFormatter(name='OrderFormatter')

Bases: OutputFormatter

A class for formatting order parameter data.

The format for the order file is column-based and the columns are:

  1. Time.

  2. Main order parameter.

  3. Collective variable 1

  4. Collective variable 2

  5. …

ORDER_FMT = ['{:>10d}', '{:>12.6f}']
__init__(name='OrderFormatter')

Initialise a OrderFormatter formatter.

format(step, data)

Yield formatted order parameters. See format_data().

format_data(step, orderdata)

Format order parameter data.

Parameters:
  • step (int) – This is the current step number.

  • orderdata (list of floats) – These are the order parameters.

Returns:

out (string) – The string to be written.

load(filename)

Read order parameter data from a file.

Since this class defines how the data is formatted it is also convenient to have methods for reading the data defined here. This method will read entire blocks of data from a file into memory. This will be slow for large files.

Parameters:

filename (string) – The path/file name of the file we want to open.

Yields:

data_dict (dict) – This is the order parameter data in the file.

class pyretis.inout.formats.order.OrderPathFile(filename, file_mode, backup=True)

Bases: FileIO

A class for handling PyRETIS order parameter path files.

__init__(filename, file_mode, backup=True)

Create the order path file with correct formatter.

class pyretis.inout.formats.order.OrderPathFormatter

Bases: OrderFormatter

A class for formatting order parameter data for paths.

__init__()

Initialise.

format(step, data)

Format the order parameter data from a path.

Parameters:
  • step (int) – The cycle number we are creating output for.

  • data (tuple or list) – Here, data[0] contains an object like PathBase which is the path we are creating output for; data[1] contains the status for this path.

Yields:

out (string) – The strings to be written.

pyretis.inout.formats.pathensemble module

Module for formatting path ensemble data from PyRETIS.

Important classes defined here

PathEnsembleFormatter (PathEnsembleFormatter)

A class for formatting path ensemble data.

PathEnsembleFile (PathEnsembleFile)

A class for handling PyRETIS path ensemble files.

pyretis.inout.formats.pathensemble.MC_CODE_TO_MOVE = {'bi': 'bias', 'mw': 'mwf'}

Move tags longer than the two-character Mc column, keyed by the code pyretis.inout.pathensemble_output.map_move_to_mc_code() writes for them, which is their first two characters.

class pyretis.inout.formats.pathensemble.PathEnsembleFile(filename, file_mode, ensemble_settings=None, backup=True)

Bases: PathEnsemble, FileIO

A class for handling PyRETIS path ensemble files.

This class inherits from the PathEnsemble and this makes it possible to run the analysis directly on this file.

__init__(filename, file_mode, ensemble_settings=None, backup=True)

Set up the file-like object.

Parameters:
  • filename (string) – The file to open.

  • file_mode (string) – Determines the mode for opening the file.

  • ensemble_settings (dict, optional) – Ensemble specific settings. A missing ensemble_number, interfaces or detect takes a default, with a warning. The optional layout is the (has_minus, has_zero_plus) that ensemble_number counts in (see PathEnsemble); without it the number counts in the full layout.

  • backup (boolean, optional) – Determines how we handle existing files when the mode is set to writing.

get_paths()

Yield paths from the file.

class pyretis.inout.formats.pathensemble.PathEnsembleFormatter

Bases: OutputFormatter

A class for formatting path ensemble data.

This class will effectively define the data which we store for each path ensemble. The data is stored in columns with the format defined below and contains:

  1. The current cycle number: ‘Step’.

  2. The number of accepted paths: ‘No.-acc’.

  3. The number of shooting moves attempted: ‘No.-shoot’.

  4. Starting location (with respect to interfaces): ‘l’. This can be L if a path starts on the left side, R if it starts on the right side and * if it did not reach the interface.

  5. Marker for crossing the middle interface: (‘m’). This is either M (when the middle interface is crossed by the path) or * (if the middle interface is not crossed).

  6. End point for the path: ‘r’. The possible values here are similar to the values for the starting location given above.

  7. The length of the generated path: ‘Length’.

  8. The status of the path: ‘Acc’. This is one of the possible path statuses defined in pyretis.core.path.

  9. The type of move executed for generating the path: ‘Mc’. This is one of the moves defined in pyretis.core.path.

  10. The smallest order parameter in the path: ‘Min-O’.

  11. The largest order parameter in the path: ‘Max-O’.

  12. The index in the path for the smallest order parameter: ‘Idx-Min’.

  13. The index in the path for the largest order parameter: ‘Idx-Max’.

  14. The order parameter for the shooting point, immediately after the shooting move: ‘O-shoot’.

  15. The index in the source path for the shooting point: ‘Idx-sh’.

  16. The index in the new path for the shooting point: ‘Idx-shN’.

  17. The statistical weight of the path: ‘Weight’.

HEADER = {'labels': ['Step', 'No.-acc', 'No.-shoot', 'l', 'm', 'r', 'Length', 'Acc', 'Mc', 'Min-O', 'Max-O', 'Idx-Min', 'Idx-Max', 'O-shoot', 'Idx-sh', 'Idx-shN', 'Weight'], 'width': [10, 10, 10, 1, 1, 1, 7, 3, 2, 16, 16, 7, 7, 16, 7, 7, 16]}
PATH_FMT = '{0:>10d} {1:>10d} {2:>10d} {3:1s} {4:1s} {5:1s} {6:>7d} {7:3s} {8:2s} {9:>16.9e} {10:>16.9e} {11:>7d} {12:>7d} {13:>16.9e} {14:>7d} {15:7d} {16:>16.9e}'
__init__()

Initialise the formatter for path ensemble data.

format(step, data)

Format path ensemble data.

Here we generate output based on the last path from the given path ensemble.

Parameters:
  • step (int) – The current cycle/step number.

  • data (object like PathEnsemble) – The path ensemble we will format here.

Yields:

out (string) – The formatted line with the data from the last path.

load(filename)

Yield the different paths stored in the file.

The lines are read on-the-fly, converted and yielded one-by-one.

Parameters:

filename (string) – The path/filename to open.

Yields:

out (dict) – The information for the current path.

static parse(line)

Parse a line to a simplified representation of a path.

Parameters:

line (string) – The line of text to parse.

Returns:

out (dict) – The dict with the simplified path information.

pyretis.inout.formats.pathensemble.move_from_mc_code(code)

Return the move tag that a written move code stands for.

The analysis names moves by their full tags (mwf, bias). The Mc column of pathensemble.txt holds the first two characters of a tag, and the Move column of a moves.txt can hold the same codes, so their readers pass a code through this function; a trials.txt holds full tags. A full tag is returned unchanged.

Parameters:

code (string) – The move code as written in a pathensemble.txt or moves.txt row.

Returns:

out (string) – The move tag: the full tag for a code in MC_CODE_TO_MOVE, otherwise the code itself.

pyretis.inout.formats.path module

Module for formatting path-trajectory data from PyRETIS.

Important classes defined here

PathExtFormatter (PathExtFormatter)

A class for formatting external trajectories. Since this format is intended for paths created by an external software it will simply contain locations for the files where the snapshots are stored.

PathIntFormatter (PathIntFormatter)

A class for formatting internal trajectories. The format used is relatively simple and does not contain information about atoms, just the coordinates. The output for n-dimensional system contains 2n columns (positions and velocities). This formatter is intended for use with objects like Path.

PathExtFile (PathExtFile)

A class for writing path data for external paths.

PathIntFile (PathIntFile)

A class for writing path data for internal paths.

class pyretis.inout.formats.path.PathExtFile(filename, file_mode, backup=True)

Bases: FileIO

A class for writing path data.

__init__(filename, file_mode, backup=True)

Create the path writer with correct format for external paths.

class pyretis.inout.formats.path.PathExtFormatter

Bases: OutputFormatter

A class for formatting external trajectories.

The external trajectories are stored as files and this path formatter includes the location of these files.

Variables:

FMT (string) – The string to use for the formatting.

FMT = '{:>10}  {:>20s}  {:>10}  {:>5}'
__init__()

Initialise the PathExtFormatter formatter.

format(step, data)

Format path data for external paths.

Parameters:
  • step (integer) – The current simulation step.

  • data (list) – Here, data[0] is assumed to be an object like Path and data[1] a string containing the status of this path.

Yields:

out (string) – The trajectory as references to files.

static parse(line)

Parse the line data by splitting text on spaces.

Parameters:

line (string) – The line to parse.

Returns:

out (list) – The columns of data.

class pyretis.inout.formats.path.PathIntFile(filename, file_mode, backup=True)

Bases: FileIO

A class for writing path data.

__init__(filename, file_mode, backup=True)

Create the path writer with correct format for internal paths.

class pyretis.inout.formats.path.PathIntFormatter

Bases: OutputFormatter

A class for formatting internal trajectories.

__init__()

Initialise the PathIntFormatter formatter.

format(step, data)

Format path data for internal paths.

Parameters:
  • step (integer) – The current simulation step.

  • data (list) – Here, data[0] is assumed to be an object like Path and data[1] a string containing the status of this path.

Yields:

out (string) – The trajectory (positions & velocities).

load(filename)

Load trajectories from a path file.

Parameters:

filename (string) – The path/file name of the file we want to open.

Yields:

data (dict) – The trajectory & comment read from the path file.

static parse(line)

Parse positions and velocities from a single line.

Parameters:

line (string) – The line to parse.

Returns:

  • pos (list of floats) – The positions read from the file.

  • vel (list of floats) – The velocities read from the file.

read_snapshots(data)

Read snapshots from data.

Parameters:

data (list of strings) – The data we are reading into snapshots.

Yields:

out (dict) – A dict representing the snapshot with positions and velocities.

pyretis.inout.formats.snapshot module

Module for formatting snapshot data from PyRETIS.

Important classes defined here

SnapshotFormatter (SnapshotFormatter)

Generic class for formatting system snapshots (coordinates). Note it is intended to format objects like System. The format is very similar to the XYZ format.

SnapshotFile (SnapshotFile)

A class for a collection of snapshots.

Important methods defined here

adjust_coordinate (adjust_coordinate())

Helper method to add dimensions when formatting data in 1D or 2D to a format that requires 3D data.

read_txt_snapshots (read_txt_snapshots())

For reading PyRETIS snapshots from a file.

class pyretis.inout.formats.snapshot.SnapshotFile(filename, file_mode, backup=True, format_settings=None)

Bases: FileIO

A class for a collection of snapshots.

__init__(filename, file_mode, backup=True, format_settings=None)

Create the snapshot file with the possible settings.

class pyretis.inout.formats.snapshot.SnapshotFormatter(write_vel=True, fmt=None)

Bases: OutputFormatter

Generic class for formatting system snapshots.

Variables:
  • write_vel (boolean) – If True, we will also format velocities

  • fmt (string) – Format to use for position output.

  • fmt_vel (string) – Format to use for position and velocity output.

__init__(write_vel=True, fmt=None)

Initialise the formatter.

Parameters:
  • write_vel (boolean, optional) – If True, the formatter will attempt to output velocities.

  • fmt (string, optional) – Selects the format to use.

_format_with_vel(particles)

Format positions of particles for output.

Parameters:

particles (object like Particles) – The particles for which we will format information.

Yields:

out (string) – The formatted output, to be written.

_format_without_vel(particles)

Format positions of particles for output.

Parameters:

particles (object like Particles) – The particles for which we will format information.

Yields:

out (string) – The formatted output, to be written.

data_keys = ('atomname', 'x', 'y', 'z', 'vx', 'vy', 'vz')
format(step, data)

Generate the snapshot output.

Parameters:
  • step (integer) – The current step number for generating the output.

  • data (object like System) – The system we are generating output for.

format_snapshot(step, system)

Format the given snapshot.

Parameters:
  • step (int) – The current simulation step.

  • system (object like System) – The system object with the positions to format.

Returns:

out (list of strings) – The formatted snapshot.

load(filename)

Read snapshots from a given file.

Parameters:

filename (string) – The path/filename to open.

Yields:

out (dict) – This dict contains the snapshot.

static parse(line)

Not implemented - line parser for snapshots.

For snapshots, we use a specialized reader that will read entire system snapshots. To avoid confusion, we just give a warning here.

pyretis.inout.formats.snapshot.adjust_coordinate(coord)

Adjust the dimensionality of coordinates.

This is a helper method for trajectory writers.

A lot of the different formats expects us to have 3 dimensional data. This method just adds dummy dimensions equal to zero.

Parameters:

coord (numpy.array) – The real coordinates.

Returns:

out (numpy.array) – The “zero-padded” coordinates.

pyretis.inout.formats.snapshot.read_txt_snapshots(filename, data_keys=None)

Read snapshots from a text file.

Parameters:
  • filename (string) – The file to read from.

  • data_keys (tuple of strings, optional) – This tuple determines the data we are to read. It can be of type ('atomname', 'x', 'y', 'z', ...).

Yields:

out (dict) – A dictionary with the snapshot.

pyretis.inout.formats.txt_table module

Module defining a table-like output format.

Important classes defined here

TxtTableFormatter (TxtTableFormatter)

A class for creating a table-like format.

PathTableFormatter (PathTableFormatter)

A class for table-like output from path simulations.

ThermoTableFormatter (ThermoTableFormatter)

A class for thermodynamic (energy) output. Useful for output from MD-simulations.

Important methods defined here

txt_save_columns (txt_save_columns)

For writing simple column-based output.

class pyretis.inout.formats.txt_table.PathTableFormatter

Bases: TxtTableFormatter

A special table output class for path ensembles.

This object will return a table of text with a header and with formatted rows for a path ensemble. The table rows will contain data from the PathEnsemble.nstats variable. This table is just meant as output to the screen during a path ensemble simulation.

__init__()

Initialise the PathTableFormatter.

format(step, data)

Generate the output for the path table.

Here we overload the TxtTableFormatter.format() method in order to write path ensemble statistics to (presumably) the screen.

Parameters:
  • step (int) – This is the current step number or a cycle number in a simulation.

  • data (object like PathEnsemble) – This is the path ensemble we are generating output for.

Yields:

out (string) – The formatted output.

class pyretis.inout.formats.txt_table.RETISResultFormatter

Bases: TxtTableFormatter

A special table output class for path ensembles in RETIS simulations.

This object will return a table of text with a header and with formatted rows for a path ensemble. The table rows will contain data from the PathEnsemble.nstats variable. This table is just meant as output to the screen during a path ensemble simulation.

__init__()

Initialise the RETISResultFormatter.

format(step, data)

Generate the output for the path table.

Here we overload the TxtTableFormatter.format() method in order to write path ensemble statistics to (presumably) the screen.

Parameters:
  • step (int) – This is the current step number or a cycle number in a simulation.

  • data (object like PathEnsemble) – This is the path ensemble we are generating output for.

Yields:

out (string) – The formatted output.

class pyretis.inout.formats.txt_table.ThermoTableFormatter

Bases: TxtTableFormatter

A special text table for energy output.

This object will return a table of text with a header and with formatted rows for energy output. Typical use is in MD simulation where we want to display energies at different steps in the simulations.

__init__()

Initialise the ThermoTableFormatter.

class pyretis.inout.formats.txt_table.TxtTableFormatter(variables, title, **kwargs)

Bases: OutputFormatter

A class for generating table output.

This class handles formatting of output data to a table-like format.

Variables:
  • variables (list of strings) – These are the variables we will use in the table.

  • fmt (string) – The format to apply to the columns.

  • row_fmt (list of strings) – A list of strings used for formatting, for constructing fmt.

  • title (string) – A title for the table.

Example

For creating a new table, a dictionary is convenient for grouping the settings:

>>> tabl = {
...    'title': 'Energy output',
...    'var': ['step', 'temp', 'vpot'
...            'ekin', 'etot', 'press'],
...    'format': {'labels': ['Step', 'Temp', 'Pot',
...               'Kin', 'Tot', 'Press'],
...               'width': (10, 12),
...               'spacing': 2,
...               'row_fmt': ['{:> 10d}', '{:> 12.6g}']
...              }
...    }
>>> table = TxtTableFormatter(tabl['var'], tabl['title'], **tabl['format'])
__init__(variables, title, **kwargs)

Initialise the TxtTable object.

Parameters:
  • variables (list of strings) – These are the variables we will use in the table. If the header is not specified, then we will create one using these variables.

  • title (string) – A title for the table.

  • kwargs (dict) – Additional settings for the formatter. This may contain:

    • widthlist of ints

      The (maximum) width of the columns. If the number of items in this list is smaller than the number of variables, we simply repeat the last width for the number of times we need.

    • labelslist of strings

      Table headers to use for the columns.

    • spacinginteger

      The separation between columns. The default value is 1.

    • row_fmtlist of strings

      The format to apply to the columns. If the number of items in this list is smaller than the number of variables, we simply repeat the last format for the number of times we need.

__str__()

Return a string with some info about the TxtTableFormatter.

format(step, data)

Generate output from a dictionary using the requested variables.

Parameters:
  • step (int) – This is the current step number or a cycle number in a simulation.

  • data (dict) – This is assumed to a dictionary containing the row items we want to format.

Yields:

out (string) – A line with the formatted output.

pyretis.inout.formats.txt_table.txt_save_columns(outputfile, header, variables, backup=False)

Save variables to a text file using numpy.savetxt.

Note that the variables are assumed to be numpy.arrays of equal shape and that the output file may also be a compressed file in gzip format (this is selected by letting the output file name end with ‘.gz’).

Parameters:
  • outputfile (string) – Name of the output file to create.

  • header (string) – A string that will be written at the beginning of the file.

  • variables (tuple or list of numpy.arrays) – These are the variables that will be saved to the text file.

  • backup (boolean, optional) – Determines if we should backup old files or not.

pyretis.inout.formats.xyz module

Module for handling the output/input of trajectory data.

This module defines some classes for writing out and reading snapshots and trajectories in a XYZ-like format. By XYZ-like we here mean that we also include velocities as part of the file.

Important methods defined here

format_xyz_data (format_xyz_data())

A method for formatting position/velocity data into a XYZ-like format. This can be used by external engines to convert to a standard format.

read_xyz_file (read_xyz_file())

A method for reading snapshots from a XYZ file.

reverse_xyz_file (reverse_xyz_file())

Method to read an XYZ-file in reverse, helps xyz_merge() merge trajectories.

txt_to_xyz (txt_to_xyz())

Method for converting/extracting paths from the internal trajectory format and writing them as a .xyz file.

write_xyz_file (write_xyz_file())

Just a convenience method for writing to a new file.

write_xyz_trajectory (write_xyz_trajectory())

A helper method to write xyz trajectories. This will also attempt to write box information to the XYZ-header.

xyz_merge (xyz_merge())

A method to merge a forward and a backward XYZ trajectory. This method is mainly used when creating a whole trajectory for visualisation.

pyretis.inout.formats.xyz.convert_snapshot(snapshot)

Convert a XYZ snapshot to numpy arrays.

Parameters:

snapshot (dict) – The dict containing a snapshot read from a XYZ-file.

Returns:

  • box (numpy.array, 1D) – The box dimensions if we manage to read it.

  • xyz (numpy.array) – The positions.

  • vel (numpy.array) – The velocities.

  • names (list of strings) – The atom names found in the file.

pyretis.inout.formats.xyz.format_xyz_data(pos, vel=None, names=None, header=None, fmt=None)

Format XYZ data for outputting.

Parameters:
  • pos (numpy.array) – The positions to write.

  • vel (numpy.array, optional) – The velocities to write.

  • names (list, optional) – The atom names.

  • header (string, optional) – Header to use for writing the XYZ-file.

  • fmt (string, optional) – A format to use for the writing

Yields:

out (string) – The formatted lines.

pyretis.inout.formats.xyz.read_xyz_file(filename)

Read files in XYZ format.

This method will read a XYZ file and yield the different snapshots found in the file.

Parameters:

filename (string) – The file to open.

Yields:

out (dict) – This dict contains the snapshot.

Examples

>>> from pyretis.inout.formats.xyz import read_xyz_file
>>> for snapshot in read_xyz_file('traj.xyz'):
...     print(snapshot['x'][0])

Note

The positions will NOT be converted to a specified set of units.

pyretis.inout.formats.xyz.reverse_xyz_file(filename, outputfile)

Reverse the order for frames in a given XYZ-file.

Parameters:
  • filename (string) – The input .xyz file to open.

  • outputfile (string) – The .xyz file to write.

Note

This method will NOT reverse velocities.

pyretis.inout.formats.xyz.write_xyz_file(filename, pos, vel=None, names=None, header=None)

Create a new XYZ file with the given file name.

Parameters:
  • filename (string) – The file to create.

  • pos (numpy.array) – The positions to write.

  • vel (numpy.array, optional) – The velocities to write.

  • names (list, optional) – The atom names.

  • header (string, optional) – Header to use for writing the XYZ-file.

Note

We will here just overwrite if the file already exists.

Examples

>>> import numpy as np
>>> from pyretis.inout.formats.xyz import write_xyz_file
>>> xyz = 10 * np.random.rand(10, 3)
>>> write_xyz_file('conf.xyz', xyz)
>>> vel = 10 * np.random.rand(10, 3)
>>> write_xyz_file('confv.xyz', xyz, vel)
pyretis.inout.formats.xyz.write_xyz_trajectory(filename, pos, vel, names, box, step=None, append=True, box_fmt='{:9.4f}')

Write XYZ snapshot to a trajectory.

This is intended as a lightweight alternative for just dumping snapshots to a trajectory file.

Parameters:
  • filename (string) – The file name to dump to.

  • pos (numpy.array) – The positions we are to write.

  • vel (numpy.array) – The velocities we are to write.

  • names (list of strings) – Atom names to write.

  • box (numpy.array) – The box dimensions/vectors

  • step (integer, optional) – If the step is given, then the step number is written to the header.

  • append (boolean, optional) – Determines if we append or overwrite an existing file.

  • box_fmt (string, optional) – The format of each box parameter on the box line of the header.

Note

By default (append=True), we will here append to the file.

pyretis.inout.formats.xyz.xyz_merge(backward, forward, merged)

Merge forward and backward trajectories into one.

Parameters:
  • backward (string) – File path to the backward trajectory.

  • forward (string) – File path to the forward trajectory.

  • merged (string) – File path to the merged (output) trajectory. This will overwrite existing files with the same file path!

Note

The velocities in the backward trajectory will not be reversed, the purpose of this method is mainly to make whole trajectories for visualisation purposes.