Simulation

Inheritance Diagram

Inheritance diagram of tenpy.simulations.simulation.Simulation

Methods

Simulation.__init__(options, *[, …])

Initialize self.

Simulation.final_measurements()

Perform a last set of measurements.

Simulation.fix_output_filenames()

Determine the output filenames.

Simulation.from_saved_checkpoint([filename, …])

Re-initialize a given simulation class from checkpoint results.

Simulation.get_backup_filename(output_filename)

Extract the name used for backups of output_filename.

Simulation.get_output_filename()

Read out the output_filename from the options.

Simulation.get_version_info()

Try to save version info which is necessary to allow reproducability.

Simulation.init_algorithm(**kwargs)

Initialize the algorithm.

Simulation.init_measurements()

Initialize and prepare measurements.

Simulation.init_model()

Initialize a model from the model parameters.

Simulation.init_state()

Initialize a tensor network psi.

Simulation.make_measurements()

Perform measurements and merge the results into self.results['measurements'].

Simulation.perform_measurements()

Emits the measurement_event to call measurement functions and collect results.

Simulation.prepare_results_for_save()

Bring the results into a state suitable for saving.

Simulation.resume_run()

Resume a simulation that was initialized from a checkpoint.

Simulation.resume_run_algorithm()

Resume running the algorithm.

Simulation.run()

Run the whole simulation.

Simulation.run_algorithm()

Run the algorithm.

Simulation.save_at_checkpoint(alg_engine)

Save the intermediate results at the checkpoint of an algorithm.

Simulation.save_results()

Save the results to an output file.

Class Attributes and Properties

Simulation.default_algorithm

name of the default algorithm engine class

Simulation.default_measurements

tuples as for Simulation.connect_measurements that get added if the Simulation.use_default_measurements is True.

Simulation.logger

class attribute.

Simulation.verbose

class tenpy.simulations.simulation.Simulation(options, *, setup_logging=True, resume_data=None)[source]

Bases: object

Base class for simulations.

Parameters
  • options (dict-like) – The simulation parameters as outlined below. Ideally, these options should be enough to fully specify all parameters of a simulation to ensure reproducibility.

  • setup_logging (bool) – Whether to call setup_logging() at the beginning of initialization.

  • resume_data (None | dict) – Ignored if None. If a dictionary, it should contain the data for resuming the simulation, results['resume_data'] (see results). Additionally, it should contain the state, i.e., include resume_data['psi'] = results['psi']. (Optionally, it can also include the model.) Note that the dict is cleared after readout to allow freeing memory.

Options

config Simulation
option summary

algorithm_class in Simulation.init_algorithm

Class or name of a subclass of :class:`~tenpy.algorithms.algorithm.Algorith [...]

algorithm_params in Simulation.init_algorithm

Dictionary with parameters for the algortihm; see the decoumentation of the [...]

connect_algorithm_checkpoint in Simulation.init_algorithm

Functions to connect to the :attr:`~tenpy.algorithms.Algorith.checkpoint` e [...]

connect_measurements in GroundStateSearch.init_measurements

Functions to connect to the :attr:`measurement_event`. [...]

directory

If not None (default), switch to that directory at the beginning of the sim [...]

initial_state_builder_class in GroundStateSearch.init_state

Class or name of a subclass of :class:`~tenpy.networks.mps.InitialStateBuil [...]

initial_state_params in GroundStateSearch.init_state

Dictionary with parameters for building `psi`; see the decoumentation of th [...]

log_params

Log parameters; see :cfg:config:`log`.

measure_initial in GroundStateSearch.init_measurements

Whether to perform a measurement on the initial state, i.e., before startin [...]

model_class in GroundStateSearch.init_model

Mandatory. Class or name of a subclass of :class:`~tenpy.models.model.Model`.

model_params in GroundStateSearch.init_model

Dictionary with parameters for the model; see the documentation of the [...]

output_filename in GroundStateSearch.get_output_filename

If ``None`` (default), no output is written to files. [...]

output_filename_params in GroundStateSearch.get_output_filename

Instead of specifying the `output_filename` directly, this dictionary descr [...]

overwrite_output in GroundStateSearch.fix_output_filenames

Only makes a difference if `skip_if_output_exists` is False and the file ex [...]

random_seed

If not ``None``, initialize the numpy random generator with the given seed.

safe_write in GroundStateSearch.fix_output_filenames

If True (default), perform a "safe" overwrite of `output_filename` as descr [...]

save_every_x_seconds in GroundStateSearch.save_at_checkpoint

By default (``None``), this feature is disabled. [...]

save_psi in GroundStateSearch.init_state

Whether the final :attr:`psi` should be included into the output :attr:`res [...]

sequential

Parameters for running simulations sequentially, see :cfg:config:`sequentia [...]

skip_if_output_exists in GroundStateSearch.fix_output_filenames

If True, raise :class:`Skip` if the output file already exists.

