This module contains utilities for use with various aspects of the Amp calculator.

Module contents

class amp.utilities.Annealer(calc, images, Tmax=None, Tmin=None, steps=None, updates=None)[source]

Bases: object

Inspired by the simulated annealing implementation of Richard J. Wagner <wagnerr@umich.edu> and Matthew T. Perry <perrygeo@gmail.com> at https://github.com/perrygeo/simanneal.

Performs simulated annealing by calling functions to calculate loss and make moves on a state. The temperature schedule for annealing may be provided manually or estimated automatically.

Can be used by something like:

>>> from amp import Amp
>>> from amp.descriptor.gaussian import Gaussian
>>> from amp.model.neuralnetwork import NeuralNetwork
>>> calc = Amp(descriptor=Gaussian(), model=NeuralNetwork())

which will initialize tha calc object as usual, and then

>>> from amp.utilities import Annealer
>>> Annealer(calc=calc, images=images)

which will perform simulated annealing global search in parameters space, and finally

>>> calc.train(images=images)

for gradient descent optimization.

Tmax = 20.0
Tmin = 2.5

Minimizes the loss of a system by simulated annealing.

Parameters:state – An initial arrangement of the system
Returns:The best state and loss found.
Return type:state, loss
auto(minutes, steps=2000)[source]

Minimizes the loss of a system by simulated annealing with automatic selection of the temperature schedule.

Keyword arguments: state – an initial arrangement of the system minutes – time to spend annealing (after exploring temperatures) steps – number of steps to spend on each stage of exploration

Returns the best state and loss found.


Returns an exact copy of the provided state Implemented according to self.copy_strategy, one of

  • deepcopy : use copy.deepcopy (slow but reliable)
  • slice: use list slices (faster but only works if state is list-like)
  • method: use the state’s copy() method
copy_strategy = 'copy'

Calculate state’s loss


Create a state change

static round_figures(x, n)[source]

Returns x rounded to n significant figures.


Saves state

save_state_on_exit = False

Takes the output from auto and sets the attributes

set_user_exit(signum, frame)[source]

Raises the user_exit flag, further iterations are stopped

steps = 10000
static time_string(seconds)[source]

Returns time in seconds as a string formatted HHHH:MM:SS.

update(step, T, L, acceptance, improvement)[source]

Prints the current temperature, loss, acceptance rate, improvement rate, elapsed time, and remaining time.

The acceptance rate indicates the percentage of moves since the last update that were accepted by the Metropolis algorithm. It includes moves that decreased the loss, moves that left the loss unchanged, and moves that increased the loss yet were reached by thermal excitation.

The improvement rate indicates the percentage of moves since the last update that strictly decreased the loss. At high temperatures it will include both moves that improved the overall state and moves that simply undid previously accepted moves that increased the loss by thermal excititation. At low temperatures it will tend toward zero as the moves that can decrease the loss are exhausted and moves that would increase the loss are no longer thermally accessible.

updates = 50
user_exit = False
exception amp.utilities.ConvergenceOccurred[source]

Bases: exceptions.Exception

Kludge to decide when scipy’s optimizers are complete.

class amp.utilities.Data(filename, db=<class amp.utilities.FileDatabase>, calculator=None)[source]

Serves as a container (dictionary-like) for (key, value) pairs that also serves to calculate them.

Works by default with python’s shelve module, but something that is built to share the same commands as shelve will work fine; just specify this in dbinstance.

Designed to hold things like neighborlists, which have a hash, value format.

This will work like a dictionary in that items can be accessed with data[key], but other advanced dictionary functions should be accessed with through the .d attribute:

>>> data = Data(...)
>>> data.open()
>>> keys = data.d.keys()
>>> values = data.d.values()
calculate_items(images, parallel, log=None)[source]

Calculates the data value with ‘calculator’ for the specified images.

images is a dictionary, and the same keys will be used for the current database.


Safely close the database.


Open the database connection with mode specified.

class amp.utilities.FileDatabase(filename)[source]

Using a database file, such as shelve or sqlitedict, that can handle multiple processes writing to the file is hard.

Therefore, we take the stupid approach of having each database entry be a separate file. This class behaves essentially like shelve, but saves each dictionary entry as a plain pickle file within the directory, with the filename corresponding to the dictionary key (which must be a string).

Like shelve, this also keeps an internal (memory dictionary) representation of the variables that have been accessed.

Also includes an archive feature, where files are instead added to a file called ‘archive.tar.gz’ to save disk space. If an entry exists in both the loose and archive formats, the loose is taken to be the new (correct) value.


Cleans up to save disk space and reduce huge number of files.

