Esempio n. 1
0
    def get_stresses(self, atoms, cutoff=3.0):
        """
        Returns local stresses on `atoms` as a ``(len(atoms), 3, 3)`` array
        """
        if not isinstance(atoms, Atoms):
            atoms = Atoms(atoms)
        
        sigma = np.zeros((len(atoms), 3, 3))
        if self.method == 'fortran':
            atoms.set_cutoff(cutoff)
            atoms.calc_connect()
            elastic_fields_fortran(atoms, a=self.a, cij=self.cij)
            
            sigma[:,0,0], sigma[:,1,1], sigma[:,2,2], sigma[:,1,2], sigma[:,0,2], sigma[:,0,1] = \
               atoms.sig_xx, atoms.sig_yy, atoms.sig_zz, atoms.sig_yz, atoms.sig_xz, atoms.sig_xy
        else:
            elastic_fields(atoms, a=self.a, cij=self.cij, **self.extra_args)

            sigma[:,0,0], sigma[:,1,1], sigma[:,2,2], sigma[:,1,2], sigma[:,0,2], sigma[0,1] = atoms.stress

        # Fill in symmetric components
        sigma[:,1,0] = sigma[:,0,1]
        sigma[:,2,1] = sigma[:,1,2]
        sigma[:,2,0] = sigma[:,0,2]

        return sigma
Esempio n. 2
0
def make_crack_advance_map(atoms, tol=1e-3):
    """
    Find mapping from atom indices to the index of atom one step ahead
    of them in the crack propagation direction (i.e. along +x).

    Requires 'LatticeConstant', 'CleavagePlane', and 'CrackFront' to
    be available in atoms.info dictionary.

    Returns integer array of shape (len(atoms),), and also adds a new
    array 'advance_map' into the Atoms object.
    """

    def find_atom_with_displacement(atoms, i, target_disps):
        """
        Return index of atom with relative displacement from i in target_disps

        Requires connnectivity to be calculated already
        """
        indices, offsets = atoms.neighbours.get_neighbors(i)
        diffs = (atoms.positions[indices] + np.dot(offsets, atoms.cell) -
                 atoms.positions[i])
        for j, diff in zip(indices, diffs):
            for target in target_disps:
                if all(abs(diff - target) < tol):
                    return j
        return 0

    a0 = atoms.info['LatticeConstant']
    cleavage_plane = atoms.info['CleavagePlane']
    crack_front = atoms.info['CrackFront']

    # lookup this crack system in the dictionary of crack advance steps
    cleavage_plane = MillerPlane(cleavage_plane)
    crack_front = MillerDirection(crack_front)
    key = str(cleavage_plane) + str(crack_front)
    steps = a0 * crack_advance_step_frac_coords[key]

    advance_map = np.zeros(len(atoms), dtype=int)

    # find biggest distance between atoms before and after a crack advance step
    max_step_length = np.sqrt((steps ** 2).sum(axis=1)).max()

    # convert from ase.Atoms to quippy.Atoms, so we can use faster
    # neighbour lists in Fortran code
    tmp_atoms = Atoms(atoms)
    tmp_atoms.set_cutoff(max_step_length + .1)
    tmp_atoms.calc_connect()

    for i in range(len(tmp_atoms)):
        advance_map[i] = find_atom_with_displacement(tmp_atoms, i, steps)

    # save the map inside the Atoms object, and return a copy
    atoms.new_array('advance_map', advance_map)
    return advance_map