use_default_measurements in GroundStateSearch.init_measurements

Each Simulation class defines a list of :attr:`default_measurements` in the [...]

option directory: str

If not None (default), switch to that directory at the beginning of the simulation.

option log_params: dict

Log parameters; see log.

option overwrite_output: bool

Whether an exisiting file may be overwritten. Otherwise, if the file already exists we try to replace filename.ext with filename_01.ext (and further increasing numbers).

option random_seed: int | None

If not None, initialize the numpy random generator with the given seed.

option sequential: dict

Parameters for running simulations sequentially, see sequential. Ignored by the simulation itself, but used by run_seq_simulations() and resume_from_checkpoint() to run a whole sequence of simulations passing on the state (and possible more).

options

Simulation parameters.

Type

Config

model

The model to be simulated.

Type

Model

psi

The tensor network state updated by the algorithm.

engine

The engine of the algorithm.

results

Collection of all the results to be saved in the end. In a standard simulation, it will have the following entries.

simulation_parameters: nested dict

The simulation parameters passed as options.

version_infodict

Information of the used library/code versions and simulation class. See get_version_info().

finished_runbool

Usefull to check whether the output file finished or was generated at a checkpoint. This flag is set to True only right at the end of run() (or resume_run()) before saving.

measurementsdict

Data of all the performed measurements.

psi :

The final tensor network state. Only included if Simulation.save_psi is True (default).

resume_datadict

Additional data for resuming the algorithm run. Not part of self.results, but only added in prepare_results_for_save() with the most up to date resume_data from get_resume_data(). Only included if Simultion.save_resume_data is True. When you want to pass this as argument to another simulation, you need to include the state, resume_data['psi'] = results['psi'].

Type

dict

measurement_event

An event that gets emitted each time when measurements should be performed. The callback functions should take psi, the simulation class itself, and a dictionary results as arguments. They should directly write the results into that dictionary.

Type

EventHandler

output_filename

Filename for output.

Type

str

_backup_filename

When writing a file a second time, instead of simply overwriting it, move it to there. In that way, we still have a non-corrupt version if something fails during saving.

Type

str

_last_save

Time of the last call to save_results(), initialized to startup time.

Type

float

loaded_from_checkpoint

True when the simulation is loaded with from_saved_checkpoint().

Type

bool

default_algorithm = 'TwoSiteDMRGEngine'

name of the default algorithm engine class

default_measurements = [('tenpy.simulations.measurement', 'measurement_index', {}, 1), ('tenpy.simulations.measurement', 'bond_dimension'), ('tenpy.simulations.measurement', 'energy_MPO'), ('tenpy.simulations.measurement', 'entropy')]

tuples as for Simulation.connect_measurements that get added if the Simulation.use_default_measurements is True.

logger = <Logger tenpy.simulations.simulation.Simulation (WARNING)>

class attribute.

Type

logger

Type

An instance of a logger; see Logging and terminal output. NB

run()[source]

Run the whole simulation.

Returns

results – The results as returned by prepare_results_for_save().

Return type

dict

classmethod from_saved_checkpoint(filename=None, checkpoint_results=None, **kwargs)[source]

Re-initialize a given simulation class from checkpoint results.

You should probably call resume_run() after sucessfull initialization.

Instead of calling this directly, consider using resume_from_checkpoint().

Parameters
  • filename (None | str) – The filename of the checkpoint to be loaded. You can either specify the filename or the checkpoint_results.

  • checkpoint_results (None | dict) – Alternatively to filename the results of the simulation so far, i.e. directly the data dicitonary saved at a simulation checkpoint.

  • **kwargs – Further keyword arguments given to the Simulation.__init__.

resume_run()[source]

Resume a simulation that was initialized from a checkpoint.

Returns

results – The results as returned by prepare_results_for_save().

Return type

dict

init_model()[source]

Initialize a model from the model parameters.

Skips initialization if model is already set.

Options

option Simulation.model_class: str | class

Mandatory. Class or name of a subclass of Model.

option Simulation.model_params: dict

Dictionary with parameters for the model; see the documentation of the corresponding model_class.

init_state()[source]

Initialize a tensor network psi.

Skips initialization if psi is already set.

Options

option Simulation.initial_state_builder_class: str | class

Class or name of a subclass of InitialStateBuilder. Used to initialize psi according to the initial_state_params.

option Simulation.initial_state_params: dict

Dictionary with parameters for building psi; see the decoumentation of the initial_state_builder_class, e.g. InitialStateBuilder.

option Simulation.save_psi: bool

Whether the final psi should be included into the output results.

init_algorithm(**kwargs)[source]

Initialize the algorithm.

If results has ‘resume_data’, it is read out, used for initialization and removed from the results.

Parameters

**kwargs – Extra keyword arguments passed on to the Algorithm.__init__(), for example the resume_data when calling resume_run.

Options

option Simulation.algorithm_class: str | class