That is, puts all files into an archive. Compresses all files in <path>/loose and places them in <path>/archive.tar.gz. If archive exists, appends/modifies.


Only present for compatibility with shelve.


Return list of keys, both of in-memory and out-of-memory items.

classmethod open(Cls, filename, flag=None)[source]

Open present for compatibility with shelve. flag is ignored; this format is always capable of both reading and writing.


Return list of values, both of in-memory and out-of-memory items. This moves all out-of-memory items into memory.

class amp.utilities.Logger(file)[source]

Logger that can also deliver timing information.

Parameters:file (str) – File object or path to the file to write to. Or set to None for a logger that does nothing.

Start a timer.

Parameters:label (str) – Label for managing multiple timers.
class amp.utilities.MessageDictionary(process_id)[source]

Standard container for all messages (typically requests, via zmq.context.socket.send_pyobj) sent from the workers to the master.

This returns a simple dictionary. This is roughly email format. Initialize with process id (e.g., ‘from’). Call with subject and data (body).

class amp.utilities.MetaDict[source]

Bases: dict

Dictionary that can also store metadata. Useful for images dictionary so that images can still be iterated by keys.

metadata = {}
exception amp.utilities.MissingDataError[source]

Bases: exceptions.Exception

Error to be raised if any images are missing key data, like energy or forces.

exception amp.utilities.TrainingConvergenceError[source]

Bases: exceptions.Exception

Error to be raised if training does not converge.

amp.utilities.assign_cores(cores, log=None)[source]

Tries to guess cores from environment.

If fed a log object, will write its progress.

amp.utilities.check_images(images, forces)[source]

Checks that all images have energies, and optionally forces, calculated, so that they can be used for training. Raises a MissingDataError if any are missing.


Creates a unique signature for a particular ASE atoms object.

This is used to check whether an image has been seen before. This is just an md5 hash of a string representation of the atoms object.

Parameters:atoms (ASE dict) – ASE atoms object.
Return type:Hash string key of ‘atoms’.
amp.utilities.hash_images(images, log=None, ordered=False)[source]

Converts input images – which may be a list, a trajectory file, or a database – into a dictionary indexed by their hashes.

Returns this dictionary. If ordered is True, returns an OrderedDict. When duplicate images are encountered (based on encountering an identical hash), a warning is written to the logfile. The number of duplicates of each image can be accessed by examinging dict_images.metadata[‘duplicates’], where dict_images is the returned dictionary.


Handles strange import cases, like pxssh which might show up in eithr the package pexpect or pxssh.

amp.utilities.make_filename(label, base_filename)[source]

Creates a filename from the label and the base_filename which should be a string.

Returns None if label is None; that is, it only saves output if a label is specified.

  • label (str) – Prefix.
  • base_filename (str) – Basic name of the file.
amp.utilities.make_sublists(masterlist, n)[source]

Randomly divides the masterlist into n sublists of roughly equal size.

The intended use is to divide a keylist and assign keys to each task in parallel processing. This also destroys the masterlist (to save some memory).

Return type:String of current time.
amp.utilities.randomize_images(images, fraction=0.8)[source]

Randomly assigns ‘fraction’ of the images to a training set and (1 - ‘fraction’) to a test set. Returns two lists of ASE images.

  • images (list or str) – List of ASE atoms objects in ASE format. This can also be the path to an ASE trajectory (.traj) or database (.db) file.
  • fraction (float) – Portion of train_images to all images.

train_images, test_images – Lists of train and test images.

Return type:


amp.utilities.setup_parallel(parallel, workercommand, log)[source]

Starts the worker processes and the master to control them.

This makes an SSH connection to each node (including the one the master process runs on), then creates the specified number of processes on each node through its SSH connection. Then sets up ZMQ for efficienty communication between the worker processes and the master process.

Uses the parallel dictionary as defined in amp.Amp. log is an Amp logger. module is the name of the module to be called, which is usually given by self.calc.__module, etc. workercommand is stub of the command used to start the servers, typically like “python -m amp.descriptor.gaussian”. Appended to this will be ” <pid> <serversocket> &” where <pid> is the unique ID assigned to each process and <serversocket> is the address of the server, like ‘node321:34292’.

Returns:server – The ssh connections (pxssh instances; if these objects are destroyed pxssh will close the sessions)

the pid_count, which is the total number of workers started. Each worker can be communicated directly through its PID, an integer between 0 and pid_count

Return type:(a ZMQ socket)
amp.utilities.start_workers(process_ids, workerhostname, workercommand, log, envcommand)[source]

A function to start a new SSH session and establish processes on that session.


Converts a string into a dictionary.

Basically just calls eval on it, but supplies words like OrderedDict and matrix.