Esempio n. 3
0
def update_qm_region(atoms, dis_type='edge', cut=3.0, rr=10.0, qr=1):
  """
  Routine for updating qm region of dislocation. 
  Args:
    dis_type: Dislocation type can be edge or screw. 
    rr: determines radius of quantum sphere.
    qr: is the number of quantum regions. 
  """
  core[:] = atoms.params['core']
  fixed_mask = (np.sqrt((atoms.positions[:,0]-core[0])**2 + (atoms.positions[:,1]-core[1])**2) < rr)
  cl = atoms.select(mask=fixed_mask, orig_index=True) 
  print 'Number of Atoms in Cluster', cl.n
  cl.set_cutoff(cut)
  cl.calc_connect()
  cl = Atoms(cl)
  x0 = Atoms('ref_slab.xyz')
  x0.set_cutoff(cut)
  x0.calc_connect()
  alpha = calc_nye_tensor(cl, x0, 3, 3, cl.n)    
  cl.screw = alpha[2,2,:]
  cl.edge  = alpha[2,0,:]
  if dis_type  == 'screw':
    defect_pos = cl.screw
  elif dis_type == 'edge':
    defect_pos = cl.edge
  total_def = 0.0
  c = np.array([0.,0.,0.])
  mom = [3.0 for at in range(len(atoms))]
  atoms.set_initial_magnetic_moments(mom)
  for i in range(cl.n):
    defect_pos = defect_pos   + cl.edge[i]
    c[1] = c[1] + cl.positions[i,0]*defect_pos[i]
    c[2] = c[2] + cl.pos[i,0]*defect_pos[i]
  c[0] = c[0]/total_def
  c[1] = c[1]/total_def
  c[2] = atoms.lattice[2,2]/2.
  core[:] = c.copy()
  old_qm_list = atoms.hybrid_vec.nonzero()[0]
  new_qm_list = update_hysteretic_qm_region(atoms, old_qm_list, core[:],
                                            qm_inner_radius,
                                            qm_outer_radius,
                                            update_marks=False)
#Force Mixing Potential requires hybrid property:
  atoms.hybrid[:] = 0
  atoms.hybrid[new_qm_list] = 1
#Distributed Force Mixing Properties:
  atoms.hybrid_vec[:] = 0
  atoms.hybrid_vec[new_qm_list] = 1
  atoms.hybrid_1[:] = atoms.hybrid_vec[:]
  atoms.params['core'] = core[:]
  return 
Esempio n. 4
0
def find_crack_tip_coordination(atoms, edge_tol=10.0,
                                strip_height=30.0, nneightol=1.3):
    """
    Return position of crack tip in `atoms`, based on atomic coordination.

    If `atoms` does not contain an `advance_map` property, then
    :func:`make_crack_advance_map` is called to generate the map.

    Parameters
    ----------
    atoms : :class:`~.Atoms' object
       The Atoms object containing the crack slab.
    edge_tol : float
       Distance from edge of system within which to exclude
       undercoodinated atoms.
    strip_height : float
       Height of strip along centre of slab in which to look
       for the track.
    nneightol : float
       Nearest neighbour tolerance, as a fraction of sum of
       covalent radii of atomic species.

    Returns
    -------
    crack_pos : array
       x, y, and z coordinates of the crack tip. Also set in ``CrackPos``
       in ``atoms.info`` dictionary.
    tip_atoms : array
       Indices of atoms near the tip Also set in ``crack_tip`` property.
    """

    old_tip_pos_y = 0
    if 'CrackPos' in atoms.info:
        old_tip_pos_y = atoms.info['CrackPos'][1]

    # Make a copy of atoms as a quippy.Atoms instance, overwriting
    # positions with time-averages values if they are available, and
    # then calculate connectivity using nneightol
    tmp_atoms = Atoms(atoms)
    if 'avgpos' in tmp_atoms.arrays:
        tmp_atoms.set_positions(tmp_atoms.arrays['avgpos'])
    tmp_atoms.calc_connect()

    nn = tmp_atoms.n_neighb
    x = tmp_atoms.positions[:, 0]
    y = tmp_atoms.positions[:, 1]

    # find undercoordinated atoms in a central strip, and not too
    # close to the left or right edges
    left = tmp_atoms.positions[:, 0].min()
    right = tmp_atoms.positions[:, 0].max()
    uc = ((nn < 4) &
          (abs(y) < strip_height) &
          (x > left + edge_tol) &
          (x < right - edge_tol))

    # position of furthest forward undercoordinated atom ABOVE old tip position
    x_above = x[uc & (y > old_tip_pos_y)].max()

    # position of furthest forward undercoordinated atom BELOW old tip position
    x_below = x[uc & (y < old_tip_pos_y)].max()

    # rightmost undercoordinated atoms, both above and below old tip
    rightmost_uc = uc & (((y > old_tip_pos_y) & (x_above == x)) |
                         ((y <= old_tip_pos_y) & (x_below == x)))

    # we want the NEXT pair of atoms, so we use the saved mapping from
    # atom indices to the indices of atoms one unit cell to the right
    if 'advance_map' not in atoms.arrays:
        print('Generating crack advance map...')
        make_crack_advance_map(atoms)

    advance_map = atoms.arrays['advance_map']
    tip_atoms = advance_map[rightmost_uc]
    tip_pos = tmp_atoms.positions[tip_atoms, :].mean(axis=0)

    # Also save results in Atoms (useful for visualisation)
    atoms.info['CrackPos'] = tip_pos
    atoms.set_array('crack_tip', np.array([False]*len(atoms)))
    crack_tip = atoms.arrays['crack_tip']
    crack_tip[tip_atoms] = True
    return tip_pos