Class or name of a subclass of Algorithm. The engine of the algorithm to be run.

option Simulation.algorithm_params: dict

Dictionary with parameters for the algortihm; see the decoumentation of the algorithm_class.

option Simulation.connect_algorithm_checkpoint: list of tuple

Functions to connect to the checkpoint event of the algorithm. Each tuple can be of length 2 to 4, with entries (module, function, kwargs, priority), the last two optionally. The mandatory module and function specify a callback measurement function. kwargs can specify extra keyword-arguments for the function, priority allows to tune the order in which the measurement functions get called. See connect_by_name() for more details.

init_measurements()[source]

Initialize and prepare measurements.

Options

option Simulation.connect_measurements: list of tuple

Functions to connect to the measurement_event. Each tuple can be of length 2 to 4, with entries (module, function, kwargs, priority), the last two optionally. The mandatory module and function specify a callback measurement function. kwargs can specify extra keyword-arguments for the function, priority allows to tune the order in which the measurement functions get called. See connect_by_name() for more details.

option Simulation.use_default_measurements: bool

Each Simulation class defines a list of default_measurements in the same format as Simulation.connect_measurements. This flag allows to explicitly disable them.

option Simulation.measure_initial: bool

Whether to perform a measurement on the initial state, i.e., before starting the algorithm run.

run_algorithm()[source]

Run the algorithm. Calls self.engine.run().

resume_run_algorithm()[source]

Resume running the algorithm. Calls self.engine.resume_run().

make_measurements()[source]

Perform measurements and merge the results into self.results['measurements'].

perform_measurements()[source]

Emits the measurement_event to call measurement functions and collect results.

Returns

results – The results from calling the measurement functions.

Return type

dict

final_measurements()[source]

Perform a last set of measurements.

get_version_info()[source]

Try to save version info which is necessary to allow reproducability.

get_output_filename()[source]

Read out the output_filename from the options.

You can easily overwrite this method in subclasses to customize the outputfilename depending on the options passed to the simulations.

Options

option Simulation.output_filename: path_like | None

If None (default), no output is written to files. If a string, this filename is used for output (up to modifications by fix_output_filenames() to avoid overwriting previous results).

option Simulation.output_filename_params: dict

Instead of specifying the output_filename directly, this dictionary describes the parameters that should be included into it. Entries of the dictionary are keyword arguments to output_filename_from_dict() with the simulation parameters (Simulation, or equivalently options) as options.

Returns

output_filename – Filename for output; None disables any writing to files. Relative to Simulation.directory, if specified. The file ending determines the output format.

Return type

str | None

fix_output_filenames()[source]

Determine the output filenames.

This function determines the output_filename and writes a one-line text into that file to indicate that we’re running a simulation generating it. Further, _backup_filename is determined.

Options

option Simulation.skip_if_output_exists: bool

If True, raise Skip if the output file already exists.

option Simulation.overwrite_output: bool

Only makes a difference if skip_if_output_exists is False and the file exists. In that case, with overwrite_output, just save everything under that name again, or with overwrite_output`=False, replace ``filename.ext` with filename_01.ext (and further increasing numbers) until we get a filename that doesn’t exist yet.

option Simulation.safe_write: bool

If True (default), perform a “safe” overwrite of output_filename as described in save_results().

get_backup_filename(output_filename)[source]

Extract the name used for backups of output_filename.

Parameters

output_filename (pathlib.Path) – The filename where data is saved.

Returns

backup_filename – The filename where to keep a backup while writing files to avoid.

Return type

pathlib.Path

save_results()[source]

Save the results to an output file.

Performs a “safe” overwrite of output_filename by first moving the old file to _backup_filename, then writing the new file, and finally removing the backup.

Calls prepare_results_for_save() to allow last-minute adjustments to the saved results.

prepare_results_for_save()[source]

Bring the results into a state suitable for saving.

For example, this can be used to convert lists to numpy arrays, to add more meta-data, or to clean up unnecessarily large entries.

Options

Cfg:configoptions :

Simulation

save_resume_databool

If True, include data from get_resume_data() into the output as resume_data.

Returns

results – A copy of results containing everything to be saved. Measurement results are converted into a numpy array (if possible).

Return type

dict

save_at_checkpoint(alg_engine)[source]

Save the intermediate results at the checkpoint of an algorithm.

Parameters

alg_engine (Algorithm) – The engine of the algorithm. Not used in this function, mostly there for compatibility with the tenpy.algorithms.Algorithm.checkpoint event.

Options

option Simulation.save_every_x_seconds: float | None

By default (None), this feature is disabled. If given, save the results obtained so far at each tenpy.algorithm.Algorithm.checkpoint when at least save_every_x_seconds seconds evolved since the last save (or since starting the algorithm). To avoid unnecessary, slow disk input/output, the value will be increased if saving takes longer than 10% of save_every_x_seconds. Use 0. to force saving at each checkpoint.