Esempio n. 5
0
def crack_strain_energy_release_rate(at, bulk=None, f_min=.8, f_max=.9, stem=None, avg_pos=False):
    """
    Compute strain energy release rate G from elastic potential energy in a strip
    """

    print 'Analytical effective elastic modulus E\' = ', at.YoungsModulus/(1-at.PoissonRatio_yx**2), 'GPa'
    print 'Analytical energy release rate G = ', crack_measure_g(at, at.YoungsModulus, at.PoissonRatio_yx, at.OrigHeight), 'J/m^2'

    if bulk is None:
        if stem is None: raise ValueError('Either "bulk" or "stem" must be present')
        bulk = Atoms(stem+'_bulk.xyz')

    if not hasattr(at, 'local_energy') or not hasattr(bulk, 'energy'):
        if stem is None: raise ValueError('local_energy property not found in Atoms and "stem" is missing')
        xmlfile = stem+'.xml'
        params = CrackParams(xmlfile)
        pot = Potential(params.classical_args, param_filename=stem+'.xml')
        pot.print_()

        if not hasattr(at, 'local_energy'):
            if avg_pos:
                tmp_pos = at.pos.copy()
                at.pos[...] = at.avgpos
            at.set_cutoff(pot.cutoff()+1.)
            at.calc_connect()
            pot.calc(at, args_str="local_energy")
            if avg_pos:
                at.pos[...] = tmp_pos

        if not hasattr(bulk, 'energy'):
            bulk.set_cutoff(pot.cutoff()+1.)
            bulk.calc_connect()
            pot.calc(bulk, args_str='energy')

    h = at.pos[2,:].max() - at.pos[2,:].min()
    h0 = at.OrigHeight
    strain = (h - h0)/h0
    print 'Applied strain', strain

    x_min = f_min*at.OrigWidth - at.OrigWidth/2.
    x_max = f_max*at.OrigWidth - at.OrigWidth/2.
    strip = np.logical_and(at.move_mask == 1, np.logical_and(at.pos[1,:] > x_min, at.pos[1,:] < x_max))
    at.add_property('strip', strip, overwrite=True)

    strip_depth = at.lattice[3,3]
    strip_width = at.pos[1,strip].max() - at.pos[1,strip].min()
    strip_height = at.pos[2,strip].max() - at.pos[2,strip].min()
    strip_volume = strip_width*strip_height*strip_depth
    print 'Strip contains', strip.sum(), 'atoms', 'width', strip_width, 'height', strip_height, 'volume', strip_volume

    strain_energy_density = (at.local_energy[strip].sum() - bulk.energy/bulk.n*strip.sum())/strip_volume

    print 'Strain energy density in strip', strain_energy_density, 'eV/A**3'

    E_effective = 2*strain_energy_density/strain**2*GPA
    print 'Effective elastic modulus E =', E_effective, 'GPa'

    G_effective = strain_energy_density*strip_height*J_PER_M2
    print 'Effective energy release rate G =', G_effective, 'J/m^2'

    return G_effective
Esempio n. 6
0
 print 'Loading atoms from file %s' % input_file
 atoms = Atoms(input_file)
 atoms = Atoms(atoms)
 if params.continuation:
     # restart from last frame of most recent trajectory file
     traj_files = sorted(glob.glob('[0-9]*.traj.xyz'))
     if len(traj_files) > 0:
         last_traj = traj_files[-1]
         input_file = last_traj + '@-1'
 
 # loading reference configuration for Nye tensor evaluation
 # convert to quippy Atoms - FIXME in long term, this should not be necesary
 x0 = Atoms(params.reference_file)
 x0 = Atoms(x0)
 x0.set_cutoff(3.0)
 x0.calc_connect()
 
 print params.param_file
 # ******* Set up potentials and calculators ********
 system_timer('init_fm_pot')
 pot_file = os.path.join(params.pot_dir, params.param_file)
 mm_pot = Potential(params.mm_init_args,
                    param_filename=params.param_file,
                    cutoff_skin=params.cutoff_skin)
 
 cluster_args = params.cluster_args.copy()
 
 if params.test_mode:
     # dummy QM potential made by swapping Ni and Al species in MM potential               
     qm_pot = Potential(params.mm_init_args,
                        param_filename='m2004flipNiAl.xml',
Esempio n. 7
0
class Potential(_potential.Potential):
    __doc__ = update_doc_string(
        _potential.Potential.__doc__,
        r"""
The :class:`Potential` class also implements the ASE
:class:`ase.calculators.interface.Calculator` interface via the
the :meth:`get_forces`, :meth:`get_stress`, :meth:`get_stresses`,
:meth:`get_potential_energy`, :meth:`get_potential_energies`
methods. This simplifies calculation since there is no need
to set the cutoff or to call :meth:`~quippy.atoms.Atoms.calc_connect`,
as this is done internally. The example above reduces to::

    atoms = diamond(5.44, 14)
    atoms.rattle(0.01)
    atoms.set_calculator(pot)
    forces = atoms.get_forces()
    print forces

Note that the ASE force array is the transpose of the QUIP force
array, so has shape (len(atoms), 3) rather than (3, len(atoms)).

The optional arguments `pot1`, `pot2` and `bulk_scale` are
used by ``Sum`` and ``ForceMixing`` potentials (see also
wrapper class :class:`ForceMixingPotential`)

An :class:`quippy.mpi_context.MPI_context` object can be
passed as the `mpi_obj` argument to restrict the
parallelisation of this potential to a subset of the

The `callback` argument is used to implement the calculation of
the :class:`Potential` in a Python function: see :meth:`set_callback` for
an example.

In addition to the builtin QUIP potentials, it is possible to
use any ASE calculator as a QUIP potential by passing it as
the `calculator` argument to the :class:`Potential` constructor, e.g.::

   from ase.calculators.morse import MorsePotential
   pot = Potential(calculator=MorsePotential)

`cutoff_skin` is used to set the :attr:`cutoff_skin` attribute.

`atoms` if given, is used to set the calculator associated
with `atoms` to the new :class:`Potential` instance, by calling
:meth:'.Atoms.set_calculator`.

.. note::

    QUIP potentials do not compute stress and per-atom stresses
    directly, but rather the virial tensor which has units of stress
    :math:`\times` volume, i.e. energy. If the total stress is
    requested, it is computed by dividing the virial by the atomic
    volume, obtained by calling :meth:`.Atoms.get_volume`. If per-atom
    stresses are requested, a per-atom volume is needed. By default
    this is taken to be the total volume divided by the number of
    atoms. In some cases, e.g. for systems containing large amounts of
    vacuum, this is not reasonable. The ``vol_per_atom`` calc_arg can
    be used either to give a single per-atom volume, or the name of an
    array in :attr:`.Atoms.arrays` containing volumes for each atom.

""",
        signature=
        'Potential(init_args[, pot1, pot2, param_str, param_filename, bulk_scale, mpi_obj, callback, calculator, cutoff_skin, atoms])'
    )

    callback_map = {}

    def __init__(self,
                 init_args=None,
                 pot1=None,
                 pot2=None,
                 param_str=None,
                 param_filename=None,
                 bulk_scale=None,
                 mpi_obj=None,
                 callback=None,
                 calculator=None,
                 cutoff_skin=1.0,
                 atoms=None,
                 fpointer=None,
                 finalise=True,
                 error=None,
                 **kwargs):

        self.atoms = None
        self._prev_atoms = None
        self.energy = None
        self.energies = None
        self.forces = None
        self.stress = None
        self.stresses = None
        self.elastic_constants = None
        self.unrelaxed_elastic_constants = None
        self.numeric_forces = None
        self._calc_args = {}
        self._default_quantities = []
        self.cutoff_skin = cutoff_skin

        if callback is not None or calculator is not None:
            if init_args is None:
                init_args = 'callbackpot'

        if param_filename is not None:
            param_str = open(param_filename).read()

        if init_args is None and param_str is None:
            raise ValueError('Need one of init_args,param_str,param_filename')

        if init_args is not None:
            if init_args.lower().startswith('callbackpot'):
                if not 'label' in init_args:
                    init_args = init_args + ' label=%d' % id(self)
            else:
                # if param_str missing, try to find default set of QUIP params
                if param_str is None and pot1 is None and pot2 is None:
                    param_str = quip_xml_parameters(init_args)

        if kwargs != {}:
            if init_args is not None:
                init_args = init_args + ' ' + dict_to_args_str(kwargs)
            else:
                init_args = dict_to_args_str(kwargs)

        _potential.Potential.__init__(self,
                                      init_args,
                                      pot1=pot1,
                                      pot2=pot2,
                                      param_str=param_str,
                                      bulk_scale=bulk_scale,
                                      mpi_obj=mpi_obj,
                                      fpointer=fpointer,
                                      finalise=finalise,
                                      error=error)

        if init_args is not None and init_args.lower().startswith(
                'callbackpot'):
            _potential.Potential.set_callback(self, Potential.callback)

            if callback is not None:
                self.set_callback(callback)

            if calculator is not None:
                self.set_callback(calculator_callback_factory(calculator))

        if atoms is not None:
            atoms.set_calculator(self)

    __init__.__doc__ = _potential.Potential.__init__.__doc__

    def calc(self,
             at,
             energy=None,
             force=None,
             virial=None,
             local_energy=None,
             local_virial=None,
             args_str=None,
             error=None,
             **kwargs):

        if not isinstance(args_str, basestring):
            args_str = dict_to_args_str(args_str)

        kw_args_str = dict_to_args_str(kwargs)

        args_str = ' '.join((self.get_calc_args_str(), kw_args_str, args_str))

        if isinstance(energy, basestring):
            args_str = args_str + ' energy=%s' % energy
            energy = None
        if isinstance(energy, bool) and energy:
            args_str = args_str + ' energy'
            energy = None

        if isinstance(force, basestring):
            args_str = args_str + ' force=%s' % force
            force = None
        if isinstance(force, bool) and force:
            args_str = args_str + ' force'
            force = None

        if isinstance(virial, basestring):
            args_str = args_str + ' virial=%s' % virial
            virial = None
        if isinstance(virial, bool) and virial:
            args_str = args_str + ' virial'
            virial = None

        if isinstance(local_energy, basestring):
            args_str = args_str + ' local_energy=%s' % local_energy
            local_energy = None
        if isinstance(local_energy, bool) and local_energy:
            args_str = args_str + ' local_energy'
            local_energy = None

        if isinstance(local_virial, basestring):
            args_str = args_str + ' local_virial=%s' % local_virial
            local_virial = None
        if isinstance(local_virial, bool) and local_virial:
            args_str = args_str + ' local_virial'
            local_virial = None

        potlog.debug(
            'Potential invoking calc() on n=%d atoms with args_str "%s"' %
            (len(at), args_str))
        _potential.Potential.calc(self, at, energy, force, virial,
                                  local_energy, local_virial, args_str, error)

    calc.__doc__ = update_doc_string(
        _potential.Potential.calc.__doc__,
        """In Python, this method is overloaded to set the final args_str to
          :meth:`get_calc_args_str`, followed by any keyword arguments,
          followed by an explicit `args_str` argument if present. This ordering
          ensures arguments explicitly passed to :meth:`calc` will override any
          default arguments.""")

    @staticmethod
    def callback(at_ptr):
        from quippy import Atoms
        at = Atoms(fpointer=at_ptr, finalise=False)
        if 'label' not in at.params or at.params[
                'label'] not in Potential.callback_map:
            raise ValueError('Unknown Callback label %s' % at.params['label'])
        Potential.callback_map[at.params['label']](at)

    def set_callback(self, callback):
        """
        For a :class:`Potential` of type `CallbackPot`, this method is
        used to set the callback function. `callback` should be a Python
        function (or other callable, such as a bound method or class
        instance) which takes a single argument, of type
        :class:`~quippy.atoms.Atoms`. Information about which quantities should be
        computed can be obtained from the `calc_energy`, `calc_local_e`,
        `calc_force`, and `calc_virial` keys in `at.params`. Results
        should be returned either as `at.params` entries (for energy and
        virial) or by adding new atomic properties (for forces and local
        energy).

        Here's an example implementation of a simple callback::

          def example_callback(at):
              if at.calc_energy:
                 at.params['energy'] = ...

              if at.calc_force:
                 at.add_property('force', 0.0, n_cols=3)
                 at.force[:,:] = ...

          p = Potential('CallbackPot')
          p.set_callback(example_callback)
          p.calc(at, energy=True)
          print at.energy
          ...
        """
        Potential.callback_map[str(id(self))] = callback

    def wipe(self):
        """
        Mark all quantities as needing to be recalculated
        """
        self.energy = None
        self.energies = None
        self.forces = None
        self.stress = None
        self.stresses = None
        self.numeric_forces = None
        self.elastic_constants = None
        self.unrelaxed_elastic_constants = None

    def update(self, atoms):
        """
        Set the :class:`~quippy.atoms.Atoms` object associated with this :class:`Potential` to `atoms`.

        Called internally by :meth:`get_potential_energy`,
        :meth:`get_forces`, etc.  Only a weak reference to `atoms` is
        kept, to prevent circular references.  If `atoms` is not a
        :class:`quippy.atoms.Atoms` instance, then a copy is made and a
        warning will be printed.
        """
        # we will do the calculation in place, to minimise number of copies,
        # unless atoms is not a quippy Atoms
        if isinstance(atoms, Atoms):
            self.atoms = weakref.proxy(atoms)
        else:
            potlog.debug(
                'Potential atoms is not quippy.Atoms instance, copy forced!')
            self.atoms = Atoms(atoms)

        # check if atoms has changed since last call
        if self._prev_atoms is not None and self._prev_atoms.equivalent(
                self.atoms):
            return

        # Mark all quantities as needing to be recalculated
        self.wipe()

        # do we need to reinitialise _prev_atoms?
        if self._prev_atoms is None or len(self._prev_atoms) != len(
                self.atoms) or not self.atoms.connect.initialised:
            self._prev_atoms = Atoms()
            self._prev_atoms.copy_without_connect(self.atoms)
            self._prev_atoms.add_property('orig_pos', self.atoms.pos)
        else:
            # _prev_atoms is OK, update it in place
            self._prev_atoms.z[...] = self.atoms.z
            self._prev_atoms.pos[...] = self.atoms.pos
            self._prev_atoms.lattice[...] = self.atoms.lattice

        # do a calc_connect(), setting cutoff_skin so full reconnect will only be done when necessary
        self.atoms.set_cutoff(self.cutoff(), cutoff_skin=self.cutoff_skin)
        potlog.debug(
            'Potential doing calc_connect() with cutoff %f cutoff_skin %r' %
            (self.atoms.cutoff, self.cutoff_skin))
        self.atoms.calc_connect()

    # Synonyms for `update` for compatibility with ASE calculator interface
    def initialize(self, atoms):
        self.update(atoms)

    def set_atoms(self, atoms):
        self.update(atoms)

    def calculation_required(self, atoms, quantities):
        self.update(atoms)
        for quantity in quantities:
            if getattr(self, quantity) is None:
                return True
        return False

    def calculate(self, atoms, quantities=None):
        """
        Perform a calculation of `quantities` for `atoms` using this Potential.

        Automatically determines if a new calculation is required or if previous
        results are still appliciable (i.e. if the atoms haven't moved since last call)
        Called internally by :meth:`get_potential_energy`, :meth:`get_forces`, etc.
        """
        if quantities is None:
            quantities = ['energy', 'forces', 'stress']

        # Add any default quantities
        quantities = set(self.get_default_quantities() + quantities)

        if len(quantities) == 0:
            raise RuntimeError('Nothing to calculate')

        if not self.calculation_required(atoms, quantities):
            return

        args_map = {
            'energy': {
                'energy': None
            },
            'energies': {
                'local_energy': None
            },
            'forces': {
                'force': None
            },
            'stress': {
                'virial': None
            },
            'numeric_forces': {
                'force': 'numeric_force',
                'force_using_fd': True,
                'force_fd_delta': 1.0e-5
            },
            'stresses': {
                'local_virial': None
            },
            'elastic_constants': {},
            'unrelaxed_elastic_constants': {}
        }

        # list of quantities that require a call to Potential.calc()
        calc_quantities = [
            'energy', 'energies', 'forces', 'numeric_forces', 'stress',
            'stresses'
        ]

        # list of other quantities we know how to calculate
        other_quantities = ['elastic_constants', 'unrelaxed_elastic_constants']

        calc_args = {}
        calc_required = False
        for quantity in quantities:
            if quantity in calc_quantities:
                calc_required = True
                calc_args.update(args_map[quantity])
            elif quantity not in other_quantities:
                raise RuntimeError(
                    "Don't know how to calculate quantity '%s'" % quantity)

        if calc_required:
            self.calc(self.atoms, args_str=dict_to_args_str(calc_args))

        if 'energy' in quantities:
            self.energy = float(self.atoms.energy)
        if 'energies' in quantities:
            self.energies = self.atoms.local_energy.view(np.ndarray)
        if 'forces' in quantities:
            self.forces = self.atoms.force.view(np.ndarray).T
        if 'numeric_forces' in quantities:
            self.numeric_forces = self.atoms.numeric_force.view(np.ndarray).T
        if 'stress' in quantities:
            stress = -self.atoms.virial.view(
                np.ndarray) / self.atoms.get_volume()
            # convert to 6-element array in Voigt order
            self.stress = np.array([
                stress[0, 0], stress[1, 1], stress[2, 2], stress[1, 2],
                stress[0, 2], stress[0, 1]
            ])
        if 'stresses' in quantities:
            lv = np.array(self.atoms.local_virial)  # make a copy
            vol_per_atom = self.get('vol_per_atom',
                                    self.atoms.get_volume() / len(atoms))
            if isinstance(vol_per_atom, basestring):
                vol_per_atom = self.atoms.arrays[vol_per_atom]
            self.stresses = -lv.T.reshape(
                (len(atoms), 3, 3), order='F') / vol_per_atom

        if 'elastic_constants' in quantities:
            cij_dx = self.get('cij_dx', 1e-2)
            cij = fzeros((6, 6))
            self.calc_elastic_constants(self.atoms,
                                        fd=cij_dx,
                                        args_str=self.get_calc_args_str(),
                                        c=cij,
                                        relax_initial=False,
                                        return_relaxed=False)
            if not get_fortran_indexing():
                cij = cij.view(np.ndarray)
            self.elastic_constants = cij

        if 'unrelaxed_elastic_constants' in quantities:
            cij_dx = self.get('cij_dx', 1e-2)
            c0ij = fzeros((6, 6))
            self.calc_elastic_constants(self.atoms,
                                        fd=cij_dx,
                                        args_str=self.get_calc_args_str(),
                                        c0=c0ij,
                                        relax_initial=False,
                                        return_relaxed=False)
            if not get_fortran_indexing():
                c0ij = c0ij.view(np.ndarray)
            self.unrelaxed_elastic_constants = c0ij

    def get_potential_energy(self, atoms):
        """
        Return potential energy of `atoms` calculated with this Potential
        """
        self.calculate(atoms, ['energy'])
        return self.energy

    def get_potential_energies(self, atoms):
        """
        Return array of atomic energies calculated with this Potential
        """
        self.calculate(atoms, ['energies'])
        return self.energies.copy()

    def get_forces(self, atoms):
        """
        Return forces on `atoms` calculated with this Potential
        """
        self.calculate(atoms, ['forces'])
        return self.forces.copy()

    def get_numeric_forces(self, atoms):
        """
        Return forces on `atoms` computed with finite differences of the energy
        """
        self.calculate(atoms, ['numeric_forces'])
        return self.numeric_forces.copy()

    def get_stress(self, atoms):
        """
        Return stress tensor for `atoms` computed with this Potential

        Result is a 6-element array in Voigt notation:
           [sigma_xx, sigma_yy, sigma_zz, sigma_yz, sigma_xz, sigma_xy]
        """
        self.calculate(atoms, ['stress'])
        return self.stress.copy()

    def get_stresses(self, atoms):
        """
        Return the per-atoms virial stress tensors for `atoms` computed with this Potential
        """
        self.calculate(atoms, ['stresses'])
        return self.stresses.copy()

    def get_elastic_constants(self, atoms):
        """
        Calculate elastic constants of `atoms` using this Potential.

        Returns  6x6 matrix :math:`C_{ij}` of elastic constants.

        The elastic contants are calculated as finite difference
        derivatives of the virial stress tensor using positive and
        negative strains of magnitude the `cij_dx` entry in
        ``calc_args``.
        """
        self.calculate(atoms, ['elastic_constants'])
        return self.elastic_constants.copy()

    def get_unrelaxed_elastic_constants(self, atoms):
        """
        Calculate unrelaxed elastic constants of `atoms` using this Potential

        Returns 6x6 matrix :math:`C^0_{ij}` of unrelaxed elastic constants.

        The elastic contants are calculated as finite difference
        derivatives of the virial stress tensor using positive and
        negative strains of magnitude the `cij_dx` entry in
        :attr:`calc_args`.
        """
        self.calculate(atoms, ['unrelaxed_elastic_constants'])
        return self.unrelaxed_elastic_constants.copy()

    def get_default_quantities(self):
        "Get the list of quantities to be calculated by default"
        return self._default_quantities[:]

    def set_default_quantities(self, quantities):
        "Set the list of quantities to be calculated by default"
        self._default_quantities = quantities[:]

    def get(self, param, default=None):
        """
        Get the value of a ``calc_args`` parameter for this :class:`Potential`

        Returns ``None`` if `param` is not in the current ``calc_args`` dictionary.

        All calc_args are passed to :meth:`calc` whenever energies,
        forces or stresses need to be re-computed.
        """
        return self._calc_args.get(param, default)

    def set(self, **kwargs):
        """
        Set one or more calc_args parameters for this Potential

        All calc_args are passed to :meth:`calc` whenever energies,
        forces or stresses need to be computed.

        After updating the calc_args, :meth:`set` calls :meth:`wipe`
        to mark all quantities as needing to be recaculated.
        """
        self._calc_args.update(kwargs)
        self.wipe()

    def get_calc_args(self):
        """
        Get the current ``calc_args``
        """
        return self._calc_args.copy()

    def set_calc_args(self, calc_args):
        """
        Set the ``calc_args`` to be used subsequent :meth:`calc` calls
        """
        self._calc_args = calc_args.copy()

    def get_calc_args_str(self):
        """
        Get the ``calc_args`` to be passed to :meth:`calc` as a string
        """
        return dict_to_args_str(self._calc_args)

    def get_cutoff_skin(self):
        return self._cutoff_skin

    def set_cutoff_skin(self, cutoff_skin):
        self._cutoff_skin = cutoff_skin
        self._prev_atoms = None  # force a recalculation

    cutoff_skin = property(get_cutoff_skin,
                           set_cutoff_skin,
                           doc="""
                           The `cutoff_skin` attribute is only relevant when the ASE-style
                           interface to the Potential is used, via the :meth:`get_forces`,
                           :meth:`get_potential_energy` etc. methods. In this case the
                           connectivity of the :class:`~quippy.atoms.Atoms` object for which
                           the calculation is requested is automatically kept up to date by
                           using a neighbour cutoff of :meth:`cutoff` + `cutoff_skin`, and
                           recalculating the neighbour lists whenever the maximum displacement
                           since the last :meth:`Atoms.calc_connect` exceeds `cutoff_skin`.
                           """)