keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
3D | Autodesk/molecular-design-toolkit | moldesign/models/openbabel.py | .py | 3,300 | 86 | """ Energy models using OpenBabel's heuristic, highly approximate drug forcefields
"""
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import moldesign as mdt
from .. import units as u
from ..utils import exports
from ..compute import packages
from .base import EnergyModelBase
# uff disabled because it doesn't pass tests
FFNAMES = {n: n.capitalize() for n in ['ghemical', 'mmff94', 'mmff94s', 'uff']}
UNITNAMES = {'kcal/mol': u.kcalpermol, 'kJ/mol': u.kjpermol}
@exports
class OpenBabelPotential(EnergyModelBase):
_PKG = packages.openbabel
DEFAULT_PROPERTIES = ['potential_energy', 'forces']
ALL_PROPERTIES = DEFAULT_PROPERTIES
PARAMETERS = [mdt.parameters.Parameter(name='forcefield',
short_description='Forcefield selection',
type=str,
default='mmff94s',
choices=['ghemical', 'mmff94', 'mmff94s'])]
def prep(self):
import openbabel as ob
if self._prepped: return
self._pbmol = mdt.interfaces.openbabel.mol_to_pybel(self.mol)
self._ff = ob.OBForceField.FindForceField(FFNAMES[self.params.forcefield])
self._ff.Setup(self._pbmol.OBMol)
self._units = UNITNAMES[self._ff.GetUnit()]
self._prepped = True
@packages.openbabel.runsremotely(is_imethod=True)
def calculate(self, requests):
import openbabel as ob
self.prep()
for atom, pbatom in zip(self.mol.atoms, self._pbmol.atoms):
pbatom.OBAtom.SetVector(*atom.position.value_in(u.angstrom))
self._ff.SetCoordinates(self._pbmol.OBMol)
energy = self._ff.Energy(True)
self._ff.GetCoordinates(self._pbmol.OBMol)
# http://forums.openbabel.org/Doing-an-energ-force-calculation-with-openbabel-td1590730.html
data = ob.toConformerData(self._pbmol.OBMol.GetData(ob.ConformerData))
force_iterator = data.GetForces()[0]
forces = np.array([[f.GetX(), f.GetY(), f.GetZ()] for f in force_iterator])
forces[np.abs(forces) < 1e-30] = 0.0 # prevent underflows
result = mdt.MolecularProperties(self.mol,
potential_energy=energy*self._units,
forces=forces*self._units/u.angstrom)
return result
# if necessary, run the entire minimization remotely for speed
@packages.openbabel.runsremotely(is_imethod=True)
def minimize(self, **kwargs):
super().minimize(**kwargs)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/models/toys.py | .py | 2,612 | 77 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import moldesign as mdt
from .. import units as u
from ..utils import exports
from .base import EnergyModelBase
@exports
class Spring(EnergyModelBase):
"""Two atoms attached by a spring"""
DEFAULT_PROPERTIES = ['potential_energy',
'force']
ALL_PROPERTIES = DEFAULT_PROPERTIES
PARAMETERS = [
mdt.parameters.Parameter(
'k', 'Spring constant',
type=u.eV/u.angstrom**2),
mdt.parameters.Parameter(
'd0', 'Equilibrium distance',
type=u.angstrom)]
def prep(self):
assert self.mol.natoms == 2
self._prepped = True
def calculate(self, requests):
dvec = self.mol.atoms[1].position - self.mol.atoms[0].position
dist = np.sqrt(dvec.dot(dvec))
pe = 0.5 * self.params.k * (dist - self.params.d0)**2
f = self.params.k * dvec * (dist - self.params.d0) / dist
forcearray = u.array([f, -f])
return {'potential_energy': pe,
'forces': forcearray}
@exports
class HarmonicOscillator(EnergyModelBase):
""" Applies a harmonic potential (centered at 0) to the x-component of every atom
"""
PARAMETERS = [
mdt.parameters.Parameter(
'k', 'Spring constant',
type=u.eV/u.angstrom**2)]
def prep(self):
if self.params.k.dimensionality != (u.eV/u.angstrom**2).dimensionality:
raise u.DimensionalityError("Spring constant must have dimensions of energy/length^2")
return True
def calculate(self, requests):
self.prep()
energy = 0.5 * self.params.k * np.sum(self.mol.positions[:, 0]**2)
forces = np.zeros((self.mol.num_atoms, 3)) * u.default.force
forces[:, 0] = - self.params.k * self.mol.positions[:, 0]
return dict(potential_energy=energy, forces=forces)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/models/base.py | .py | 6,189 | 168 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import numpy as np
import moldesign as mdt
from .. import units as u
from ..method import Method
class EnergyModelBase(Method):
"""
Base class for all energy models
"""
# TODO:should add some architecture to check implementations, e.g.
# TODO: ensure prep gets called when necessary, make sure all parameters can be consumed
DEFAULT_PROPERTIES = ['potential_energy', 'forces']
"""List[str]: list of the properties that are always calculated by this method"""
ALL_PROPERTIES = DEFAULT_PROPERTIES
"""List[str]: List of all the properties that this model can calculate"""
PARAMETERS = []
_CALLS_MDT_IN_DOCKER = False # gets set to true if a python-interfaced dependency is missing
def calculate(self, requests):
"""Calculate the the default properties and any additiona requests
Arguments:
requests (List[str]): the requested properties to calculate
Returns:
utils.DotDict: A dict of calculated properties (or a job object that will return them)
"""
self.prep()
raise NotImplementedError('EnergyModelBase is an abstract base class')
def minimize(self, method='bfgs', **kwargs):
"""
If the energy model provides its own minimizer, it should be hooked up here
"""
raise NotImplementedError()
def get_formal_charge(self):
"""Determine the formal charge of the molecular system.
This can be set either as a molecular attribute OR in the parameters of the energy model.
Returns:
u.Scalar[charge]: the formal charge used for this model
"""
if 'charge' in self.params and self.params.charge is not None:
return self.params.charge.value_in(u.q_e)
elif hasattr(self.mol, 'charge'):
return self.mol.charge.value_in(u.q_e)
else:
return 0
def finite_difference_force(self, direction=0, stepsize=0.025 * u.angstrom):
"""
Compute force using a finite difference with the given step size.
Args:
direction (int): EITHER +1, -1, (for one-sided finite differences) or
0 (for central difference - better but twice as expensive)
step (u.Scalar[lenght]): step size to take in each direction
Returns:
u.Vector[force]: force vector, len= `self.mol.ndims`
"""
# TODO: this should totally be parallelized - how do we request/configure/control this?
forces = np.zeros(self.mol.ndims) * u.default.force
properties = []
if direction in (-1, 1):
e0 = self.mol.calc_potential_energy()
else:
assert direction == 0, 'Finite difference direction must be -1, 0, or 1'
for iatom, idim in itertools.product(range(self.mol.num_atoms), range(3)):
print('\rFinite differencing %s for atom %d/%d'%('xyz'[iatom],
iatom+1,
self.mol.num_atoms), end=' ')
if direction == 0:
self.mol.positions[iatom, idim] += stepsize / 2.0
eplus = self.mol.calc_potential_energy()
pplus = self.mol.properties
self.mol.positions[iatom, idim] -= stepsize
eminus = self.mol.calc_potential_energy()
pminus = self.mol.properties
self.mol.positions[iatom, idim] += stepsize / 2.0 # resets the position
properties.append((pminus, pplus))
forces[iatom, idim] = (eminus - eplus) / stepsize
elif direction in (-1, 1):
self.mol.positions[iatom, idim] += direction * stepsize
enew = self.mol.calc_potential_energy()
properties.append(self.mol.properties)
forces[iatom, idim] = (e0 - enew) / (direction * stepsize)
self.mol.positions[iatom, idim] -= direction * stepsize
return forces, properties
def prep(self):
"""
Prepare to run. Possibly do a test to ensure that the model is ready.
"""
raise NotImplementedError('EnergyModelBase is an abstract base class')
class MMBase(EnergyModelBase):
"""Common interface for molecular mechanics"""
PARAMETERS = (EnergyModelBase.PARAMETERS +
list(mdt.parameters.mm_model_parameters.values()))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.mdtforcefield = None
class QMBase(EnergyModelBase):
"""Common interface for quantum mechanics"""
PARAMETERS = list(mdt.parameters.qm_model_parameters.values())
DEFAULT_PROPERTIES = ['potential_energy',
'nuclear_repulsion',
'dipole_moment',
'orbitals',
'orbital_energies']
ALL_PROPERTIES = DEFAULT_PROPERTIES
# properties will be a pretty long list for most packages
def set_wfn_guess(self):
raise NotImplementedError
class QMMMBase(EnergyModelBase):
# DEFAULT_PROPERTIES = ['potential_energy',
# 'forces',
# 'qm_props',
# 'mm_props']
# ALL_PROPERTIES = DEFAULT_PROPERTIES
PARAMETERS = MMBase.PARAMETERS + QMBase.PARAMETERS
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/models/pyscf.py | .py | 22,179 | 542 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import future.utils
from functools import reduce
from past.utils import old_div
import numpy as np
import moldesign as mdt
from .. import units as u
from .. import compute, orbitals, utils
from ..compute import packages
from ..interfaces.pyscf_interface import mol_to_pyscf, StatusLogger, SPHERICAL_NAMES
from .base import QMBase
from ..molecules import AtomicProperties
if future.utils.PY2:
from cStringIO import StringIO
else:
from io import StringIO
class LazyClassMap(object):
""" For lazily importing classes from modules (when there's a lot of import overhead)
Class names should be stored as their *absolute import strings* so that they can be imported
only when needed
Example:
>>> myclasses = LazyClassMap({'od': 'collections.OrderedDict'})
>>> myclasss['od']()
OrderedDict()
"""
def __init__(self, mapping):
self.mapping = mapping
def __getitem__(self, key):
import importlib
fields = self.mapping[key].split('.')
cls = fields[-1]
modname = '.'.join(fields[:-1])
mod = importlib.import_module(modname)
return getattr(mod, cls)
def __contains__(self, item):
return item in self.mapping
def __iter__(self):
return iter(self.mapping)
# PySCF metadata constants
THEORIES = LazyClassMap({'hf': 'pyscf.scf.RHF', 'rhf': 'pyscf.scf.RHF',
'uhf': 'pyscf.scf.UHF',
'mcscf': 'pyscf.mcscf.CASSCF', 'casscf': 'pyscf.mcscf.CASSCF',
'casci': 'pyscf.mcscf.CASCI',
'mp2': 'pyscf.mp.MP2',
'dft': 'pyscf.dft.RKS', 'rks': 'pyscf.dft.RKS', 'ks': 'pyscf.dft.RKS'})
NEEDS_REFERENCE = set('mcscf casscf casci mp2'.split())
NEEDS_FUNCTIONAL = set('dft rks ks uks'.split())
IS_SCF = set('rhf uhf hf dft rks ks'.split())
FORCE_CALCULATORS = LazyClassMap({'rhf': 'pyscf.grad.RHF', 'hf': 'pyscf.grad.RHF',
'rks': 'pyscf.grad.RKS', 'ks': 'pyscf.grad.RKS'})
@utils.exports
class PySCFPotential(QMBase):
DEFAULT_PROPERTIES = ['potential_energy',
'wfn',
'mulliken']
ALL_PROPERTIES = DEFAULT_PROPERTIES + ['forces',
'nuclear_forces',
'electronic_forces']
PARAM_SUPPORT = {'theory': ['rhf', 'rks', 'mp2'],
'functional': ['b3lyp', 'blyp', 'pbe0', 'x3lyp', 'MPW3LYP5']}
FORCE_UNITS = u.hartree / u.bohr
_PKG = packages.pyscf
@mdt.utils.kwargs_from(QMBase)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.pyscfmol = None
self.reference = None
self.kernel = None
self.logs = StringIO()
self.logger = self._get_logger('PySCF interface')
@packages.pyscf.runsremotely(is_imethod=True, persist_refs=True)
def calculate(self, requests=None):
self.logger = self._get_logger('PySCF calc')
do_forces = 'forces' in requests
if do_forces and self.params.theory not in FORCE_CALCULATORS:
raise ValueError('Forces are only available for the following theories:'
','.join(FORCE_CALCULATORS))
if do_forces:
force_calculator = FORCE_CALCULATORS[self.params.theory]
self.prep(force=True) # rebuild every time
# Set up initial guess
if self.params.wfn_guess == 'stored':
dm0 = self.params.initial_guess.density_matrix_ao
else:
dm0 = None
# Compute reference WFN (if needed)
refobj = self.pyscfmol
if self.params.theory in NEEDS_REFERENCE:
reference = self._build_theory(self.params.get('reference', 'rhf'),
refobj)
kernel, failures = self._converge(reference, dm0=dm0)
refobj = self.reference = kernel
else:
self.reference = None
# Compute WFN
theory = self._build_theory(self.params['theory'],
refobj)
if self.params['theory'] not in IS_SCF:
theory.kernel()
self.kernel = theory
else:
self.kernel, failures = self._converge(theory, dm0=dm0)
# Compute forces (if requested)
if do_forces:
grad = force_calculator(self.kernel)
else:
grad = None
props = self._get_properties(self.reference, self.kernel, grad)
if self.params.store_orb_guesses:
self.params.wfn_guess = 'stored'
self.params.initial_guess = props['wfn']
return props
def _get_properties(self, ref, kernel, grad):
""" Analyze calculation results and return molecular properties
Args:
ref (pyscf.Kernel): Reference kernel (can be None)
kernel (pyscf.Kernel): Theory kernel
grad (pyscf.Gradient): Gradient calculation
Returns:
dict: Molecular property names and values
"""
result = {}
if self.reference is not None:
result['reference_energy'] = (ref.e_tot*u.hartree).defunits()
# TODO: check sign on correlation energy. Is this true for anything besides MP2?
if hasattr(kernel, 'e_corr'):
result['correlation_energy'] = (kernel.e_corr *u.hartree).defunits()
result['potential_energy'] = result['correlation_energy'] +\
result['reference_energy']
else:
result['potential_energy'] = (kernel.e_tot*u.hartree).defunits()
orb_calc = ref
else:
result['potential_energy'] = (kernel.e_tot*u.hartree).defunits()
orb_calc = kernel
if grad is not None:
f_e = -1.0 * grad.grad_elec() * self.FORCE_UNITS
f_n = -1.0 * grad.grad_nuc() * self.FORCE_UNITS
result['electronic_forces'] = f_e.defunits()
result['nuclear_forces'] = f_n.defunits()
result['forces'] = result['electronic_forces'] + result['nuclear_forces']
if self.params.theory in ('casscf', 'mcscf'):
from pyscf.mcscf import CASCI
casobj = CASCI(ref,
self.params.active_orbitals,
self.params.active_electrons)
elif self.params.theory == 'casci':
casobj = kernel
if self.params.theory in ('casscf', 'mcscf', 'casci'):
orb_calc = kernel # get the orbs directly from the post-HF theory
casobj.fcisolver.nroots = self.params.get('num_states',
self.params.state_average)
casresult = casobj.kernel()
result['state_energies'] = (casresult[0] * u.hartree).defunits()
result['ci_vectors'] = list(map(self._parse_fci_vector, casresult[2]))
# potential_energy is the energy of the molecule's assigned state
result['state_averaged_energy'] = result['potential_energy']
result['potential_energy'] = result['state_energies'][self.mol.electronic_state_index]
# TODO: add 'reference wavefunction' to result
ao_obj = ref
dips, tdips = _get_multiconf_dipoles(self.pyscfmol, casobj, len(casobj.ci))
result['state_dipole_moments'] = dips
result['transition_dipole_moments'] = tdips
result['dipole_moment'] = dips[0]
# TODO: this is general, put it somewhere else
oscs = {}
nstates = len(result['state_energies'])
for i in range(nstates):
for j in range(i+1, nstates):
excitation_energy = result['state_energies'][j]-result['state_energies'][i]
tdip = result['transition_dipole_moments'][i, j].norm()
oscs[i, j] = (2.0*tdip ** 2*u.m_e*excitation_energy/
(3.0*u.q_e ** 2*u.hbar ** 2)).to(u.ureg.dimensionless).magnitude
oscs[j, i] = -oscs[i, j]
result['oscillator_strengths'] = oscs
else:
ao_obj = orb_calc
ao_matrices = self._get_ao_matrices(ao_obj)
scf_matrices = self._get_scf_matrices(orb_calc, ao_matrices)
if hasattr(orb_calc, 'mulliken_pop'):
ao_pop, atom_pop = orb_calc.mulliken_pop(verbose=-1)
result['mulliken'] = AtomicProperties({a: p * u.q_e
for a, p in zip(self.mol.atoms, atom_pop)})
if hasattr(orb_calc, 'dip_moment'):
result['dipole_moment'] = orb_calc.dip_moment() * u.debye
# Build the electronic state object
basis = orbitals.basis.BasisSet(self.mol,
orbitals=self._get_ao_basis_functions(),
h1e=ao_matrices.h1e.defunits(),
overlaps=scf_matrices.pop('sao'),
name=self.params.basis)
el_state = orbitals.wfn.ElectronicWfn(self.mol,
self.pyscfmol.nelectron,
aobasis=basis,
fock_ao=scf_matrices['fock_ao'],
density_matrix_ao=scf_matrices['density_matrix_ao'],
description=self.theoryname)
# Build and store the canonical orbitals
cmos = []
for iorb, (coeffs, energy) in enumerate(zip(orb_calc.mo_coeff.T,
orb_calc.mo_energy * u.hartree)):
cmos.append(orbitals.Orbital(coeffs, wfn=el_state))
if hasattr(orb_calc, 'get_occ'):
for orb, occ in zip(cmos, orb_calc.get_occ()):
orb.occupation = occ
el_state.add_orbitals(cmos, orbtype='canonical')
# Return the result
result['wfn'] = el_state
return result
def prep(self, force=False):
# TODO: spin, isotopic mass, symmetry
for p in 'basis theory'.split():
if self.params.get(p, None) is None:
raise ValueError('Parameter "%s" is required' % p)
if self._prepped and not force: return
self.pyscfmol = self._build_mol()
self._prepped = True
def _build_mol(self):
"""TODO: where does charge go? Model or molecule?"""
pyscfmol = mol_to_pyscf(self.mol, self.params.basis,
symmetry=self.params.get('symmetry', None),
charge=self.get_formal_charge())
pyscfmol.stdout = self.logs
return pyscfmol
def _converge(self, method, dm0=None):
"""
Automatically try a bunch of fallback methods for convergence
see also https://www.molpro.net/info/2015.1/doc/manual/node176.html#sec:difficulthf
"""
# TODO: make this user configurable
# TODO: generalize outside of pyscf
energy = method.kernel(dm0=dm0)
failed = []
# stop here if it converged
if method.converged:
return method, failed
# fallback 1: don't use previous density matrix OR change initial_guess
failed.append(method)
if dm0 is not None:
method.init_guess = 'atom'
else:
method.init_guess = 'minao'
self.logger.handled('SCF failed to converge. Retrying with initial guess %s' % method.init_guess)
energy = method.kernel()
if method.converged:
return method, failed
# fallback 2: level shift, slower convergence
# this probably won't converge, but is intended to get us in the right basin for the next step
# TODO: should dynamically adjust level shift instead of hardcoded cycles
self.logger.handled('SCF failed to converge. Performing %d iterations with level shift of -0.5 hartree'
% (old_div(method.max_cycle, 2)))
failed.append(method)
method.init_guess = 'minao'
method.level_shift = -0.5
method.max_cycle /= 2
energy = method.kernel()
if method.converged:
return method, failed
# fallback 2 cont.: remove level shift and try to converge
self.logger.handled('Removing level shift and continuing')
level_shift_dm = method.make_rdm1()
method.level_shift = 0.0
method.max_cycle *= 2
energy = method.kernel(dm0=level_shift_dm)
if method.converged:
return method, failed
raise mdt.QMConvergenceError(method)
def _build_theory(self, name, refobj):
if name in ('mcscf', 'casci', 'casscf'):
theory = THEORIES[name](refobj,
self.params.active_orbitals,
self.params.active_electrons)
if name != 'casci' and self.params.state_average > 1:
theory = theory.state_average_([old_div(1.0,self.params.state_average)
for i in range(self.params.state_average)])
else:
theory = THEORIES[name](refobj)
theory.callback = StatusLogger('%s procedure:' % self.theoryname,
['cycle', 'e_tot'],
self.logger)
if 'scf_cycles' in self.params:
theory.max_cycle = self.params.scf_cycles
if 'functional' in self.params:
self._assign_functional(theory, name,
self.params.get('functional', None))
return theory
_OCCMAP = {('0', '0'): '0',
('1', '0'): 'a',
('0', '1'): 'b',
('1', '1'): '2'}
@property
def theoryname(self):
p = self.params
if p.theory == 'rks':
th = 'RKS(%s)' % p.functional.upper()
elif p.theory in ('casscf', 'casci'):
th = '%s(%d,%d)' % (p.theory.upper(), p.active_orbitals, p.active_electrons)
if p.theory == 'casscf' and p.state_average > 1:
th += ' SA-%d' % p.state_average
else:
th = p.theory.upper()
return '%s/%s' % (th, p.basis)
def _parse_fci_vector(self, ci_vecmat):
""" Translate the PySCF FCI matrix into a dictionary of configurations and weights
Args:
ci_vecmat (np.ndarray): ci vector from a PySCF FCI calculation
Returns:
Mapping[str, float]: dictionary of configuration weights (normalized) organized by
configuration label. Configurations labeled by their active space orbital
occupations: 0 (unoccupied), a (alpha electron only), b (beta electron only), or '2'
(doubly occupied)
Example:
>>> import numpy as np
>>> model = PySCFPotential(active_orbitals=2, active_electrons=2)
>>> model._parse_fci_vector(np.array([[1.0, 2.0],[3.0, 4.0]]))
{'20': 1.0,
'ba': 2.0,
'ab': 3.0,
'02': 4.0}
"""
from pyscf.fci import cistring
conf_bin = cistring.gen_strings4orblist(list(range(self.params.active_orbitals)),
old_div(self.params.active_electrons,2))
civecs = {}
for i, ca in enumerate(conf_bin):
for j, cb in enumerate(conf_bin):
astring = bin(ca)[2:].zfill(self.params.active_orbitals)
bstring = bin(cb)[2:].zfill(self.params.active_orbitals)
s = ''.join(reversed([self._OCCMAP[a, b] for a, b in zip(astring, bstring)]))
civecs[s] = ci_vecmat[i, j]
return civecs
@staticmethod
def _assign_functional(kernel, theory, fname):
if theory in NEEDS_FUNCTIONAL:
if fname is not None:
kernel.xc = fname
else:
raise ValueError('No functional specified for reference theory "%s"' % theory)
def _get_ao_basis_functions(self):
""" Convert pyscf basis functions into a list of atomic basis functions
Notes:
PySCF stores *shells* instead of a flat list, so we need to do a little hacky
guesswork to do this conversion. We include consistentcy checks with the annotated
list of basis functions stored from ``mole.cart_labels()``
As of PySCF v1.0, only cartesian orbitals appear to be supported, and that's all
supported here right now
Returns:
List[moldesign.Gaussians.AtomicBasisFunction]
"""
bfs = []
pmol = self.pyscfmol
orblabels = iter(pmol.spheric_labels())
for ishell in range(pmol.nbas): # loop over shells (n,l)
atom = self.mol.atoms[pmol.bas_atom(ishell)]
angular = pmol.bas_angular(ishell)
num_momentum_states = angular*2 + 1
exps = pmol.bas_exp(ishell) / (u.bohr**2)
num_contractions = pmol.bas_nctr(ishell)
coeffs = pmol.bas_ctr_coeff(ishell)
for ictr in range(num_contractions): # loop over contractions in shell
for ibas in range(num_momentum_states): # loop over angular states in shell
label = next(orblabels)
sphere_label = label[3]
l, m = SPHERICAL_NAMES[sphere_label]
assert l == angular
# Note: this is for metadata only, should not be used in any calculations
n = int(''.join(x for x in label[2] if x.isdigit()))
primitives = [orbitals.SphericalGaussian(atom.position.copy(),
exp, l, m,
coeff=coeff[ictr],
normalized=True)
for exp, coeff in zip(exps, coeffs)]
bfs.append(orbitals.AtomicBasisFunction(atom,
n=n, l=angular, m=m,
primitives=primitives))
return bfs
def _get_basis_name(self):
"""
Translate basis_orbitals set name into a spec that pyscf recognizes
:return:
"""
# TODO: actually implement this
return self.params.basis
@staticmethod
def _get_ao_matrices(mf):
h1e = mf.get_hcore() * u.hartree
sao = mf.get_ovlp()
return utils.DotDict(h1e=h1e, sao=sao)
def _get_scf_matrices(self, mf, ao_mats):
dm = mf.make_rdm1()
veff = mf.get_veff(dm=dm) * u.hartree
fock = ao_mats.h1e + veff
scf_matrices = dict(density_matrix_ao=dm,
h2e=veff,
fock_ao=fock)
scf_matrices.update(ao_mats)
return scf_matrices
def _get_logger(self, logname):
# the "Logger" import can cause pickling problems, so we do it here
from ..helpers import Logger
return Logger(logname)
def _get_multiconf_dipoles(basis, mcstate, nstates):
""" Compute dipoles and transition dipoles. Adapted from PySCF examples
Note:
Dipole moments are computed using the center of the nuclear charge as the origin. Dipole
moments will need to be annotated or translated appropriately for charges systems.
Args:
basis ():
mcstate ():
nstates ():
Returns:
List[u.Vector[dipole]]: Dipole moments for each state
Mapping[Tuple[int, int], u.Vector[dipole]]: mapping from pairs of state ids to transition
dipole moments
References:
https://github.com/sunqm/pyscf/blob/e4d824853c49b7c19eb35cd6f9fe6ea675de932d/examples/1-advanced/030-transition_dipole.py
"""
nuc_charges = [basis.atom_charge(i) for i in range(basis.natm)]
nuc_coords = [basis.atom_coord(i) for i in range(basis.natm)]
nuc_charge_center = np.einsum('z,zx->x', nuc_charges, nuc_coords)/sum(nuc_charges)
basis.set_common_orig_(nuc_charge_center)
nuc_dip = np.einsum('i,ix->x', nuc_charges, nuc_coords-nuc_charge_center) * u.a0 * u.q_e
dip_ints = basis.intor('cint1e_r_sph', comp=3)
orbcas = mcstate.mo_coeff[:, mcstate.ncore:mcstate.ncore+mcstate.ncas]
dipoles, transitions = [], {}
for istate in range(nstates):
for fstate in range(istate, nstates):
t_dm1 = mcstate.fcisolver.trans_rdm1(mcstate.ci[istate], mcstate.ci[fstate],
mcstate.ncas, mcstate.nelecas)
t_dm1_ao = reduce(np.dot, (orbcas, t_dm1, orbcas.T))
moment = np.einsum('xij,ji->x', dip_ints, t_dm1_ao) * u.a0 * u.q_e
if istate == fstate:
dipoles.append(moment)
else:
transitions[istate, fstate] = transitions[fstate, istate] = moment
for idip, d in enumerate(dipoles):
dipoles[idip] = nuc_dip - d
return dipoles, transitions
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/models/openmm.py | .py | 16,925 | 400 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import tempfile
from future.utils import native_str
import moldesign.molecules
from ..compute import packages
from ..molecules import Trajectory, MolecularProperties
from ..utils import exports
from ..interfaces import openmm as opm
from .base import MMBase
from .. import parameters
openmm_platform_selector = parameters.Parameter(
'compute_platform', 'OpenMM computing platform',
type=str, default='auto', choices=['opencl', 'cuda', 'cpu', 'reference', 'auto'],
help_url='http://docs.openmm.org/7.1.0/userguide/library.html#platforms')
numcpus = parameters.num_cpus.copy()
numcpus.relevance = parameters.WhenParam('compute_platform', parameters.op.eq, 'cpu')
numcpus.help = ('Sets number of threads for OpenMM CPU platform. '
'If 0, uses OpenMM defaults (which can be controlled '
'via the OPENMM_NUM_THREADS environment variable). ')
numcpus.help_url = \
'http://docs.openmm.org/7.1.0/userguide/library.html#platform-specific-properties'
@exports
class OpenMMPotential(MMBase, opm.OpenMMPickleMixin):
"""Creates an OpenMM "context" to drive energy calculations.
Note that, while a dummy integrator is assigned, a different context will
be created for any MD calculations.
Attributes:
sim (simtk.openmm.app.Simulation): OpenMM simulation object (once created)
"""
# NEWFEATURE: need to set/get platform (and properties, e.g. number of threads)
_PKG = packages.openmm
DEFAULT_PROPERTIES = ['potential_energy', 'forces']
PARAMETERS = MMBase.PARAMETERS + [openmm_platform_selector, numcpus]
_CALLS_MDT_IN_DOCKER = packages.openmm.force_remote
_openmm_compatible = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._reset()
def _reset(self):
self.sim = None
self.mm_system = None
self.mm_integrator = None
self._prepped_integrator = 'uninitialized'
self._constraints_set = False
self._required_tolerance = None
def get_openmm_simulation(self):
if packages.openmm.force_remote:
raise ImportError("Can't create an OpenMM object on this machine - OpenMM not "
"installed")
else:
if not self._prepped: self.prep()
return self.sim
@packages.openmm.runsremotely(is_imethod=True)
def calculate(self, requests=None):
"""
Drive a calculation and, when finished, update the parent molecule with the results.
TODO: this update is SYNCHRONOUS, unlike other `calculate` methods that run remotely.
TODO: Probably need to update DummyJob (call it localjob, syncjob?) to handle this
:param requests: list of quantities to calculate
:return: PythonJob-like object
"""
if requests is None:
requests = self.DEFAULT_PROPERTIES
self.prep()
self._set_openmm_state()
state = self.sim.context.getState(getForces=True, getEnergy=True)
props = MolecularProperties(self.mol,
potential_energy=opm.simtk2pint(state.getPotentialEnergy()),
forces=opm.simtk2pint(state.getForces(), flat=False))
return props
def prep(self):
""" Construct the OpenMM simulation objects
Note:
An OpenMM simulation object consists of both the system AND the integrator. This routine
therefore constructs both. If self.mol does not use an OpenMM integrator, we create
an OpenMM simulation with a "Dummy" integrator that doesn't ever get used.
"""
if packages.openmm.force_remote:
return True
from simtk.openmm import app
if getattr(self.mol.integrator, '_openmm_compatible', False):
_prepped = (self._prepped and self.mol.integrator._prepped and
self.mol.integrator is self._prepped_integrator)
setup_integrator = True
else:
_prepped = self._prepped
setup_integrator = False
if _prepped:
return
self._reset()
system_params = self._get_system_params()
self.mm_system = self.mol.ff.parmed_obj.createSystem(**system_params)
if (self.params.nonbonded != 'nocutoff'
and not self.params.periodic
and self.params.implicit_solvent):
# TODO: remove this workaround once fix for pandegroup/openmm#1848 is released
tmpfile = os.path.join(tempfile.mkdtemp(), 'prmtop')
self.mol.ff.parmed_obj.write_parm(tmpfile)
om_prmtop = app.AmberPrmtopFile(tmpfile)
self.mm_system = om_prmtop.createSystem(**system_params)
if setup_integrator:
try:
self._set_constraints()
except moldesign.NotSupportedError as exc:
print("Warning: dynamics not supported: %s" % exc.args[0])
self.mm_integrator = self.mol.integrator.get_openmm_integrator()
else:
self.mm_integrator = self._make_dummy_integrator()
platform, platform_properties = self._get_platform()
if self._required_tolerance:
self.mm_integrator.setConstraintTolerance(float(self._required_tolerance))
self.sim = app.Simulation(self.mol.ff.parmed_obj.topology,
self.mm_system,
self.mm_integrator,
platform=platform,
platformProperties=platform_properties)
if setup_integrator:
self.mol.integrator.energy_model = self
self.mol.integrator.sim = self.sim
self.mol.integrator._prepped = True
self._prepped = True
self._prepped_integrator = self.mol.integrator
print('Created OpenMM kernel (Platform: %s)' % self.sim.context.getPlatform().getName())
def minimize(self, **kwargs):
if self.constraints_supported():
traj = self._minimize(**kwargs)
if packages.openmm.force_remote or (not kwargs.get('wait', False)):
self._sync_remote(traj.mol)
traj.mol = self.mol
return traj
else:
return super().minimize(**kwargs)
def _sync_remote(self, mol):
# TODO: this is a hack to update the molecule object after a minimization
# We need a better pattern for this, ideally one that doesn't
# require an explicit wrapper like this - we shouldn't have to copy
# the properties over manually
self.mol.positions = mol.positions
self.mol.momenta = mol.momenta
self.mol.properties = mol.properties
self.mol.time = mol.time
@packages.openmm.runsremotely(is_imethod=True)
def _minimize(self, nsteps=500,
force_tolerance=None,
frame_interval=None):
""" Run an OpenMM minimization.
Note:
We're not able to support `frame_interval` for this method;
see https://github.com/pandegroup/openmm/issues/1155
Args:
nsteps(int): maximum number of steps
force_tolerance (moldesign.units.MdtQuantity): RMSD tolerance for convergence
[energy/length]
"""
# NEWFEATURE: write/find an openmm "integrator" to do this minimization.
# openmm doesn't work with small step numbers, and doesn't support
# callbacks during minimization, so frame_interval is disabled.
if frame_interval is not None:
raise ValueError('frame_interval not supported by OpenMM minimizer.'
' Use a method from moldesign.minimizers instead')
self.prep()
trajectory = Trajectory(self.mol)
self._set_openmm_state()
trajectory.new_frame(annotation='initial structure, energy=%s' %
self.mol.calc_potential_energy().defunits())
self.sim.minimizeEnergy(maxIterations=nsteps, tolerance=0.01) # tolerance is in kj/mole ...
self._sync_to_openmm()
new_energy = self.mol.calc_potential_energy()
trajectory.new_frame(annotation='minimization result, energy=%s' % new_energy.defunits())
return trajectory
def constraints_supported(self):
""" Check whether this molecule's constraints can be enforced in OpenMM
This sort of overlaps with _set_constraints, but doesn't have dependencies on OpenMM
"""
for constraint in self.mol.constraints:
if constraint.desc not in ('position', 'distance', 'hbonds'):
return False
else:
return True
def _set_constraints(self):
if self._constraints_set:
return
system = self.mm_system
fixed_atoms = set()
# openmm uses a global tolerance, calculated as ``constraint_violation/constraint_dist``
# (since only distance constraints are supported). Here we calculate the necessary value
required_tolerance = None
# Constrain atom positions
for constraint in self.mol.constraints:
if constraint.desc == 'position':
fixed_atoms.add(constraint.atom)
system.setParticleMass(constraint.atom.index, 0.0)
# Constrain distances between atom pairs
elif constraint.desc == 'distance':
system.addConstraint(constraint.a1.index,
constraint.a2.index,
opm.pint2simtk(constraint.value))
if required_tolerance is None:
required_tolerance = 1e-5
required_tolerance = min(required_tolerance, constraint.tolerance/constraint.value)
elif constraint.desc == 'hbonds':
continue # already dealt with at system creation time
else:
raise moldesign.NotSupportedError("OpenMM does not support '%s' constraints" %
constraint.desc)
# Workaround for OpenMM issue: can't have an atom that's both
# fixed *and* has a distance constraint. If both atoms in the distance constraint are
# also fixed, then we can just remove the constraint
if len(fixed_atoms) > 0:
num_constraints = system.getNumConstraints()
ic = 0
while ic < num_constraints:
i, j, dist = system.getConstraintParameters(ic)
ai = self.mol.atoms[i]
aj = self.mol.atoms[j]
if (ai in fixed_atoms) and (aj in fixed_atoms):
system.removeConstraint(ic)
num_constraints -= 1
elif (ai in fixed_atoms) or (aj in fixed_atoms): # only one is fixed
raise ValueError('In OpenMM, fixed atoms cannot be part of a constrained '
'bond (%s)' % moldesign.molecules.bonds.Bond(ai, aj))
else:
ic += 1
self._constraints_set = True
self._required_tolerance = required_tolerance
@staticmethod
def _make_dummy_integrator():
from simtk import unit as stku
from simtk import openmm
return openmm.VerletIntegrator(2.0 * stku.femtoseconds)
def _set_openmm_state(self): # TODO: periodic state
self.sim.context.setPositions(opm.pint2simtk(self.mol.positions))
self.sim.context.setVelocities(opm.pint2simtk(self.mol.velocities))
self.sim.context.setTime(opm.pint2simtk(self.mol.time))
def _sync_to_openmm(self, positions=True, momenta=True, time=True):
"""
Syncs the moldesign molecule's positions, momenta, and time to the simulation's
"""
state = None
get_positions = (positions is True)
get_velocities = (momenta is True)
if get_positions or get_velocities:
state = self.sim.context.getState(getPositions=get_positions,
getVelocities=get_velocities)
if get_positions:
positions = state.getPositions()
if get_velocities:
velocities = state.getVelocities()
for iatom, atom in enumerate(self.mol.atoms):
if positions != False: #this is weird because of numpy comparisons
atom.position = opm.simtk2pint(positions[iatom])
if velocities != False:
atom.momentum = opm.simtk2pint(velocities[iatom]) * atom.mass
if time is True:
if state is None:
state = self.sim.context.getState()
time = opm.simtk2pint(state.getTime())
elif time:
time = opm.simtk2pint(time)
if time:
self.mol.time = time
def _get_system_params(self):
""" Translates the spec from MMBase into system parameter keywords for createSystem
"""
# TODO: CMM motion
from simtk.openmm import app
# translates MDT keywords into OpenMM keywords
nonbonded_names = {'nocutoff': app.NoCutoff,
'ewald': app.Ewald,
'pme': app.PME,
'cutoff': (app.CutoffPeriodic
if self.params.periodic
else app.CutoffNonPeriodic)}
implicit_solvent_names = {'obc': app.OBC2,
'obc1': app.OBC1,
'obc2': app.OBC2,
None: None}
system_params = dict(nonbondedMethod=nonbonded_names[self.params.nonbonded],
implicitSolvent=implicit_solvent_names[self.params.implicit_solvent])
if self.params.nonbonded != 'nocutoff':
system_params['nonbondedCutoff'] = opm.pint2simtk(self.params.cutoff)
system_params['rigidWater'] = False # not currently supported (because I'm lazy)
system_params['constraints'] = None
if self.mol.integrator is not None:
if self.mol.integrator.params.get('constrain_water', False):
system_params['rigidWater'] = True
if self.mol.integrator.params.get('constrain_hbonds', False):
system_params['constraints'] = app.HBonds
# Deal with h-bonds listed in molecular constraints
for constraint in self.mol.constraints:
if constraint.desc == 'hbonds':
system_params['constraints'] = app.HBonds
break
return system_params
def _get_platform(self):
from simtk import openmm
preference = ['CUDA', 'OpenCL', 'CPU', 'Reference']
from_lower = {x.lower(): x for x in preference}
properties = {}
if self.params.compute_platform.lower() == 'auto':
for platname in preference:
try:
platform = openmm.Platform.getPlatformByName(platname)
except Exception: # it just throws "Exception" unfortunately
continue
else:
use_platform = platname
break
else:
raise moldesign.NotSupportedError("Likely OpenMM installation error. "
"none of the expected platforms were found: "
+ ', '.join(preference))
else:
use_platform = self.params.compute_platform
self.params.compute_platform = use_platform.lower()
platform = openmm.Platform.getPlatformByName(from_lower[self.params.compute_platform])
if self.params.compute_platform == 'cpu' and self.params.num_cpus > 0:
# need to use native_strs here or the swig interface gets confused
properties[native_str('Threads')] = native_str(self.params.num_cpus)
return platform, properties
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/spherical.py | .py | 5,899 | 161 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from ..mathutils import spherical_harmonics
from .. import units as u
from .. import utils
from . import Primitive, Gaussian, CartesianGaussian, PrimitiveSum
class SphericalGaussian(Primitive):
r""" Stores a 3-dimensional real spherical gaussian function:
.. math::
G_{nlm}(\mathbf r) = C Y^l_m(\mathbf r - \mathbf r_0) r^l e^{-\alpha \left| \mathbf r - \mathbf r_0 \right|^2}
where:
- *C* is ``self.coeff``,
- :math:`\alpha` is ``self.alpha``,
- :math:`\mathbf r_0` is ``self.center``,
- _(l,m)_ are given by ``(self.l, self.m)``, and
- :math:`Y^l_m(\mathbf{r})` are the orthonormal real-valued spherical harmonics.
This function is evaluated as the the product of three terms that can be accessed separately:
- ``self.coeff`` - the constant prefactor _C_
- ``self.radial_part(r)`` - :math:`e^{-a\left| \mathbf r - \mathbf r_0 \right|^2}`
- ``self.angular_part(r)`` - :math:`Y^l_m(\mathbf r - \mathbf r_0) r^l`
References:
Schlegel and Frisch. Transformation between cartesian and pure spherical harmonic gaussians.
Int J Quantum Chem 54, 83-87 (1995). doi:10.1002/qua.560540202
https://en.wikipedia.org/wiki/Table_of_spherical_harmonics#Real_spherical_harmonics
"""
center = utils.Alias('radial_part.center')
alpha = utils.Alias('radial_part.alpha')
ndims = ndim = num_dims = 3
def __init__(self, center, alpha, l, m, coeff=None, normalized=True):
assert len(center) == 3, "Spherical gaussians must be 3-dimensional"
self.l = l
self.m = m
self.radial_part = Gaussian(center, alpha, coeff=1.0, normalized=False)
self._spherical_harmonic = spherical_harmonics.Y(l, m)
super().__init__(coeff=coeff, normalized=normalized)
def __repr__(self):
return ("<3D Gaussian (Spherical) (coeff: {coeff:4.2f}, "
"alpha: {alpha:4.2f}, "
"(l,m) = {qnums}>").format(
center=self.center, alpha=self.alpha, coeff=self.coeff,
qnums=(self.l, self.m))
def __mul__(self, other):
raise NotImplementedError("Cannot yet multiply spherical gaussian functions")
def _get_wfn_units(self):
return u.MdtQuantity(self.coeff * u.default.length**self.l).units
def __call__(self, coords):
""" Evaluate this function at the given coordinates.
Can be called either with a 1D column (e.g., ``[1,2,3]*u.angstrom ``) or
an ARRAY of coordinates (``[[0,0,0],[1,1,1]] * u.angstrom``)
Args:
coords (Vector[length]): 3D Coordinates or list of 3D coordinates
Returns:
Scalar or Vector: function value(s) at the passed coordinates
"""
result, disp, r2 = self.radial_part(coords, _getvals=True)
result *= r2**(self.l/2.0) * self._spherical_harmonic(disp)
return result * self.coeff
def overlap(self, other, normalized=False):
r""" Overlap of this function with another basis function
.. math::
\int f_1(\mathbf r) f_2(\mathbf r) d^N \mathbf r
Args:
other (Primitive):
normalized (bool): If True, return the overlap of the two NORMALIZED functions.
Returns:
Scalar: value of the overlap
"""
from scipy.special import factorial
from ..data import ODD_FACTORIAL
if (self.center != other.center).any():
return self.to_cart().overlap(other)
elif self.l != other.l or self.m != other.m:
return 0.0
else:
newexp = self.alpha + other.alpha
power = self.l + other.l + 2
# In this case, radial part integrates to 1, so we just
# integrate r^(2+l) exp(-(a1+a2) r^2) from 0 to infinity
if power % 2 == 0:
n = power // 2
val = np.sqrt(np.pi/newexp) * ODD_FACTORIAL[2*n-1] / (newexp**n * 2**(n+1))
else:
n = (power - 1) // 2
val = factorial(n, True) / (2 * newexp**(n+1))
val *= self.coeff * other.coeff
if normalized:
return val / (self.norm * other.norm)
else:
return val
def angular_part(self, coords):
if len(coords.shape) > 1:
axis = 1
else:
axis = None
disp = coords - self.center
prd = disp*disp
r2 = prd.sum(axis=axis)
return r2**(self.l/2.0) * self._spherical_harmonic(disp)
def to_cart(self):
""" Convert this function to a linear combination of cartesian functions
Returns:
List[CartesianGaussian]: cartesian components of this function
"""
carts = [CartesianGaussian(self.center, self.alpha,
cart_fn.powers, self.coeff * cart_fn.coeff,
normalized=False)
for cart_fn in spherical_harmonics.SPHERE_TO_CART[self.l, self.m]]
return PrimitiveSum(carts)
@property
def integral(self):
return self.to_cart().integral
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/atomic_basis_fn.py | .py | 4,085 | 120 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from . import PrimitiveSum, SHELLS, SPHERICALNAMES
class AtomicBasisFunction(PrimitiveSum):
""" Stores an atomic basis function.
Note:
Either l and m should be passed, or cart, but not both.
Args:
atom (moldesign.Atom): The atom this basis function belongs to
index (int): the index of this basis function (it is stored as
``wfn.basis[self.index]``)
n (int): principal quantum number (``n>=1``) - shell metadata (used for labeling only)
l (int): total angular momentum quantum number (``l<=n-1``)
m (int): z-angular momentum quantum number (optional -
for spherical sets only; ``|m|<=l``)
cart (str): cartesian component (optional; for cartesian sets only)
primitives (List[PrimitiveBase]): List of primitives, if available
"""
def __init__(self, atom, n=None, l=None, m=None, cart=None, primitives=None):
super().__init__(primitives)
self._atom = atom
self.atom_index = atom.index
self.n = n
self.l = l
self.m = m
if cart is not None:
assert self.m is None, 'Both cartesian and spherical components passed!'
assert len(cart) == self.l, \
'Angular momentum does not match specified component %s' % cart
for e in cart:
assert e in 'xyz'
self.cart = ''.join(sorted(cart))
else:
self.cart = None
# These quantities can't be defined until we assemble the entire basis
self.coeffs = None
self.molecule = atom.molecule
self.basis = None
self.occupation = None
self.wfn = None
@property
def atom(self):
""" moldesign.Atom: the atom this basis function belongs to
We get the atom via an indirect reference, making it easier to copy the wavefunction
"""
if self.wfn is not None:
return self.wfn.mol.atoms[self.atom_index]
else:
return self._atom
@property
def orbtype(self):
""" A string describing the orbital's angular momentum state.
Examples:
>>> AtomicBasisFunction(n=1, l=0).orbtype
's'
>>> AtomicBasisFunction(n=2, l=1, cart='y').orbtype
'py'
>>> AtomicBasisFunction(n=3, l=2, m=0).orbtype
'd(z^2)'
"""
if self.l == 0: t = 's'
elif self.cart is not None: t = SHELLS[self.l] + self.cart
else: t = SPHERICALNAMES[self.l, self.m]
return t
@property
def aotype(self):
""" A string describing the orbital's state.
Examples:
>>> AtomicBasisFunction(n=1, l=0).aotype
'1s'
>>> AtomicBasisFunction(n=2, l=1, cart='y').aotype
'2py'
>>> AtomicBasisFunction(n=3, l=2, m=0).aotype
'3d(z^2)'
"""
t = self.orbtype
if self.n:
return '%s%s' % (self.n, t)
else:
return t
def __str__(self):
return 'AO ' + self.name
@property
def name(self):
try:
return '%s on atom %s' % (self.aotype, self.atom.name)
except:
return 'Basis Fn'
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.name) | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/primitives.py | .py | 4,973 | 165 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import itertools
import numpy as np
from .. import utils
class Primitive(object):
""" Abstract base class for basis function primitives. All functions are assumed real.
"""
def __init__(self, coeff=None, normalized=False):
self.coeff = 1.0 # initialize with a dummy value
if normalized or (coeff is None):
self.normalize()
if coeff is not None:
self.coeff *= coeff
def _get_wfn_units(self):
return NotImplementedError()
def copy(self):
return copy.deepcopy(self)
def normalize(self):
""" Give this function unit norm by adjusting its coefficient
"""
self.coeff /= self.norm
def overlap(self, other, normalized=False):
r""" Overlap of this function with another:
.. math::
\int f_1(\mathbf r) f_2(\mathbf r) d^N \mathbf r
Args:
other (Primitive):
normalized (bool): If True, return the overlap of the two NORMALIZED functions.
Note:
This implementation computes overlap by computing the integral of the product of the
two functions. Subclasses may override this method if more efficient techniques
are applicable
Returns:
Scalar: value of the overlap
"""
newfn = self * other
integral = newfn.integral
if normalized:
integral /= (self.norm*other.norm)
return integral
@property
def norm(self):
r""" The L2-Norm of this object, calculated as the square root of its self overlap.
.. math::
\sqrt{\int \left| G(\mathbf r) \right|^2 d^N \mathbf r}
"""
return np.sqrt(self.overlap(self))
def iterprimitives(self):
yield self
class PrimitiveSum(object):
""" Stores a linear combination of primitive functions.
Args:
primitives (List[Primitives]): List of primitives, if available
"""
__getitem__ = utils.Alias('primitives.__getitem__')
__len__ = utils.Alias('primitives.__len__')
__iter__ = utils.Alias('primitives.__iter__')
iterprimitives = __iter__
def __init__(self, primitives):
self.primitives = primitives
self._wfn_units = self.primitives[0]._get_wfn_units()
def _get_wfn_units(self):
return self._wfn_units
def __call__(self, coords):
outvals = np.zeros(len(coords)) * self._get_wfn_units()
for primitive in self.primitives:
outvals += primitive(coords)
return outvals
@property
def num_primitives(self):
return len(self.primitives)
@property
def center(self):
c = self.primitives[0].center.copy()
for p in self:
if (p.center != c).any():
raise ValueError("This is a sum over multiple centers")
else:
return c
@property
def norm(self):
""" Scalar: :math:`\sqrt{<i|i>}`
"""
norm = 0.0
for p1 in self.primitives:
for p2 in self.primitives:
norm += p1.overlap(p2)
return np.sqrt(norm)
def normalize(self):
""" Scale primitive coefficients to normalize this basis function
"""
prefactor = 1.0 / self.norm
for primitive in self.primitives:
primitive.coeff *= prefactor
def overlap(self, other):
""" Calculate orbital overlap with another object
Args:
other (AbstractFunction or Orbital): object to calculate overlaps with
"""
olap = sum(p1.overlap(p2)
for p1, p2 in itertools.product(self.iterprimitives(),
other.iterprimitives()))
return olap
@property
def integral(self):
return sum(x.integral for x in self)
def __str__(self):
return '%s with %d primitives' % (self.__class__.__name__, self.num_primitives)
def __repr__(self):
return '<%s>' % self
def __mul__(self, other):
newprims = [p1*p2
for p1, p2 in itertools.product(self.iterprimitives(), other.iterprimitives())]
return PrimitiveSum(newprims)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/cartesian.py | .py | 11,060 | 282 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import numpy as np
from .. import units as u
from .. import utils
from . import Primitive, PrimitiveSum, Gaussian
class CartesianGaussian(Primitive):
r""" Stores an N-dimensional gaussian function of the form:
.. math::
G(\mathbf r) = C \times \left( \prod_{i=1}^N{{r_i}^{p_i} } \right)
e^{-\alpha |\mathbf r - \mathbf{r}_0|^2}
For a three-dimensional gaussian, this is
..math::
G(x,y,z) = C \times x^{p_1} y^{p_2} z^{p_3} e^{-\alpha |\mathbf r - \mathbf{r}_0|^2}
where *C* is ``self.coeff``, :math:`\alpha` is ``self.alpha``, *r0* is ``self.center``, and
:math:`p_1, p_2, ...` are given in the array ``self.powers``
This function is evaluated as the the product of three terms that can be accessed separately:
- ``self.coeff`` - the constant prefactor _C_
- ``self.radial_part(r)`` - :math:`e^{-\alpha \left| \mathbf r - \mathbf r_0 \right|^2}`
- ``self.angular_part(r)`` - :math:`\prod_{i=1}^N{{r_i}^{p_i} }`
Args:
center (Vector[length]): location of the gaussian's centroid
powers (List[int]): cartesian powers in each dimension (see
equations in :class:`CartesianGaussian` docs)
alpha (Scalar[1/length**2]): gaussian width parameter
coeff (Scalar): multiplicative coefficient (if None, gaussian will be automatically
normalized)
Note:
The dimensionality of the gaussian is determined by the dimensionality
of the centroid location vector and the power vector. So, if scalars are passed for the
``center`` and ``powers``, it's 1-D. If length-3 vectors are passed for ``center``
and ``powers``, it's 3D.
References:
Levine, Ira N. Quantum Chemistry, 5th ed. Prentice Hall, 2000. 486-94.
"""
center = utils.Alias('radial_part.center')
alpha = utils.Alias('radial_part.alpha')
ndims = ndim = num_dims = utils.Alias('radial_part.ndim')
def __init__(self, center, alpha, powers, coeff=None, normalized=True):
assert len(powers) == len(center), "Inconsistent dimensionality - number of cartesian " \
"powers must match dimensionality of centroid vector"
self.powers = np.array(powers)
self.shell = sum(self.powers)
self.radial_part = Gaussian(center, alpha, coeff=1.0, normalized=False)
super().__init__(coeff=coeff, normalized=normalized)
def __repr__(self):
return ("<{ndim}-D cartesian gaussian (norm: {norm:4.2f}, "
"cartesian powers: {powers}, "
"alpha: {exp:4.2f}, "
"center: {center}>").format(
ndim=self.ndim,
center=self.center, exp=self.alpha,
powers=tuple(self.powers), norm=self.norm)
def _get_wfn_units(self):
return u.MdtQuantity(self.coeff * u.default.length**self.angular).units
@property
def angular(self):
""" Angular momentum of this function (sum of cartesian powers)
"""
return self.powers.sum()
def overlap(self, other, normalized=False):
r""" Overlap of this function with another basis function
.. math::
\int f_1(\mathbf r) f_2(\mathbf r) d^N \mathbf r
Args:
other (Primitive):
normalized (bool): If True, return the overlap of the two NORMALIZED functions.
Returns:
Scalar: value of the overlap
"""
olap = 0.0
for other_prim in other.iterprimitives():
if hasattr(other_prim, 'to_cart'):
other_prim = other_prim.to_cart()
for p in other_prim.iterprimitives():
olap += self._overlap_cart_cart(p)
if normalized:
olap = olap / (self.norm * other.norm)
return olap
def _overlap_cart_cart(self, other):
""" Overlap of two cartesian functions. Uses the PyQuante2 python implementation
Users shouldn't need to call directly, this should be automatically called when necessary
"""
from ..external.pyquante2.one import overlap
lengthunits = u.default.get_default(self.center)
alphaunits = (1/lengthunits**2).units
alphas = [alphaunits.value_of(g.alpha) for g in (self, other)]
centers = [lengthunits.value_of(g.center) for g in (self, other)]
olap_base = overlap(alphas[0], self.powers, centers[0],
alphas[1], other.powers, centers[1])
olap = self.coeff * other.coeff * olap_base
if lengthunits != u.dimensionless:
olap *= lengthunits ** (3 + sum(self.powers) + sum(other.powers))
return olap
def __call__(self, coords):
""" Evaluate this function at the given coordinates.
Can be called either with a 1D column (e.g., ``[1,2,3]*u.angstrom ``) or
an ARRAY of coordinates (``[[0,0,0],[1,1,1]] * u.angstrom``)
Args:
coords (Vector[length, len=3] or Matrix[length, shape=(*,3)]): Coordinates or
list of 3D coordinates
Examples:
>>> g = CartesianGaussian([0,0,0]*u.angstrom, alpha=1.0/u.angstrom**2, powers=(0,0,0))
>>> # Value at a single coordinate:
>>> g([0,0,0] * u.angstrom)
1.0
>>> # Values at a list of coordinates
>>> g[[0,0,0], [0,0,1], [0.5,0.5,0.5] * u.angstrom]
array([ 1.0, 0.36787944, 0.47236655])
Returns:
Scalar or Vector: function value(s) at the passed coordinates
"""
result = self.radial_part(coords)
if self.shell > 0:
result *= self.angular_part(coords)
return result * self.coeff
def angular_part(self, coords):
if self.shell == 0:
return 1.0
if len(coords.shape) > 1:
axis = 1
else:
axis = None
disp = coords - self.center
if hasattr(disp, 'units'):
mag = disp.magnitude
units = disp.units ** self.powers.sum()
else:
mag = disp
units = 1.0
return np.product(mag**self.powers, axis=axis) * units
def __mul__(self, other):
""" Returns product of two cartiesian gaussian functions as a list of product gaussians
The returned gaussians all have the same center and width, and differ only in their
angular parts.
Args:
other (CartesianGaussian): other gaussian basis function
Returns:
CartesianGaussian or PrimitiveSum[CartesianGaussian]: product functions
"""
from scipy.special import binom
if (self.center == other.center).all(): # this case is much easier than the general one
cpy = self.copy()
cpy.radial_part.alpha = self.alpha + other.alpha
cpy.powers = self.powers + other.powers
cpy.coeff = self.coeff * other.coeff
return cpy
newcenter = self.radial_part * other.radial_part
partial_coeffs = [{} for idim in range(self.ndim)]
for idim in range(self.ndim):
r_self = self.center[idim]
r_other = other.center[idim]
r_new = newcenter.center[idim]
for m in range(self.powers[idim]+1):
for k in range(other.powers[idim]+1):
powercoeff = (binom(self.powers[idim], m) * binom(other.powers[idim], k) *
((r_new - r_self) ** (self.powers[idim]-m)) *
((r_new - r_other) ** (other.powers[idim]-k)))
if powercoeff == 0.0:
continue
newpower = m+k
if newpower not in partial_coeffs[idim]:
partial_coeffs[idim][newpower] = powercoeff
else:
partial_coeffs[idim][newpower] += powercoeff
new_gaussians = []
for powers in itertools.product(*[x.keys() for x in partial_coeffs]):
final_coeff = self.coeff * other.coeff * newcenter.coeff
for idim, p in enumerate(powers):
final_coeff *= partial_coeffs[idim][p]
new_gaussians.append(CartesianGaussian(newcenter.center, newcenter.alpha,
powers=powers, coeff=final_coeff,
normalized=False))
if len(new_gaussians) == 0: # no non-zero components, just return a zeroed gaussian
return CartesianGaussian(newcenter, newcenter.alpha,
self.powers + other.powers, coeff=0.0,
normalized=False)
elif len(new_gaussians) == 1:
return new_gaussians[0]
else:
return PrimitiveSum(new_gaussians)
@property
def integral(self):
r"""Integral of this this gaussian over all N-dimensional space.
This is implemented only for 0 and positive integer cartesian powers.
The integral is 0 if any of the powers are odd. Otherwise, the integral
is given by:
.. math::
\int G(\mathbf r) d^N \mathbf r & = c \int d^N e^{-a x^2} \mathbf r
\prod_{i=1}^N{{r_i}^{p_i} } \\
&= (2a)^{-\sum_i p_i} \left( \frac{\pi}{2 a} \right) ^ {N/2} \prod_{i=1}^N{(p_i-1)!!}
where *N* is the dimensionality of the gaussian, :math:`p_i` are the cartesian powers,
and _!!_ is the "odd factorial" (:math:`n!!=1\times 3\times 5 \times ... \times n`)
References:
Dwight, Herbert B. Tables of Integrals and other Mathematical Data, 3rd ed.
Macmillan 1957. 201.
"""
from ..data import ODD_FACTORIAL
integ = self.coeff * self.radial_part.integral
for p in self.powers:
if p == 0: # no contribution
continue
elif p % 2 == 1: # integral of odd function is exactly 0
return 0.0
elif p < 0:
raise ValueError('Powers must be positive or 0')
else:
integ *= ODD_FACTORIAL[p-1]/((2.0 * self.alpha) ** (p//2))
return integ
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/__init__.py | .py | 271 | 14 | def toplevel(o):
__all__.append(o.__name__)
return o
__all__ = []
from .primitives import *
from .gaussians import *
from .orbitals import *
from .cartesian import *
from .spherical import *
from .atomic_basis_fn import *
from .basis import *
from .wfn import *
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/orbitals.py | .py | 14,474 | 392 | """ Class definitions for atomic and molecular orbitals.
Notes:
In this documentation, we use the following conventions for labeling orbitals:
- atomic orbitals using lower case greek labels and subscripts, e.g.,
:math:`\left| \mu \right \rangle, F_{\nu \lambda}, etc.
- molecular orbitals use lower case labels and subscripts, e.g.,
:math:`\left| i \right \rangle, F_{kl}, etc.
- adiabatic electronic states are indexed using capital letters, _N_, _L_, _M_, etc.
"""
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from moldesign import units as u
from moldesign.utils import Alias
SHELLS = {0: 's', 1: 'p', 2: 'd', 3: 'f', 4: 'g', 5: 'h'}
ANGMOM = {v: k for k, v in SHELLS.items()}
# See https://en.wikipedia.org/wiki/Table_of_spherical_harmonics#Real_spherical_harmonics
SPHERICALNAMES = {(0, 0): 's', (1, -1): 'p(x)', (1, 0): 'p(z)', (1, 1): 'p(y)',
(2, 0): 'd(z^2)', (2, -2): 'd(xy)', (2, -1): 'd(yz)',
(2, 1): 'd(xz)', (2, 2): 'd(x^2-y^2)',
(3, -3): 'f(3yx^2-y^3)', (3, -2): 'f(xyz)', (3, -1): 'f(yz^2)',
(3, 0): 'f(z^3)', (3, 1): 'f(xz^2)', (3, 2): 'f(zx^2-zy^2)',
(3, 3): 'f(x^3-3xy^2)'}
ANGULAR_NAME_TO_COMPONENT = {'': (0, 0), 'x': (1, 1), 'y': (1, -1), 'z': (1, 0),
'z^2': (2, 0), 'xy': (2, -2), 'yz': (2, -1), 'xz': (2, 1),
'x^2-y^2': (2, 2),
'zx^2-zy^2': (3, 2), 'xyz': (3, -2), 'z^3': (3, 0),
'3yx^2-y^3': (3, -3), 'x^3 - 3xy^2': (3, 3), 'xz^2': (3, 1),
'yz^2': (3, -1)}
class Orbital(object):
r"""
Stores a single orbital and its meta-data
Generally wants to be part of a set of MolecularOrbitals
The orbital is defined as
.. math::
\left| i \right \rangle = \sum_\mu c_{i \mu} \left| \mu \right \rangle
where the coefficients :math:`c_{i \mu}` are stored in ``self.coeffs`` and the basis orbitals
:math:`\left| \mu \right \rangle` are stored at ``self.basis``
"""
def __init__(self, coeffs, basis=None, wfn=None,
occupation=None, name='unnamed'):
""" Initialization:
Args:
coeffs (numpy.array): orbital coefficients
basis (moldesign.orbitals.basis.BasisSet): basis for this orbital
wfn (moldesign.orbitals.wfn.ElectronicWfn): total electronic wavefunction that this orbital is a part of
occupation (float): occupation of this orbital
name (str): optional label for this orbital:
"""
self.coeffs = np.array(coeffs)
self.name = name
self.molecule = None
self.basis = basis
self.occupation = occupation
self.wfn = wfn
self.index = None # will be set by the containing MolecularOrbitals object
# Assign the basis functions
if wfn is not None and wfn.aobasis is not None:
if self.basis is not None:
assert wfn.aobasis is self.basis
else:
self.basis = wfn.aobasis
if self.basis is not None:
assert len(self.coeffs) == len(self.basis)
def overlap(self, other):
""" Calculate overlap with another orbital
Args:
other (Orbital): calculate the overlap with this orbital
Returns:
float: orbital overlap
"""
return self.coeffs.dot(self.basis.overlaps.dot(other.coeffs))
def fock_element(self, other):
""" Calculate fock matrix element with another orbital
Args:
other (Orbital): calculate the fock element with this orbital
Returns:
u.Scalar[energy]: fock matrix element
"""
return self.wfn.fock_ao.dot(other.coeffs).ldot(self.coeffs) # uses ldot to preserve units
@property
def energy(self):
""" u.Scalar[energy]: This orbital's energy
Note:
This is equivalent to self.fock(self)
"""
return self.fock_element(self)
def __call__(self, coords):
""" Calculate the orbital's value at a position (or list of positions)
Args:
coords (u.Vector[length]): Coordinates (shape ``(len(coords), 3)``)
Returns:
u.Scalar[length**(-3/2)]: value of the orbital
"""
return self.basis(coords, coeffs=self.coeffs)
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.name)
__len__ = Alias('coeffs.__len__')
class MolecularOrbitals(object):
"""
Stores a wfn of molecular orbitals in an AO wfn
Orbitals are accessed as orbs[orbital index, ao index]
"""
def __init__(self, orbitals, wfn=None, basis=None,
canonical=False,
orbtype=None):
""" Initialization:
Args:
orbitals (List[Orbital] OR numpy.array): EITHER a list of orbitals OR an
array of coefficients (indexed as coeffs[orbital_index, basis_index])
basis (moldesign.orbitals.basis.BasisSet): orbital basis set
wfn (moldesign.orbitals.wfn.ElectronicWfn): total electronic wavefunction that this orbital is a part of
canonical (bool): designate these as the canonical orbitals
orbtype (str): description of these orbitals
"""
# Determine if these are the canonical orbitals
if canonical:
assert orbtype is None or orbtype == 'canonical'
orbtype = 'canonical'
if orbtype == 'canonical':
canonical = True
if not hasattr(orbitals[0], 'basis'):
coeffs = orbitals
orbitals = []
for c in coeffs:
orbitals.append(Orbital(c, basis=basis, wfn=wfn))
self.orbitals = orbitals
self.coeffs = np.array([orb.coeffs for orb in self.orbitals])
self.wfn = wfn
self.basis = basis
self.orbtype = orbtype
if self.wfn is None:
self.wfn = self.orbitals[0].wfn
if self.basis is None:
self.basis = self.orbitals[0].basis
for iorb, orbital in enumerate(self.orbitals):
orbital.index = iorb
assert orbital.basis == self.basis
assert orbital.wfn == self.wfn
orbital.coeffs = self.coeffs[iorb, :]
if canonical:
self._set_cmo_names()
def align_phases(self, other, threshold=0.5, assert_same_type=True):
""" Flip the signs of these orbitals to bring them into maximum coincidence
with another set of orbitals
Args:
other (MolecularOrbitals): the "reference" set of orbitals to match phases with
threshold (float): only flip orbital if the overlap is less than -1*threshold
assert_same_type (bool): require that ``self.orbtype == other.orbtype``
Note:
This function assumes that the overlap matrix is the same for both sets of
orbitals - this is a reasonable assumption if the two sets of orbitals were
calculated at very similar molecular geometries.
"""
if assert_same_type:
assert self.orbtype == other.orbtype, "Orbital type mismatch: %s vs. %s" % (
self.orbtype, other.orbtype)
for thisorb, otherorb in zip(self, other):
if thisorb.overlap(otherorb) < -1.0 * threshold:
thisorb.coeffs *= -1.0
# TODO: print a warning if overlap is small?
def calc_eris(self):
""" Calculate electron repulsion integrals in this basis
Returns:
ERI4FoldTensor: table of electron repulsion integrals
Note:
Currently uses PySCF/libint to calculate the integrals, regardless of the program
that generated the wavefunction
"""
from moldesign.interfaces.pyscf_interface import get_eris_in_basis
return get_eris_in_basis(self.wfn.aobasis, self.coeffs)
def overlap(self, other):
""" Calculate overlaps between this and another set of orbitals
Args:
other (MolecularOrbitals):
Returns:
numpy.ndarray: overlaps between the two sets of orbitals
Example:
>>> canonical = mol.wfn.canonical
>>> atomic = mol.wfn.basis
>>> overlaps = canonical.overlap(atomic)
>>> overlaps[i, j] == canonical.orbitals[i].overlap(atomic.orbitals[j])
True
"""
return self.coeffs.dot(self.wfn.aobasis.overlaps.dot(other.coeffs.T))
def __iter__(self):
return iter(self.orbitals)
def __len__(self):
return len(self.orbitals)
def __str__(self):
return '%s orbitals' % self.orbtype
def __repr__(self):
return '<%d %s %s in %s>' % (len(self), self.orbtype,
self.__class__.__name__, str(self.wfn))
def __getitem__(self, item):
return self.orbitals[item]
def _to_ao_density_matrix(self):
c = self.coeffs * self.occupations[:, None]/2.0
return 2.0*c.T.dot(c)
@property
def energies(self):
"""u.Vector[energy]: energies of the molecular orbitals
This is just the diagonal of the fock matrix"""
return self.fock.diagonal()
@property
def occupations(self):
""" np.ndarray: orbital occupation numbers
"""
return np.array([orb.occupation for orb in self.orbitals])
@property
def fock(self):
"""u.Array[energy]: Fock matrix for these orbitals"""
return self.from_ao(self.wfn.fock_ao)
@property
def overlaps(self):
"""np.array: overlap matrix for these orbitals"""
return self.from_ao(self.wfn.aobasis.overlaps)
@property
def h1e(self):
"""u.Array[energy]: 1-electron matrix elements for these orbitals"""
return self.from_ao(self.wfn.aobasis.h1e)
@property
def h2e(self):
"""u.Array[energy]: 2-electron matrix elements for these orbitals"""
return self.fock - self.h1e
def from_ao(self, ao_operator):
""" Transform an operator into this orbital basis from the ao basis
Given the matrix elements :math:`\hat O_{\mu \nu}` of an operator over AO basis indices
:math:`\mu,\nu`, returns the operator's matrix elements :math:`\hat O_{ij}` over
orbital indices :math:`i,j`:
..math::
\hat O_{ij} =
\left \langle i \right| \hat O \left| j \right \rangle =
\sum_{\mu \nu}C_{i \mu} O_{\mu \nu} C_{j \nu}
where :math:`C_{i \mu}` is the expansion coefficient for AO basis function :math:`\mu` in
molecular orbital _i_.
Args:
ao_operator (u.Array): matrix elements of the operator in the ao basis
Returns:
u.Array: matrix elements of the operator in this orbital basis
Note:
Assumes that this set of orbitals is orthogonal
"""
# Dot doesn't place nice with units, so we need to pass them explicitly
ao_units = u.get_units(ao_operator)
return self.coeffs.dot(ao_operator.dot(self.coeffs.T)) * ao_units
def to_ao(self, mo_operator):
""" Transform an operator from this orbital basis into the AO basis
Given the matrix elements :math:`\hat O_{ij}` of an operator over orbital basis indices
:math:`i,j`, returns the operator's matrix elements :math:`\hat O_{\mu \nu}` over
orbital indices :math:`\mu, \nu`:
..math::
\hat O_{\mu \nu} =
\left \langle \mu \right| \hat O \left| \nu \right \rangle =
\sum_{i,j,\lambda,\kappa}S_{\mu \lambda} C_{i \lambda} O_{ij} C_{j \kappa} S_{\kappa \nu}
where :math:`S_{\mu \nu} = \left \langle \mu | \nu \right \rangle` is the AO overlap matrix
and :math:`C_{i \mu}` is the expansion coefficient for AO basis function :math:`\mu` in
molecular orbital _i_.
Args:
mo_operator (u.Array): matrix elements of the operator in this orbital basis
Returns:
u.Array: matrix elements of the operator in the AO basis
"""
units = u.get_units(mo_operator)
s = self.wfn.aobasis.overlaps
o_ao = s.dot(self.coeffs.T).dot(mo_operator).dot(self.coeffs).dot(s)
return o_ao * units
def _set_cmo_names(self):
for i, orb in enumerate(self.orbitals):
if orb.name != 'unnamed' and orb.name is not None:
continue
if i <= self.wfn.homo:
if i < self.wfn.homo - 2:
orb.name = 'cmo %d' % i
elif i == self.wfn.homo:
orb.name = 'HOMO'
else:
orb.name = 'HOMO-%d' % (self.wfn.homo - i)
else:
if i == self.wfn.lumo:
orb.name = 'LUMO'
elif i <= self.wfn.lumo + 2:
orb.name = 'LUMO+%d' % (i - self.wfn.lumo)
else:
orb.name = 'virt cmo %d' % i
class ERI4FoldTensor(object):
def __init__(self, mat, basis_orbitals):
self.mat = mat
self.basis_orbitals = basis_orbitals
self.nbasis = len(self.basis_orbitals)
mapping = np.zeros((self.nbasis, self.nbasis), dtype='int')
ij = 0
for i in range(self.nbasis):
for j in range(i + 1):
mapping[i, j] = mapping[j, i] = ij
ij += 1
self.mapping = mapping
def __getitem__(self, item):
i, j, k, l = item
return self.mat[self.mapping[i, j], self.mapping[k, l]]
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/gaussians.py | .py | 5,009 | 154 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from .. import units as u
from . import Primitive
class Gaussian(Primitive):
r""" N-dimensional gaussian function.
The function is given by:
.. math::
G(\mathbf r) = C e^{-\alpha\left| \mathbf r - \mathbf r_0 \right|^2}
where *C* is ``self.coeff``, *a* is ``self.alpha``, and :math:`\mathbf r_0` is ``self.center``.
Args:
center (Vector): centroid of this function (r_0 in the equation above)
alpha (Scalar): constant in the exponential (alpha in the equation above)
coeff (Scalar): coefficient for this function. If normalized=True, the coefficient
multiplies the _normalized_ gaussian. If not passed, the gaussian will automatically
be normalized
normalized (bool): if True, normalize the function before applying the coefficient
"""
def __init__(self, center, alpha, coeff=None, normalized=True):
self.center = u.default.convert(center)
self.alpha = u.default.convert(alpha)
super().__init__(coeff=coeff, normalized=normalized)
def _get_wfn_units(self):
return u.MdtQuantity(self.coeff).units
def __call__(self, coords, _getvals=False):
""" Evaluate this function at the given coordinates.
Can be called either with a 1D column (e.g., ``[1,2,3]*u.angstrom ``) or
an ARRAY of coordinates (``[[0,0,0],[1,1,1]] * u.angstrom``)
Args:
_include_angular (bool): include the contribution from the non-exponential parts
(for computational efficiency, this can be omitted now and included later)
Args:
coords (Vector[length]): 3D Coordinates or list of 3D coordinates
Returns:
Scalar or Vector: function value(s) at the passed coordinates
"""
if len(coords.shape) > 1:
axis = 1
else:
axis = None
disp = coords - self.center
prd = disp*disp # don't use np.dot - allow multiple coords at once
r2 = prd.sum(axis=axis)
result = self.coeff * np.exp(-self.alpha * r2)
if _getvals:
return result, disp, r2 # extra quantities so that they don't need to be recomputed
else:
return result
def __repr__(self):
return ("<{ndim}-D gaussian (coeff: {coeff:4.2f}, "
"exponent: {exp:4.2f}, "
"center: {center}>").format(
ndim=self.ndim,
center=self.center, exp=self.alpha,
coeff=self.coeff)
@property
def ndim(self):
return len(self.center)
num_dimensions = ndims = ndim
def __mul__(self, other):
""" Returns a new gaussian centroid.
"""
a1 = self.alpha
a2 = other.alpha
x1 = self.center
x2 = other.center
alpha = a1 + a2
center = (a1*x1 + a2*x2)/(a1+a2)
prefactor = self.coeff * other.coeff
for i in range(self.ndim):
prefactor *= np.exp(-(a1*x1[i]**2 + a2*x2[i]**2) +
alpha * center[i]**2)
return Gaussian(center, alpha, coeff=prefactor, normalized=False)
@property
def integral(self):
r"""Integral of this this gaussian over all N-dimensional space
"""
return self.coeff * (np.pi/self.alpha)**(self.ndim/2.0)
def to_cart(self):
from . import CartesianGaussian
return CartesianGaussian(self.center, self.alpha, (0,0,0),
self.coeff, normalized=False)
def cart_to_powers(s):
""" Convert a string to a list of cartesian powers
Examples:
>>> cart_to_powers('y')
[0, 1, 0]
>>> cart_to_powers('xxyz')
[2, 1, 1]
>>> cart_to_powers('zx^3')
[3,0,1]
"""
powers = [0, 0, 0]
chars = iter(s)
lastchar = None
while True:
try:
char = next(chars)
except StopIteration:
break
if char == '^':
power = int(next(chars))
powers[DIMLABELS[lastchar]] += power - 1
lastchar = None
else:
powers[DIMLABELS[char]] += 1
lastchar = char
return powers
DIMLABELS = {'x': 0, 'y': 1, 'z': 2}
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/basis.py | .py | 4,187 | 121 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from ..utils import Attribute
from . import toplevel, MolecularOrbitals
@toplevel
class BasisSet(MolecularOrbitals):
"""
Stores a basis, typically of atomic orbitals.
This is a case of a general set of molecular orbitals, where the coefficient matrix
must be the identity
Args:
mol (mdt.Molecule): the molecule these basis functions belong to
orbitals (List[AtomicBasisFunction]): list of basis functions comprising this set
name (str): name of this basis set
h1e (Matrix[energy]): 1-electron elements of the hamiltonian
overlaps (Matrix): overlap matrix
"""
overlaps = Attribute('_overlaps')
h1e = Attribute('_h1e')
def __init__(self, mol, orbitals, name=None,
h1e=None, overlaps=None,
angulartype=None,
**kwargs):
self.mol = mol
self.orbitals = orbitals
self.coeffs = np.identity(len(self.orbitals))
self.basis = self
self.orbtype = 'aobasis'
self.angulartype = angulartype
assert self.angulartype in (None, 'spherical', 'cartesian')
self.wfn = None
for iorb, orbital in enumerate(self.orbitals):
orbital.index = iorb
orbital.coeffs = self.coeffs[iorb, :]
orbital.basis = self
self.basisname = name
self.h1e = h1e
self.overlaps = overlaps
for kw, val in kwargs.items():
setattr(self, kw, val)
self._basis_fn_by_atom = {}
for fn in self.orbitals:
self._basis_fn_by_atom.setdefault(fn.atom.index, []).append(fn)
def __call__(self, coords, coeffs=None):
"""Calculate the amplitude of a list of orbitals at the specified coordinates.
Returns an array of orbital amplitudes. The amplitude of the _n_th orbital at the
_j_th coordinate is stored at position ``(j, n)`` in the returned array.
Args:
coords (Matrix[shape=(*,3)]): List of coordinates.
coeffs (Matrix[shape=(*, nbasis)]): List of ao coefficients (optional;
if not passed, the amplitudes of all basis functions will be returned
Returns:
Matrix:
- if ``coeffs`` is passed, an array of orbital amplitudes at the given positions
of size ``(len(coords), len(coeffs))``.
- if ``coeffs`` is NOT passed, an array of basis function amplitudes
of size ``(len(coords), len(aobasis))``.
"""
basis_vals = np.zeros((len(coords), len(self))) * self.orbitals[0]._get_wfn_units()
for ibf, bf in enumerate(self.orbitals):
basis_vals[:, ibf] = bf(coords)
if coeffs is None:
return basis_vals
else:
return np.dot(basis_vals, coeffs.T)
def get_basis_functions_on_atom(self, atom):
""" Return a list of basis functions on this atom
Args:
atom (moldesign.Atom): query atom
Returns:
List[AtomicBasisFunction]: basis functions centered on this atom
"""
return self._basis_fn_by_atom[atom.index]
def __repr__(self):
return '<%s (%s) of %s>' % (self.__class__.__name__, self.basisname, self.mol)
@property
def fock(self):
return self.wfn.fock_ao
@property
def density_matrix(self):
return self.wfn.density_matrix_ao
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/orbitals/wfn.py | .py | 5,817 | 147 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import copy
from . import Orbital, MolecularOrbitals
from ..utils import DotDict
class ElectronicWfn(object):
""" Stores the results of a quantum chemistry calculation.
This is necessarily pretty flexible, but generally stores an LCAO wfn and one or more sets of
orbitals. Can also store CI vectors, etc.
These objects will usually be created by quantum chemical energy models.
Args:
mol (moldesign.Molecule): Molecule this wavefunction belongs to
num_electrons (int): number of electrons in this wavefunction
model (moldesign.models.base.EnergyModelBase): The model this wavefunction was created with
aobasis (moldesign.orbitals.BasisSet): The basis functions for the enclosed orbitals
nbasis (int): number of AO basis functions
fock_ao (moldesign.units.Array[energy]): fock matrix in the AO basis
positions (moldesign.units.Array[length]): positions of the nuclei for this wfn
civectors (np.ndarray): CI vectors (if applicable)
description (str): text describing the wfn (e.g. 'RHF/STO-3G', 'CAS(2,2)/SA3/6-31G**')
density_matrix_ao (np.ndarray): density matrix in the ao basis
"""
def __init__(self, mol, num_electrons,
model=None,
aobasis=None, fock_ao=None,
positions=None,
civectors=None,
description=None,
density_matrix_ao=None):
self.mol = mol
self.model = model
self.civectors = civectors
self.aobasis = aobasis
if aobasis:
self.nbasis = len(self.aobasis)
else:
self.nbasis = None
self.orbitals = DotDict()
self.fock_ao = fock_ao
self.num_electrons = num_electrons
self.homo = self.num_electrons//2 - 1
self.lumo = self.homo + 1
self._has_canonical = False
self.density_matrix_ao = density_matrix_ao
self.description = description
if positions is None:
self.positions = mol.positions.copy()
else:
self.positions = positions.copy()
if self.aobasis is not None:
self.aobasis.wfn = self
atomic_orbs = [Orbital(c, basis=self.aobasis, wfn=self, name=bf.name)
for c,bf in zip(np.identity(len(self.aobasis)), self.aobasis)]
self.orbitals.atomic = MolecularOrbitals(atomic_orbs, wfn=self,
basis=self.aobasis,
orbtype='atomic')
for orb in self.aobasis.orbitals:
orb.wfn = self
def copy(self):
""" Create a copy of this wavefunction
Returns:
ElectronicWfn: a copy of this wavefunction. Note that all attributes are deepcopied
EXCEPT for self.mol, which still points to the original molecule
"""
return copy.deepcopy(self, memo={id(self.mol): self.mol})
def __repr__(self):
return '<ElectronicWfn (%s) of %s>' % (self.description, str(self.mol))
def __str__(self):
return '%s wfn' % self.description
def set_canonical_mos(self, orbs):
if orbs.wfn is None:
orbs.wfn = self
self._has_canonical = True
def align_orbital_phases(self, other, assert_same=True):
"""Align this wavefunction's orbitals to have the same phase as those in `other`.
Args:
other (ElectronicWfn): reference wfn to align phases with
assert_same (bool): raise an exception if the two wavefunctions do not have the same
kinds of orbitals
"""
for orbtype in self.orbitals:
if orbtype not in other.orbitals:
if assert_same:
assert False, '%s has orbital type %s, but %s does not.' % (
self, orbtype, other)
else: continue
self.orbitals[orbtype].align_phases(other.orbitals[orbtype])
def run_nbo(self, **kwargs):
from moldesign.interfaces import nbo_interface
nbo_interface.run_nbo(self.mol, **kwargs)
def add_orbitals(self, orbs, orbtype='canonical', **kwargs):
for orb in orbs:
if orb.wfn is None:
orb.wfn = self
mo_object = MolecularOrbitals(orbs,
wfn=self,
orbtype=orbtype)
self.orbitals[orbtype] = mo_object
if orbtype == 'canonical' and not self._has_canonical:
self.set_canonical_mos(mo_object)
return mo_object
@property
def molecular_orbitals(self):
"""A synonym for self.orbitals['canonical'], since this is usually what's wanted"""
return self.orbitals['canonical']
@molecular_orbitals.setter
def molecular_orbitals(self, val):
"""A synonym for self.orbitals['canonical'], since this is usually what's wanted"""
self.orbitals['canonical'] = val
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/compute/compute.py | .py | 6,358 | 203 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import moldesign as mdt
from .. import utils
from ..helpers import display_log
default_engine = None
def get_image_path(image_name, _devmode=None):
""" Returns a fully qualified tag that points to the correct registry
Args:
image_name (str): name of the image (without tags, repository, etc.)
Examples:
>>> config.update({'default_repository':'my.docker.registry/orgname/myrepo:',
'default_version_tag':'latest'})
>>> get_image_path('myimage')
'my.docker.registry/orgname/myrepo:myimage-latest'
>>> config.update({'default_repository':'docker.io/myorg',
'default_version_tag':'0.2'})
>>> get_image_path('someimage')
'docker.io/myorg/someimage:0.2
"""
from .configuration import config
if _devmode is None:
_devmode = config.devmode
if _devmode:
return image_name + ':dev'
if not config.default_repository:
name = image_name
elif config.default_repository[-1] in '/:':
name = '%s%s' % (config.default_repository, image_name)
else:
name = '%s/%s' % (config.default_repository, image_name)
if not config.default_repository:
img = name
elif config.default_repository[-1] == ':':
img = '%s-%s' % (name, config.default_version_tag)
elif config.default_version_tag:
img = '%s:%s' % (name, config.default_version_tag)
else:
raise ValueError('Faulty docker repository configuration not recognized')
return img
class DummyJob(object):
"""
A job that doesn't actually need to run.
Useful as a return value for processes that return a job object.
"""
status = 'finished'
wait = kill = lambda self: None
get_stdout_stream = get_stderr_stream = lambda self: ''
stdout = stderr = ''
@staticmethod
def get_output_files(filename=None):
if filename is not None:
return {}[filename] # raises the exception on purpose
else:
return {}
def __init__(self, result, updated_object=None):
self.result = result
if updated_object:
self.updated_object = updated_object
def run_job(job, engine=None, wait=True, jobname=None, display=True,
_return_result=False):
""" Helper for running jobs.
Args:
job (pyccc.Job): The job to run
engine (pyccc.Engine): Engine to run this job on (default:
``moldesign.compute.get_engine()``)
image (str): URL for the docker image
wait (bool): if True, block until this function completes and return the function's
return value. Otherwise, return a job object immediately that can be queried later.
display (bool): if True, show logging output for this job
Returns:
pyccc job object OR function's return value
"""
import pyccc
# this is a hacky list of jobs that's mostly for debugging
mdt._lastjobs[mdt._njobs] = job
mdt._lastjobs[-1] = job
mdt._njobs += 1
if job.engine is None:
engine = utils.if_not_none(engine, mdt.compute.get_engine())
job.engine = engine
if engine is None:
raise ValueError('No compute engine configured! Configure MDT using '
'moldesign.compute.config')
if isinstance(job.engine, pyccc.engines.Docker):
check_pull_image(job.engine.client, job.image)
job.submit()
jobname = utils.if_not_none(jobname, job.name)
if display:
display_log(job.get_display_object(), jobname)
if wait:
job.wait()
if _return_result: return job.result
return job
def check_pull_image(client, image):
from .. import widgets
if image_present(client, image):
return
elif widgets.nbmolviz_enabled:
from IPython.display import display
from nbmolviz.mdtconfig.images import DockerImageView
widget = DockerImageView(image, client)
display(widget)
widget.pull()
else:
# No fancy UI here, just print a message indicating that the image will be pulled
print('Pulling image "%s" from dockerhub ...' % image)
def image_present(client, image):
from docker import errors
try:
imginfo = client.inspect_image(image)
except errors.ImageNotFound:
return False
else:
return True
@utils.args_from(run_job, only='engine wait jobname display'.split())
def runremotely(func, args=None, kwargs=None,
jobname=None, engine=None, image=None, wait=True, display=True,
persist_refs=True, when_finished=None):
""" Runs a python command remotely.
Args:
job (pyccc.Job): The job to run
Returns:
pyccc.PythonJob OR object: reference to the job if wait=False, or the function's
return value, if wait=True
"""
import pyccc
if args is None:
args = []
if kwargs is None:
kwargs = {}
if image is None:
image = mdt.compute.config.default_python_image
if jobname is None:
jobname = func.__name__
if args:
jobname += str(args[0])
call = pyccc.PythonCall(func, *args, **kwargs)
job = pyccc.PythonJob(command=call, image=image, engine=engine, name=jobname,
submit=False, persist_references=persist_refs,
sendsource=False, when_finished=when_finished)
job = run_job(job, wait=wait, display=display)
if wait:
return job.result
else:
return job
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/compute/configuration.py | .py | 10,041 | 283 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from past.builtins import basestring
import future.utils
import os
import sys
import yaml
import warnings
from pyccc import engines
from .. import utils
from . import compute
from .. import _version
from .. import exceptions
RUNNING_ON_WORKER = (os.environ.get('IS_PYCCC_JOB', '0') == '1')
COMPUTE_CONNECTION_WARNING = """
WARNING: Failed to connect to Docker - MDT won't be able to run
any software not already installed on your machine.
Make sure Docker is installed and running!
To install it, go to https://www.docker.com/get-docker
"""
config = utils.DotDict()
""" dict: dictionary of parameters (read from user's moldesign.yml at startup)
This dictionary configures how MDT interacts with "computational engines" - the systems that run
jobs, usually using docker images.
Notes:
Values in this dictionary can be configured at runtime; however, after changing them,
you should update the compute configuration by running
``moldesign.compute.reset_compute_engine()``
Configuration is specified using the following keys:
Args:
engine_type (str): The computational job engine to use. Currently supported:
'docker' (default) or 'subprocess'
default_repository (str): Repository to pull MDT's standard images from.
default: 'docker.io/autodesk/moldesign:'
default_version_tag (str): Default version tag for docker images
(default: last tagged release (like ``moldesign.__version__``))
default_docker_url (str): URL for communicating with docker if ``engine_type=='docker'``.
(default: Determined from $DOCKER_HOST, usually this will be the client you run on
the command line)
run_remote (Mapping[str,bool]): Whether to run a given python package in docker by default
run_local (Mapping[str,bool]): Whether to run a given executable locally or in docker
MDT uses a non-standard docker tagging system to store its docker images. Generally,
a given image is pulled from a URL of the form:
``http://[some_docker_registry/orgname/reponame]:[imagename]-[versiontag]``
For instance, the ambertools 0.6 image is stored in the default repository at:
``http://docker.io/autodesk/moldesign:ambertools-0.6``
"""
ENVVAR = "MOLDESIGN_CONFIG"
""" str: name of environmental variable that stores path to moldesign.yml file.
If this variable is not set, ``$HOME/.moldesign/moldesign.yml`` will be used by default."""
DEFAULT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.moldesign', 'moldesign.yml')
""" str: default search path for moldesign.yml."""
# TODO: we're currently hardcoding this at release - there's got to be a better way
_vers = _version.get_versions()['version']
if '+' in _vers:
_vers = _vers[:_vers.index('+')]
DEFAULT_VERSION_TAG = _vers
CONFIG_DEFAULTS = utils.DotDict(engine_type='docker',
default_repository='docker.io/autodesk/moldesign:',
default_docker_host='',
default_version_tag=DEFAULT_VERSION_TAG,
run_remote={},
run_local={},
devmode=False)
DEF_CONFIG = CONFIG_DEFAULTS.copy()
""" dict: default configuration to be written to moldesign.yml if it doesn't exist
"""
config.update(DEF_CONFIG)
def registry_login(client, login):
print('Logging into docker registry @ %s ...' % login['registry'], end=' ')
sys.stdout.flush()
try:
client.login(**login)
except Exception as exc:
warnings.warn('Failed to connect to %s. ' % login['registry'] +
'Some functions may time out.')
else:
print('done')
def update_saved_config(**keys):
path = _get_config_path()
if not os.path.exists(path):
confdir = os.path.dirname(path)
if not os.path.exists(confdir):
os.mkdir(confdir)
print('Created moldesign configuration directory %s' % confdir)
oldconf = {}
else:
with open(path, 'r') as conffile:
oldconf = yaml.load(conffile)
for k,v in keys.items():
if k in oldconf:
assert isinstance(oldconf[k], dict) == isinstance(v, dict), "Is key %s a mapping?" % k
if isinstance(v, dict):
if k not in oldconf:
oldconf[k] = {}
oldconf[k].update(v)
else:
oldconf[k] = v
with open(path, 'w') as f:
yaml.safe_dump(oldconf, f, default_flow_style=False)
print('Wrote moldesign configuration to %s' % path)
def get_engine():
if compute.default_engine is None:
try:
reset_compute_engine()
except:
print(COMPUTE_CONNECTION_WARNING, file=sys.stderr)
raise
return compute.default_engine
def init_config():
"""Called at the end of package import to read initial configuration and setup cloud computing.
"""
from . import packages
config.update(CONFIG_DEFAULTS)
path = _get_config_path()
if os.path.exists(path):
try:
with open(path, 'r') as infile:
newconf = yaml.load(infile)
if not isinstance(newconf, dict):
raise TypeError('Cannot read configuration "%s" from %s.' % (newconf, path))
except (IOError, KeyError, TypeError) as e:
print(('WARNING: exception while reading configuration: %s. '
'using built-in default configuration') % e)
else:
config.update(newconf)
_check_override('default_version_tag', DEFAULT_VERSION_TAG, path)
if 'default_version_tag' not in config:
config.default_version_tag = DEFAULT_VERSION_TAG
if future.utils.PY2:
expcted_docker_python_image = compute.get_image_path('moldesign_complete_py2')
else:
expcted_docker_python_image = compute.get_image_path('moldesign_complete')
if config.get('default_python_image', None) is None:
config.default_python_image = expcted_docker_python_image
for pkg, do_remote in list(config.run_remote.items()):
if do_remote:
try:
getattr(packages, pkg).force_remote = True
except AttributeError:
print('WARNING: unknown key "%s" in %s' % (pkg, path),
file=sys.stderr)
for pkg, do_local in list(config.run_local.items()):
if do_local:
try:
getattr(packages, pkg).run_local = True
except AttributeError:
print('WARNING: unknown key "%s" in %s' % (pkg, path),
file=sys.stderr)
def _check_override(tagname, expected, path):
if tagname in config and config.default_version_tag != expected:
print('WARNING: Configuration file specifies a different value for %s! '
"Remove the `%s` field from %s unless you know what you're doing"
% (tagname, tagname, path))
def _get_config_path():
if ENVVAR in os.environ:
path = os.environ[ENVVAR]
else:
path = DEFAULT_CONFIG_PATH
return path
def reset_compute_engine():
"""Read the configuration dict at ``moldesign.compute.config`` and set up compute engine
Sets the module-level variable ``default_engine``.
Returns:
dict: copy of the config dictionary used to set the engine
"""
from moldesign import compute
compute.default_engine = None
if config.engine_type == 'docker':
connect_docker()
elif config.engine_type == 'subprocess':
connect_subprocess()
elif config.engine_type in ('ccc', 'docker-machine'):
raise ValueError('Computational engine type "%s" is no longer supported by MDT. '
'Please install docker (https://docker.io) and set: \n'
' engine_type: docker'
'in ~/.moldesign/moldesign.yml')
else:
raise ValueError('Unrecognized engine %s' % config.engine_type)
def connect_subprocess():
compute.default_engine = engines.Subprocess()
print("""WARNING: running all computational jobs as subprocesses on this machine.
This requires that you have all necessary software installed locally.
To change the engine, call moldesign.configure() or modify moldesign.compute.config .""")
def connect_docker():
import requests, docker
if config.default_docker_host:
notice = 'Connecting to docker host at %s'%config.default_docker_host
hosturl = config.default_docker_host
else:
notice = "Connecting to your docker engine"
hosturl = None
with utils.textnotify(notice):
try:
compute.default_engine = engines.Docker(hosturl)
compute.default_engine.client.ping()
except (requests.exceptions.RequestException, docker.errors.DockerException):
location = 'running locally' if hosturl is None else ("at URL %s" % hosturl)
raise exceptions.DockerError(
'Failed to connect to docker %s.' % location)
_connect_docker_registry()
def _connect_docker_registry():
from moldesign import compute
if config.get('docker_registry_login', None):
registry_login(compute.default_engine.client, config.docker_registry_login)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/compute/__init__.py | .py | 135 | 7 | __all__ = ['config']
from .compute import *
from .configuration import *
from .remote_procedure_calls import *
from . import packages
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/compute/packages.py | .py | 10,966 | 299 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import subprocess
import importlib
import pkg_resources
from future.utils import PY2
from .. import utils
from .remote_procedure_calls import RpcWrapper
if PY2:
PYIMAGELABEL = 'moldesign_complete_py2'
else:
PYIMAGELABEL = 'moldesign_complete'
CHEMDOCKER_REPO = 'docker.io/chemdocker'
with open(os.path.join(os.path.dirname(__file__), 'CHEMDOCKER_TAG')) as f:
CHEMDOCKER_TAG = f.read().strip()
class InterfacedPackage(object):
""" Object that describes an external python package MDT can access
These packages should _not_ be considered dependencies (unless required=True). MDT doesn't
require them in order to run. If they aren't installed, MDT can be used to automatically
Note that you can supply a ``docker_image`` or a ``docker_image_label``, or neither, or both.
A ``docker_image`` must be the complete path to a docker image (see below), and will take
precedence. If not supplied, the ``docker_image_label`` will be used to create a docker path
using the :method:`moldesign.compute.get_image_path` function.
If neither is supplied, MDT will use the ``config.default_python_image`` docker image.
Args:
packagename (str): name of the package
expectedversion (str): version of this package that MDT was tested against
engine (pyccc.EngineBase): compute engine to run on
docker_image (str): full name of docker image (optional)
(i.e., ``docker.io/autodesk/moldesign:moldesign_complete-0.7.4``)
docker_image_label (str): MDT image label (i.e., ``moldesign_complete``)
importname (str): name to import this package
(i.e., it can be imported as ``import [importname]``)
required (bool): whether this package MUST be installed for MDT to function (default False)
"""
def __init__(self, packagename, expectedversion,
engine=None,
docker_image=None,
docker_image_label=PYIMAGELABEL,
importname=None, required=False):
self.name = packagename # for named_dict
self.packagename = packagename
if importname is None:
self.importname = packagename
else:
self.importname = importname
self.expectedversion = expectedversion
self.required = required
self.docker_image = docker_image
self.docker_image_label = docker_image_label
self.engine = engine
if PY2:
def is_installed(self):
import imp
try:
imp.find_module(self.importname)
except (ImportError, OSError) as exc:
return False
else:
return True
else:
def is_installed(self):
spec = importlib.util.find_spec(self.importname)
return spec is not None
def get_docker_image_path(self):
from . import get_image_path, config
if self.docker_image is not None:
image = self.docker_image
elif self.docker_image_label is not None:
image = get_image_path(self.docker_image_label)
else:
image = config.default_python_image
return image
def installed_version(self):
try:
return pkg_resources.get_distribution(self.packagename).version
except pkg_resources.DistributionNotFound:
return None
@property
def force_remote(self):
from .configuration import config
if not self.is_installed():
return True
return config['run_remote'].get(self.name, False)
@force_remote.setter
def force_remote(self, value):
from .configuration import config
if not value and not self.is_installed():
raise ValueError("Cannot run \"%s\" locally - it's not installed in this environment")
config['run_remote'][self.name] = value
@utils.kwargs_from(RpcWrapper.__init__)
def runsremotely(self, _f=None, **kwargs):
""" Wraps functions that can be run in a remote docker container.
The function will run remotely whenever ``self.force_remote=True``
Args:
**kwargs: __init__ arguments from :class:`RunsRemotely`
"""
def wrapper(f):
wrapped = RpcWrapper(self, **kwargs)(f)
return wrapped
if _f is not None: # called without arguments, directly wrap the function
assert not kwargs
return wrapper(_f)
else:
return wrapper
biopython = InterfacedPackage('biopython', '1.68',
importname='Bio', required=True,)
parmed = InterfacedPackage('parmed', '2.7.3', required=True)
# can't find any run-time mechanism to get the version for openbabel ...
openbabel = InterfacedPackage('openbabel', '2.4')
pdbfixer = InterfacedPackage('pdbfixer', '1.4')
pyscf = InterfacedPackage('pyscf', '1.1')
openmm = InterfacedPackage('OpenMM', '7.1.1', importname='simtk')
packages = [biopython, parmed, openbabel, pdbfixer, pyscf, openmm]
class InterfacedExecutable(object):
""" Object that describes an external executable that MDT can call
All open source executables are provided as public docker containers with
MDT. Others, such as NBO, must be provided by the user.
Note that you can supply a ``docker_image`` or a ``docker_image_label``, or both.
A ``docker_image`` must be the complete path to a docker image (see below), and will take
precedence. If not supplied, the ``docker_image_label`` will be used to create a docker path
using the :method:`moldesign.compute.get_image_path` function.
Args:
exename (str): name of the program
expectedversion (str): version of this program that MDT was tested against
docker_image (str): full name of docker image (optional)
(i.e., ``docker.io/autodesk/moldesign:nwchem-0.7.4``)
docker_image_label (str): MDT image label (i.e., ``nwchem``)
path (str): only relevant when ``self.run_local == True`` - local path to the
executable
version_flag(str): command line flag to print the version number (set to ``None``
if not applicable)
"""
def __init__(self, exename, expectedversion, docker_image_label=None,
docker_image=None,
path=None, version_flag='--version'):
self.name = exename # for named_dict
self.exename = exename
self.expectedversion = expectedversion
self.docker_image = docker_image
self.docker_image_label = docker_image_label
self.engine = None
self._path = path
self.version_flag = version_flag
@property
def run_local(self):
from .configuration import config
return config['run_local'].get(self.name, False)
@run_local.setter
def run_local(self, value):
from .configuration import config
config['run_local'][self.name] = value
def get_docker_image_path(self):
from . import get_image_path, config
if self.docker_image is not None:
image = self.docker_image
elif self.docker_image_label is not None:
image = get_image_path(self.docker_image_label)
else:
raise ValueError('No docker image data for executable "%s"' % self.name)
return image
@property
def path(self):
if self._path is not None:
return self._path
p = utils.which(self.exename)
if p is not None:
return p
# check local directory too
elif os.path.isfile(self.exename) and os.access(self.exename, os.X_OK):
return os.path.abspath(self.exename)
else:
return None
@path.setter
def path(self, value):
self._path = value
def installed_version(self):
if not self.is_installed():
return None
try:
return subprocess.check_output([self.path, self.version_flag]).strip()
except subprocess.CalledProcessError:
return None
def is_installed(self):
if not self.path:
return False
return os.path.exists(self.path)
def make_job(self, **kwargs):
import pyccc
from . import compute
kwargs['submit'] = False
if self.run_local:
kwargs['engine'] = pyccc.Subprocess()
elif self.docker_image is not None:
kwargs['image'] = self.docker_image
else:
kwargs['image'] = compute.get_image_path(self.docker_image_label)
job = pyccc.Job(**kwargs)
return job
def _getimage(name):
return '%s/%s:%s' % (CHEMDOCKER_REPO, name, CHEMDOCKER_TAG)
nwchem = InterfacedExecutable('nwchem.exe', None, 'nwchem',
docker_image=_getimage('nwchem-6.6'))
opsin = InterfacedExecutable('opsin', None, 'opsin', version_flag=None,
docker_image=_getimage('opsin'))
nab = InterfacedExecutable('nab', '17', 'ambertools', version_flag=None,
docker_image=_getimage('ambertools-17'))
symmol = InterfacedExecutable('symmol', None, 'symmol', version_flag=None,
docker_image=_getimage('symmol'))
tleap = InterfacedExecutable('tleap', '16', 'ambertools', version_flag=None,
docker_image=_getimage('ambertools-16'))
antechamber = InterfacedExecutable('antechamber', '16', 'ambertools', version_flag=None,
docker_image=_getimage('ambertools-16'))
nbo = InterfacedExecutable('nbo', '6.1', 'nbo', version_flag=None)
executables = [nwchem, opsin, nab, symmol, tleap, antechamber]
def print_env():
print(' * Interfaces: ')
for pkg in packages:
if pkg.is_installed():
print(' %s: installed' % pkg.name)
else:
print(' %s: not found' % pkg.name)
print('\n * Executables:')
for exe in executables:
if exe.is_installed():
print(' %s: installed' % exe.name)
else:
print(' %s: not found' % exe.name)
__all__ = [x.name for x in packages + executables]
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/compute/remote_procedure_calls.py | .py | 5,016 | 128 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import types
import future.utils
from pyccc import python as bpy
import moldesign as mdt
from moldesign import utils
from . import configuration, run_job
from ..helpers import display_log
class RpcWrapper(object):
""" A wrapper that lets to transparently execute python functions in remote
environments - usually in docker containers.
These wrappers are built to allow a lot of run-time flexibility based on the description
of the package (``self.pkg``) that's being called.
Note:
This ONLY works for pure functions - where you're interested in the
return value only. Side effects - including any object state - will be discarded.
Args:
pkg (mdt.compute.packages.InterfacedPackage): package to run this command with
display (bool): Create a jupyter logging display for the remote job
(default: True in Jupyter notebooks, False otherwise)
jobname (str): Name metadata - defaults to the __name__ of the function
sendsource (bool): if False (default), call this function directly on the remote worker;
if True, send the function's source code (for debugging, mostly)
persist_refs (bool): Persist python object references across the RPC roundtrip
is_imethod (bool): This is an instancemethod
Note: we can't determine this at import-time without going to great lengths ...
- see, e.g., http://stackoverflow.com/questions/2366713/ )
"""
def __init__(self, pkg,
display=True,
jobname=None,
sendsource=False,
is_imethod=False,
persist_refs=False):
self.pkg = pkg
self.display = display
self.sendsource = sendsource
self.jobname = jobname
self.is_imethod = is_imethod
self.persist_refs = persist_refs
def __call__(self, func):
"""
This gets called with the function we wish to wrap
"""
from .compute import get_image_path
assert callable(func)
if self.jobname is None:
self.jobname = func.__name__
assert func.__name__ != 'wrapper' # who wraps the wrappers?
@utils.args_from(func,
wraps=True,
inject_kwargs={'wait': True})
def wrapper(*args, **kwargs):
""" Wraps a python function so that it will be executed remotely using a compute engine
Note:
At runtime, this documentation should be replaced with that of the wrapped function
"""
f = func # keeps a reference to the original function in this closure
wait = kwargs.get('wait', True)
if wait and not self.pkg.force_remote:
return f(*args, **kwargs)
# Bind instance methods to their objects
if self.is_imethod:
f, args = _bind_instance_method(f, args)
# Submit job to remote engine
python_call = bpy.PythonCall(f, *args, **kwargs)
engine = utils.if_not_none(self.pkg.engine, mdt.compute.get_engine())
job = bpy.PythonJob(engine=engine,
image=self.pkg.get_docker_image_path(),
command=python_call,
name=self.jobname,
sendsource=self.sendsource,
interpreter='python', # always run in image's native interpreter
persist_references=self.persist_refs,
submit=False)
return run_job(job, wait=wait, _return_result=True)
wrapper.__name__ = func.__name__
wrapper.__wrapped__ = func
return wrapper
def _bind_instance_method(f, args):
# We can't call this function like normal, because the decorators can't identify
# instance methods. Instead, we'll create another bound copy of the instancemethod (probably
# only need to do this once)
fn_self = args[0]
if future.utils.PY2 == 2:
f = types.MethodType(f, fn_self, fn_self.__class__)
else:
f = types.MethodType(f, fn_self)
args = args[1:]
return f, args
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/forcefields/amber.py | .py | 1,415 | 50 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import moldesign as mdt
from .. import data
from ..utils import exports
from . import TLeapForcefield
@exports
class TLeapLib(TLeapForcefield):
""" A forcefield from TLeap's library
"""
def __init__(self, *ffnames):
self.names = ffnames
sourcelines = ['source %s' % data.AMBER_LEAPRC[ffn] for ffn in ffnames]
super().__init__(sourcelines)
def __str__(self):
return "TLeap data: %s" % ','.join(self.names)
@exports
class DefaultAmber(TLeapLib):
def __init__(self):
super().__init__(*data.AMBER_DEFAULT)
@exports
class GAFF2ForceField(TLeapLib):
def __init__(self):
super().__init__('gaff2')
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/forcefields/errors.py | .py | 6,575 | 167 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import html
from .. import utils
from .. import units as u
from ..widgets import nbmolviz_enabled
def show_parameterization_results(errormessages, molin, molout=None):
print('Forcefield assignment: %s' % ('Success' if molout is not None else 'Failure'))
if not nbmolviz_enabled:
for err in errormessages:
print(utils.html_to_text(err.desc))
else:
from nbmolviz.uielements.logwidget import display_log
from nbmolviz.widgets.parameterization import ParameterizationDisplay
report = ParameterizationDisplay(errormessages, molin, molout)
display_log(report, title='ERRORS/WARNINGS', show=True)
class ForceFieldMessage(object):
def __init__(self, message):
self.message = message
self.desc = message
self.short = message
def show(self, viewer):
viewer.ribbon(opacity=0.7)
def unshow(self, viewer):
pass
class StructureOk(ForceFieldMessage):
"""
A blank message if no other warnings are generated.
"""
MSG = 'No errors or warnings'
def __init__(self):
super().__init__(self.MSG)
class MissingTerms(ForceFieldMessage):
def __init__(self, message):
self.message = message
self.desc = self.message
self.short = self.message
class UnknownAtom(ForceFieldMessage):
def __init__(self, message, residue, atom):
self.message = message
self.residue = residue
self.atom = atom
self.desc = ('ERROR: Atom name "%s" was not found in the "%s" template<br>%s' % (
self.atom.name, self.residue.resname, self.atom)
+ '<p>TLeap message:<i>%s</i>' % self.message)
self.short = 'ERR: %s: unknown atom name "%s" for residue %s' % (self.atom,
self.atom.name,
self.atom.residue.resname)
def show(self, viewer):
viewer.licorice(atoms=self.residue.atoms)
viewer.vdw(atoms=[self.atom])
def unshow(self, viewer):
viewer.ribbon(opacity=0.7)
class MissingAtom(ForceFieldMessage):
def __init__(self, message, residue, atom):
self.message = message
self.residue = residue
self.atom = atom
self.desc = 'INFO: Atom %s in %s (chain %s) was added to the system using the "%s" template' % (
self.atom.name, self.residue.name, self.residue.chain.name, self.residue.resname) + \
'<p>TLeap message:<i>%s</i>' % self.message
self.short = 'INFO: Missing heavy atom %s (index %d)' % (self.atom, self.atom.index)
def show(self, viewer):
viewer.licorice(atoms=self.residue.atoms, render=False)
viewer.vdw(atoms=[self.atom])
def unshow(self, viewer):
viewer.ribbon(opacity=0.7)
class UnknownResidue(ForceFieldMessage):
def __init__(self, message, residue):
self.message = message
self.residue = residue
self._label = None
self.desc = ('ERROR: Residue type "%s" was not found in residue templates<br>%s' % (self.residue.resname, self.residue)
+ '<p>TLeap message:<i>%s</i>' % self.message)
self.short = 'ERR: %s: unknown res type "%s"' % (self.residue, self.residue.resname)
def show(self, viewer):
viewer.licorice(opacity=1.0, atoms=self.residue.atoms, render=False)
self._label = viewer.draw_label(position=self.residue.com, text=self.residue.name)
def unshow(self, viewer):
viewer.ribbon(opacity=0.7, render=False)
if self._label: viewer.remove(self._label)
self._label = None
class UnusualBond(ForceFieldMessage):
def __init__(self, message, atoms, residues):
self.message = message
self.atoms = atoms
self.residues = residues
self._has_atoms = (self.atoms[0] is not None) and (self.atoms[1] is not None)
self._shape = None
if self._has_atoms:
self.desc = 'WARNING: Unusual distance between {a1} and {a2}: {d:.3f}'.format(
d=self.atoms[0].distance(self.atoms[1]), a1=self.atoms[0], a2=self.atoms[1]) \
+ '<p>TLeap message:<br><i>%s</i>' % html.escape(self.message)
self.short = 'WARN: Unusual dist: {} - {} = ({:.1f})'.format(self.atoms[0],
self.atoms[1],
self.atoms[0].distance(self.atoms[1]))
else:
if self.residues[0] is self.residues[1]:
self.short = 'WARN: Unusual bond length in %s' % self.residues[0]
else:
self.short = 'WARN: unusual bond length between %s and %s' % (self.residues[0],
self.residues[1])
self.desc = 'TLeap message:<br><i>%s</i>' % html.escape(self.message)
def show(self, viewer):
if self._has_atoms:
res_opacity = 0.7
else:
res_opacity = 0.9
viewer.licorice(opacity=res_opacity, atoms=self.residues[0], render=False)
viewer.licorice(opacity=res_opacity, atoms=self.residues[1], render=False)
if self._has_atoms:
self._shape = viewer.draw_cylinder(start=self.atoms[0].position,
end=self.atoms[1].position,
radius=0.1 * u.angstrom,
opacity=1.0,
color='red')
def unshow(self, viewer):
viewer.ribbon(opacity=0.7, render=False)
if self._shape: viewer.remove(self._shape)
self._shape = None
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/forcefields/forcefieldbase.py | .py | 6,735 | 173 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import moldesign as mdt
from ..exceptions import ForcefieldAssignmentError
from .errors import show_parameterization_results
from ..utils import exports
class Forcefield(object):
""" Abstract class for biomolecular forcefield definitions such as amber14sb or charm22.
These contain both atom typing templates AND forcefield parameters. Most of this data
is not exposed through the python API (currently); internally, these are collections
of references to definition files (such as amber leaprc and lib files)
"""
def assign(self, mol, display=True):
""" Assign this forcefield to a molecule.
This will create a new ForcefieldParams object at ``mol.ff``. The molecule will not be
otherwise modified
Args:
mol (moldesign.Molecule): molecule to assign the forcefield to. It's ``ff``
attribute will be overwritten with the new parameters
display (bool): in jupyter, creates a parameterization display if the assignment fails
(ignored outside of jupyter)
Raises:
ForcefieldAssignmentError: if the forcefield cannot be assigned
"""
raise NotImplementedError()
def create_prepped_molecule(self, mol, display=True):
""" Return a modified _copy_ of the passed molecule with assigned forcefield.
The modified copy may be modified in one or more of the following ways:
1) Missing atoms added from residue templates
2) Bond topology changed to fit residue templates
3) Residue names changed to fit this FF's residue naming conventions
Args:
mol (moldesign.Molecule): molecule to create a copy of for forcefield assignment
display (bool): in jupyter, creates a parameterization error display upon failure
(ignored outside of jupyter)
Raises:
ForcefieldAssignmentError: if the forcefield cannot be assigned
Returns:
moldesign.Molecule: A modified copy of the passed molecule
"""
raise NotImplementedError()
def check(self, mol, display=True):
""" Return True if this forcefield can be assigned to the given molecule without errors,
otherwise return the exception object (without raising it)
Args:
mol (moldesign.Molecule): molecule to assign the forcefield to. It's ``ff``
attribute will be overwritten with the new parameters
display (bool): in jupyter, creates a parameterization display if the assignment fails
(ignored outside of jupyter)
Returns:
Any: ``True`` if the forcefield can be assigned, ``ForcefieldAssignmentError``
object otherwise
"""
raise NotImplementedError()
def add_ff(self, ff):
""" Adds additional forcefield terms to this forcefield object.
Note:
These parameters are NOT currently checked for overlaps or compatibility with
the pre-existing defintion!
Args:
ff (Forcefield): another forcefield to add
"""
raise NotImplementedError()
@exports
class TLeapForcefield(Forcefield):
""" Amber-type forcefield.
Assignment routines for these forcefields are backed by ambertools (mostly tleap)
Args:
fflines (List[str]): commands to load this forcefield
file_list (Dict[str, pyccc.FileReference]): any files necessary for assigning parameters
(e.g. lib files, frcmod files)
"""
TYPE = 'amber'
def __str__(self):
return "TLeap data at %x" % id(self)
def __init__(self, fflines, file_list=None):
self.names = None
self._fflines = fflines
self._file_list = file_list if file_list is not None else {}
super().__init__()
def assign(self, mol):
newmol = self.create_prepped_molecule(mol)
if newmol.num_atoms != mol.num_atoms:
raise ForcefieldAssignmentError(
"Can't assign forcefield - this molecule is missing atoms. "
"Use `ForceField.create_prepped_molecule` to add them automatically.",
[])
else:
# TODO: much more rigorous consistency checking
newmol.ff.copy_to(mol)
# deal with residue types that were automatically renamed:
for newres, oldres in zip(newmol.residues, mol.residues):
oldres.resname = newres.resname
def create_prepped_molecule(self, mol, display=True):
from ..interfaces import tleap_interface
clean_molecule = tleap_interface._prep_for_tleap(mol)
job = tleap_interface._run_tleap_assignment(clean_molecule, self._fflines, self._file_list)
if 'output.inpcrd' in job.get_output():
prmtop = job.get_output('output.prmtop')
inpcrd = job.get_output('output.inpcrd')
params = tleap_interface.AmberParameters(prmtop, inpcrd, job)
m = mdt.read_amber(params.prmtop, params.inpcrd)
newmol = mdt.helpers.restore_topology(m, mol)
newmol.ff = mdt.forcefields.ForcefieldParams(newmol, params)
else:
newmol = None
errors = tleap_interface._parse_tleap_errors(job, clean_molecule)
show_parameterization_results(errors, clean_molecule, molout=newmol)
if newmol is not None:
return newmol
else:
raise ForcefieldAssignmentError(
'TLeap failed to assign force field parameters for %s' % mol,
errors, job=job, mol=mol)
def add_ff(self, ff):
self._fflines.extend(ff._fflines)
for fname, fobj in ff._file_list.items():
if fname in self._file_list:
raise ValueError("Can't combine forcefields - two files with same name (%s)"
%fname)
self._file_list.update(ff._file_list)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/forcefields/__init__.py | .py | 173 | 12 | def toplevel(o):
__all__.append(o.__name__)
return o
__all__ = []
from . import errors
from .ffparams import *
from .forcefieldbase import *
from .amber import *
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/forcefields/ffparams.py | .py | 7,010 | 202 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import moldesign as mdt
from moldesign import units as u
class ForcefieldParams(object):
""" Stores the forcefield parameters for a specific molecule.
This is a shim around a parmed object.
Args:
mol (mdt.Molecule): Molecule this force field is for
ffobj (parmed.Structure OR mdt.AmberParms OR Forcefield): forcefield specification
Attributes:
parmed_obj (parmed.Structure): parmed object containing the forcefield parameters
"""
def __init__(self, mol, ffobj):
import parmed
self.mol = mol
if isinstance(ffobj, parmed.Structure):
self.parmed_obj = copy.copy(ffobj)
self.sourcedata = ffobj
elif hasattr(ffobj, 'to_parmed'):
self.sourcedata = ffobj
self.parmed_obj = ffobj.to_parmed()
else:
raise ValueError('Unrecognized force field class "%s"' % ffobj.__class__.__name__)
def copy_to(self, mol):
mol.ff = self.__class__(mol, copy.copy(self.parmed_obj))
return mol.ff
def __setstate__(self, state):
""" Workaround for https://github.com/ParmEd/ParmEd/issues/874
This function can be removed once parmed 0.7.4 is released - AMV 5.19.17
"""
self.__dict__.update(state)
self.parmed_obj.initialize_topology()
def get_atom_terms(self, atom):
return AtomTerms(atom, self.parmed_obj.atoms[atom.index])
def get_bond_term(self, bond_or_atom1, atom2=None):
if atom2 is None:
bond = bond_or_atom1
else:
bond = mdt.Bond(bond_or_atom1, atom2)
pmdatom = self.parmed_obj.atoms[bond.a1.index]
indices = [bond.a1.index, bond.a2.index]
for pmdbond in pmdatom.bonds:
pmdindices = sorted((pmdbond.atom1.idx, pmdbond.atom2.idx))
if pmdindices == indices:
assert self.parmed_obj.atoms[pmdindices[0]].element == bond.a1.atnum
assert self.parmed_obj.atoms[pmdindices[1]].element == bond.a2.atnum
return BondTerm(bond, pmdbond)
else:
raise ValueError("No ForceField term found for bond: %s" % bond)
def get_term(self, *atoms):
pmdterm = self._get_pmd_term(*atoms)
return LEN_TO_TERM[len(atoms)](atoms, pmdterm)
def _get_pmd_term(self, *atoms):
termlist = getattr(self.parmed_obj.atoms[atoms[0].index],
LEN_TO_TERM[len(atoms)].pmdlist)
searchatoms = [self.parmed_obj.atoms[atom.index] for atom in atoms]
for term in termlist:
if term.same_atoms(searchatoms):
return term
else:
raise ValueError("No ForceField term found with atoms: %s" % atoms)
class ParmedAtomAttribute(object):
def __init__(self, attrname, units):
self.attrname = attrname
self.units = units
@staticmethod
def _get_pmd_obj(instance):
return instance.pmdobj
def __get__(self, instance, owner):
obj = self._get_pmd_obj(instance)
return getattr(obj, self.attrname) * self.units
def __set__(self, instance, value):
obj = self._get_pmd_obj(instance)
setattr(obj, self.attrname, value.value_in(self.units))
class ParmedTermAttribute(ParmedAtomAttribute):
@staticmethod
def _get_pmd_obj(instance):
return instance.pmdobj.type
def __set__(self, *args):
# these are defined by *TYPE*, so will need to create singleton classes
# when modifying these terms.
raise NotImplementedError()
class ForceFieldTerm(object):
""" MDT-like proxy for a forcefield term
"""
def __init__(self, mdtobj, pmdobj):
self.mdtobj = mdtobj
self.pmdobj = pmdobj
def __str__(self):
return "%s for %s, ParmEd params %s" % (self.__class__.__name__,
self.mdtobj,
str(self.pmdobj.type)[1:-1]) # strips brackets
def __repr__(self):
return '<%s>' % str(self)
class AtomTerms(ForceFieldTerm):
partial_charge = ParmedAtomAttribute('charge', u.q_e)
ljsigma = ParmedAtomAttribute('sigma', u.angstrom)
ljepsilon = ParmedAtomAttribute('epsilon', u.kcalpermol)
class BondTerm(ForceFieldTerm):
pmdlist = 'bonds'
force_constant = ParmedTermAttribute('k', u.kcalpermol / u.angstrom)
equilibrium_length = ParmedTermAttribute('req', u.angstrom)
class AngleTerm(ForceFieldTerm):
pmdlist = 'angles'
force_constant = ParmedTermAttribute('k', u.kcalpermol / u.degrees)
equilibrium_length = ParmedTermAttribute('req', u.angstrom)
class DihedralTerm(ForceFieldTerm):
pmdlist = 'dihedrals'
force_constant = ParmedTermAttribute('phi_k', u.kcalpermol / u.degrees)
periodicity = ParmedTermAttribute('per', 1)
phase = ParmedTermAttribute('phase', u.degrees)
coulomb_14_factor = ParmedTermAttribute('scee', 1.0)
lj_14_factor = ParmedTermAttribute('scnb', 1.0)
LEN_TO_TERM = {1: AtomTerms, 2: BondTerm, 3: AngleTerm, 4: DihedralTerm}
class FFParameters(object):
""" DEPRACATED: will be removed in favor of ParmEd interface
This object contains assigned force field parameters for a specific system
The base focuses on the AMBER / CHARMM - type force
"""
# TODO: this needs to describe attenuation for things close together
# TODO: deal with nonbonded exceptions
def __init__(self, bonds, angles, dihedrals, partial_charges, lennard_jones):
self.bonds = bonds
self.angles = angles
self.dihedrals = dihedrals
self.partial_charges = partial_charges # maps atoms to their partial charges
self.lennard_jones = lennard_jones # maps atoms to LJ terms
# lookups
self.bond_term = {term.bond: term for term in self.bonds}
self.angle_term = {tuple(term.atoms): term for term in self.angles}
for term in self.angles: self.angle_term[tuple(reversed(term.atoms))] = term
self.dihedral_term = {}
for term in self.dihedrals:
self.dihedral_term.setdefault(tuple(term.atoms), []).append(term)
self.dihedral_term.setdefault(tuple(reversed(term.atoms)), []).append(term)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/integrators/verlet.py | .py | 2,603 | 74 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .. import units as u
from ..molecules import Trajectory
from ..utils import exports
from .base import IntegratorBase
@exports
class VelocityVerlet(IntegratorBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# TODO: raise exception if any constraints are requested ...
def run(self, run_for):
"""
Users won't call this directly - instead, use mol.run
Propagate position, momentum by a single timestep using velocity verlet
:param run_for: number of timesteps OR amount of time to run for
"""
if not self._prepped:
self.prep()
nsteps = self.time_to_steps(run_for, self.params.timestep)
# Set up trajectory and record the first frame
self.mol.time = 0.0 * u.default.time
self.traj = Trajectory(self.mol)
self.mol.calculate()
self.traj.new_frame()
next_trajectory_frame = self.params.frame_interval
# Dynamics loop
for istep in range(nsteps):
self.step()
if istep + 1 >= next_trajectory_frame:
self.traj.new_frame()
next_trajectory_frame += self.params.frame_interval
return self.traj
def prep(self):
self.time = 0.0 * self.params.timestep
self._prepped = True
def step(self):
# Move momenta from t-dt to t-dt/2
phalf = self.mol.momenta + 0.5 * self.params.timestep * self.mol.calc_forces(wait=True)
# Move positions from t-dt to t
self.mol.positions += phalf * self.params.timestep / self.mol.dim_masses
# Move momenta from t-dt/2 to t - triggers recomputed forces
self.mol.momenta = phalf + 0.5 * self.params.timestep * self.mol.calc_forces(wait=True)
self.time += self.params.timestep
self.mol.time = self.time
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/integrators/__init__.py | .py | 63 | 4 | from . import base
from .verlet import *
from .openmm import *
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/integrators/base.py | .py | 2,301 | 66 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from moldesign import parameters
from moldesign.method import Method
class IntegratorBase(Method):
"""Base class for all integrators"""
PARAMETERS = list(parameters.integrator_parameters.values())
def run(self, run_for):
"""
To be called by parent molecule
:param run_for: number of steps (if integer), or amount of time (if has units of time)
:return: trajectory
"""
raise NotImplementedError('This is an abstract base class!')
def prep(self):
"""
Prepare to run. Possibly do a test run.
This might need to call the mol.model.build. Make sure you don't have a
circular call here
:return:
"""
raise NotImplementedError()
@staticmethod
def time_to_steps(time, timestep):
try:
dims = time.dimensionality
assert len(dims) == 1 and dims['[time]'] == 1.0
except (AttributeError, AssertionError):
assert isinstance(time, int), "argument to integrator.run must have units of time or be an int"
return time
else:
return int(round(float(time / timestep)))
class MDBase(IntegratorBase):
PARAMETERS = IntegratorBase.PARAMETERS + list(parameters.md_parameters.values())
class ConstantTemperatureBase(MDBase):
PARAMETERS = MDBase.PARAMETERS + list(parameters.constant_temp_parameters.values())
class LangevinBase(ConstantTemperatureBase):
PARAMETERS = ConstantTemperatureBase.PARAMETERS + list(parameters.langevin_parameters.values()) | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/integrators/openmm.py | .py | 4,202 | 118 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pyccc
import pyccc.exceptions
from .. import exceptions
from ..compute import packages
from ..interfaces.openmm import MdtReporter, pint2simtk, OpenMMPickleMixin
from ..utils import exports
from .base import IntegratorBase, LangevinBase
class OpenMMBaseIntegrator(IntegratorBase, OpenMMPickleMixin):
_openmm_compatible = True
def prep(self):
if not self.mol.energy_model._openmm_compatible:
raise exceptions.NotSupportedError(
("%s requires an OpenMM-based energy model (current "
"energy model '%s' is not supported with this integrator") %
(self.mol.energy_model.__class__.__name__, self.__class__.__name__))
# For OpenMM integrators, all system setup is delegated to the energy model
# this will create values for self.energy_model, self.sim, and and self._prepped
self.mol.energy_model.prep()
def run(self, run_for, wait=False):
try:
traj = self._run(run_for)
except pyccc.exceptions.ProgramFailure:
raise pyccc.exceptions.ProgramFailure(
'OpenMM crashed silently. Please examine the output. '
'This may be due to large forces from, for example, '
'an insufficiently minimized starting geometry.')
if packages.openmm.force_remote or (not wait):
self.mol.energy_model._sync_remote(traj.mol)
traj.mol = self.mol
return traj
@packages.openmm.runsremotely(is_imethod=True)
def _run(self, run_for):
self.prep()
self.energy_model._set_constraints() # calling this just to raise an exception if necessary
nsteps = self.time_to_steps(run_for, self.params.timestep)
self.energy_model._set_openmm_state()
self.reporter = self._attach_reporters()
self.reporter.annotation = self._describe_dynamics()
self.reporter.report_from_mol()
self.sim.step(nsteps) # this is the actual dynamics loop
self.energy_model._sync_to_openmm()
if self.reporter.last_report_time != self.mol.time:
self.reporter.report_from_mol()
return self.reporter.trajectory
def _attach_reporters(self):
"""
Make sure the simulation has reporters for this run
:return:
"""
report_interval = self.time_to_steps(self.params.frame_interval,
self.params.timestep)
reporter = MdtReporter(self.mol, report_interval)
self.sim.reporters = [reporter]
return reporter
def _describe_dynamics(self):
raise NotImplementedError()
@exports
class OpenMMVerlet(OpenMMBaseIntegrator):
def get_openmm_integrator(self):
from simtk import openmm
integrator = openmm.VerletIntegrator(pint2simtk(self.params.timestep))
return integrator
def _describe_dynamics(self):
return 'Constant energy dynamics'
@exports
class OpenMMLangevin(LangevinBase, OpenMMBaseIntegrator):
def get_openmm_integrator(self):
from simtk import openmm
integrator = openmm.LangevinIntegrator(
pint2simtk(self.params.temperature),
pint2simtk(self.params.collision_rate),
pint2simtk(self.params.timestep))
return integrator
def _describe_dynamics(self):
return 'Langevin dynamics @ %s' % self.params.temperature
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/residue.py | .py | 17,344 | 487 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from past.builtins import basestring
import collections
import moldesign as mdt
from .. import utils, data
from . import MolecularHierarchy, AtomList, toplevel, ChildList
@toplevel
class Residue(MolecularHierarchy):
""" A biomolecular residue - most often an amino acid, a nucleic base, or a solvent
molecule. In PDB structures, also often refers to non-biochemical molecules.
Its children are almost always residues.
Attributes:
parent (mdt.Molecule): the molecule this residue belongs to
chain (Chain): the chain this residue belongs to
"""
@utils.args_from(MolecularHierarchy)
def __init__(self, **kwargs):
""" Initialization
Args:
**kwargs ():
"""
self.chain = kwargs.get('chain', None)
super().__init__(**kwargs)
if self.index is None and self.molecule is not None:
self.index = self.molecule.residues.index(self)
self.chainindex = None
self._backbone = None
self._sidechain = None
self._template_name = None
self._name = None
def copy(self):
""" Create a copy of this residue and all topology within.
Returns:
Residue: copy of this residue and all its atoms. This copy will NOT
reference any parent molecule
"""
newatoms = super().copy_atoms()
return newatoms[0].residue
def _subcopy(self, memo=None):
""" Private data mangement method for copying a residue.
Returns a shallow copy intended to be deepcopied to avoid corrupting the original
data.
See :method:`moldesign.Residue.copy` for the public interface for copying these objects.
"""
import copy
if memo is None:
memo = {'bondgraph':{}}
if self in memo:
return
newresidue = copy.copy(self)
newresidue.chain = None
newresidue.molecule = None
newresidue.children = ChildList(newresidue)
memo[self] = newresidue
if self.chain is not None:
if self.chain not in memo:
newchain = copy.copy(self.chain)
newchain.molecule = None
newchain.children = ChildList(newchain)
memo[self.chain] = newchain
memo[self.chain].add(newresidue)
@property
def name(self):
if self._name is not None:
return self._name
elif self.pdbname is None:
return None
elif self.pdbindex is None:
return self.pdbname
elif self.pdbname[-1].isdigit():
return '%s (seq # %s)' % (self.pdbname, self.pdbindex)
else:
return self.pdbname + str(self.pdbindex)
def _repr_markdown_(self):
return self.markdown_summary()
def markdown_summary(self):
""" Markdown-formatted information about this residue
Returns:
str: markdown-formatted string
"""
if self.type == 'placeholder':
return '`%s`'%repr(self)
if self.molecule is None:
lines = ["<h3>Residue %s</h3>"%self.name]
else:
lines = ["<h3>Residue %s (index %s)</h3>"%(self.name, self.index)]
if self.type == 'protein':
lines.append('**Residue codes**: %s / %s'%(self.resname, self.code))
else:
lines.append("**Residue code**: %s"%self.resname)
lines.append('**Type**: %s'%self.type)
if self.resname in data.RESIDUE_DESCRIPTIONS:
lines.append('**Description**: %s'%data.RESIDUE_DESCRIPTIONS[self.resname])
lines.append('**<p>Chain:** %s'%self.chain.name)
lines.append('**PDB sequence #**: %s'%self.pdbindex)
terminus = None
if self.type == 'dna':
if self.is_3prime_end:
terminus = "3' end"
elif self.is_5prime_end:
terminus = "5' end"
elif self.type == 'protein':
if self.is_n_terminal:
terminus = 'N-terminus'
elif self.is_c_terminal:
terminus = 'C-terminus'
if terminus is not None:
lines.append('**Terminal residue**: %s of chain %s'%(terminus, self.chain.name))
if self.molecule is not None:
lines.append("**Molecule**: %s"%self.molecule.name)
lines.append("**<p>Number of atoms**: %s"%self.num_atoms)
if self.backbone:
lines.append("**Backbone atoms:** %s"%', '.join(x.name for x in self.backbone))
lines.append("**Sidechain atoms:** %s"%', '.join(x.name for x in self.sidechain))
else:
lines.append("**Atom:** %s"%', '.join(x.name for x in self.atoms))
return '<br>'.join(lines)
@name.setter
def name(self, value):
self._name = value
@property
def atoms(self):
return self.children
@property
def bonded_residues(self):
""" List[moldesign.Residue]: list of residues this residue is bonded to
"""
residues = collections.OrderedDict()
for atom in self.bonded_atoms:
residues[atom.residue] = None
return list(residues.keys())
def add(self, atom, key=None):
"""Deals with atom name clashes within a residue - common for small molecules"""
if atom.residue is not None:
assert atom.residue is self, 'Atom already assigned to a residue'
atom.residue = self
if key is not None or atom.name not in self.children:
return super().add(atom, key=key)
else:
return super().add(atom, key='%s%s' % (atom.name, len(self)))
add.__doc__ = MolecularHierarchy.add.__doc__
@property
def is_n_terminal(self):
"""bool: this is the last residue in a peptide
Raises:
ValueError: if this residue is not an amino acid
"""
if self.type != 'protein':
raise ValueError('%s is not a recognized peptide monomer' % self)
return self._is_starting_residue
@property
def is_c_terminal(self):
"""bool: this is the first residue in a peptide
Raises:
ValueError: if this residue is not an amino acid
"""
if self.type != 'protein':
raise ValueError('%s is not a recognized peptide monomer' % self)
return self._is_ending_residue
@property
def is_5prime_end(self):
"""bool: this is the first base in a strand
Raises:
ValueError: if this residue is not a DNA base
"""
if self.type != 'dna':
raise ValueError('%s is not a recognized nucleic acid monomer' % self)
return self._is_starting_residue
@property
def is_3prime_end(self):
"""bool: this is the last base in a strand
Raises:
ValueError: if this residue is not a DNA base
"""
if self.type != 'dna':
raise ValueError('%s is not a recognized nucleic acid monomer' % self)
return self._is_ending_residue
@property
def is_monomer(self):
"""bool: this residue is not part of a biopolymer
"""
return self._is_ending_residue and self._is_starting_residue
@property
def _is_ending_residue(self):
"""bool: this is the last residue in a polymer"""
try:
nextres = self.next_residue
except StopIteration:
return True
except KeyError:
# If we're here, the residue is missing some atoms. We'll fall back to checking the
# next residues in line
if self.index == len(self.molecule.residues) - 1:
return True
else:
print('WARNING: %s is missing expected atoms. Attempting to infer chain end' % self)
nextres = self.molecule.residues[self.index + 1]
return not self._same_polymer(nextres)
else:
return False
@property
def _is_starting_residue(self):
"""bool: this is the first residue in a polymer"""
try:
prevres = self.prev_residue
except StopIteration:
return True
except KeyError:
# If we're here, the residue is missing some atoms. We'll fall back to checking the
# next residues in line
if self.index <= 0:
assert self.index == 0
return True
else:
print('WARNING: %s is missing expected atoms. Attempting to infer chain start' % \
self)
nextres = self.molecule.residues[self.index - 1]
return not self._same_polymer(nextres)
else:
return False
def _same_polymer(self, otherres):
return (otherres.type == self.type) and (otherres.chain is self.chain)
def assign_template_bonds(self):
"""Assign bonds from bioresidue templates.
Only assigns bonds that are internal to this residue (does not connect different residues).
The topologies here assume pH7.4 and may need to be corrected for other pHs
See Also:
:ref:`moldesign.Chain.assign_biopolymer_bonds` for assigning inter-residue bonds
Raises:
ValueError: if ``residue.resname`` is not in bioresidue templates
KeyError: if an atom in this residue is not recognized """
try:
resname = self.resname
if self.type == 'protein':
if self.is_n_terminal:
resname = self.resname + '_LSN3' # the protonated form (with NH3+ on the end)
elif self.is_c_terminal:
resname = self.resname + '_LEO2H' # deprotonated form (COO-)
elif self.is_monomer:
resname = self.resname + '_LFZW' # free zwitterion form
bonds_by_name = data.RESIDUE_BONDS[resname]
self._template_name = resname
except KeyError:
if len(self) == 1 and self.type not in ('water', 'ion'):
print('INFO: no bonds assigned to residue %s' % self)
return
else:
raise KeyError("No bonding template for residue '%s'" % resname)
# intra-residue bonds
bond_graph = {atom: {} for atom in self}
for atom in self:
for nbrname, order in bonds_by_name.get(atom.name, {}).items():
try:
nbr = self[nbrname]
except KeyError: # missing atoms are normal (often hydrogen)
pass
else:
bond_graph[atom][nbr] = bond_graph[nbr][atom] = order
# copy bonds into the right structure (do this last to avoid mangling the graph)
for atom in bond_graph:
atom.bond_graph.update(bond_graph[atom])
@property
def next_residue(self):
"""Residue:
The next residue in the chain (in the C-direction for proteins, 3'
direction for nucleic acids)
Raises:
NotImplementedError: If we don't know how to deal with this type of biopolymer
StopIteration: If there isn't a next residue (i.e. it's a 3'- or C-terminus)
"""
if self.chain.type == 'protein':
return self._get_neighbor('C', 'C-terminus')
elif self.chain.type == 'dna':
return self._get_neighbor("O3'", "3' end")
else:
raise NotImplementedError('We only deal with dna and amino acids right now')
@property
def prev_residue(self):
"""Residue: The next residue in the chain (in the N-direction for proteins, 5' direction for
nucleic acids)
Raises:
NotImplementedError: If we don't know how to deal with this type of biopolymer
StopIteration: If there isn't a previous residue (i.e. it's a 5'- or N-terminus)
"""
if self.chain.type == 'protein':
return self._get_neighbor('N', 'N-terminus')
elif self.chain.type == 'dna':
try:
return self._get_neighbor("P", "5' end")
except KeyError:
raise StopIteration("No 5' bond for this residue")
else:
raise NotImplementedError('We only deal with dna and amino acids right now')
def _get_neighbor(self, atomname, name):
"""Return the first residue found that's bound to the passed atom name
"""
conn_atom = self[atomname]
for nbr in conn_atom.bond_graph:
if nbr.residue is not self:
return nbr.residue
else:
raise StopIteration('%s reached' % name)
@property
def resname(self):
"""str: Synonym for pdbname"""
return self.pdbname
@resname.setter
def resname(self, val):
self.pdbname = val
@property
def type(self):
"""str: Classification of the residue (protein, solvent, dna, water, unknown)"""
return data.RESIDUE_TYPES.get(self.resname, 'unknown')
@property
def code(self):
"""str: one-letter amino acid code or two letter nucleic acid code, or '?' otherwise"""
return data.RESIDUE_ONE_LETTER.get(self.pdbname, '?')
@property
def atomnames(self):
"""Residue: synonym for ```self``` for for the sake of readability:
```molecule.chains['A'].residues[123].atomnames['CA']```
"""
return self
@property
def backbone(self):
""" AtomList: all backbone atoms for nucleic and protein residues
(indentified using PDB names); returns None for other residue types
"""
if self._backbone is None:
if self.type not in data.BACKBONES:
return None
self._backbone = AtomList()
for name in data.BACKBONES[self.type]:
try:
self._backbone.append(self[name])
except KeyError:
pass
return self._backbone
@property
def sidechain(self):
""" AtomList: all sidechain atoms for nucleic and protein residues
(defined as non-backbone atoms); returns None for other residue types
"""
if self._sidechain is None:
if self.backbone is None:
return None
bb = set(self.backbone)
self._sidechain = [atom for atom in self if atom not in bb]
return self._sidechain
@property
def is_standard_residue(self):
""" bool: this residue is a "standard residue" for the purposes of a PDB entry.
In PDB files, this will be stored using 'ATOM' if this is a standard residue
and 'HETATM' records if not.
Note:
We currently define "standard" residues as those whose 3 letter residue code appears in
the ``moldesign.data.RESIDUE_DESCRIPTIONS`` dictionary. Although this seems to work
well, we'd welcome a PR with a less hacky method.
References:
PDB format guide: http://www.wwpdb.org/documentation/file-format
"""
return self.resname in mdt.data.RESIDUE_DESCRIPTIONS
def __str__(self):
return 'Residue %s (index %s, chain %s)' % (self.name, self.index, self.chain.name)
class HasResidues(object):
""" Mixin for classes that *contain* residues (i.e. Molecules and Chains)
"""
def get_residues(self, **queries):
"""Allows keyword-based residue queries. Returns residues that match ALL queries.
Args:
**queries (dict): attributes (or residue attributes) to match
Examples:
>>> mol.get_residues(type='protein') # returns all amino acid residues in molecule
>>> mol.chains['A'].get_residues(resname='ALA') # returns all alanines in chain A
>>> mol.get_residues(chain='A') # all residues in chain A
Returns:
List[Residues]: residues matching the query
"""
if not queries:
return list(self.residues)
result = []
for res in self.residues:
for field, val in queries.items():
if field == 'chain' and isinstance(val, basestring):
if res.chain.name != val:
break
else:
continue
elif getattr(res, field, None) != val:
break
else:
result.append(res)
return result | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/bonds.py | .py | 7,733 | 236 | # coding: utf-8
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from past.builtins import basestring
import numpy as np
from . import toplevel
from .. import units as u
from .. import mathutils
from .. import geom
@toplevel
class Bond(object):
"""
A bond between two atoms.
Args:
a1 (Atom): First atom
a2 (Atom): Second atom (the order of atoms doesn't matter)
Notes:
Comparisons and hashes involving bonds will return True if the atoms involved in the bonds
are the same. ``Bond`` objects are _views_ on the BondGraph object; there may be zero, one,
or many ``Bond`` objects corresponding to any given chemical bond.
Attributes:
a1 (Atom): First atom in the bond; assigned so that ``self.a1.index < self.a2.index``
a2 (Atom): Second atom in the bond; assigned so that ``self.a2.index > self.a1.index``
order (int or None): order of the bond between the atoms (or None of they are not bonded)
"""
SYMBOLS = {1: u'-', 2: u'=', 3: u'≡'}
def __init__(self, a1, a2):
if a1.molecule is not a2.molecule:
raise ValueError('Cannot create bond for atoms in different molecules.')
if a1.index is not None and a2.index is not None and a1.index > a2.index:
a1, a2 = a2, a1
self.a1 = a1
self.a2 = a2
def __str__(self):
return "%s bond between %s and %s (order: %s)" % (self.type,
self.a1._shortstr(), self.a2._shortstr(),
self.order)
def __repr__(self):
return "<%s>" % self
@property
def order(self):
a1order = self.a1.bond_graph.get(self.a2, None)
a2order = self.a2.bond_graph.get(self.a1, None)
if a1order == a2order:
return a1order
elif a1order is None:
return a2order
elif a2order is None:
return a1order
else: # inconsistent
raise ValueError('Inconsistent bond orders between %s and %s' % (self.a1, self.a2))
@order.setter
def order(self, order):
if order is None: # i.e., delete the bond if it exists
if self.order is None:
return # already done
elif self.molecule:
self.molecule.delete_bond(self)
else:
self.a1.bond_graph.pop(self.a2, None)
self.a2.bond_graph.pop(self.a1, None)
else: # create the bond or modify its order
for atom in (self.a1, self.a2):
nbr = self.partner(atom)
if atom.molecule is self.molecule:
atom.bond_graph[nbr] = order
@property
def exists(self):
""" bool: whether or not this bond exists
"""
return self.order is not None
@property
def type(self):
return self.a1.symbol + self.SYMBOLS.get(self.order, u'?̶') + self.a2.symbol
def __eq__(self, other):
return (self.a1 is other.a1) and (self.a2 is other.a2)
def __hash__(self):
"""Has this object using the atoms involved in its bond"""
return hash((self.a1, self.a2))
def partner(self, atom):
""" Return this atom's *partner* in the bond -- i.e., the other atom in the bond
Args:
atom (mdt.Atom): return the atom that this one is bonded to
Returns:
mdt.Atom: the passed atom's partner
Raises:
ValueError: if the passed atom is not part of this bond
"""
if atom is self.a1:
return self.a2
elif atom is self.a2:
return self.a1
else:
raise ValueError('%s is not part of this bond' % atom)
@property
def length(self):
return self.a1.distance(self.a2)
@length.setter
def length(self, value):
geom.set_distance(self.a1, self.a2, value,
adjustmol=self.exists and not self.is_cyclic)
@property
def name(self):
""" str: name of the bond """
return '{a1.name} (#{a1.index}) - {a2.name} (#{a2.index}) (order: {order})'.format(
a1=self.a1, a2=self.a2, order=self.order)
@property
def molecule(self):
"""moldesign.Molecule: molecule this bond belongs to (or None if not assigned
Raises:
ValueError: if the atoms are assigned to different molecules
"""
if self.a1.molecule is not self.a2.molecule:
raise ValueError("Atoms in %s belong to different molecules" % self)
else:
return self.a1.molecule
@property
def midpoint(self):
return (self.a1.position + self.a2.position) / 2.0
@property
def is_cyclic(self):
"""
bool: True if this bond is in one or more rings
"""
visited = set([self.a2])
def check_for_cycles(atom):
visited.add(atom)
for nbr in atom.bond_graph:
if nbr is self.a2 and atom is not self.a1:
return True
if nbr not in visited:
in_cycle = check_for_cycles(nbr)
if in_cycle:
return True
return False # if here, not in a cycle
check_for_cycles(self.a1)
def align(self, other, centered=True):
""" Rotates the entire molecule to align this bond with another object.
Args:
other (str or Vector[len=3] or Bond): Object to align this bond with, which may be:
- a string: 'x', 'y', or 'z',
- a len-3 vector, or
- another :class:`Bond` object
centered (bool): if True (default), center this bond at the origin OR the midpoint of
the other bond
"""
mol = self.molecule
centering = -self.midpoint
if isinstance(other, Bond):
direction = (other.a2.position - other.a1.position).normalized()
if centered:
centering += other.midpoint
elif isinstance(other, basestring):
arr = np.zeros(3)
arr[DIMLABELS[other]] = 1.0
direction = arr
else:
direction = other
target = mathutils.normalized(u.array(direction))
vec = (self.a2.position - self.a1.position).normalized()
angle, normal = mathutils.alignment_rotation(vec, target)
if centered:
mol.positions += centering
if abs(mathutils.normalize_angle(angle)) > 1e-3 * u.degrees:
mol.rotate(angle, normal, center=self.midpoint)
@property
def ff(self):
"""mdt.forcefield.BondTerm: the force-field term for this bond (or ``None`` if no
forcefield is present)
"""
if self.molecule.ff is not None:
return self.molecule.ff.get_bond_term(self)
else:
return None
DIMLABELS = {'x': 0, 'y': 1, 'z':2}
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/atomcollections.py | .py | 17,857 | 523 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from past.builtins import basestring
import copy
import collections
import itertools
import numpy as np
import moldesign as mdt
from .. import units as u
from .. import utils, external, mathutils, widgets
from . import toplevel
class AtomGroup(object):
""" Mixin functions for objects that have a ``self.atoms`` attribute with a list of atoms
Attributes:
atoms (List[Atom]): a list of atoms
"""
draw2d = widgets.WidgetMethod('atomgroups.draw2d')
draw3d = widgets.WidgetMethod('atomgroups.draw3d')
draw = widgets.WidgetMethod('atomgroups.draw')
def __init__(self, *args, **kwargs):
""" This should never be called directly - it will be called by the `super` methods
of its subclasses """
super().__init__(*args, **kwargs)
self._atom_attrs = None
self.viz2d = None
self.viz3d = None
@property
def num_atoms(self):
""" int: number of atoms in this object """
return len(self.atoms)
natoms = num_atoms
@property
def heavy_atoms(self):
""" AtomList: a list of all heavy atoms (i.e., non-hydrogen) in this object """
return AtomList([a for a in self.atoms if a.atnum != 1])
@property
def mass(self):
""" u.Scalar[mass]: total mass of this object
"""
return u.unitsum(a.mass for a in self.atoms)
@property
def momentum(self):
""" u.Vector[momentum]: total momentum of this object
"""
return self.momenta.sum(axis=0)
@property
def velocity(self):
""" u.Vector[velocity]: center of mass velocity of this object
"""
return self.momentum/self.mass
@property
def kinetic_energy(self):
r""" u.Scalar[energy]: Classical kinetic energy :math:`\sum_{\text{atoms}} \frac{p^2}{2m}`
"""
from ..helpers import kinetic_energy
return kinetic_energy(self.momenta, self.masses)
def get_atoms(self, *keywords, **queries):
"""Allows keyword-based atom queries. Returns atoms that match ALL queries.
Args:
*keywords (list): pre-set keywords (currently, just selects by residue type)
**queries (dict): attributes (or residue attributes) to match
Examples:
>>> mol.get_atoms('protein') # returns all atoms in proteins
>>> mol.get_atoms(name='CA') # returns all alpha carbons
>>> mol.get_atoms('dna', symbol='P') # returns all phosphorus in DNA
Returns:
AtomList: the atoms matching this query
"""
if not (queries or keywords):
return mdt.AtomList(self.atoms)
atoms = self.atoms
KEYS = 'protein dna rna water unknown ion'.split()
for key in keywords:
if key in KEYS:
atoms = mdt.AtomList(atom for atom in atoms
if atom.residue.type == key)
else:
raise ValueError("Invalid keyword '%s': valid values are %s" % (key, KEYS))
result = mdt.AtomList()
for atom in atoms:
for field, val in queries.items():
if getattr(atom, field, None) != val and getattr(atom.residue, field, None) != val:
break
else:
result.append(atom)
return result
def calc_distance_array(self, other=None):
""" Calculate an array of pairwise distance between all atoms in self and other
Args:
other (AtomContainer): object to calculate distances to (default: self)
Returns:
u.Array[length]: 2D array of pairwise distances between the two objects
Example:
>>> dists = self.calc_distance_array(other)
>>> dists[i, j] == self.atoms[i].distance(other.atoms[j])
"""
from scipy.spatial.distance import cdist
other = utils.if_not_none(other, self)
try:
other_positions = other.positions.defunits_value()
except AttributeError:
other_positions = np.array([other.position.defunits_value()])
distances = cdist(self.positions.defunits_value(), other_positions)
return distances * u.default.length
def calc_displacements(self):
""" Calculate an array of displacements between all atoms in this object
Returns:
u.Array[length]: array of pairwise displacements between atoms
Example:
>>> displacements = self.calc_displacements(other)
>>> displacements[i, j] == (self.atoms[i].position - self.atoms[j].position)
"""
# TODO: allow other, similar to calc_distance array
return utils.pairwise_displacements(self.positions)
def distance(self, other):
"""Returns closest distance between this and the other entity
Args:
other (AtomContainer): object to calculate distance to
Returns:
u.Scalar[length]: closest distance between self and other
Example:
>>> distance = self.distance(other)
>>> distance == self.calc_distance_array(other).min()
"""
distance_array = self.calc_distance_array(other)
return distance_array.min()
@property
def center_of_mass(self):
""" units.Vector[length]: The (x,y,z) coordinates of this object's center of mass """
if self.num_atoms == 0: # nicer exception than divide-by-zero
raise ValueError('"%s" has no atoms' % str(self))
total_mass = 0.0 * u.default.mass
com = np.zeros(3) * u.default.length * u.default.mass
for atom in self.atoms:
total_mass += atom.mass
com += atom.position * atom.mass
com = com / total_mass
return com
@center_of_mass.setter
def center_of_mass(self, value):
vec = value - self.com
self.translate(vec)
com = center_of_mass # synonym
def _getatom(self, a):
""" Given an atom's name, index, or object, return the atom object
"""
if a is None:
return None
elif isinstance(a, basestring) or isinstance(a, int):
return self[a]
else:
return a
def angle(self, a1, a2, a3):
""" Calculate the angle between three atoms.
Atoms can be passed as the atoms themselves or as the atom names
Args:
a1, a2, a3 (str OR int OR moldesign.Atom): atoms defining the angle
Returns:
units.Scalar[angle]
"""
# TODO: use single dispatch to also accept two bonds
return mdt.geom.angle(*list(map(self._getatom, (a1, a2, a3))))
def dihedral(self, a1, a2, a3=None, a4=None):
""" Calculate the dihedral angle between atoms a1, a2, a3, a4.
Atoms can be passed as the atoms themselves or as the atom names
Args:
a1, a2, a3, a4 (str OR int OR moldesign.Atom): atoms defining the dihedral
Returns:
units.Scalar[angle]
"""
return mdt.geom.dihedral(*list(map(self._getatom, (a1, a2, a3, a4))))
def copy_atoms(self):
""" Copy a group of atoms along and relevant topological information.
This specifically copies:
- the atoms themselves (along with their positions, momenta, and bond graphs)
- any residues they are are part of
- any chains they are part of
- any bonds between them
It does NOT copy:
- other atoms that are part of these atoms' residues
- other residues that are part of these atoms chains
- the molecule these atoms are part of
Returns:
AtomList: list of copied atoms
"""
graph = {}
memo = {'bondgraph':graph}
for atom in self.atoms:
atom._subcopy(memo)
tempatoms = [memo[atom] for atom in self.atoms]
newatoms, newbonds = copy.deepcopy((tempatoms, graph))
for atom in newatoms:
atom.bond_graph = newbonds[atom]
return AtomList(newatoms)
###########################################
# Routines to modify the geometry
def rotate(self, angle, axis, center=None):
"""Rotate this object in 3D space
Args:
angle (u.Scalar[angle]): angle to rotate by
axis (u.Vector[length]): axis to rotate about (len=3)
center (u.Vector[length]): center of rotation (len=3) (default: origin)
"""
center = utils.if_not_none(center, self.com)
if hasattr(angle, 'units'): angle = angle.value_in(u.radians)
rotmat = external.transformations.rotation_matrix(angle, axis, point=center)
self.transform(rotmat)
def translate(self, vector):
"""Translate this object in 3D space
Args:
vector (u.Vector[length]): translation vector, len=3
"""
for atom in self.atoms:
atom.position += vector
def transform(self, matrix):
""" Transform this object's coordinates using the provided 4x4 matrix
Args:
matrix (numpy.ndarray): transformation matrix, shape=(4,4)
"""
# TODO: deal with units ... hard because the matrix has diff units for diff columns
assert matrix.shape == (4, 4)
self.positions = mathutils.apply_4x4_transform(matrix, self.positions)
def atoms_within(self, radius, other=None, include_self=False):
""" Return all atoms in an object within a given radius of this object
Args:
radius (u.Scalar[length]): radius to search for atoms
other (AtomContainer): object containing the atoms to search (default:self.molecule)
include_self (bool): if True, include the atoms from this object (since, by definition,
their distance from this object is 0)
Returns:
AtomList: list of the atoms within ``radius`` of this object
"""
if other is None:
other = self.atoms[0].molecule
if not include_self:
filter_atoms = set(self.atoms)
else:
filter_atoms = set()
distances = self.calc_distance_array(other=other)
mindists = distances.min(axis=0)
close_atoms = AtomList(atom for dist,atom in zip(mindists, other.atoms)
if dist <= radius and atom not in filter_atoms)
return close_atoms
def residues_within(self, radius, other=None, include_self=False):
""" Return all atoms in an object within a given radius of this object
Args:
radius (u.Scalar[length]): radius to search for atoms
other (AtomContainer): object containing the atoms to search (default:self.molecule)
include_self (bool): if True, include the atoms from this object (since, by definition,
their distance from this object is 0)
Returns:
AtomList: list of the atoms within ``radius`` of this object
"""
atoms = self.atoms_within(radius, other=other, include_self=include_self)
residues = collections.OrderedDict((atom.residue, None) for atom in atoms)
return list(residues.keys())
class _AtomArray(object):
def __init__(self, attrname):
self.attrname = attrname
def __get__(self, instance, owner):
return u.array([getattr(atom, self.attrname) for atom in instance.atoms])
def __set__(self, instance, value):
assert len(value) == instance.num_atoms
for atom, atomval in zip(instance.atoms, value):
setattr(atom, self.attrname, atomval)
class AtomContainer(AtomGroup):
"""
Mixin functions for NON-MOLECULE objects that have a list of atoms at``self.atoms``
"""
positions = _AtomArray('position')
masses = _AtomArray('mass')
momenta = _AtomArray('momentum')
velocities = _AtomArray('velocity')
def __add__(self, other):
l = mdt.AtomList(self.atoms)
l.extend(other.atoms)
return l
@property
def bond_graph(self):
""" Dict[moldesign.Atom: List[moldesign.Atom]]: bond graph for all atoms in this object
"""
return {atom: atom.bond_graph for atom in self.atoms}
@property
def bonds(self):
""" Iterable[moldesign.Bond]: iterator over bonds from this object's atoms
"""
bg = self.bond_graph
for atom, nbrs in bg.items():
for nbr, order in nbrs.items():
if atom.index < nbr.index or nbr not in bg:
yield mdt.Bond(atom, nbr)
def get_bond(self, a1, a2):
return mdt.Bond(a1, a2)
@property
def internal_bonds(self):
""" Iterable[moldesign.Bond]: iterator over bonds that connect two atoms in this object
"""
bg = self.bond_graph
for atom, nbrs in bg.items():
for nbr, order in nbrs.items():
if atom.index < nbr.index and nbr in bg:
yield mdt.Bond(atom, nbr)
@property
def external_bonds(self):
"""
Iterable[moldesign.Bond]: iterator over bonds that bond these atoms to other atoms
"""
bg = self.bond_graph
for atom, nbrs in bg.items():
for nbr, order in nbrs.items():
if nbr not in bg:
yield mdt.Bond(atom, nbr)
@property
def bonded_atoms(self):
""" List[moldesign.Atom]: list of external atoms this object is bonded to
"""
bg = self.bond_graph
atoms = []
for atom, nbrs in bg.items():
for nbr, order in nbrs.items():
if nbr not in bg:
atoms.append(nbr)
return atoms
def bonds_to(self, other):
""" Returns list of bonds between this object and another one
Args:
other (AtomContainer): other object
Returns:
List[moldesign.Bond]: bonds between this object and another
"""
bonds = []
otheratoms = set(other.atoms)
for bond in self.internal_bonds:
if bond.a1 in otheratoms or bond.a2 in otheratoms:
bonds.append(bond)
return bonds
@toplevel
class AtomList(AtomContainer, list): # order is important, list will override methods otherwise
""" A list of atoms with various helpful methods for creating and manipulating atom selections
Args:
atomlist (List[AtomContainer]): list of objects that are either atoms or contain a list of
atoms at ``atomlist.atoms``
"""
def __init__(self, atomlist=()):
atoms = []
for obj in atomlist:
if hasattr(obj, 'atoms'):
atoms.extend(obj.atoms)
else:
atoms.append(obj)
super().__init__(atoms)
def __getitem__(self, item):
result = super().__getitem__(item)
if isinstance(item, slice):
return type(self)(result)
else:
return result
def __getslice__(self, i, j):
result = super().__getslice__(i, j)
return type(self)(result)
def __str__(self):
return '[Atoms: %s]' % ', '.join(atom._shortstr() for atom in self)
def __repr__(self):
try:
return '<AtomList: [%s]>' % ', '.join(atom._shortstr() for atom in self)
except (KeyError, AttributeError):
return '<AtomList at %x (__repr__ failed)>' % id(self)
copy = AtomContainer.copy_atoms
def intersection(self, *otherlists):
""" Return a list of atoms that appear in all lists (including this one).
Args:
*otheriters (Iterable): one or more lists of atoms
Returns:
moldesign.AtomList: intersection of this lists with all passed lists. Preserves order
in this list
"""
s = set(self).intersection(*otherlists)
return type(self)(o for o in self if o in s)
def union(self, *otherlists):
""" Return a list of atoms that appear in any lists (including this one).
Args:
*otherlists (Iterable): one or more lists of atoms
Returns:
moldesign.AtomList: union of this list of atoms with all passed lists of atoms.
Equivalent to concatenating all lists then removing duplicates
"""
found = set()
newlist = type(self)()
for item in itertools.chain(self, *otherlists):
if item not in found:
found.add(item)
newlist.append(item)
return newlist
def unique(self):
""" Return only unique atoms from this list
Returns:
moldesign.AtomList: copy of this list without any duplicates. Preserves order.
"""
return self.union()
def __sub__(self, other):
otherset = set(other)
return type(self)(atom for atom in self if atom not in otherset)
# alias for self so that this works with AtomContainer methods
@property
def atoms(self):
return self
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/primary_structure.py | .py | 7,384 | 202 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
from . import MolecularHierarchy, Residue, Chain, ChildList
from .. import utils
# TODO: fully delegate all biochemical property management and views to this object.
# TODO: atom.residue, atom.chain, mol.residues should all delegate to PrimaryStructure
class PrimaryStructure(MolecularHierarchy):
""" A tree-like structure that encapsulates the biochemical organization of a ``Molecule``
*Most* of the state related to the biochemical hierarchy is stored
here, with one major exception: each atom stores a reference to its containing residue. That
data must be consistent with the data in this object
Args:
mol (moldesign.Molecule): molecule this object stores hierarchy for
"""
def __init__(self, mol):
super().__init__(molecule=mol, name='root')
self._defchain = Chain(name=None,
index=None,
molecule=None)
self._defres = Residue(name=None,
index=None,
pdbindex=None,
pdbname=None,
chain=self._defchain,
molecule=None)
self.residues = None
def __str__(self):
return str(self.children)
def __repr__(self):
return '<Molecule instance: %s>' % str(self.children)
def rebuild_hierarchy(self):
"""
Set up the chain/residue/atom hierarchy
This rebuilds the primary structure tree using each object's parents. If atoms
don't have a residue, they are assigned a default residue. If residues don't have a
chain, they're assigned a default chain.
"""
self.children = ChildList(self)
conflicts = set()
self._fix_atom_pdbnames(conflicts)
self.residues = self._rebuild_residues()
self._rebuild_chains(conflicts)
if conflicts:
print('WARNING: %s modified due to name clashes' % (', '.join(conflicts)))
def _fix_atom_pdbnames(self, conflicts):
""" Rename atom pdbindices to avoid name conflicts
"""
pdbatoms = [atom for atom in self.molecule.atoms if atom.pdbindex is not None]
if pdbatoms:
min_pdb_atom = min(pdbatoms, key=lambda x: x.pdbindex)
last_pdb_idx = min_pdb_atom.pdbindex-min_pdb_atom.index-1
else:
last_pdb_idx = 0
for atom in self.molecule.atoms:
# assign PDB indices
if atom.pdbindex is None:
atom.pdbindex = last_pdb_idx+1
if last_pdb_idx is not None and atom.pdbindex <= last_pdb_idx:
atom.pdbindex = last_pdb_idx+1
conflicts.add('atom indices')
last_pdb_idx = atom.pdbindex
def _rebuild_residues(self):
""" Recreate list of residues
"""
num_biores = 0
foundresidues = collections.OrderedDict() # used as an ordered set
for atom in self.molecule.atoms:
res = atom.residue if atom.residue is not None else self._defres
if res not in foundresidues:
# rebuild first - names/ordering may have changed
res.rebuild()
# add it to the structure
res.index = len(foundresidues)
foundresidues[res] = None
if res.type in ('dna', 'rna', 'protein'):
num_biores += 1
if res.molecule is None:
res.molecule = self.molecule
else:
assert res.molecule is self.molecule
if atom not in res:
res.add(atom)
self.molecule.is_biomolecule = (num_biores >= 2)
return list(foundresidues)
def _rebuild_chains(self, conflicts):
""" Recreate list of chains, renaming as necessary to avoid conflicts
"""
for residue in self.residues:
chain = residue.chain if residue.chain is not None else self._defchain
if chain not in self:
# rebuild first - names/ordering may have changed
chain.rebuild()
# rename chain to avoid conflicts if necessary
oldname = chain.name
if chain.name is None and len(self.residues) > 1:
chain.name = 'A'
while chain.name in self:
if chain.name is None:
chain.name = 'A'
chain.name = chr(ord(chain.name)+1)
# add it to the structure
chain.index = len(self)
self.add(chain)
if chain.name != oldname:
conflicts.add('chain ids')
if chain.molecule is None:
chain.molecule = self.molecule
else:
assert chain.molecule is self.molecule
if residue not in chain:
chain.add(residue)
def _repr_markdown_(self):
"""A markdown description of biomolecular structure.
Returns:
str: Markdown string"""
lines = []
if len(self.residues) > 1:
table = self._get_residue_table()
lines.append('### Residues')
lines.append(table.markdown(replace={0: ' '})+'|') # extra '|' is bug workaround (?)
lines.append('### Biopolymer chains')
seqs = []
for chain in self:
seq = chain._get_sequence(_html=True)
if not seq.strip(): # don't write anything if there's no sequence
continue
seqs.append('**%s**: %s' % (chain.name, seq))
lines.append('<br>'.join(seqs))
return lines
def _get_residue_table(self):
"""Creates a data table summarizing this molecule's primary structure.
Returns:
moldesign.utils.MarkdownTable: markdown-formatted table"""
table = utils.MarkdownTable(*(['chain']+
'protein dna rna unknown water solvent ion'.split()))
for chain in self:
counts = {}
unk = []
for residue in chain.residues:
cat = residue.type
if cat == 'unknown':
unk.append(residue.name)
counts[cat] = counts.get(cat, 0)+1
counts['chain'] = '<b>%s</b>'%chain.name
if 0 < len(unk) <= 4:
counts['unknown'] = ','.join(unk)
table.add_line(counts)
return table
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/__init__.py | .py | 380 | 19 | def toplevel(o):
__all__.append(o.__name__)
return o
__all__ = []
from .properties import *
from .bond_graph import *
from .coord_arrays import *
from .atomcollections import *
from .bonds import *
from .atoms import *
from .biounits import *
from .residue import *
from .chain import *
from .primary_structure import *
from .molecule import *
from .trajectory import *
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/chain.py | .py | 11,755 | 316 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import moldesign as mdt
from .. import utils, data
from . import MolecularHierarchy, toplevel, HasResidues
@toplevel
class Chain(MolecularHierarchy, HasResidues):
""" Biomolecular chain class - its children are almost always residues.
Attributes:
parent (mdt.Molecule): the molecule this residue belongs to
chain (Chain): the chain this residue belongs to
"""
@utils.args_from(MolecularHierarchy)
def __init__(self, name=None, **kwargs):
for key in ('pdbname', 'pdbindex'):
val = kwargs.pop(key, None)
if val is not None:
if name is not None and val != name:
raise ValueError('Inconsistent name for chain: %s' % kwargs)
name = val
super().__init__(name=name, **kwargs)
self._type = None
self._5p_end = self._3p_end = self._n_terminal = self._c_terminal = None
@property
def pdbindex(self):
return self.name
@pdbindex.setter
def pdbindex(self, val):
if val is not None:
self.name = val
pdbname = pdbindex
@property
def type(self):
""" str: the type of chain - protein, DNA, solvent, etc.
This field returns the type of chain, classified by the following rules:
1) If the chain contains only one type of residue, it is given that classification
(so a chain containing only ions has type "ion"
2) If the chain contains a biopolymer + ligands and solvent, it is classified as a
biopolymer (i.e. 'protein', 'dna', or 'rna'). This is the most common case with .pdb
files from the PDB.
3) If the chain contains multiple biopolymer types, it will be given a hybrid classification
(e.g. 'dna/rna', 'protein/dna') - this is rare!
4) If it contains multiple kinds of non-biopolymer residues, it will be called "solvent"
(if all non-bio residues are water/solvent/ion) or given a hybrid name as in 3)
"""
if self._type is None:
counts = collections.Counter(x.type for x in self.residues)
unique_types = sum(bool(v) for v in counts.values())
if unique_types == 1:
if self.num_residues == 1:
self._type = data.CHAIN_MONOMER_NAMES.get(self.residues[0].type,
self.residues[0].type)
else:
self._type = self.residues[0].type
else:
polymer_types = sum(bool(counts[t]) for t in data.BIOPOLYMER_TYPES)
if polymer_types == 1: # the most common case - a polymer + solvent/ligands
for residue in self.residues:
if residue.type in data.BIOPOLYMER_TYPES: break
else:
assert False, "No biopolymer found but polymer_types==1"
self._type = residue.type
elif polymer_types > 1: # for rare cases, e.g. "DNA/RNA/PROTEIN"
self._type = '/'.join(k for k in data.BIOPOLYMER_TYPES if counts[k])
elif polymer_types == 0:
if counts['unknown'] > 0: # some molecule + solvent
self._type = '/'.join(k for k in counts if counts[k])
else: # just solvent
self._type = 'solvent'
return self._type
@property
def polymer_residues(self):
for res in self.residues:
if res.type in ('dna', 'protein'):
yield res
@property
def solvent_residues(self):
for res in self.residues:
if res.type in ('water', 'solvent', 'ion'):
yield res
@property
def unclassified_residues(self):
for res in self.residues:
if res.type == 'unknown':
yield res
def get_ligand(self):
""" Return a (single) ligand if it exists; raises ValueError if there's not exactly one
This is a utility routine to get a single ligand from a chain. If there's exactly one
residue, it is returned. If not, ValueError is raised - use
:meth:`Chain.unclassified_residues` to get an iterator over all unclassified residues.
Returns:
moldesign.Residue: ligand residue
Raises:
ValueError: if the chain does not contain exactly one unclassifiable residue
"""
iterator = self.unclassified_residues
try:
ligand = next(iterator)
except StopIteration:
raise ValueError('This chain does not appear to contain any ligands')
try:
nextligand = next(iterator)
except StopIteration:
return ligand
else:
raise ValueError('Multiple ligands detected. Use `chain.unclassified_residues` to '
'iterate over them')
def copy(self):
""" Create a copy of this chain and all topology within.
Returns:
Chain: copy of this chain and all atoms/residues it contains. This copy will NOT
reference any parent molecule
"""
newatoms = super().copy_atoms()
return newatoms[0].chain
@property
def num_residues(self):
return len(self)
nresidues = numresidues = num_residues
@property
def residues(self):
"""ChildList: list of residues in this chain """
return self.children
def add(self, residue, **kwargs):
if residue.chain is None:
residue.chain = self
else:
assert residue.chain is self, "Residue is not a member of this chain"
return super().add(residue, **kwargs)
def _get_chain_end(self, restype, selfattr, test):
currval = getattr(self, selfattr)
if currval is None or not getattr(currval, test):
for residue in self.residues:
if residue.type != restype:
continue
if getattr(residue, test):
setattr(self, selfattr, residue)
break
return getattr(self, selfattr)
@property
def c_terminal(self):
"""moldesign.Residue: The chain's C-terminus (or ``None`` if it does not exist)"""
return self._get_chain_end('protein', '_c_terminal', 'is_c_terminal')
@property
def n_terminal(self):
"""moldesign.Residue: The chain's N-terminus (or ``None`` if it does not exist)"""
return self._get_chain_end('protein', '_n_terminal', 'is_n_terminal')
@property
def fiveprime_end(self):
"""moldesign.Residue: The chain's 5' base (or ``None`` if it does not exist)"""
return self._get_chain_end('dna', '_5p_end', 'is_5prime_end')
@property
def threeprime_end(self):
"""moldesign.Residue: The chain's 3' base (or ``None`` if it does not exist)"""
return self._get_chain_end('dna', '_3p_end', 'is_3prime_end')
def assign_biopolymer_bonds(self):
"""Connect bonds between residues in this chain.
See Also:
:ref:`moldesign.Residue.assign_template_bonds`
Raises:
ValueError: if ``residue.resname`` is not in bioresidue templates
KeyError: if an atom in this residue is not recognized """
residues = list(self)
residues.sort(key=lambda x: int(x.pdbindex))
bond_graph = {}
for ires in range(len(residues)-1):
r1 = residues[ires]
r2 = residues[ires+1]
# don't assign bonds unless these are contiguous bioresidues
if r1.pdbindex + 1 != r2.pdbindex:
continue
restype = r1.type
if r2.type != restype:
continue
# Create the bonds
if restype == 'protein':
bond_graph[r1['C']] = {r2['N']: 1}
bond_graph[r2['N']] = {r1['C']: 1}
elif restype == 'dna':
bond_graph[r1["O3'"]] = {r2['P']: 1}
bond_graph[r2['P']] = {r1["O3'"]: 1}
elif restype == 'rna':
raise NotImplementedError('RNA not yet implemented')
# copy bonds into the right structure (do this last to avoid mangling the graph)
for atom in bond_graph:
atom.bond_graph.update(bond_graph[atom])
@property
def sequence(self):
"""str: this chain's residue sequence with one-letter residue codes
"""
return self._get_sequence()
def _get_sequence(self, _html=False):
if _html:
outputs = ['<span style="word-wrap:break-word;font-family:monospace">']
else:
outputs = []
# get a list of ALL residues, including missing ones
missing = self.molecule.metadata.get('missing_residues', {}).get(self.pdbname, {})
all_residues = list(self.residues)
all_residues.extend(mdt.helpers.MissingResidue(self.pdbname, resname, resnum)
for resnum, resname in missing.items())
all_residues.sort(key=lambda r: r.pdbindex)
bracket_open = False
for res in all_residues:
if res.type not in ('protein', 'dna', 'rna'): # don't display non-biological residues
continue
elif getattr(res, 'missing', False): # deal with missing residues
if bracket_open:
outputs.append(']')
bracket_open = False
if _html:
outputs.append(
'<span title="%s%s (MISSING), chain %s" style="color:Red">%s</span>' %
(res.resname, res.pdbindex, self.pdbname, res.code))
else:
outputs.append('-')
elif res.code == '?': # unknown residue type
if not bracket_open:
outputs.append('[')
bracket_open = True
else:
outputs.append(',')
if _html:
outputs.append('<span title="%s (idx %d), chain %s">%s</span>' %
(res.name, res.index, res.chain.name, res.pdbname))
else:
outputs.append(res.pdbname)
else: # we have a normal residue name
if bracket_open:
outputs.append(']')
bracket_open = False
if _html:
outputs.append('<span title="%s (idx %d), chain %s">%s</span>' %
(res.name, res.index, res.chain.name, res.code))
else:
outputs.append(res.code)
if bracket_open:
outputs.append(']')
if _html:
outputs.append('</span>')
return ''.join(outputs)
def __str__(self):
return 'Chain %s' % self.name
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/trajectory.py | .py | 16,080 | 451 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import time
import numpy as np
import moldesign as mdt
from .. import widgets, utils
from .. import units as u
from . import MolecularProperties, AtomicProperties
from . import toplevel
class Frame(utils.DotDict):
""" A snapshot of a molecule during its motion. This is really just a dictionary of properties.
These properties are those accessed as ``molecule.properties``, and can vary
substantially depending on the origin of the trajectory. They also include relevant dynamical
data and metadata (such as ``time``, ``momenta``, ``minimization_step``, etc.)
Properties can be accessed either as attributes (``frame.property_name``) or as keys
(``frame['property_name']``)
Some properties with specific meaning are described below:
Attributes:
annotation (str): text describing this frame (will be displayed automatically when
visualized)
minimization_step (int): for minimization trajectories
time (u.Scalar[time]): time during a dynamical trajectory
Example:
>>> mol = mdt.from_name('benzene')
>>> mol.set_potential_model(moldesign.models.RHF(basis='3-21g'))
>>> traj = mol.minimize()
>>> starting_frame = traj.frames[0]
>>> assert starting_frame.potential_energy >= traj.frames[-1].potential_energy
>>> assert starting_frame.minimization_step == 0
"""
def __init__(self, traj, frameidx):
super().__init__()
self.traj = traj
self.frameidx = frameidx
for key in self.traj.properties:
if key == 'frameidx':
continue
self[key] = getattr(traj, key)[self.frameidx]
def __str__(self):
return 'Frame %d in trajectory "%s"' % (self.frameidx, self.traj.name)
def __repr__(self):
try:
return '<%s>' % self
except (KeyError, AttributeError):
return '<Frame at %x (exception in __repr__)>' % id(self)
def write(self, *args, **kwargs):
self.traj._apply_frame(self)
return self.traj._tempmol.write(*args, **kwargs)
def as_molecule(self):
self.traj._apply_frame(self)
return mdt.Molecule(self.traj._tempmol)
class _TrajAtom(object):
""" A helper class for querying individual atoms' dynamics
"""
def __init__(self, traj, index):
self.traj = traj
self.index = index
self.real_atom = self.traj.mol.atoms[self.index]
@property
def position(self):
return self._arrayslice('positions')
@property
def momentum(self):
return self._arrayslice('momenta')
@property
def force(self):
return self._arrayslice('forces')
def _arrayslice(self, attr):
return getattr(self.traj, attr)[:, self.index, :]
def __getattr__(self, item):
if item in ('traj', 'index', 'real_atom'):
raise AttributeError('Internal Error: _TrajAtom.%s has not been initialized' % item)
try: # first, look for time-dependent properties
val = getattr(self.traj, item)
except AttributeError: # otherwise, just return an atomic property
return getattr(self.real_atom, item)
if not isinstance(val[0], AtomicProperties):
raise ValueError('%s is not an atomic quantity' % item)
else:
return u.array([f[self.real_atom] for f in val])
def __dir__(self):
attrs = [self.ATOMIC_ARRAYS.get(x, x) for x in dir(self.traj)]
attrs.extend(dir(self.atom))
def distance(self, other):
return mdt.geom.distance(self, other)
class TrajectoryAnalysisMixin(object):
"""
Organizational class with analysis methods for trajectories
"""
@property
def kinetic_energy(self):
from ..helpers import kinetic_energy
convert_units = True
energies = []
for frame in self.frames:
if 'momenta' in frame:
energies.append(
kinetic_energy(frame.momenta, self.mol.masses))
else:
convert_units = False
energies.append(None)
if convert_units:
arr = u.array(energies)
return u.default.convert(arr)
else:
return energies
@property
def kinetic_temperature(self):
from ..helpers import kinetic_temperature
convert_units = True
temps = []
energies = self.kinetic_energy
dof = self.mol.dynamic_dof
for energy, frame in zip(energies, self.frames):
if energy is not None:
temps.append(kinetic_temperature(energy, dof))
else:
convert_units = False
temps.append(None)
if convert_units:
arr = u.array(temps)
return u.default.convert(arr)
else:
return temps
def distance(self, a1, a2):
a1, a2 = list(map(self._get_traj_atom, (a1, a2)))
return mdt.distance(a1, a2)
def angle(self, a1, a2, a3):
a1, a2, a3 = list(map(self._get_traj_atom, (a1, a2, a3)))
return mdt.angle(a1, a2, a3)
def dihedral(self, a1, a2, a3=None, a4=None):
a1, a2, a3, a4 = list(map(self._get_traj_atom, (a1, a2, a3, a4)))
return mdt.dihedral(a1, a2, a3, a4)
def rmsd(self, atoms=None, reference=None):
r""" Calculate root-mean-square displacement for each frame in the trajectory.
The RMSD between times :math:`t` and :math:`t0` is given by
:math:`\text{RMSD}(t;t_0) =\sqrt{\sum_{i \in \text{atoms}} \left( \mathbf{R}_i(t) -
\mathbf{R}_i(t_0) \right)^2}`,
where :math:`\mathbf{R}_i(t)` is the position of atom *i* at time *t*.
Args:
atoms (list[mdt.Atom]): list of atoms to calculate the RMSD for (all atoms in the
``Molecule``)
reference (u.Vector[length]): Reference positions for RMSD. (default:
``traj.frames[0].positions``)
Returns:
u.Vector[length]: list of RMSD displacements for each frame in the trajectory
"""
if reference is None: refpos = self.frames[0].positions
else: refpos = reference.positions
atoms = mdt.utils.if_not_none(atoms, self.mol.atoms)
indices = np.array([atom.index for atom in atoms])
rmsds = []
for f in self.frames:
diff = (refpos[indices] - f.positions[indices])
rmsds.append(np.sqrt((diff*diff).sum()/len(atoms)))
return u.array(rmsds).defunits()
@toplevel
class Trajectory(TrajectoryAnalysisMixin):
""" A ``Trajectory`` stores information about a molecule's motion and how its properties
change as it moves.
A trajectory object contains
1. a reference to the :class:`moldesign.Molecule` it describes, and
2. a list of :class:`Frame` objects, each one containing a snapshot of the molecule at a
particular point in its motion.
Args:
mol (moldesign.Molecule): the trajectory will describe the motion of this molecule
unit_system (u.UnitSystem): convert all attributes to this unit system (default:
``moldesign.units.default``)
first_frame(bool): Create the trajectory's first :class:`Frame` from the molecule's
current position
Attributes:
mol (moldesign.Molecule): the molecule object that this trajectory comes from
frames (List[Frame]): a list of the trajectory frames in the order they were created
info (str): text describing this trajectory
unit_system (u.UnitSystem): convert all attributes to this unit system
"""
draw = widgets.WidgetMethod('trajectory.draw')
draw_orbitals = widgets.WidgetMethod('trajectory.draw_orbitals')
plot = widgets.WidgetMethod('trajectory.plot')
def __init__(self, mol, unit_system=None, first_frame=False, name=None):
self._init = True
self.info = "Trajectory"
self.frames = []
self.mol = mol
self.unit_system = utils.if_not_none(unit_system, mdt.units.default)
self.properties = utils.DotDict()
self._reset()
self.name = utils.if_not_none(name, 'untitled')
if first_frame: self.new_frame()
def _reset(self):
self._viz = None
self._atoms = None
self._tempmol = mdt.Molecule(self.mol.atoms, copy_atoms=True)
MOL_ATTRIBUTES = ['positions', 'momenta', 'time']
"""List[str]: Always store these molecular attributes"""
def copy(self):
newtraj = copy.copy(self)
newtraj.frames = self.frames[:]
newtraj.properties = self.properties.copy()
newtraj._reset()
return newtraj
@property
def num_frames(self):
"""int: number of frames in this trajectory"""
return len(self)
__len__ = mdt.utils.Alias('frames.__len__')
__iter__ = mdt.utils.Alias('frames.__iter__')
def __getattr__(self, attr):
if attr == 'properties' or attr not in self.properties:
return self.__getattribute__(attr)
else:
return self.properties[attr]
@property
def atoms(self):
if self._atoms is None:
self._atoms = self._make_traj_atoms()
return self._atoms
def _make_traj_atoms(self):
return [_TrajAtom(self, i) for i in range(self.mol.num_atoms)]
def __str__(self):
return 'Trajectory for molecule "%s" (%d frames)' % (self.mol, self.num_frames)
def __repr__(self):
try:
return '<%s>' % str(self)
except (KeyError, AttributeError):
return '<Trajectory object @ %s (exception in repr)>' % hex(id(self))
def __add__(self, other):
newtraj = Trajectory(self.mol, unit_system=self.unit_system)
for frame in self.frames + other.frames:
newtraj.new_frame(**frame)
return newtraj
def new_frame(self, properties=None, **additional_data):
""" Create a new frame, EITHER from the parent molecule or from a list of properties
Args:
properties (dict): dictionary of properties (i.e. {'positions':[...],
'potential_energy':...})
**additional_data (dict): any additional data to be added to the trajectory frame
Returns:
int: frame number (0-based)
"""
# get list of properties for this frame
props = dict(self.mol.properties)
if properties is not None:
props.update(properties)
for attr in self.MOL_ATTRIBUTES:
if attr not in props:
props[attr] = getattr(self.mol, attr)
props.update(additional_data)
# add properties to trajectory
for key, value in props.items():
if key not in self.properties:
self._new_property(key, value)
else:
proplist = getattr(self, key)
assert len(proplist) == self.num_frames
proplist.append(value)
# backfill missing data with None
for key in self.properties:
proplist = self.properties[key]
if len(proplist) < self.num_frames+1:
assert len(proplist) == self.num_frames
try:
proplist.append(None)
except TypeError:
newpl = list(proplist)
newpl.append(None)
self.properties[key] = newpl
# TODO: less awkward way of keeping track of # of frames
self.frames.append(Frame(self, self.num_frames))
def _new_property(self, key, value):
""" Create a new list of properties for each frame. To facilitate analysis, will try
to create this list as one of the following classes (in order of preference):
1) resizeable numpy array
2) resizeable MdtQuantity array
3) list
If this property wasn't already present, we will add it to all previous frames with a
value of ``None``
"""
assert key not in self.properties
if self.num_frames != 0:
proplist = [None] * self.num_frames
proplist.append(value)
elif isinstance(value, (AtomicProperties, dict)):
proplist = [value]
else:
try:
proplist = self.unit_system.convert(u.array([value]))
except (ValueError, TypeError, u.UndefinedUnitError):
proplist = [value]
else:
proplist.make_resizable()
if proplist.dimensionless:
proplist = proplist._magnitude
self.properties[key] = proplist
def _get_traj_atom(self, a):
if a is None:
return None
elif isinstance(a, mdt.Atom):
return self.atoms[a.index]
else:
assert isinstance(a, _TrajAtom)
DONOTAPPLY = set(['kinetic_energy'])
def _apply_frame(self, frame):
"""
Reconstruct the underlying molecule with the given frame.
Right now, any data not passed is ignored, which may result in properties that aren't synced up
with each other ...
"""
# TODO: need to prevent multiple things using the _tempmol from conflicting with each other
m = self._tempmol
for prop in self.MOL_ATTRIBUTES:
if (prop not in self.DONOTAPPLY
and prop in self.properties
and prop is not None):
setattr(m, prop, frame[prop])
m.properties = MolecularProperties(m)
for attr in frame:
m.properties[attr] = frame[attr]
# TODO: need to fix this - it creates import problems
#@utils.args_from(mdt.converters.write_trajectory,
# allexcept=['traj'],
# append_docstring_description=True)
def write(self, *args, **kwargs):
return mdt.fileio.write_trajectory(self, *args, **kwargs)
def align_orbital_phases(self, reference_frame=None):
"""
Try to remove orbital sign flips between frames.
If `reference_frame` is not passed, we'll start with frame 0 and
align successive pairs of orbitals.
If `reference_frame` is an int, we'll move forwards and backwards from that frame number.
Otherwise, we'll try to align every orbital frame to those in reference_frame
Args:
reference_frame (int or Frame): ``Frame`` containing the orbitals to align with
(default: align each frame with the previous one)
"""
if reference_frame is None:
iframe = 0
relative_alignment = True
elif isinstance(reference_frame, int):
iframe = reference_frame
relative_alignment = True
else:
relative_alignment = False
if relative_alignment:
for i in range(iframe+1, self.num_frames):
self.frames[i].wfn.align_orbital_phases(
self.frames[i-1].wfn)
for i in range(iframe-1, -1, -1):
self.frames[i].wfn.align_orbital_phases(
self.frames[i+1].wfn)
else:
for frame in self.frames:
frame.wfn.align_orbital_phases(reference_frame.wfn)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/bond_graph.py | .py | 3,993 | 115 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from future.utils import PY2
import collections
from .. import utils
if not PY2: # we'll skip the type hints in Python 2
from typing import Mapping
import moldesign as mdt # needed for the late-binding type hints
class AtomBondDict(utils.NewUserDict):
""" Holds the bonds for a given atom
This object does the legwork of making sure that the bond graph remains symmetric - it makes
sure any modifications to this data are reflected on the symmetric side of the graph
"""
if not PY2:
__metaclass__ = Mapping['mdt.Atom', int]
def __init__(self, parent, atom):
super().__init__()
self.parent = parent
self.atom = atom
def __setitem__(self, otheratom, order):
self._setitem_super(otheratom, order)
if self.parent is not None:
self.parent[otheratom]._setitem_super(self.atom, order)
def _setitem_super(self, atom, order):
super().__setitem__(atom, order)
def __delitem__(self, otheratom):
self._delitem_super(otheratom)
if self.parent is not None:
self.parent[otheratom]._delitem_super(self.atom)
def _delitem_super(self, otheratom):
super().__delitem__(otheratom)
class BondGraph(utils.NewUserDict):
""" The bond graph of a molecule. This object manages the molecular bonding topology.
This object can generally be treated as a dict, with two important exceptions:
1. it maintains symmetry, so that setting ``bond_graph[a][b] = o`` will automatically set
``bond_graph[b][a] = o``
2. It has exactly one entry for every atom in the molecule; it does not expose any methods
for adding or deleting these entries.
"""
if not PY2:
__metaclass__ = Mapping['mdt.Atom', AtomBondDict]
def __init__(self, molecule):
""" Initializes the object, and raises up the bond state of all atoms in the molecule
"""
super().__init__()
self.molecule = molecule
self._add_atoms(molecule.atoms)
def __str__(self):
'Bond graph for %s' % self.molecule
def __repr__(self):
return '<%s>' % self.molecule
def _add_atoms(self, atoms):
""" Move bonds defined in the atom to this object.
If the atom is already present in the graph, do nothing.
This method raises state - it centralizes bonding information about the molecule in
one place. However, bonding information about atoms OUTSIDE of the molecule is left
untouched.
Args:
atoms (List[moldesign.Atom]): atom to initialize
"""
add_atoms = [atom for atom in atoms if atom not in self]
for atom in add_atoms:
super().__setitem__(atom, AtomBondDict(self, atom))
for atom in add_atoms:
bg = atom._bond_graph
for nbr, order in list(bg.items()):
if nbr in self:
self[atom][nbr] = order
del bg[nbr]
def __setitem__(self, key, args):
raise NotImplementedError('Bond graphs cannot be manipulated using this method')
def __delitem__(self, key):
raise NotImplementedError('Bond graphs cannot be manipulated using this method')
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/molecule.py | .py | 45,660 | 1,213 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.from __future__ import print_function
import itertools
import string
import collections
import numpy as np
import moldesign as mdt
from . import toplevel
from .. import helpers, utils
from .. import units as u
from ..compute import DummyJob
from ..exceptions import NotCalculatedError
from ..min.base import MinimizerBase
from . import PrimaryStructure, AtomGroup, Bond, HasResidues, BondGraph, MolecularProperties
from ..widgets import WidgetMethod
from .coord_arrays import *
class MolConstraintMixin(object):
""" Functions for applying and managing geometrical constraints.
Note:
This is a mixin class designed only to be mixed into the :class:`Molecule` class. Routines
are separated are here for code organization only - they could be included in the main
Molecule class without changing any functionality
"""
def clear_constraints(self):
"""
Clear all geometry constraints from the molecule.
Note:
This does NOT clear integrator options - such as "constrain H bonds"
"""
self.constraints.clear()
self._reset_methods()
def constrain_atom(self, atom, pos=None):
""" Constrain the position of an atom
Args:
atom (moldesign.Atom): The atom to constrain
pos (moldesign.units.MdtQuantity): position to fix this atom at (default: atom.position) [length]
Returns:
moldesign.geometry.FixedPosition: constraint object
"""
self.constraints.append(mdt.geom.FixedPosition(atom, value=pos))
self._reset_methods()
return self.constraints[-1]
def constrain_distance(self, atom1, atom2, dist=None):
""" Constrain the distance between two atoms
Args:
atom1 (moldesign.Atom)
atom2 (moldesign.Atom)
dist ([length]): distance value (default: current distance)
Returns:
moldesign.geometry.DistanceConstraint: constraint object
"""
self.constraints.append(
mdt.geom.DistanceConstraint(atom1, atom2, value=dist))
self._reset_methods()
return self.constraints[-1]
def constrain_angle(self, atom1, atom2, atom3, angle=None):
""" Constrain the bond angle atom1-atom2-atom3
Args:
atom1 (moldesign.Atom)
atom2 (moldesign.Atom)
atom3 (moldesign.Atom)
angle ([angle]): angle value (default: current angle)
Returns:
moldesign.geometry.AngleConstraint: constraint object
"""
self.constraints.append(
mdt.geom.AngleConstraint(atom1, atom2, atom3, value=angle))
self._reset_methods()
return self.constraints[-1]
def constrain_dihedral(self, atom1, atom2, atom3, atom4, angle=None):
""" Constrain the bond angle atom1-atom2-atom3
Args:
atom1 (moldesign.Atom)
atom2 (moldesign.Atom)
atom3 (moldesign.Atom)
atom4 (moldesign.Atom)
angle ([angle]): angle value (default: current angle)
Returns:
moldesign.geom.AngleConstraint: constraint object
"""
self.constraints.append(
mdt.geom.DihedralConstraint(atom1, atom2, atom3, atom4, value=angle))
self._reset_methods()
return self.constraints[-1]
def constrain_hbonds(self, usecurrent=False):
""" Constrains the lengths of all bonds involving hydrogen.
By default, the lengths will be constrained to their forcefield equilibrium values.
They can also be constrained to their current values by setting ``usecurrent=True``
Args:
mol (moldesign.Molecule): Constrain all h-bonds in this molecule
usecurrent (bool): if False (default), set the constraint values to their forcefield
equilibrium values (this will fail if no forcefield is assigned). If True, constrain
the hydrogen bonds at the current values.
Raises:
AttributeError: if usecurrent=False but no forcefield is assigned
"""
self.constraints.append(mdt.geom.HBondsConstraint(self, usecurrent))
self._reset_methods()
return self.constraints[-1]
class MolPropertyMixin(object):
""" Functions for calculating and accessing molecular properties.
Note:
This is a mixin class designed only to be mixed into the :class:`Molecule` class. Routines
are separated are here for code organization only - they could be included in the main
Molecule class without changing any functionality
"""
@property
def kinetic_temperature(self):
r""" [temperature]: temperature calculated using the equipartition theorem,
:math:`\frac{2 E_{\text{kin}}}{k_b f}`,
where :math:`E_{\text{kin}}` is the kinetic energy and :math:`f` is the number of
degrees of freedom (see :meth:`dynamic_dof <Molecule.dynamic_dof>`)
"""
return helpers.kinetic_temperature(self.kinetic_energy,
self.dynamic_dof)
@property
def dynamic_dof(self):
""" int: Count the number of spatial degrees of freedom of the system,
taking into account any constraints
"""
df = self.ndims
if self.integrator is not None:
if self.integrator.params.get('remove_translation', False):
df -= 3
if self.integrator.params.get('remove_rotation', False):
if self.num_atoms > 2:
df -= 3
const_hbonds = const_water = False
if self.integrator is not None:
const_hbonds = self.integrator.params.get('constrain_hbonds', False)
const_water = self.integrator.params.get('constrain_water', False)
if const_hbonds: # TODO: deal with molecular hydrogen
for atom in self.atoms:
if atom.atnum == 1:
df -= 1
if const_water:
for residue in self.residues:
if residue.type == 'water': # constrained water has 6 degrees of freedom
if const_hbonds: # two are already accounted for
df -= 1
else:
df -= 3
for constraint in self.constraints: # TODO: deal better with overlaps!
if (const_hbonds
and isinstance(constraint, mdt.geom.DistanceConstraint)
and (constraint.a1.atnum == 1 or constraint.a2.atnum == 1)):
continue
df -= constraint.dof
return df
@property
def charge(self):
return self._charge
@charge.setter
def charge(self, val):
if not hasattr(val, 'units'):
val = val * u.q_e
self._charge = val
@property
def num_electrons(self):
"""int: The number of electrons in the system, based on the atomic numbers and self.charge"""
return sum(atom.atnum for atom in self.atoms) - self.charge.value_in(u.q_e)
@property
def homo(self):
"""int: The array index (0-based) of the highest occupied molecular orbital (HOMO).
Note:
This assumes a closed shell ground state! """
return self.num_electrons // 2 - 1
@property
def lumo(self):
"""int: The array index (0-based) of the lowest unoccupied molecular orbital (LUMO).
Note:
This assumes a closed shell ground state! """
return self.num_electrons // 2
def get_stoichiometry(self, html=False):
""" Return this molecule's stoichiometry
Returns:
str
"""
counts = {}
for atom in self.atoms:
counts[atom.symbol] = counts.get(atom.symbol, 0) + 1
my_elements = sorted(counts.keys())
if html: template = '%s<sub>%d</sub>'
else: template = '%s%d'
return ''.join([template % (k, counts[k]) for k in my_elements])
@property
def wfn(self):
""" moldesign.orbitals.ElectronicWfn: return the molecule's current electronic state,
if calculated.
Raises:
NotCalculatedError: If the electronic state has not yet been calculated at this
geometry
"""
return self.get_property('wfn')
def calc_property(self, name, **kwargs):
""" Calculate the given property if necessary and return it
Args:
name (str): name of the property (e.g. 'potential_energy', 'forces', etc.)
Returns:
object: the requested property
"""
result = self.calculate(requests=[name], **kwargs)
return result[name]
def get_property(self, name):
""" Return the given property if already calculated; raise NotCalculatedError otherwise
Args:
name (str): name of the property (e.g. 'potential_energy', 'forces', etc.)
Raises:
NotCalculatedError: If the molecular property has not yet been calculated at this
geometry
Returns:
object: the requested property
"""
if name in self.properties and self.properties.geometry_matches(self):
return self.properties[name]
else:
raise NotCalculatedError(
("The '{0}' property hasn't been calculated yet. "
"Calculate it with the molecule.calculate_{0}() method").format(name))
def calculate_forces(self, **kwargs):
""" Calculate forces and return them
Returns:
units.Vector[force]
"""
return self.calc_property('forces')
def calculate_potential_energy(self, **kwargs):
""" Calculate potential energy and return it
Returns:
units.Scalar[energy]: potential energy at this position
"""
return self.calc_property('potential_energy')
def calculate_dipole(self, **kwargs):
""" Calculate forces and return them
Returns:
units.Vector[length*charge]: dipole moment at this position (len=3)
"""
return self.calc_property('dipole')
def calculate_wfn(self, **kwargs):
""" Calculate forces and return them
Returns:
moldesign.orbitals.ElectronicWfn: electronic wavefunction object
"""
return self.calc_property('wfn')
@property
def potential_energy(self):
""" units.Scalar[energy]: return the molecule's current potential energy, if calculated.
Raises:
NotCalculatedError: If the potential energy has not yet been calculated at this
geometry
"""
return self.get_property('potential_energy')
@property
def forces(self):
""" units.Vector[force]: return the current force on the molecule, if calculated.
Raises:
NotCalculatedError: If the forces have not yet been calculated at this geometry
"""
return self.get_property('forces')
@property
def dipole(self):
""" units.Vector[length*charge]: return the molecule's dipole moment, if calculated (len=3).
Raises:
NotCalculatedError: If the dipole moment has not yet been calculated at this
geometry
"""
return self.get_property('dipole')
@property
def properties(self):
"""MolecularProperties: Molecular properties calculated at this geometry
"""
# ADD_FEATURE: some sort of persistent caching so that they aren't lost
if not self._properties.geometry_matches(self):
self._properties = MolecularProperties(self)
return self._properties
@properties.setter
def properties(self, val):
""" Sanity checks - make sure that these properties correspond to the correct geoemtry.
"""
assert val.geometry_matches(self), \
"Can't set properties - they're for a different molecular geometry"
self._properties = val
# synonyms for backwards compatibility
calc_wfn = calculate_wfn
calc_dipole = calculate_dipole
calc_potential_energy = calculate_potential_energy
calc_forces = calculate_forces
class MolTopologyMixin(object):
""" Functions for building and keeping track of bond topology and biochemical structure.
Note:
This is a mixin class designed only to be mixed into the :class:`Molecule` class. Routines
are here for code organization only - they could be included in the main
Atom class without changing any functionality
"""
def copy(self, name=None):
""" Create a copy of the molecule and all of its substructures, metadata, and methods
Returns:
Molecule: copied molecule
"""
if name is None:
name = self.name + ' copy'
newmol = Molecule(self.atoms,
name=name,
pdbname=self.pdbname,
charge=self.charge,
metadata=self.metadata)
if self.energy_model is not None:
newmodel = self._copy_method('energy_model')
newmol.set_energy_model(newmodel)
if self.integrator is not None:
newintegrator = self._copy_method('integrator')
newmol.set_integrator(newintegrator)
if self.ff is not None:
self.ff.copy_to(newmol)
newmol.constraints = [c.copy(newmol) for c in self.constraints]
newmol.properties = self.properties.copy_to(mol=newmol)
return newmol
def _copy_method(self, methodname):
method = getattr(self, methodname)
newmethod = method.__class__()
newmethod.params.clear()
newmethod.params.update(method.params)
return newmethod
def _rebuild_from_atoms(self):
""" Rebuild component data structures based on atomic data
"""
self.is_biomolecule = False
self.ndims = 3 * self.num_atoms
self._positions = np.zeros((self.num_atoms, 3)) * u.default.length
self._momenta = np.zeros((self.num_atoms, 3)) * u.default.momentum
self.masses = np.zeros(self.num_atoms) * u.default.mass
self.dim_masses = u.broadcast_to(self.masses, (3, self.num_atoms)).T
self._assign_atom_indices()
self.chains.rebuild_hierarchy()
self._dof = None
self._topology_changed()
def _assign_atom_indices(self):
"""
Create geometry-level information based on constituent atoms, and mark the atoms
as the property of this molecule
"""
idim = 0
for idx, atom in enumerate(self.atoms):
atom._set_molecule(self)
atom.index = idx
idim += 3
self.masses[idx] = atom.mass
# Here, we index the atom arrays directly into the molecule
atom._index_into_molecule('_position', self.positions, idx)
atom._index_into_molecule('_momentum', self.momenta, idx)
def is_identical(self, other, verbose=False):
""" Test whether two molecules are "identical"
We specifically test these quantities for equality:
- positions
- momenta
- chain names
- residue names
- atom names / numbers / masses
- bonds
Note:
This tests geometry and topology only; it does not test
energy models or any calculated properties; it also ignores the ``time`` attribute.
Args:
other (moldesign.Molecule): molecule to test against
verbose (bool): when returning False, print the reasons why
Returns:
bool: true if all tested quantities are equal
"""
if not self.same_topology(other, verbose=verbose):
return False
if (self.positions != other.positions).any():
if verbose:
mismatch = (self.positions != other.positions).any(axis=1).sum()
print("%d atoms have different positions." % mismatch)
return False
if (self.momenta != other.momenta).any():
if verbose:
mismatch = (self.momenta != other.momenta).any(axis=1).sum()
print("%d atoms have different momenta."%mismatch)
return False
return True
residues = utils.Alias('chains.residues')
@property
def num_residues(self):
return len(self.chains.residues)
nresidues = numresidues = num_residues
@property
def num_chains(self):
return len(self.chains)
nchains = numchains = num_chains
def combine(self, *others):
""" Create a new molecule from a group of other AtomContainers
Notes:
- Chain IDs and sequence numbers are automatically assigned if they are missing
- Chains will be renamed to prevent chain ID clashes
- Residue resnames are not changed.
Args:
*others (AtomContainer or AtomList or List[moldesign.Atom]):
Returns:
mdt.Molecule: a new Molecule that's the union of this structure with all
others. Chains will be renamed as necessary to avoid clashes.
"""
new_atoms = []
charge = 0
names = []
chain_names = collections.OrderedDict((x, None) for x in string.ascii_uppercase)
taken_names = set()
seen_chains = set()
for obj in itertools.chain([self], others):
objatoms = mdt.helpers.get_all_atoms(obj).copy()
for atom in objatoms:
chain = atom.chain
if chain not in seen_chains:
seen_chains.add(chain)
if chain.pdbindex is None or chain.pdbindex in taken_names:
chain.pdbindex = chain.name = next(iter(chain_names.keys()))
chain_names.pop(chain.pdbindex, None)
taken_names.add(chain.pdbindex)
new_atoms.extend(objatoms)
charge += getattr(obj, 'charge', 0*u.q_e)
if hasattr(obj, 'name'):
names.append(obj.name)
elif objatoms[0].molecule is not None:
names.append('%d atoms from %s' % (len(objatoms), objatoms[0].molecule.name))
else:
names.append('list of %d unowned atoms' % len(objatoms))
return mdt.Molecule(new_atoms,
copy_atoms=True,
charge=charge,
name='%s extended with %d atoms' %
(self.name, len(new_atoms) - self.num_atoms),
metadata=utils.DotDict(description=
'Union of %s' % ', '.join(names)))
def same_topology(self, other, verbose=False):
""" Test whether two molecules have equivalent topologies
We specifically test these quantities for equality:
- chain names
- residue names
- atom names / numbers / masses
- bonds
Note:
This tests geometry and topology only; it does not test
energy models or any calculated properties; it also ignores the ``time`` attribute.
Args:
other (moldesign.Molecule): molecule to test against
verbose (bool): when returning False, print the reasons why
Returns:
bool: true if all tested quantities are equal
"""
if self.num_atoms != other.num_atoms:
if verbose: print('INFO: Different numbers of atoms')
return False
if self.num_chains != other.num_chains:
if verbose: print('INFO: Different numbers of chains')
return False
if self.num_residues != other.num_residues:
if verbose: print('INFO: Different numbers of residues')
return False
for a1, a2 in itertools.zip_longest(
itertools.chain(self.atoms, self.residues, self.chains),
itertools.chain(other.atoms, other.residues, other.chains)):
if a1.name != a2.name:
if verbose:
print('INFO: %s[%d]: names "%s" and "%s"' % (a1.__class__.__name__, a1.index,
a1.name, a2.name))
return False
if (self.masses != other.masses).any():
return False
for a1, a2 in zip(self.atoms, other.atoms):
if a1.atnum != a2.atnum:
if verbose:
print('INFO: atoms[%d]: atom numbers %d and %d' % (a1.index, a1.atnum, a2.atnum))
return False
return self.same_bonds(other, verbose=verbose)
def same_bonds(self, other, verbose=False):
for myatom, otheratom in zip(self.atoms, other.atoms):
mybonds = self.bond_graph[myatom]
otherbonds = other.bond_graph[otheratom]
if len(mybonds) != len(otherbonds):
if verbose:
print('INFO: atoms[%d] has %d bonds in self, %d bonds in other' % (
myatom.index, len(mybonds), len(otherbonds)))
return False
for mynbr, myorder in mybonds.items():
othernbr = other.atoms[mynbr.index]
if othernbr not in otherbonds or otherbonds[othernbr] != myorder:
if verbose:
print('INFO: atoms[%d] bonded to atom[%d] (order %d) in self but not other' % (
myatom.index, mynbr.index, myorder))
return False
return True
def not_identical(self, other):
return not self.is_identical(other)
class MolSimulationMixin(object):
""" Functions calculating energies, running dynamics, and minimizing geometry.
Note:
This is a mixin class designed only to be mixed into the :class:`Molecule` class. Routines
are separated are here for code organization only - they could be included in the main
Atom class without changing any functionality
"""
def run(self, run_for):
""" Starts the integrator's default integration
Args:
run_for (int or [time]): number of steps or amount of time to run for
Returns:
moldesign.trajectory.Trajectory
"""
if self.integrator is None:
raise AttributeError('Cannot simulate; no integrator set for %s' % self)
init_time = self.time
traj = self.integrator.run(run_for)
print('Done - integrated "%s" from %s to %s' % (self, init_time, self.time))
return traj
def calculate(self, requests=None, wait=True, use_cache=True):
"""
Runs a potential energy calculation on the current geometry, returning the requested quantities.
If `requests` is not passed, the properties specified in the energy_models DEFAULT_PROPERTIES
will be calculated.
Args:
requests (List[str]): list of quantities for the model to calculate,
e.g. ['dipole', 'forces']
wait (bool): if True, wait for the calculation to complete before returning. \
If false, return a job object - this will not update the molecule's properties!
use_cache (bool): Return cached results if possible
Returns:
MolecularProperties
"""
if self.energy_model is None:
raise AttributeError('Cannot calculate properties; no energy model set for %s' % self)
if requests is None:
requests = []
# Figure out what needs to be calculated,
# and either launch the job or set the result
to_calculate = set(list(requests) + self.energy_model.DEFAULT_PROPERTIES)
if use_cache:
to_calculate = to_calculate.difference(self.properties)
if len(to_calculate) == 0:
job = self.properties
else:
job = self.energy_model.calculate(to_calculate)
if wait:
# We'll wait for the job to complete, then
# returns the molecule's calculated properties
if hasattr(job, 'wait'):
job.wait()
properties = job.result
else:
properties = job
self.properties.update(properties)
return self.properties
else:
# We're not waiting for the job to complete - return a job object
if hasattr(job, 'wait'):
return job
else:
return DummyJob(job)
def set_energy_model(self, model, **params):
""" Associate an energy model with this molecule
Args:
model (moldesign.methods.EnergyModelBase): The energy model to associate with this
molecule
**params (dict): a dictionary of parameters for the model
Note:
For convenience, ``model`` can be an instance, a class, or a constructor (with
call signature ``model(**params) -> model instance)``
"""
# If passed the class or constructor, create an instance of the energy model
if not issubclass(type(model), mdt.models.base.EnergyModelBase) and callable(model):
model = model()
self.energy_model = model
self.properties = MolecularProperties(self)
model.mol = self
model.params.update(params)
if 'charge' not in model.params:
if self.charge != 0:
model.params.charge = self.charge
elif model.params['charge'] != self.charge:
print("Warning: molecular charge (%s) does not match energy model's charge (%s)" % (
self.charge.value_in(u.q_e), model.params.charge.value_in(u.q_e)))
model._prepped = False
def set_integrator(self, integrator, **params):
""" Associate an integrator with this molecule
Args:
integrator (moldesign.integrators.IntegratorBase): The integrator to associate with this
molecule
**params (dict): a dictionary of parameters for the integrator
Note:
For convenience, ``integrator`` can be an instance, a class, or a constructor (with
call signature ``integrator(**params) -> integrator instance)``
"""
# If passed the class or constructor, create an instance of the integrator
if (not issubclass(type(integrator), mdt.integrators.base.IntegratorBase) and
callable(integrator)):
integrator = integrator()
self.integrator = integrator
integrator.mol = self
integrator.params.update(params)
integrator._prepped = False
@utils.args_from(MinimizerBase,
allexcept=['self'],
inject_kwargs={'assert_converged': False})
def minimize(self, assert_converged=False, **kwargs):
"""Perform an energy minimization (aka geometry optimization or relaxation).
If ``force_tolerance`` is not specified, the program defaults are used.
If specified, the largest force component must be less than force_tolerance
and the RMSD must be less than 1/3 of it. (based on GAMESS OPTTOL keyword)
Args:
assert_converged (bool): Raise an exception if the minimization does not converged.
Returns:
moldesign.trajectory.Trajectory
"""
if self.energy_model is None:
raise AttributeError('Cannot minimize molecule; no energy model set for %s' % self)
try:
trajectory = self.energy_model.minimize(**kwargs)
except NotImplementedError:
trajectory = mdt.minimize(self, **kwargs)
print('Reduced energy from %s to %s' % (trajectory.potential_energy[0],
trajectory.potential_energy[-1]))
if assert_converged:
raise NotImplementedError()
return trajectory
def _reset_methods(self):
"""
Called whenever a property is changed that the energy model and/or integrator
need to know about
"""
# TODO: what should this do with the property object?
if self.energy_model is not None:
self.energy_model._prepped = False
if self.integrator is not None:
self.integrator._prepped = False
def _topology_changed(self):
self._reset_methods()
self.ff = None
def _topology_consistency_check(self):
""" Debugging method for checking that internal data structures are consistent
Raises:
AssertionError: if topology is corrupted
"""
self._atom_consistency_check()
self._bond_consistency_check()
self._residue_consistency_check()
self._chain_consistency_check()
def _residue_consistency_check(self):
""" Debugging method for checking that the residue structure is internally consistent
Raises:
AssertionError: if topology is corrupted
"""
all_atoms = set(self.atoms)
all_residues = set(self.residues)
all_chains = set(self.chains)
assert len(all_residues) == len(self.residues)
atoms_in_residues = set()
chains_from_residues = set()
assert len(all_atoms) == self.num_atoms == len(self.atoms)
for residue in self.residues:
assert residue.molecule is self
chains_from_residues.add(residue.chain)
for atom in residue.iteratoms():
assert atom not in atoms_in_residues, 'Atom in more than 1 residue'
atoms_in_residues.add(atom)
assert atom in all_atoms
assert atom.residue is residue
assert residue.chain in all_chains
assert chains_from_residues == all_chains
assert atoms_in_residues == all_atoms
def _chain_consistency_check(self):
""" Debugging method for checking that the chain structure is internally consistent
Raises:
AssertionError: if topology is corrupted
"""
all_residues = set(self.residues)
all_chains = set(self.chains)
assert len(all_chains) == len(self.chains)
residues_from_chains = set()
for chain in self.chains:
assert chain.molecule is self
for residue in chain:
assert residue not in residues_from_chains, 'Residue in more than 1 chain'
residues_from_chains.add(residue)
assert residue in all_residues
assert residue.molecule is self
assert residue.chain is chain
assert residues_from_chains == all_residues
def _bond_consistency_check(self):
""" Debugging method for checking that the chain structure is internally consistent
Raises:
AssertionError: if topology is corrupted
"""
all_atoms = set(self.atoms)
for atom in all_atoms:
if atom not in self.bond_graph:
assert not atom.bond_graph
continue
bonds = self.bond_graph[atom]
assert atom.bond_graph == bonds
for nbr in bonds:
assert nbr.bond_graph[atom] == atom.bond_graph[nbr]
def _atom_consistency_check(self):
""" Debugging method for checking that the chain structure is internally consistent
Raises:
AssertionError: if topology is corrupted
"""
all_residues = set(self.residues)
all_chains = set(self.chains)
residues_from_atoms = set()
chains_from_atoms = set()
for iatom, atom in enumerate(self.atoms):
assert atom.index == iatom
assert atom.molecule is self
assert atom.residue in all_residues
assert atom.chain in all_chains
residues_from_atoms.add(atom.residue)
chains_from_atoms.add(atom.chain)
assert residues_from_atoms == all_residues
assert chains_from_atoms == all_chains
@toplevel
class Molecule(AtomGroup,
MolConstraintMixin,
MolPropertyMixin,
MolTopologyMixin,
MolSimulationMixin,
HasResidues):
"""
``Molecule`` objects store a molecular system, including atoms, 3D coordinates, molecular
properties, biomolecular entities, and other model-specific information. Interfaces with
simulation models take place through the molecule object.
Molecule objects will generally be created by reading files or parsing other input; see, for
example: :meth:`moldesign.read`, :meth:`moldesign.from_smiles`,
:meth:`moldesign.from_pdb`, etc.
This constructor is useful, however for copying other molecular structures (see
examples below).
Args:
atomcontainer (AtomContainer or AtomList or List[moldesign.Atom]): atoms that make up
this molecule.
Note:
If the passed atoms don't already belong to a molecule, they will be assigned
to this one. If they DO already belong to a molecule, they will be copied,
leaving the original molecule untouched.
name (str): name of the molecule (automatically generated if not provided)
copy_atoms (bool): Create the molecule with *copies* of the passed atoms
(they will be copied automatically if they already belong to another molecule)
pdbname (str): Name of the PDB file
charge (units.Scalar[charge]): molecule's formal charge
electronic_state_index (int): index of the molecule's electronic state
metadata (dict): Arbitrary metadata dictionary
Examples:
Use the ``Molecule`` class to create copies of other molecules and substructures thereof:
>>> benzene = mdt.from_name('benzene')
>>> benzene_copy = mdt.Molecule(benzene, name='benzene copy')
>>> protein = mdt.from_pdb('3AID')
>>> carbon_copies = mdt.Molecule([atom for atom in protein.atoms if atom.atnum==6])
>>> first_residue_copy = mdt.Molecule(protein.residues[0])
**Molecule instance attributes:**
Attributes:
atoms (AtomList): List of all atoms in this molecule.
bond_graph (mdt.molecules.BondGraph): symmetric dictionary specifying bonds between the
atoms:
``bond_graph = {atom1:{atom2:bond_order, atom3:bond_order}, atom2:...}``
``bond_graph[atom1][atom2] == bond_graph[atom2][atom1]``
residues (List[moldesign.Residue]): flat list of all biomolecular residues in this molecule
chains (Dict[moldesign.Chain]): Biomolecular chains - individual chains can be
accessed as ``mol.chains[list_index]`` or ``mol.chains[chain_name]``
name (str): A descriptive name for molecule
charge (units.Scalar[charge]): molecule's formal charge
constraints (List[moldesign.geom.GeometryConstraint]): list of constraints
ndims (int): length of the positions, momenta, and forces arrays (usually 3*self.num_atoms)
num_atoms (int): number of atoms (synonym: natoms)
num_bonds (int): number of bonds (synonym: nbonds)
positions (units.Array[length]): Nx3 array of atomic positions
momenta (units.Array[momentum]): Nx3 array of atomic momenta
masses (units.Vector[mass]): vector of atomic masses
dim_masses (units.Array[mass]): Nx3 array of atomic masses (for numerical convenience -
allows you to calculate velocity, for instance, as
``velocity = mol.momenta/mol.dim_masses``
time (units.Scalar[time]): current time in dynamics
energy_model (moldesign.models.base.EnergyModelBase): Object that calculates
molecular properties - driven by `mol.calculate()`
integrator (moldesign.integrators.base.IntegratorBase): Object that drives movement of 3D
coordinates in time, driven by mol.run()
is_biomolecule (bool): True if this molecule contains at least 2 biochemical residues
**Molecule methods and properties**
See also methods offered by the mixin superclasses:
- :class:`moldesign.molecules.AtomContainer`
- :class:`moldesign.molecules.MolPropertyMixin`
- :class:`moldesign.notebook_display.MolNotebookMixin`
- :class:`moldesign.molecules.MolSimulationMixin`
- :class:`moldesign.molecules.MolTopologyMixin`
- :class:`moldesign.molecules.MolConstraintMixin`
- :class:`moldesign.molecules.MolNotebookMixin`
"""
positions = ProtectedArray('_positions')
momenta = ProtectedArray('_momenta')
draw_orbitals = WidgetMethod('molecules.draw_orbitals')
configure_methods = WidgetMethod('molecules.configure_methods')
_PERSIST_REFERENCES = True # relevant for `pyccc` RPC calls
def __init__(self, atomcontainer,
name=None,
copy_atoms=False,
pdbname=None,
charge=None,
metadata=None):
super().__init__()
# initial property init
self.name = 'uninitialized molecule'
self._constraints = None
self._charge = None
self._properties = None
atoms, name = self._get_initializing_atoms(atomcontainer, name, copy_atoms)
if metadata is None:
metadata = getattr(atomcontainer, 'metadata', utils.DotDict())
self.atoms = atoms
self.bond_graph = BondGraph(self)
self.time = getattr(atomcontainer, 'time', 0.0 * u.default.time)
self.pdbname = pdbname
self.constraints = []
self.energy_model = None
self.integrator = None
self.metadata = metadata
self.electronic_state_index = 0
if charge is not None:
self.charge = charge
else:
self.charge = getattr(atomcontainer, 'charge',
u.unitsum(atom.formal_charge for atom in self.atoms))
# Builds the internal memory structures
self.chains = PrimaryStructure(self)
self._rebuild_from_atoms()
if name is not None:
self.name = name
elif not self.is_small_molecule:
self.name = 'unnamed macromolecule'
else:
self.name = self.get_stoichiometry()
self._properties = MolecularProperties(self)
self.ff = None
def _get_initializing_atoms(self, atomcontainer, name, copy_atoms):
""" Make a copy of the passed atoms as necessary, return the name of the molecule
"""
# copy atoms from another object (i.e., a molecule)
oldatoms = helpers.get_all_atoms(atomcontainer)
if copy_atoms or (oldatoms[0].molecule is not None):
atoms = oldatoms.copy_atoms()
if name is None: # Figure out a reasonable name
if oldatoms[0].molecule is not None:
name = oldatoms[0].molecule.name+' copy'
elif hasattr(atomcontainer, 'name') and isinstance(atomcontainer.name, str):
name = utils.if_not_none(name, atomcontainer.name+' copy')
else:
name = 'unnamed'
else:
atoms = oldatoms
return atoms, name
def __repr__(self):
try:
return '<%s (%s), %d atoms>' % (self.name,
self.__class__.__name__,
len(self.atoms))
except (KeyError, AttributeError):
return '<molecule (error in __repr__) at %s>' % id(self)
def __str__(self):
return 'Molecule: %s' % self.name
@property
def constraints(self):
return self._constraints
@constraints.setter
def constraints(self, val):
self._constraints = utils.ExclusiveList(val, key=utils.methodcaller('_constraintsig'))
def _repr_markdown_(self):
"""A markdown description of this molecule.
Returns:
str: Markdown
"""
# TODO: remove leading underscores for descriptor-protected attributes
lines = ['### Molecule: "%s" (%d atoms)'%(self.name, self.natoms)]
description = self.metadata.get('description', None)
if description is not None:
description = self.metadata.description[:5000]
url = self.metadata.get('url', None)
if url is not None:
description = '<a href="%s" target="_blank">%s</a>'% \
(url, description)
lines.append(description)
lines.extend([
'**Mass**: %s' % self.mass,
'**Formula**: %s' % self.get_stoichiometry(html=True),
'**Charge**: %s' % self.charge])
if self.energy_model:
lines.append('**Potential model**: %s'%str(self.energy_model))
if self.integrator:
lines.append('**Integrator**: %s'%str(self.integrator))
lines.extend(self.chains._repr_markdown_())
return '\n\n'.join(lines)
def new_bond(self, a1, a2, order):
""" Create a new bond
Args:
a1 (moldesign.Atom): First atom in the bond
a2 (moldesign.Atom): Second atom in the bond
order (int): order of the bond
Returns:
moldesign.Bond
"""
assert a1.molecule == a2.molecule == self
return a1.bond_to(a2, order)
@property
def velocities(self):
""" u.Vector[length/time]: Nx3 array of atomic velocities
"""
return (self.momenta/self.dim_masses).defunits()
@velocities.setter
def velocities(self, value):
self.momenta = value * self.dim_masses
@property
def num_bonds(self):
"""int: number of chemical bonds in this molecule"""
return sum(atom.nbonds for atom in self.atoms) // 2
nbonds = num_bonds
def add_atom(self, newatom):
""" Add a new atom to the molecule
Args:
newatom (moldesign.Atom): The atom to add
(it will be copied if it already belongs to a molecule)
"""
self.add_atoms([newatom])
def add_atoms(self, newatoms):
"""Add new atoms to this molecule.
*Copies* of the passed atoms will be added if they already belong to another molecule.
Args:
newatoms (List[moldesign.Atom]))
"""
owner = newatoms[0].molecule
for atom in newatoms:
if atom.molecule is not owner:
raise ValueError('Cannot add atoms from multiple sources - add them separately.')
if owner is not None: # copy if the atoms are already owned
newatoms = mdt.AtomList(newatoms).copy()
self.atoms.extend(newatoms)
self.bond_graph._add_atoms(newatoms)
self._rebuild_from_atoms()
def delete_bond(self, bond_or_atom, a2=None):
""" Remove this bond from the molecule's topology
Args:
bond_or_atom (Bond or Atom): bond to remove (or the first of two atom)
a2 (Atom): second atom in bond (if first argument was also an atom)
"""
if a2 is None: # it's a bond
a1, a2 = bond_or_atom.a1, bond_or_atom.a2
else: # they passed 2 atoms
a1 = bond_or_atom
self.bond_graph[a1].pop(a2)
self._topology_changed()
def write(self, filename=None, **kwargs):
""" Write this molecule to a string or file.
Calls :ref:`moldesign.converters.write`
Args:
filename (str): filename to write (if not passed, write to string)
format (str): file format (if filename is not passed, format must be specified)
Guessed from file extension if not passed
"""
# TODO: make it easier to do the right thing, which is write to .pkl.bz2
return mdt.write(self, filename=filename, **kwargs)
@property
def is_small_molecule(self):
"""bool: True if molecule's mass is less than 500 Daltons (not mutually exclusive with
:meth:`self.is_biomolecule <Molecule.is_biomolecule>`)"""
return self.mass <= 500.0 * u.amu
@property
def bonds(self):
""" Iterator over all bonds in the molecule
Yields:
moldesign.atoms.Bond: bond object
"""
for atom in self.bond_graph:
for nbr in self.bond_graph[atom]:
if atom.index > nbr.index: continue # don't double count
yield Bond(atom, nbr)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/biounits.py | .py | 7,897 | 239 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from past.builtins import basestring
from sortedcontainers import SortedListWithKey
import functools
import moldesign as mdt
from .. import utils
from . import toplevel, AtomList, AtomContainer
class ChildList(AtomContainer):
""" A list of biochemical objects that can be accessed by name or by index.
"""
__len__ = utils.Alias('_childinorder.__len__')
__iter__ = utils.Alias('_childinorder.__iter__')
index = utils.Alias('_childinorder.index')
def __str__(self):
return str([item.name for item in self])
def __repr__(self):
try:
return '<Children of %s: %s>' % (self.parent, self)
except (KeyError, AttributeError):
return '<ChildList @ %x (exception in self.__repr__)>' % id(self)
def __init__(self, parent):
super().__init__()
self.parent = parent
self._childbyname = {}
self._childinorder = SortedListWithKey(key=_SortKey)
def __dir__(self):
return (list(self.__dict__.keys()) + list(self.__class__.__dict__.keys())
+ list(self._childbyname.keys()))
def __getitem__(self, item):
if isinstance(item, (int, slice)):
try:
return self._childinorder[item]
except IndexError:
raise IndexError("No object with index %d in %s" % (item, self.parent))
else:
try:
return self._childbyname[item]
except KeyError:
raise KeyError("No object with name '%s' in %s" % (item, self.parent))
def __setitem__(self, key, val):
if key in self._childbyname:
raise KeyError('%s already exists in %s' % (key, self.parent))
self._childbyname[key] = val
self._childinorder.add(val)
def __contains__(self, item):
if isinstance(item, basestring) or item is None:
return (item in self._childbyname)
else:
try:
return (item in self._childinorder)
except TypeError: # meaning that the comparison couldn't even be made
return False
def __getattr__(self, item):
if item == '_childbyname':
return self.__getattribute__('_childbyname')
try:
return self._childbyname[item]
except KeyError:
raise AttributeError('ChildList object in %s has no attribute %s.' %
(self.parent.__repr__(), item))
def iteratoms(self):
"""Iterate over all atoms
Yields:
Atom: all atoms in this entity and/or its children
"""
for child in self:
if isinstance(child, mdt.Atom):
yield child
else:
for atom in child.iteratoms():
yield atom
@property
def atoms(self):
""" AtomList: a sorted list of all atoms in this entity and/or its children
"""
return AtomList(self.iteratoms())
def rebuild(self):
self._childbyname = {obj.name: obj for obj in self._childinorder}
self._childinorder = SortedListWithKey([obj for obj in self._childbyname.values()],
key=_SortKey)
@functools.total_ordering
class _SortKey(object):
def __init__(self, obj):
self.obj = obj
def __eq__(self, other):
return self.obj is other.obj
def __ne__(self, other):
# if not present, this always returns True in python 2. (???)
return not self == other
def __lt__(self, other):
try:
return self.obj.index < other.obj.index
except TypeError:
pass
try:
return self.obj.pdbindex < other.obj.pdbindex
except TypeError:
return id(self.obj) < id(other.obj)
class MolecularHierarchy(AtomContainer):
"""
Generalized storage mechanism for hierarchical representation of biomolecules,
e.g. by residue, chain, etc. Permits other groupings, provided that everything is
tree-like.
All children of a given entity must have unique names. An individual child can be retrieved with
``x.childname`` or ``x['childname']`` or ``x[index]``
Yields:
BioContainer or mdt.Atom: this entity's children, in order
"""
__getitem__ = utils.Alias('children.__getitem__')
__len__ = utils.Alias('children.__len__')
__iter__ = utils.Alias('children.__iter__')
__contains__ = utils.Alias('children.__contains__')
atoms = utils.Alias('children.atoms')
iteratoms = utils.Alias('children.iteratoms')
rebuild = utils.Alias('children.rebuild')
def __init__(self, name=None, molecule=None, index=None, pdbname=None, pdbindex=None,
**kwargs):
""" Initialization:
Args:
name (str): Name of this biocontainer
parent (mdt.Molecule): molecule this biocontainer belongs to
index (int): index of this biocontainer in the parent molecule
pdbname (str): PDB-format name of this biocontainer
pdbindex (str): Index of this biocontainer in PDB format
"""
super().__init__()
self.children = ChildList(self)
self.molecule = molecule
self.name = name
self.index = index
self.pdbname = pdbname
self.pdbindex = pdbindex
for name, val in kwargs.items():
setattr(self, name, val)
def add(self, item, key=None):
""" Add a child to this entity.
Raises:
KeyError: if an object with this key already exists
Args:
item (MolecularHierarchy or mdt.Atom): the child object to add
key (str): Key to retrieve this item (default: ``item.name`` )
"""
if key is None:
key = item.name
self.children[key] = item
__setitem__ = add
def __dir__(self):
return (list(self.__dict__.keys()) +
list(self.__class__.__dict__.keys()) +
[x.name for x in self.children])
def __hash__(self):
""" Explicitly hash by object id
"""
return id(self)
def __eq__(self, other):
return self is other
def __repr__(self):
try:
if self.molecule is not None:
return '<%s in %s>' % (self, self.molecule)
else:
return '<%s (no molecule)>' % self
except (KeyError, AttributeError):
return '<%s at %s (exception in __repr__)>' % (self.__class__.__name__,
id(self))
def __str__(self):
return '%s %s (index=%s)' % (self.__class__.__name__,
self.name, str(self.index))
def __call__(self, **kwargs):
"""
Allow for some simple queries, i.e. mol.chain['A'].residue(pdbname='ALA')
"""
retlist = []
for child in self:
for key, val in kwargs.items():
if hasattr(child, key) and getattr(child, key) == val:
retlist.append(child)
return retlist
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/coord_arrays.py | .py | 2,878 | 83 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module contains python "descriptors" (nothing to do with chemoinformatic "descriptors") that
help maintain the links between an atom's coordinates and its molecule's coordinates
"""
class ProtectedArray(object):
"""
Descriptor for arrays that shouldn't be reassigned.
Makes sure array attributes (specifically position and momentum) are modified in place
Args:
name (str): name of the instance attribute
"""
def __init__(self, name):
self.name = name
def __get__(self, instance, cls=None):
return getattr(instance, self.name)
def __set__(self, instance, value):
self.__get__(instance)[:] = value
class AtomArray(ProtectedArray):
"""
Descriptor for atom coordinates are stored in the parent molecule.
Makes sure that the arrays and their references are maintained during both
reassignment and copying/pickling
Args:
atomname (str): name of the attribute in the atom instance
parentname (str): name of the corresponding attribute in the molecule instance
"""
def __init__(self, atomname, moleculename):
self.name = atomname
self.moleculename = moleculename
def __get__(self, instance, cls=None):
if instance.molecule is None:
return getattr(instance, self.name)
else:
return getattr(instance.molecule, self.moleculename)[instance.index]
class AtomCoordinate(object):
""" Descriptor for use with the ``Atom`` class.
Gives access to 3D coordinates as ``atom.x,atom.y,atom.z`` instead of
``atom.position[0],atom.position[1],atom.position[2]``
Args:
quantity (str): name of the attribute that this accesses
index (int): component of the attribute that this accesses
"""
def __init__(self, attrname, index):
self.attrname = attrname
self.index = index
def __get__(self, instance, cls):
array = getattr(instance, self.attrname)
return array[self.index]
def __set__(self, instance, value):
array = getattr(instance, self.attrname)
array[self.index] = value | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/atoms.py | .py | 19,059 | 500 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
import numpy as np
import moldesign as mdt
from .. import data, utils
from .. import units as u
from ..widgets import WidgetMethod
from . import toplevel, AtomContainer, AtomList, AtomArray, AtomCoordinate, Bond
class AtomPropertyMixin(object): # TODO: this isn't worth it, just put it back into Atom
""" Functions accessing computed atomic properties.
Note:
This is a mixin class designed only to be mixed into the :class:`Atom` class. Routines
are separated are here for code organization only - they could be included in the main
Atom class without changing any functionality
"""
distance = utils.Alias('_container.distance')
atoms_within = utils.Alias('_container.atoms_within')
residues_within = utils.Alias('_container.residues_within')
@utils.args_from(AtomContainer.calc_distance_array)
def calc_distances(self, *args, **kwargs):
array = self._container.calc_distance_array(*args, **kwargs)
return array[0]
@property
def _container(self):
""" AtomContainer: a container with just this atom in it.
This is a convenience method for accessing to all of the :class:`AtomContainer`'s
useful methods for dealing with geometry
"""
return AtomList([self])
@property
def ff(self):
""" utils.DotDict: This atom's force field parameters, if available (``None``
otherwise)
"""
if self.molecule.ff is None:
return None
else:
return self.molecule.ff.get_atom_terms(self)
@property
def basis_functions(self):
""" List[mdt.orbitals.AtomicBasisFunction]: This atom's basis functions, if available
(``None`` otherwise)
"""
if self.molecule is None:
return None
try:
wfn = self.molecule.wfn
except mdt.exceptions.NotCalculatedError:
return None
try:
return wfn.aobasis.get_basis_functions_on_atom(self)
except KeyError:
return None
@property
def properties(self):
""" utils.DotDict: Returns any calculated properties for this atom
"""
props = utils.DotDict()
for name, p in self.molecule.properties.items():
if hasattr(p, 'type') and p.type == 'atomic':
props[name] = p[self]
return props
# TODO: units need to stay up to date if defaults change
_position0 = np.zeros(3) * u.default.length
_momentum0 = np.zeros(3) * (u.default.length * u.default.mass/u.default.time)
@toplevel
class Atom(AtomPropertyMixin):
""" A data structure representing an atom.
``Atom`` objects store information about individual atoms within a larger molecular system,
providing access to atom-specific geometric, biomolecular, topological and property
information. Each :class:`Molecule<moldesign.Molecule>` is composed of a list of atoms.
Atoms can be instantiated directly, but they will generally be created
automatically as part of molecules.
Args:
name (str): The atom's name (if not passed, set to the element name + the atom's index)
atnum (int): Atomic number (if not passed, determined from element if possible)
mass (units.Scalar[mass]): The atomic mass (if not passed, set to the most abundant isotopic
mass)
chain (moldesign.Chain): biomolecular chain that this atom belongs to
residue (moldesign.Residue): biomolecular residue that this atom belongs to
pdbname (str): name from PDB entry, if applicable
pdbindex (int): atom serial number in the PDB entry, if applicable
element (str): Elemental symbol (if not passed, determined from atnum if possible)
**Atom instance attributes:**
Attributes:
name (str): A descriptive name for this atom
element (str): IUPAC elemental symbol ('C', 'H', 'Cl', etc.)
index (int): the atom's current index in the molecule
(``self is self.parent.atoms[ self.index]``)
atnum (int): atomic number (synonyms: atomic_num)
mass (u.Scalar[mass]): the atom's mass
position (units.Vector[length]): atomic position vector. Once an atom is part of a molecule,
this quantity will refer to ``self.molecule.positions[self.index]``.
momentum (units.Vector[momentum]): atomic momentum vector. Once an atom is part of a
molecule, this quantity will refer to ``self.molecule.momenta[self.index]``.
x,y,z (u.Scalar[length]): x, y, and z components of ``atom.position``
vx, vy, vz (u.Scalar[length/time]): x, y, of ``atom.velocity``
px, py, pz (u.Scalar[momentum]): x, y, and z of ``atom.momentum``
fx, fy, fz (u.Scalar[force]): x, y, and z ``atom.force``
residue (moldesign.Residue): biomolecular residue that this atom belongs to
chain (moldesign.Chain): biomolecular chain that this atom belongs to
parent (moldesign.Molecule): molecule that this atom belongs to
index (int): index in the parent molecule: ``atom is atom.parent.atoms[index]``
**Atom methods and properties**
See also methods offered by the mixin superclasses:
- :class:`AtomGeometryMixin`
- :class:`AtomPropertyMixin`
"""
x, y, z = (AtomCoordinate('position', i) for i in range(3))
vx, vy, vz = (AtomCoordinate('velocity', i) for i in range(3))
px, py, pz = (AtomCoordinate('momentum', i) for i in range(3))
fx, fy, fz = (AtomCoordinate('force', i) for i in range(3))
position = AtomArray('_position', 'positions')
momentum = AtomArray('_momentum', 'momenta')
atomic_number = utils.Synonym('atnum')
draw2d = WidgetMethod('atoms.draw2d')
draw3d = WidgetMethod('atoms.draw3d')
draw = WidgetMethod('atoms.draw')
_PERSIST_REFERENCES = True # relevant for `pyccc` helper library
#################################################################
# Methods for BUILDING the atom and indexing it in a molecule
def __init__(self, name=None, atnum=None, mass=None, residue=None,
formal_charge=None, pdbname=None, pdbindex=None, element=None,
metadata=None, position=None, momentum=None):
# Allow user to instantiate an atom as Atom(6) or Atom('C')
if atnum is None and element is None:
if isinstance(name, int): # Ex: name=6 becomes atnum=6
atnum, name = name, None
elif name in data.ATOMIC_NUMBERS: # Ex: name='Na' becomes element='Na'
element, name = name, None
# Determine the element
if atnum:
self.atnum = atnum
if element:
assert atnum == data.ATOMIC_NUMBERS[element.capitalize()], \
"Atomic number '%s' does match specified element '%s'" % (atnum, element)
elif element:
if element.capitalize() in data.ATOMIC_NUMBERS:
self.atnum = data.ATOMIC_NUMBERS[element.capitalize()]
else:
raise KeyError("Unknown element '%s'" % element)
elif name[0].upper() in data.ATOMIC_NUMBERS: # Ex: name='Ca' -> atnum=6
self.atnum = data.ATOMIC_NUMBERS[name[0].upper()]
else:
raise KeyError('Could not determine the atomic number of this atom. '
'You can set it explicitly with the "atnum" keyword.')
self.name = utils.if_not_none(name, self.elem)
self.pdbname = utils.if_not_none(pdbname, self.name)
self.pdbindex = pdbindex
if mass is None: self.mass = data.ATOMIC_MASSES[self.atnum]
else: self.mass = mass
self.formal_charge = utils.if_not_none(formal_charge, 0.0 * u.q_e)
if not hasattr(self.formal_charge, 'units'):
self.formal_charge *= u.q_e
self.residue = residue
self.molecule = None
self.index = None
if position is None:
self._position = _position0.copy()
else:
self._position = position
if momentum is None:
self._momentum = _momentum0.copy()
else:
self._momentum = momentum
self._bond_graph = {}
self.metadata = utils.DotDict()
if metadata:
self.metadata.update(metadata)
def _subcopy(self, memo=None):
""" Private data mangement method for copying the local substructure of an atom.
This is a shallow copy, and is intended to be deepcopied to avoid corrupting the original
atom's data.
Generally, the public interface for this is the ``copy`` methods of objects like
Molecules, AtomLists, Residues etc. ...
"""
import copy
if memo is None:
memo = {'bondgraph':{}}
if self in memo:
return
newatom = copy.copy(self)
newatom.molecule = None
newatom.residue = None
newatom.bond_graph = {}
memo[self] = newatom
# This separates the bond graph from the atoms for serialization; otherwise it creates
# highly recursive relationships between all the atoms
memo['bondgraph'][newatom] = {}
for nbr, order in self.bond_graph.items():
if nbr not in memo:
continue
else:
memo['bondgraph'][newatom][memo[nbr]] = order
memo['bondgraph'][memo[nbr]][newatom] = order
if self.residue is not None:
if self.residue not in memo:
self.residue._subcopy(memo)
memo[self.residue].add(newatom)
@property
def chain(self):
if self.residue is not None:
return self.residue.chain
else:
return None
@chain.setter
def chain(self, val):
raise AttributeError("To assign an atom to a chain, assign it to a residue _within_ that"
"chain.")
def __str__(self):
desc = '%s %s (elem %s)' % (self.__class__.__name__, self.name, self.elem)
molstring = ''
if self.molecule:
molstring = ', index %d' % self.index
if self.molecule.is_biomolecule:
molstring += ' (res %s chain %s)' % (self.residue.name, self.chain.name)
return '%s%s' % (desc, molstring)
def _shortstr(self):
""" A shorter string representation for easier-to-read lists of atoms
"""
fields = [self.name]
if self.molecule:
fields.append('#%d' % self.index)
if self.molecule.is_biomolecule:
fields.append('in %s.%s' % (self.chain.name, self.residue.name))
return ' '.join(fields)
def __repr__(self):
try:
if self.molecule:
return '<%s in molecule %s>' % (self, self.molecule)
else:
return '<%s>' % self
except (KeyError, AttributeError):
return '<%s at %s (exception in __repr__)>' % (self.__class__.__name__, id(self))
@utils.args_from(AtomContainer.copy_atoms)
def copy(self, *args, **kwargs):
""" Copy an atom (delegate to AtomContainer)
"""
return self._container.copy_atoms(*args, **kwargs)[0]
def __getstate__(self):
"""Helper for pickling"""
state = self.__dict__.copy()
if self.molecule is not None: # then these don't belong to the atom anymore
state['_bond_graph'] = None
state['_position'] = self.position
state['_momentum'] = self.momentum
return state
def _set_molecule(self, molecule):
""" Permanently make this atom part of a molecule (private)
Args:
parent (moldesign.Molecule): the molecule that this atom will become a part of
"""
if self.molecule and (molecule is not self.molecule):
raise ValueError('Atom is already part of a molecule')
self.molecule = molecule
def _index_into_molecule(self, array_name, moleculearray, index):
""" Link the atom's positions and momenta to the parent molecule (private)
Args:
array_name (str): the private name of the array (assumes private name is '_'+array_name)
moleculearray (u.Array): the molecule's master array
index: the atom's index in the molecule
Note:
This will be called by the molecule's init method
"""
oldarray = getattr(self, array_name)
moleculearray[index, :] = oldarray
setattr(self, '_' + array_name, None) # remove the internally stored version
def bond_to(self, other, order):
""" Create or modify a bond with another atom
Args:
other (Atom): atom to bond to
order (int): bond order
Returns:
moldesign.molecules.bonds.Bond: bond object
"""
if self.molecule is other.molecule:
self.bond_graph[other] = other.bond_graph[self] = order
if self.molecule is not None:
self.molecule._topology_changed()
else: # allow unassigned atoms to be bonded to anything for building purposes
self.bond_graph[other] = order
return Bond(self, other)
@property
def bond_graph(self):
""" Mapping[Atom, int]: dictionary of this atoms bonded neighbors, of the form
``{bonded_atom1, bond_order1, ...}``
"""
if self.molecule is None:
return self._bond_graph
else:
return self.molecule.bond_graph[self]
@bond_graph.setter
def bond_graph(self, value):
if self.molecule is None:
self._bond_graph = value
else:
self._bond_graph = None
self.molecule.bond_graph[self] = value
@property
def bonds(self):
""" List[Bond]: list of all bonds this atom is involved in
"""
return [Bond(self, nbr) for nbr in self.bond_graph]
@property
def heavy_bonds(self):
""" List[Bond]: list of all heavy atom bonds (where BOTH atoms are not hydrogen)
Note:
this returns an empty list if called on a hydrogen atom
"""
if self.atnum == 1:
return []
else:
return [Bond(self, nbr)
for nbr in self.bond_graph
if nbr.atnum > 1]
@property
def bonded_atoms(self):
""" List[moldesign.Atom]: a list of the atoms this atom is bonded to
"""
return [bond.partner(self) for bond in self.bonds]
@property
def force(self):
""" (units.Vector[force]): atomic force vector. This quantity must be calculated - it is
equivalent to ``self.molecule.forces[self.index]``
Raises:
moldesign.NotCalculatedError: if molecular forces have not been calculated
"""
f = self.molecule.forces
return f[self.index]
@property
def velocity(self):
""" u.Vector[length/time, 3]: velocity of this atom; equivalent to
``self.momentum/self.mass``
"""
return (self.momentum / self.mass).defunits()
@velocity.setter
def velocity(self, value):
self.momentum = value * self.mass
@property
def num_bonds(self):
""" int: the number of other atoms this atom is bonded to
"""
return len(self.bond_graph)
nbonds = num_bonds
@property
def valence(self):
""" int: the sum of this atom's bond orders
"""
return sum(v for v in self.bond_graph.values())
@property
def symbol(self):
""" str: elemental symbol
"""
return data.ELEMENTS.get(self.atnum, '?')
elem = element = symbol
def markdown_summary(self):
"""Return a markdown-formatted string describing this atom
Returns:
str: markdown-formatted string
"""
if self.molecule is None:
lines = ["<h3>Atom %s</h3>"%self.name]
else:
lines = ["<h3>Atom %s (index %d)</h3>"%(self.name, self.index)]
lines.append('**Atomic number**: %d'%self.atnum)
lines.append("**Mass**: %s"%self.mass)
lines.append('**Formal charge**: %s'%self.formal_charge)
if self.molecule is not None:
lines.append('\n')
if self.molecule.is_biomolecule:
if self.pdbindex is not None:
lines.append('**PDB serial #**: %s'%self.pdbindex)
lines.append("**Residue**: %s (index %d)"%(self.residue.name, self.residue.index))
lines.append("**Chain**: %s"%self.chain.name)
lines.append("**Molecule**: %s"%self.molecule.name)
for ibond, (nbr, order) in enumerate(self.bond_graph.items()):
lines.append('**Bond %d** (order = %d): %s (index %s) in %s' % (
ibond + 1, order, nbr.name, nbr.index, nbr.residue.name))
if self.basis_functions:
lines.append('**Basis functions:**<br>'+ '<br>'.join(map(str, self.basis_functions)))
if self.ff:
lines.append('\n**Forcefield partial charge**: %s'%self.ff.partial_charge)
# TODO: deal with other LJ types, e.g., AB?
lines.append(u'**Forcefield LJ params**: '
u'\u03C3=%s, \u03B5=%s'%(
self.ff.ljsigma.defunits(),
self.ff.ljepsilon.defunits()))
# position and momentum
table = utils.MarkdownTable('', 'x', 'y', 'z')
table.add_line(['**position /** {}'.format(u.default.length)]+
['%12.3f'%x.defunits_value() for x in self.position])
table.add_line(['**momentum /** {}'.format(u.default.momentum)]+
['%12.3e'%m.defunits_value() for m in self.momentum])
if self.molecule is not None and 'forces' in self.molecule.properties:
table.add_line(['**force /** {.units}'.format(self.force.defunits())]+
['%12.3e'%m.defunits_value() for m in self.force])
lines.append('\n\n' + table.markdown() + '\n\n')
# All other assigned properties
return '<br>'.join(lines)
def _repr_markdown_(self):
return self.markdown_summary()
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/molecules/properties.py | .py | 3,962 | 117 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from . import toplevel
from .. import utils, units
@toplevel
class MolecularProperties(utils.DotDict):
""" Stores property values for a molecule.
These objects will be generally created and updated by EnergyModels, not by users.
Args:
mol (Molecule): molecule that these properties are associated with
**properties (dict): values of molecular properties (MUST include positions as a key)
"""
def __init__(self, mol, **properties):
self.mol = mol
positions = properties.pop('positions', mol.positions)
super().__init__(positions=positions.copy(), **properties)
def copy_to(self, mol):
"""
Args:
mol (moldesign.Molecule): molecule to copy these properties to
Returns:
MolecularProperties: copied instance, associated with the new molecule
"""
newprops = self.__class__(mol, positions=self.positions)
for name, val in self.items():
if name == 'positions':
continue
elif hasattr(val, 'copy_to'):
newprops[name] = val.copy_to(mol)
elif hasattr(val, 'copy'):
newprops[name] = val.copy()
else:
newprops[name] = val
return newprops
def geometry_matches(self, mol):
""" Returns true if a molecule's positions are the same as in these properties.
Allows for some very slight numerical noise due to units conversion and associated issues.
Returns:
bool: True if the molecule's ``position`` is the same as these properties' ``position``
"""
return units.arrays_almost_equal(self.positions, mol.positions)
def __getitem__(self, item):
return units.default.convert_if_possible(super().__getitem__(item))
def __getattr__(self, item):
return units.default.convert_if_possible(super().__getattr__(item))
class AtomicProperties(utils.NewUserDict):
"""
Stores calculated atomic properties
Internally, references atoms by their indices rather than by object, which lets us
copy molecular properties without weird reference issues
Args:
mapping (Mapping[moldesign.Atom, Any]): map of atoms to properties
"""
type = 'atomic' # backwards-compatible signal that this is a map from atoms to property values
def __init__(self, mapping=None):
super().__init__()
if mapping is not None:
self.update(mapping)
def copy(self):
new = self.__class__()
super(self.__class__, new).update(self)
return new
def update(self, mapping):
for k,v in mapping.items():
self[k] = v
# TODO: check that passed atoms actually belong to the correct molecule
def __setitem__(self, atom, value):
super().__setitem__(self._getkey(atom), value)
def __getitem__(self, atom):
return super().__getitem__(self._getkey(atom))
@staticmethod
def _getkey(atom):
if isinstance(atom, int):
k = atom
else:
k = atom.index
return k
def __contains__(self, atom):
return super().__contains__(self._getkey(atom))
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_minimizers.py | .py | 6,257 | 182 | import collections
import numpy as np
import pytest
import moldesign as mdt
from .helpers import assert_something_resembling_minimization_happened
from moldesign import units as u
from moldesign.compute import packages
__PYTEST_MARK__ = 'minimization'
@pytest.fixture(scope='function')
def harmonic_atom():
mol = mdt.Molecule([mdt.Atom(1)])
mol.atoms[0].x = 2.0 * u.angstrom
mol.set_energy_model(mdt.models.HarmonicOscillator, k=2.0*u.kcalpermol/u.angstrom**2)
return mol
@pytest.fixture(scope='function')
def scrambled():
mol = mdt.from_smiles('C=C')
mol.set_energy_model(mdt.models.OpenBabelPotential, forcefield='mmff94s')
mol.com = [0, 0, 0] * u.angstrom
_apply_noise(mol, scale=5.0)
e0 = mol.calculate_potential_energy()
p0 = mol.positions.copy()
return mol, e0, p0
@pytest.mark.parametrize('MinClass', (mdt.min.GradientDescent,
mdt.min.BFGS,
mdt.min.SmartMin))
def test_basic_minimization(harmonic_atom, MinClass):
mol = harmonic_atom
e0 = mol.calculate_potential_energy()
p0 = mol.positions.copy()
minimizer = MinClass(mol)
traj = minimizer()
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.parametrize('MinClass', (mdt.min.GradientDescent,
mdt.min.BFGS,
mdt.min.SmartMin))
def test_basic_minimization_remotely(harmonic_atom, MinClass):
mol = harmonic_atom
e0 = mol.calculate_potential_energy()
p0 = mol.positions.copy()
minimizer = MinClass(mol)
traj = minimizer.runremotely()
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
MINIMIZERS = collections.OrderedDict([('gradient_descent', mdt.min.gradient_descent),
('leastsqr', mdt.min.sequential_least_squares),
('bfgs', mdt.min.bfgs),
('smart', mdt.min.minimize)])
# (ordered because pytest+xdist needs a definite ordering of parameters)
def test_extreme_forces_with_smart_minimizer(scrambled):
mol, e0, p0 = scrambled
traj = mdt.minimize(mol, nsteps=500)
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.skipif(not packages.openbabel.is_installed(),
reason='Redundant with regular test in this environment')
@pytest.mark.screening
def test_remote_with_smart_minimizer(scrambled):
mol, e0, p0 = scrambled
minimizer = mdt.min.SmartMin(mol, nsteps=500)
traj = minimizer.runremotely()
assert traj.mol is mol
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.skipif(not packages.openbabel.is_installed(),
reason='Redundant with regular test in this environment')
def test_remote_with_smart_minimizer_async(scrambled):
mol, e0, p0 = scrambled
job = mdt.min.minimize(mol, nsteps=500, remote=True, wait=False)
assert (mol.positions == p0).all() # shouldn't have changed yet
job.wait()
assert (mol.positions != p0).any() # NOW it should have changed yet
traj = job.result
assert traj.mol is mol
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.skipif(packages.openbabel.is_installed(),
reason='Requires that openbabel NOT installed')
def test_remote_minimization_automatic_if_openbabel_not_installed(scrambled):
mol, e0, p0 = scrambled
# a bit of an API hack - remote overridden if the model isn't installed locally
job = mdt.min.minimize(mol, nsteps=500, remote=False, wait=False)
assert (mol.positions == p0).all() # shouldn't have changed yet
job.wait()
assert (mol.positions != p0).any() # NOW it should have changed yet
traj = job.result
assert traj.mol is mol
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.parametrize('minkey',(MINIMIZERS.keys()))
def test_constrained_distance_minimization(minkey):
minimizer = MINIMIZERS[minkey]
mol = mdt.Molecule([mdt.Atom(1), mdt.Atom(2)])
mol.atoms[0].x = 2.0 * u.angstrom
mol.atoms[1].x = 3.0 * u.angstrom
mol.atoms[1].y = 2.0 * u.angstrom
mol.set_energy_model(mdt.models.HarmonicOscillator, k=2.0*u.kcalpermol/u.angstrom**2)
e0 = mol.calculate_potential_energy()
p0 = mol.positions.copy()
mol.constrain_distance(mol.atoms[0], mol.atoms[1])
if minkey == 'bfgs': # BFGS expected to fail here
with pytest.raises(mdt.exceptions.NotSupportedError):
minimizer(mol)
return
traj = minimizer(mol)
assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.parametrize('minkey',(MINIMIZERS.keys()))
@pytest.mark.screening
def test_constrained_dihedral_minimization(minkey):
minimizer = MINIMIZERS[minkey]
mol = mdt.from_smiles('C=C')
assert mol.atoms[0].atnum == mol.atoms[1].atnum == 6 # make sure we're picking the right atoms
dihedral = mdt.DihedralMonitor(mol.atoms[0], mol.atoms[1])
assert dihedral.value == 0.0
dihedral.value = 45 * u.degrees
constraint = dihedral.constrain()
mol.set_energy_model(mdt.models.OpenBabelPotential, forcefield='mmff94s')
e0_1 = mol.calculate_potential_energy()
p0_1 = mol.positions.copy()
if minkey == 'bfgs': # BFGS expected to fail here
with pytest.raises(mdt.exceptions.NotSupportedError):
minimizer(mol)
return
traj = minimizer(mol, nsteps=100)
assert_something_resembling_minimization_happened(p0_1, e0_1, traj, mol)
assert constraint.error() <= 1.0 * u.degree
traj_twists = traj.dihedral(mol.atoms[0], mol.atoms[1])
assert (abs(traj_twists - 45 * u.degrees) <= 1.0 * u.degree).all()
e0_2 = mol.potential_energy
p0_2 = mol.positions.copy()
mol.clear_constraints()
traj2 = minimizer(mol, nsteps=100)
assert_something_resembling_minimization_happened(p0_2, e0_2, traj2, mol)
assert dihedral.value <= 5.0 * u.degrees
def _apply_noise(mol, scale=0.05):
noise = np.random.normal(size=(mol.num_atoms, 3), scale=scale) * u.angstrom
mol.positions += noise
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_objects.py | .py | 3,342 | 142 | import pickle
import pytest
import numpy as np
from moldesign.utils import Alias
from .object_fixtures import *
from .molecule_fixtures import *
from .object_fixtures import TESTDICT
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
class ComposedClass(object):
delegated = Alias('s.lower')
def __init__(self):
self.s = 'ABC'
@pytest.mark.parametrize('objkey', pickleable)
def test_pickling(objkey, request):
obj = request.getfixturevalue(objkey)
for iprotocol in (0,1,2):
x = pickle.dumps(obj, protocol=iprotocol)
y = pickle.loads(x)
assert type(y) == type(obj)
def test_alias():
t = ComposedClass()
assert t.delegated() == 'abc'
def test_dotdict_get(dotdict):
dd = dotdict
assert dd == dotdict
assert dd.get('c', None) == 3
assert dd.get('ccc', None) is None
assert dd.a == TESTDICT['a']
assert dd.d == TESTDICT['d']
def test_dotdict_iterators(dotdict):
dd = dotdict
assert len(dd) == len(TESTDICT)
assert set(dd.keys()) == set(TESTDICT.keys())
assert set(dd.values()) == set(TESTDICT.values())
assert dd
for item in TESTDICT:
assert item in dd
def test_dotdict_copy(dotdict):
dd = dotdict.copy()
assert dd == dotdict
assert dd._od == dotdict._od
dd.a = 4
assert dd.a == dd['a'] == 4
assert dotdict.a == dotdict['a'] == 1
del dd.a
assert 'a' not in dd
assert 'a' in dotdict
@pytest.mark.screening
def test_dotdict_removals(dotdict):
dd = dotdict.copy()
assert dd.pop('_a-a-a', None) is None
assert dd.pop('d', 4) == 'e'
assert 'd' not in dd
dd.d = 5
assert 'd' in dd
# item deletion
del dd.d
assert 'd' not in dd
assert len(dd) == len(TESTDICT) - 1
del dd[3]
assert 3 not in dd
def test_dotdict_clear(dotdict):
dd = dotdict.copy()
dd.clear()
assert len(dd) == 0
assert not dd
assert 'd' not in dd
assert 'c' not in dd
assert 'a' not in dd
with pytest.raises(AttributeError):
dd.c
with pytest.raises(KeyError):
dd['c']
def test_dotdict_introspection(dotdict):
dd = dotdict.copy()
assert not hasattr(dd, 'abcd')
assert hasattr(dd, 'c')
assert getattr(dd, 'c', None) is 3
assert getattr(dd, 'ddd', None) is None
with pytest.raises(AttributeError):
dd.ddd
with pytest.raises(KeyError):
dd['ddd']
dd['d'] = 'e'
def test_dotdict_consistency(dotdict):
dd = dotdict.copy()
dd['k'] = 12345
assert getattr(dd, 'k') == 12345
setattr(dd, 'newkey', -42)
assert dd['newkey'] == -42
def test_dotdict_preserves_ordering(dotdict):
assert list(dotdict.keys()) == list(TESTDICT.keys())
assert list(dotdict.values()) == list(TESTDICT.values())
assert list(dotdict.items()) == list(TESTDICT.items())
@pytest.mark.screening
def test_eigenspace_with_ndarray_identity_permutation():
from moldesign.mathutils import Eigenspace
evals = np.arange(3)
evecs = np.array([[0,1,0],
[1,0,0],
[0,0,1]],
dtype='float')
espace = Eigenspace(evals, evecs)
assert (espace.transform([1,0,0]) == [0,1.0, 0.0]).all()
assert (espace.transform(np.identity(3)) == espace.evecs).all()
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_dna_primary_structure.py | .py | 2,948 | 109 | """ Tests introspection and methods for dna primary structure
"""
import itertools
import pytest
import moldesign as mdt
from moldesign import units as u
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
fixture_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
fixture_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@typedfixture('dna')
def bdna_actg_helix():
dna = mdt.build_dna_helix('ACTG')
return dna
@pytest.mark.parametrize('fixture', fixture_types['dna'])
def test_dna_chain_properties(fixture, request):
mol = request.getfixturevalue(fixture)
assert mol.chains['A'].type == 'dna'
@pytest.mark.parametrize('fixture', fixture_types['dna'])
@pytest.mark.screening
def test_dna_residue_iteration(fixture, request):
mol = request.getfixturevalue(fixture)
assert mol.chains['A'].type == 'dna'
firstres = mol.chains['A'].residues[0]
for res in mol.chains['A']:
if res.type == 'dna':
lastres = res
lr = firstres
for res in mol.chains['A'][1:]:
if res is lastres:
break
assert res.prev_residue is lr
assert lr.next_residue is res
lr = res
lastseq = -1
for ires, res in enumerate(mol.chains['A'].polymer_residues):
if ires == 0:
assert res is firstres
assert res.pdbindex > lastseq
lastseq = res.pdbindex
assert res is lastres
@pytest.mark.parametrize('fixture', fixture_types['dna'])
def test_dna_chain_terminals(fixture, request):
mol = request.getfixturevalue(fixture)
assert mol.chains['A'].type == 'dna'
firstres = mol.chains['A'].residues[0]
for res in mol.chains['A']:
if res.type == 'dna':
lastres = res
assert firstres.is_5prime_end
assert lastres.is_3prime_end
assert mol.chains['A'].fiveprime_end is firstres
assert mol.chains['A'].threeprime_end is lastres
for res in mol.chains['A'][1:]:
if res is lastres:
break
assert not res.is_3prime_end
assert not res.is_5prime_end
with pytest.raises(StopIteration):
firstres.prev_residue
with pytest.raises(StopIteration):
lastres.next_residue
@pytest.mark.parametrize('fixture', fixture_types['dna'])
def test_protein_methods_on_dna_dont_work(fixture, request):
mol = request.getfixturevalue(fixture)
with pytest.raises(ValueError):
mol.residues[0].is_n_terminal
with pytest.raises(ValueError):
mol.residues[0].is_c_terminal
assert mol.chains[0].c_terminal is None
assert mol.chains[0].n_terminal is None
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_pdb_processing.py | .py | 5,266 | 162 | """
This file collects tests relating to the many special cases we deal with when
trying to process biomolecular structures from the pdb.
These currently just test the specific cases that we've implemented fixes for
"""
import pytest
import moldesign as mdt
from .helpers import get_data_path
import parmed
from distutils.version import LooseVersion
@pytest.fixture
def pdb_3ac2():
return mdt.read(get_data_path('3ac2.pdb.bz2'))
@pytest.fixture
def pdb_3ac2_roundtrip(pdb_3ac2):
return mdt.read(pdb_3ac2.write('pdb'), format='pdb')
@pytest.mark.parametrize('mol', 'pdb_3ac2 pdb_3ac2_roundtrip'.split())
def test_missing_terminal_atoms_3ac2(request, mol):
""" Tests that we can still detect terminal residues even if the peptide-bonded atoms
are missing from the structure
"""
mol = request.getfixturevalue(mol)
assert mol.chains['A'].n_terminal is not None
assert mol.chains['A'].c_terminal is not None
@pytest.fixture
def pdb_1hpk():
return mdt.read(get_data_path('1hpk.pdb'))
@pytest.fixture
def pdb_1hpk_roundtrip(pdb_1hpk):
return mdt.read(pdb_1hpk.write('pdb'), format='pdb')
@pytest.mark.parametrize('mol', 'pdb_1hpk pdb_1hpk_roundtrip'.split())
def test_1hpk(request, mol):
mol = request.getfixturevalue(mol)
mol = mdt.interfaces.tleap_interface._prep_for_tleap(mol)
for residx in (0, 21, 49, 61, 73, 78):
residue = mol.residues[residx]
assert residue.resname == 'CYX'
assert residue.name[:3] == 'CYX'
@pytest.fixture
def pdb_2jaj():
return mdt.read(get_data_path('2jaj.pdb.gz'))
@pytest.fixture
def pdb_2jaj_roundtrip(pdb_2jaj):
return mdt.read(pdb_2jaj.write('pdb'), format='pdb')
@pytest.mark.parametrize('mol', 'pdb_2jaj pdb_2jaj_roundtrip'.split())
@pytest.mark.screening
def test_negative_residue_numbers_2jaj(request, mol):
if (mol == 'pdb_2jaj_roundtrip' and
LooseVersion(getattr(parmed, '__version__', '0.0.0')) <= LooseVersion('2.7.3')):
pytest.xfail("This test requires ParmEd 2.7.4 (not yet released as of this writing)")
mol = request.getfixturevalue(mol)
res = mol.chains['B'].residues[0]
assert res.pdbindex == -4
assert res.index == 272
assert res.name == 'GLY-4'
@pytest.mark.parametrize('mol', 'pdb_2jaj pdb_2jaj_roundtrip'.split())
def test_missing_residues_xtal_2jaj(request, mol):
if mol == 'pdb_2jaj_roundtrip':
pytest.xfail('Writing missing residue records is not yet supported.')
mol = request.getfixturevalue(mol)
missingres = mol.metadata.missing_residues
for expected in MISSINGRES_2JAJ:
assert missingres[expected[0]][expected[2]] == expected[1]
def test_missing_residues_nmr_5b7a():
mol = mdt.read(get_data_path('5b7a.pdb.bz2'))
missingres = mol.metadata.missing_residues
for expected in MISSINGRES_5B7A:
assert missingres[expected[0]][expected[2]] == expected[1]
assert mol.metadata.description == 'STRUCTURES OF HUMAN SUMO'
@pytest.fixture
def pdb_1pyn():
return mdt.read(get_data_path('1pyn.pdb.gz'))
@pytest.fixture
def pdb_1pyn_roundtrip(pdb_1pyn):
return mdt.read(pdb_1pyn.write('pdb'), format='pdb')
@pytest.mark.parametrize('mol', 'pdb_1pyn pdb_1pyn_roundtrip'.split())
@pytest.mark.screening
def test_numeric_residue_name_1PYN(request, mol):
""" The ligand in this residue is named "941", which causes a little trickiness
"""
import parmed
mol = request.getfixturevalue(mol)
ligand = mdt.Molecule(mol.residues[283])
params = mdt.create_ff_parameters(ligand, charges='gasteiger')
params._file_list['mol.lib'].put('/tmp/tmp.lib')
contents = parmed.load_file('/tmp/tmp.lib')
assert len(contents) == 1
assert list(contents.keys())[0] == '941'
def test_single_chain_2p8w():
mol = mdt.read(get_data_path('2p8w.cif.bz2'))
assert mol.num_chains == 3
assert mol.chains['C'].num_residues == 1
assert mol.chains['C'].residues['GNP843'].num_atoms == 32
def test_missing_atoms_3b5x():
mol = mdt.read(get_data_path('3b5x.cif.bz2'))
assert mol.num_chains == 2
assert mol.num_atoms == 1144
assert mol.num_residues == 1144
MISSINGRES_2JAJ = [('A', 'GLY', -4), ('A', 'PRO', -3), ('A', 'LEU', -2), ('A', 'GLY', -1),
('A', 'MET', 0), ('A', 'ALA', 1), ('A', 'GLY', 2), ('A', 'LEU', 3),
('A', 'GLY', 4), ('A', 'HIS', 5), ('A', 'PRO', 6), ('A', 'ALA', 7),
('A', 'ALA', 32), ('A', 'LYS', 33), ('A', 'VAL', 282), ('A', 'ASP', 283),
('A', 'SER', 284), ('B', 'GLY', 34), ('B', 'GLU', 35), ('B', 'ALA', 168),
('B', 'ASP', 169), ('B', 'GLY', 170), ('B', 'VAL', 282), ('B', 'ASP', 283),
('B', 'SER', 284)]
MISSINGRES_5B7A = [('A', 'PRO', 0),
('A', 'ASP', -1),
('A', 'MET', -13),
('A', 'GLY', -12),
('A', 'SER', -11),
('A', 'SER', -10),
('A', 'HIS', -9),
('A', 'HIS', -8),
('A', 'HIS', -7),
('A', 'HIS', -6),
('A', 'HIS', -5),
('A', 'HIS', -4),
('A', 'SER', -3),
('A', 'GLN', -2)]
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/molecule_fixtures.py | .py | 10,512 | 353 | import random
import pytest
import numpy as np
import moldesign as mdt
import moldesign.units as u
from moldesign.utils import exports
from .helpers import get_data_path
__all__ = ['molecule_standards']
molecule_standards = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
__all__.append(func.__name__)
for t in types:
molecule_standards.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
######################################
# Tests around PDB ID 3AID
@typedfixture('molecule')
def pdb3aid():
mol = mdt.read(get_data_path('3aid.pdb.gz'))
return mol
@typedfixture('submolecule')
def ligand_residue_3aid(pdb3aid):
unknown = pdb3aid.chains['A'](type='unknown')
assert len(unknown) == 1
return unknown[0]
@typedfixture('submolecule')
def ligand_3aid_atoms(ligand_residue_3aid):
return ligand_residue_3aid.atoms
@typedfixture('molecule')
def ligand3aid(ligand_residue_3aid):
newmol = mdt.Molecule(ligand_residue_3aid)
return newmol
@typedfixture('molecule')
def ethylene_waterbox_2na_2cl():
mol = mdt.from_smiles('C=C')
solvated = mdt.add_water(mol, padding=15.0*u.angstrom, ion_concentration=0.6*u.molar)
return solvated
@exports
@pytest.fixture
def random_atoms_from_3aid(pdb3aid):
atoms = mdt.molecules.atomcollections.AtomList(random.sample(pdb3aid.atoms, 10))
return atoms
@exports
@pytest.fixture(scope='session')
def cached_small_molecule():
mol = mdt.from_smiles('CNCOS(=O)C')
mol.positions += 0.001*np.random.random(mol.positions.shape)*u.angstrom # move out of minimum
return mol
@exports
@pytest.fixture
def small_molecule(cached_small_molecule):
return cached_small_molecule.copy()
@exports
@pytest.fixture(scope='session')
def cached_benzene():
return mdt.from_smiles('c1ccccc1')
@exports
@pytest.fixture
def benzene(cached_benzene):
return cached_benzene.copy()
@typedfixture('molecule')
def h2():
mol = mdt.Molecule([mdt.Atom('H1'),
mdt.Atom('H2')])
mol.atoms[0].x = 0.5 * u.angstrom
mol.atoms[1].x = -0.25 * u.angstrom
mol.atoms[0].bond_to(mol.atoms[1], 1)
return mol
@typedfixture('molecule')
def heh_plus():
mol = mdt.Molecule([mdt.Atom('H'),
mdt.Atom('He')])
mol.atoms[1].z = 1.0 * u.angstrom
mol.charge = 1 * u.q_e
mol.atoms[0].bond_to(mol.atoms[1], 1)
return mol
@exports
@pytest.fixture(scope='session')
def cached_ethylene():
return mdt.from_smiles('C=C')
@exports
@pytest.fixture
def ethylene(cached_ethylene):
return cached_ethylene.copy()
@exports
@pytest.fixture(scope='session')
def cached_pdb1yu8():
return mdt.read(get_data_path('1yu8.pdb'))
@exports
@pytest.fixture
def pdb1yu8():
return mdt.read(get_data_path('1yu8.pdb'))
@exports
@pytest.fixture(scope='session')
def cached_mol_from_xyz():
return mdt.read("""43
c1.pdb
C -1.21700 1.04300 2.45300
C -0.14200 0.18700 2.19500
C -0.31600 -0.99500 1.46200
C -1.59800 -1.33100 1.02200
C -2.68200 -0.48500 1.28100
C -2.50400 0.70500 1.98200
O -3.53000 1.57400 2.25000
O -1.13200 2.21500 3.14700
C 0.14200 2.61500 3.63500
C 0.86700 -1.90600 1.12900
C 1.10600 -1.99700 -0.40500
O 2.06900 -1.52700 1.78600
O 1.81300 -0.81200 -0.83600
C 1.98100 -3.18300 -0.81100
O 2.18000 -3.27400 -2.21400
C 1.18300 0.32500 -1.28900
C 0.13100 0.33800 -2.23300
C -0.38800 1.56800 -2.65400
C 0.15900 2.77500 -2.20100
C 1.23000 2.75900 -1.31000
C 1.72800 1.53500 -0.85900
O -0.31100 -0.88000 -2.70600
C -1.43500 -0.90100 -3.58200
H 0.84400 0.42500 2.57000
H -1.77600 -2.25500 0.47700
H -3.67600 -0.75700 0.93200
H -4.35900 1.18400 1.93700
H -0.03000 3.54300 4.18500
H 0.84500 2.80900 2.81200
H 0.56300 1.86400 4.31600
H 0.63600 -2.91500 1.49500
H 0.14200 -2.06200 -0.91500
H 2.51900 -0.89500 1.20400
H 1.52900 -4.10700 -0.41600
H 2.97500 -3.07900 -0.36800
H 1.34400 -3.10100 -2.67400
H -1.20600 1.60000 -3.36300
H -0.25300 3.71600 -2.56000
H 1.68000 3.68900 -0.97300
H 2.55900 1.49100 -0.16100
H -1.60900 -1.95000 -3.81500
H -1.22800 -0.35800 -4.51600
H -2.32500 -0.48000 -3.09700
""", format='xyz')
@exports
@pytest.fixture
def mol_from_xyz(cached_mol_from_xyz):
return cached_mol_from_xyz.copy()
@exports
@pytest.fixture(scope='session')
def cached_mol_from_sdf():
return mdt.read("""
OpenBabel02271712493D
11 10 0 0 0 0 0 0 0 0999 V2000
0.9114 -0.0615 0.0032 C 0 0 0 0 0 0 0 0 0 0 0 0
0.4168 1.3750 0.0264 C 0 0 0 0 0 0 0 0 0 0 0 0
0.9114 2.1503 -1.1831 C 0 0 0 0 0 0 0 0 0 0 0 0
0.5568 -0.5828 -0.8916 H 0 0 0 0 0 0 0 0 0 0 0 0
0.5460 -0.6043 0.8807 H 0 0 0 0 0 0 0 0 0 0 0 0
2.0053 -0.0987 0.0111 H 0 0 0 0 0 0 0 0 0 0 0 0
-0.6785 1.3847 0.0446 H 0 0 0 0 0 0 0 0 0 0 0 0
0.7625 1.8663 0.9425 H 0 0 0 0 0 0 0 0 0 0 0 0
0.5568 1.6932 -2.1123 H 0 0 0 0 0 0 0 0 0 0 0 0
0.5460 3.1815 -1.1499 H 0 0 0 0 0 0 0 0 0 0 0 0
2.0053 2.1774 -1.2097 H 0 0 0 0 0 0 0 0 0 0 0 0
2 1 1 0 0 0 0
3 2 1 0 0 0 0
4 1 1 0 0 0 0
5 1 1 0 0 0 0
6 1 1 0 0 0 0
7 2 1 0 0 0 0
8 2 1 0 0 0 0
9 3 1 0 0 0 0
10 3 1 0 0 0 0
11 3 1 0 0 0 0
M END
$$$$
""", format='sdf')
@exports
@pytest.fixture
def mol_from_sdf(cached_mol_from_sdf):
return cached_mol_from_sdf.copy()
@typedfixture('molecule')
def nucleic():
# ACTG.pdb contains a molecule generated using mdt.build_dna('ACTG')
mol = mdt.read(get_data_path('ACTG.pdb'))
return mol
########################################################################################
# Molecules with forcefields assigned - these use a session-scoped constructor w/ a copy factory
@exports
@pytest.fixture(scope='session')
def cached_mol_parameterized_with_zeros(cached_small_molecule):
return _param_small_mol(cached_small_molecule.copy(), 'zero')
@typedfixture('hasmodel')
def mol_with_zerocharge_params(cached_mol_parameterized_with_zeros):
return cached_mol_parameterized_with_zeros.copy()
@exports
@pytest.fixture(scope='session')
def cached_mol_parameterized_with_am1bcc(cached_small_molecule):
""" We don't use this fixture directly, rather use another fixture that copies these results
so that we don't have to repeatedly call tleap/antechamber
"""
return _param_small_mol(cached_small_molecule.copy(), 'am1-bcc')
@typedfixture('hasmodel')
def mol_with_am1bcc_params(cached_mol_parameterized_with_am1bcc):
return cached_mol_parameterized_with_am1bcc.copy()
@exports
@pytest.fixture(scope='session')
def cached_mol_parameterized_with_gasteiger(cached_small_molecule):
""" We don't use this fixture directly, rather use another fixture that copies these results
so that we don't have to repeatedly call tleap/antechamber
"""
mol = cached_small_molecule.copy()
mol.set_energy_model(mdt.models.GaffSmallMolecule, partial_charges='gasteiger')
mol.energy_model.prep()
return mol
@typedfixture('hasmodel')
def mol_with_gast_params(cached_mol_parameterized_with_gasteiger):
return cached_mol_parameterized_with_gasteiger.copy()
def _param_small_mol(cached_small_molecule, chargemodel):
mol = cached_small_molecule.copy()
params = mdt.create_ff_parameters(mol, charges=chargemodel, baseff='gaff2')
params.assign(mol)
mol.set_energy_model(mdt.models.ForceField)
return mol
@exports
@pytest.fixture(scope='session')
def cached_protein_with_default_amber_ff(cached_pdb1yu8):
""" We don't use this fixture directly, rather use another fixture that copies these results
so that we don't have to repeatedly call tleap/antechamber
"""
mol = cached_pdb1yu8
ff = mdt.forcefields.DefaultAmber()
newmol = ff.create_prepped_molecule(mol)
newmol.set_energy_model(mdt.models.ForceField)
return newmol
@typedfixture('hasmodel')
def protein_default_amber_forcefield(cached_protein_with_default_amber_ff):
return cached_protein_with_default_amber_ff.copy()
@exports
@pytest.fixture(scope='session')
def cached_h2_rhf_sto3g():
mol = h2() # fixture is not cached, so just call it directly
mol.set_energy_model(mdt.models.PySCFPotential, basis='sto-3g', theory='rhf')
mol.calculate(requests=['forces'])
return mol
@exports
@pytest.fixture
def h2_rhf_sto3g(cached_h2_rhf_sto3g):
return cached_h2_rhf_sto3g.copy()
@exports
@pytest.fixture(scope='session')
def cached_h2_rhf_augccpvdz():
mol = h2()
mol.set_energy_model(mdt.models.RHF, basis='aug-cc-pvdz')
mol.calculate()
return mol
@exports
@pytest.fixture
def h2_rhf_augccpvdz(cached_h2_rhf_augccpvdz):
return cached_h2_rhf_augccpvdz.copy()
@exports
@pytest.fixture(scope='session')
def cached_acetylene_dft_631g():
mol = mdt.from_smiles('C#C')
mol.set_energy_model(mdt.models.B3LYP, basis='6-31g')
mol.calculate()
return mol
@exports
@pytest.fixture
def acetylene_dft_631g(cached_acetylene_dft_631g):
return cached_acetylene_dft_631g.copy()
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_openbabel_xface.py | .py | 2,159 | 71 | import pytest
import moldesign as mdt
from .molecule_fixtures import *
registered_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@typedfixture('hasmodel')
def openbabel_mmff94(small_molecule):
small_molecule.set_energy_model(mdt.models.OpenBabelPotential, forcefield='mmff94')
return small_molecule
@typedfixture('hasmodel')
def openbabel_mmff94s(small_molecule):
small_molecule.set_energy_model(mdt.models.OpenBabelPotential, forcefield='mmff94s')
return small_molecule
@typedfixture('hasmodel')
def openbabel_ghemical(small_molecule):
small_molecule.set_energy_model(mdt.models.OpenBabelPotential, forcefield='ghemical')
return small_molecule
# This test (along with the uff energy model) is disabled because it does not appear to return a
# gradient that's consistent with the energy surface
@typedfixture('hasmodel')
@pytest.mark.xfail("OpenBabel's UFF implementation appears to return incorrect gradients")
def openbabel_uff(small_molecule):
small_molecule.set_energy_model(mdt.models.OpenBabelPotential, forcefield='uff')
return small_molecule
@pytest.mark.parametrize('fixture', registered_types['hasmodel'])
@pytest.mark.screening
def test_ob_energy_models(request, fixture):
mol = request.getfixturevalue(fixture)
assert mol.energy_model is not None
assert isinstance(mol.calculate_potential_energy(), mdt.units.MdtQuantity)
def test_ob_smiles_read():
mol = mdt.interfaces.openbabel.from_smiles('CC')
_assert_its_ethane(mol)
def test_ob_inchi_read():
mol = mdt.interfaces.openbabel.from_inchi('InChI=1S/C2H6/c1-2/h1-2H3')
_assert_its_ethane(mol)
def _assert_its_ethane(mol):
assert mol.num_atoms == 8
assert len(mol.get_atoms(symbol='H')) == 6
assert len(mol.get_atoms(symbol='C')) == 2
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_tools.py | .py | 3,739 | 126 | """ Tests topology manipulation tools
"""
import collections
import pytest
import moldesign as mdt
from moldesign import units as u
from .helpers import get_data_path, assert_almost_equal
from .molecule_fixtures import ligand3aid,pdb3aid,benzene,small_molecule,pdb1yu8, ligand_residue_3aid
registered_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@pytest.fixture
def ammonium_nocharge():
return mdt.from_smiles('[NH4]')
@pytest.fixture
def ammonium_charged():
return mdt.from_smiles('[NH4+]')
@pytest.mark.parametrize('objkey',
['ammonium_nocharge', 'ammonium_charged'])
def test_ammonium_formal_charge(objkey, request):
mol = request.getfixturevalue(objkey)
mdt.assign_formal_charges(mol)
assert mol.charge == 1 * u.q_e
for atom in mol.atoms:
if atom.atnum == 7:
assert atom.formal_charge == 1 * u.q_e
else:
assert atom.atnum == 1
assert atom.formal_charge == 0 * u.q_e
def test_set_hybridization_and_saturate():
# Creates just the carbons of ethylene, expects the routine to figure out the rest
atom1 = mdt.Atom(6)
atom2 = mdt.Atom(6)
atom2.x = 1.35 * u.angstrom
atom1.bond_to(atom2, 1)
mol = mdt.Molecule([atom1, atom2])
newmol = mdt.set_hybridization_and_saturate(mol)
pytest.xfail('This is apparently broken')
assert newmol.num_atoms == 6
assert newmol.atoms[0].bond_graph[atom1] == 2
assert len(newmol.get_atoms(atnum=1)) == 4
@pytest.fixture
def c2_no_hydrogen_from_smiles():
mymol = mdt.from_smiles('[CH0][CH0]')
return mymol
def test_c2_no_hydrogen_from_smiles(c2_no_hydrogen_from_smiles):
mymol = c2_no_hydrogen_from_smiles
atomcounts = collections.Counter(atom.element for atom in mymol.atoms)
assert atomcounts['C'] == 2
assert len(atomcounts) == 1
assert mymol.num_bonds == 1
assert mymol.num_atoms == 2
bonds = list(mymol.bonds)
assert len(bonds) == 1
b = bonds[0]
assert b.order == 1
assert b.a1.index == 0
assert b.a2.index == 1
@pytest.mark.screening
def test_add_hydrogen_to_c2(c2_no_hydrogen_from_smiles):
newmol = mdt.add_hydrogen(c2_no_hydrogen_from_smiles)
atomcounts = collections.Counter(atom.element for atom in newmol.atoms)
assert newmol.num_atoms == 8
assert atomcounts['C'] == 2
assert atomcounts['H'] == 6
assert len(atomcounts) == 2
assert newmol.num_bonds == 7
for atom, bondgraph in newmol.bond_graph.items():
if atom.atnum == 1:
assert len(bondgraph) == 1
assert list(bondgraph.keys())[0].elem == 'C'
assert list(bondgraph.values())[0] == 1
else:
assert atom.atnum == 6
assert len(bondgraph) == 4
for nbr in bondgraph:
assert bondgraph[nbr] == 1
def test_split_chains_3p3k():
mol = mdt.read(get_data_path('3p3k.pdb.gz'))
assert mol.num_chains == 1 # not really testing this, just for sanity's sake
newmol = mdt.split_chains(mol)
assert newmol.num_chains == 3
assert newmol.chains['A'] is newmol.chains[0]
assert newmol.chains['A'].type == 'protein'
assert newmol.chains['B'] is newmol.chains[1]
assert newmol.chains['B'].type == 'protein'
assert newmol.chains['C'] is newmol.chains[2]
assert newmol.chains['C'].type == 'water'
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_trajectory.py | .py | 4,352 | 155 | import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from .object_fixtures import h2, h2_harmonic, h2_trajectory
@pytest.mark.internal
def test_frames_synched_with_trajectory(h2_trajectory):
traj = h2_trajectory
for iframe, frame in enumerate(traj):
assert frame.potential_energy == traj.potential_energy[iframe]
assert iframe == traj.num_frames-1
assert traj.potential_energy.units == traj.unit_system.energy
assert traj.positions.units == traj.unit_system.length
assert traj.positions.shape == (traj.num_frames, traj.mol.num_atoms, 3)
assert traj.potential_energy.shape == (traj.num_frames,)
@pytest.fixture
def precanned_trajectory():
a1 = mdt.Atom(6)
a2 = mdt.Atom(1)
a3 = mdt.Atom(7)
mol = mdt.Molecule([a1, a2, a3])
traj = mdt.Trajectory(mol)
a1.x = 1.0 * u.angstrom
a3.y = 1.0 * u.angstrom
traj.new_frame(somenumber=1, someletter='a')
mol.time = 1.0 * u.fs
a1.x = 2.0 * u.angstrom
traj.new_frame(somenumber=2, someletter='b')
mol.time = 2.0 * u.fs
a2.x = -1.0 * u.angstrom
a3.x = -1.0 * u.angstrom
traj.new_frame(somenumber=3, someletter='c')
return traj
@pytest.mark.internal
@pytest.mark.screening
def test_geometry_analysis_precanned(precanned_trajectory):
traj = precanned_trajectory
a1, a2, a3 = traj.mol.atoms
angles = traj.angle(a1, a2, a3)
desired = ([90.0]*3)*u.degrees
np.testing.assert_allclose(angles.value_in(u.degrees),
desired.value_in(u.degrees))
d12 = traj.distance(a1, a2)
desired = [1.0, 2.0, 3.0] * u.angstrom
np.testing.assert_allclose(d12.value_in(u.angstrom),
desired)
rmsd = traj.rmsd()
desired = [0.0, 1.0/np.sqrt(3), 1.0] * u.angstrom
np.testing.assert_allclose(rmsd.value_in(u.angstrom),
desired.value_in(u.angstrom))
time = traj.time
desired = [0.0, 1.0, 2.0] * u.fs
np.testing.assert_allclose(time.value_in(u.fs),
desired.value_in(u.fs))
assert all(traj.somenumber == np.array([1, 2, 3]))
assert traj.someletter == list('abc')
@pytest.mark.internal
@pytest.mark.screening
def test_frame_to_molecule_conversion(precanned_trajectory):
traj = precanned_trajectory
f0_position = u.angstrom*[[1, 0, 0],
[0, 0, 0],
[0, 1, 0]]
f2_position = u.angstrom*[[2, 0, 0],
[-1, 0, 0],
[-1, 1, 0]]
f0 = traj.frames[0]
mol = f0.as_molecule()
assert mol.same_topology(traj.mol)
assert (mol.positions == f0_position).all()
assert mol.time == 0.0 * u.fs
# test ability to directly write a frame
readmol = mdt.read(f0.write('xyz'), format='xyz')
np.testing.assert_allclose(readmol.positions.value_in(u.angstrom),
f0_position.value_in(u.angstrom))
m2 = traj.frames[-1].as_molecule()
assert m2.same_topology(mol)
assert (m2.positions == f2_position).all()
assert m2.time == 2.0 * u.fs
@pytest.mark.internal
@pytest.mark.screening
def test_property_backfill(precanned_trajectory):
traj = precanned_trajectory
oldnumframes = len(traj)
traj.mol.time += 1.0*u.fs
traj.new_frame(somenewthing=5)
assert traj.somenewthing == [None] * oldnumframes + [5]
@pytest.mark.internal
def test_add_traj(precanned_trajectory):
newtraj = precanned_trajectory + precanned_trajectory
assert newtraj.num_frames == 2 * precanned_trajectory.num_frames
@pytest.fixture(scope='module')
def h2_wfn_traj():
mol = h2().copy()
mol.set_energy_model(mdt.models.RHF, basis='sto-3g')
traj = mdt.Trajectory(mol)
for i in range(3):
mol.calculate()
traj.new_frame()
mol.atoms[0].x += 0.2 * u.angstrom
return traj
def test_align_phases(h2_wfn_traj):
# TODO: actually check that the orbitals were aligned
h2_wfn_traj.align_orbital_phases()
h2_wfn_traj.align_orbital_phases(reference_frame=1)
h2_wfn_traj.align_orbital_phases(reference_frame=h2_wfn_traj.frames[0])
def test_mulliken_charge_trajectory(h2_wfn_traj):
traj = h2_wfn_traj
atom = traj.atoms[0]
assert len(atom.mulliken) == traj.num_frames | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_ambertools_xface.py | .py | 2,990 | 94 | import pytest
import moldesign as mdt
from . import helpers
from .molecule_fixtures import *
@pytest.mark.parametrize('fixturename', molecule_standards['hasmodel'])
def test_model_assigned(fixturename, request):
mol = request.getfixturevalue(fixturename)
assert mol.ff is not None
@pytest.mark.parametrize('objkey',
'ethylene ligand3aid mol_from_xyz mol_from_sdf'.split())
def test_parameterization_from_formats(objkey, request):
mol = request.getfixturevalue(objkey)
assert not mol.ff
params = mdt.create_ff_parameters(mol, charges='gasteiger')
assert params is not None
_test_succesful_parameterization(mol)
@pytest.mark.screening
def test_parameterize_multiple_identical_small_molecules():
m1 = mdt.from_smiles('O')
params = mdt.create_ff_parameters(m1, charges='am1-bcc')
assert params is not None
m2 = m1.copy()
m2.translate([4.0, 0.0, 0.0] * mdt.units.angstrom)
mol = m1.combine(m2)
ff = mdt.forcefields.DefaultAmber()
ff.add_ff(params)
ff.assign(mol)
_test_succesful_parameterization(mol)
@pytest.mark.parametrize('chargemodel',
'esp gasteiger zero am1-bcc'.split())
def test_charge_models(ethylene, chargemodel):
mol = ethylene
if chargemodel == 'esp':
pytest.xfail("ESP not yet implemented")
assert not mol.ff
params = mdt.create_ff_parameters(mol, charges=chargemodel)
assert params is not None
_test_succesful_parameterization(mol)
def _test_succesful_parameterization(mol):
assert mol.ff
mol.set_energy_model(mdt.models.ForceField)
mol.calculate()
assert 'potential_energy' in mol.properties
assert 'forces' in mol.properties
def test_1yu8_default_amber_fix_and_assignment(protein_default_amber_forcefield):
_test_succesful_parameterization(protein_default_amber_forcefield)
def test_ff_assignment_doesnt_change_topology(pdb3aid):
m = pdb3aid
protein = mdt.Molecule(m.get_atoms('protein'))
ligand = mdt.Molecule(m.get_atoms('unknown'))
ligff = mdt.create_ff_parameters(ligand, charges='gasteiger')
mdt.guess_histidine_states(protein)
mol = protein.combine(ligand)
ff = mdt.forcefields.DefaultAmber()
ff.add_ff(ligff)
mdready = ff.create_prepped_molecule(mol)
assert mdready.num_residues == mol.num_residues
assert mdready.num_chains == mol.num_chains
for c1, c2 in zip(mdready.chains, mol.chains):
assert c1.name == c2.name
assert c1.num_residues == c2.num_residues
assert c1.index == c2.index
for newr, oldr in zip(mdready.residues, mol.residues):
assert newr.index == oldr.index
if newr.resname == 'HIS':
assert oldr.resname in 'HIS HID HIE HIP'.split()
else:
assert newr.resname == oldr.resname
assert newr.pdbindex == oldr.pdbindex
assert newr.chain.index == oldr.chain.index
for atom in oldr:
assert atom.name in newr
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_biopython_xface.py | .py | 649 | 25 | import io
import pytest
import Bio.PDB
import moldesign as mdt
from .helpers import get_data_path
from .molecule_fixtures import pdb3aid
@pytest.fixture
def biopy_3aid():
import gzip
parser = Bio.PDB.PDBParser()
s = gzip.open(get_data_path('3aid.pdb.gz'), 'r').read().decode('utf-8')
structure = parser.get_structure('3aid', io.StringIO(s))
return structure
@pytest.mark.screening
def test_biopy_to_mdt(biopy_3aid, pdb3aid):
mol = mdt.interfaces.biopython_to_mol(biopy_3aid)
assert mol.num_atoms == pdb3aid.num_atoms
assert mol.num_residues == pdb3aid.num_residues
assert mol.numchains == pdb3aid.num_chains
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/__init__.py | .py | 0 | 0 | null | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_io.py | .py | 8,850 | 307 | """ Tests for molecule creation and file i/o
"""
import io
import os
import subprocess
from future.utils import PY2, native_str
from builtins import str
import collections
import pathlib
import gzip
import bz2
import pickle
import numpy
import pytest
import moldesign as mdt
mdt.compute.config.engine_type = 'docker'
from moldesign import units as u
from .helpers import get_data_path, native_str_buffer, requires_internet_connection
from .object_fixtures import h2_trajectory, h2_harmonic, h2
__PYTEST_MARK__ = 'io'
@pytest.fixture
def bipyridine_sdf():
return mdt.read(get_data_path('bipyridine.sdf'))
@pytest.fixture
def bipyridine_xyz():
return mdt.read(get_data_path('bipyridine.xyz'))
@pytest.fixture
def bipyridine_mol2():
return mdt.read(get_data_path('bipyridine.mol2'))
@pytest.fixture
def bipyridine_iupac():
return mdt.from_name('bipyridine')
@pytest.fixture
def bipyridine_inchi():
return mdt.from_inchi('InChI=1S/C10H8N2/c1-3-7-11-9(5-1)10-6-2-4-8-12-10/h1-8H')
@pytest.fixture
def bipyridine_smiles():
return mdt.from_smiles('c1ccnc(c1)c2ccccn2')
ATOMDATA = { # (symbol, valence, mass)
1: ('H', 1, 1.008 * u.amu),
6: ('C', 4, 12.000 * u.amu),
7: ('N', 3, 14.003 * u.amu),
8: ('O', 2, 15.995 * u.amu)}
@pytest.mark.parametrize('key', 'iupac smiles inchi xyz sdf'.split())
@pytest.mark.screening
def test_auto_unique_atom_names(key, request):
mol = request.getfixturevalue('bipyridine_'+key)
atomnames = set(atom.name for atom in mol.atoms)
assert len(atomnames) == mol.num_atoms
def test_atom_names_preserved_from_input_file_mol2(bipyridine_mol2):
mol = bipyridine_mol2
for atom in mol.atoms:
assert atom.name == atom.symbol + str(atom.index)
@pytest.fixture
def propane_pdb():
return mdt.read(get_data_path('propane.pdb'))
def test_pdb_with_missing_chains(propane_pdb):
""" In response to an observed bug where various conversions would fail with a PDB file
that's missing chain data
"""
mol = propane_pdb
if not mdt.compute.packages.openbabel.force_remote:
pbmol = mdt.interfaces.mol_to_pybel(mol)
assert len(pbmol.atoms) == mol.num_atoms
pmedmol = mdt.interfaces.mol_to_parmed(mol)
assert len(pmedmol.atoms) == mol.num_atoms
@pytest.mark.parametrize('key', 'mol2 xyz sdf iupac smiles inchi'.split())
@pytest.mark.screening
def test_read_bipyridine_from_format(key, request):
mol = request.getfixturevalue('bipyridine_'+key)
atomcounts = collections.Counter(atom.symbol for atom in mol.atoms)
assert len(atomcounts) == 3
assert atomcounts['C'] == 10
assert atomcounts['N'] == 2
assert atomcounts['H'] == 8
assert mol.charge == 0
assert abs(mol.mass - 156.069*u.amu) < 0.001 * u.amu
for atom in mol.atoms:
assert atom.formal_charge == 0.0
symb, val, mss = ATOMDATA[atom.atnum]
assert atom.symbol == symb
assert atom.valence == val
assert abs(atom.mass - mss) < 0.001 * u.amu
assert mol.num_bonds == 21
bondorders = collections.Counter(bond.order for bond in mol.bonds)
assert bondorders[2] == 6
assert bondorders[1] == 15
assert len(bondorders) == 2
@pytest.mark.parametrize('suffix', ['gz','bz2'])
def test_compressed_write(bipyridine_xyz, tmpdir, suffix):
# Note: compressed read is tested elsewhere when reading test data files
path = pathlib.Path(native_str(tmpdir))
dest = path / ('bipyr.xyz.' + suffix)
bipyridine_xyz.write(dest)
# don't use MDT's reader here! Need to make sure it's really gzip'd
if suffix == 'gz':
opener = gzip.open
elif suffix == 'bz2':
opener = bz2.BZ2File
else:
raise ValueError('Unrecognized suffix "%s"' % suffix)
if PY2:
mode = 'r'
else:
mode = 'rt'
if suffix == 'bz2':
opener = bz2.open
with opener(str(dest), mode) as infile:
content = infile.read()
mol = mdt.read(content, format='xyz')
assert mol.num_atoms == bipyridine_xyz.num_atoms
@pytest.fixture
def dna_pdb():
return mdt.read(pathlib.Path(get_data_path('ACTG.pdb')))
@pytest.fixture
def dna_mmcif():
return mdt.read(get_data_path('ACTG.cif'))
@pytest.fixture
def dna_sequence():
return mdt.build_bdna('ACTG')
@pytest.fixture
def pdb_1kbu():
return mdt.read(pathlib.Path(get_data_path('1KBU.pdb.bz2')))
@pytest.fixture
def mmcif_1kbu():
return mdt.read(get_data_path('1KBU.cif.bz2'))
@requires_internet_connection
def test_from_pdb_pdb_format():
mol = mdt.from_pdb('3aid')
assert mol.metadata.pdbid == '3aid'
assert mol.metadata.sourceformat == 'pdb'
assert mol.num_atoms == 1912
@requires_internet_connection
def test_from_pdb_mmcif_format():
mol = mdt.from_pdb('3aid', usecif=True)
assert mol.metadata.pdbid == '3aid'
assert mol.metadata.sourceformat == 'mmcif'
assert mol.metadata.sourceurl.split('.')[-1] == 'cif'
assert mol.num_atoms == 1912
@requires_internet_connection
@pytest.mark.skip("Takes over 10 minutes right now ...")
def test_mmcif_fallback_if_no_pdb_file():
mol = mdt.from_pdb('4V5X')
assert mol.metadata.pdbid.lower() == '4v5x'
assert mol.metadata.sourceformat == 'mmcif'
assert mol.metadata.sourceurl.split('.')[-1] == 'cif'
@pytest.mark.parametrize('key', 'pdb mmcif sequence'.split())
def test_read_dna_from_format(key, request):
if key == 'mmcif':
pytest.xfail(reason='Known mmcif parser bug, fix this by 0.7.4')
mol = request.getfixturevalue('dna_'+key)
def test_write_file_to_buffer(bipyridine_smiles):
mol = bipyridine_smiles
buffer = native_str_buffer()
mol.write(buffer, format='pdb')
buffer.seek(0)
newmol = mdt.read(buffer.getvalue(), format='pdb')
assert mol.num_atoms == newmol.num_atoms
def test_write_pickle_to_buffer(bipyridine_smiles):
mol = bipyridine_smiles
buffer = io.BytesIO()
mol.write(buffer, format='pkl')
newmol = pickle.loads(buffer.getvalue())
assert newmol.is_identical(mol, verbose=True)
def test_read_from_buffer():
s = native_str("2\nmy xyz file\n H 1.0 1.0 1.0\n H 1.0 2.0 1.0\n")
buffer = native_str_buffer(s)
h2 = mdt.read(buffer, format='xyz')
assert h2.num_atoms == 2
@pytest.mark.parametrize('key', 'mmcif pdb'.split())
@pytest.mark.screening
def test_1kbu_assembly_data(key, request):
mol = request.getfixturevalue('%s_1kbu' % key)
assert len(mol.properties.bioassemblies) == 1
assert '1' in mol.properties.bioassemblies
assembly = mol.properties.bioassemblies['1']
assert len(assembly.transforms) == 2
assert set(assembly.chains) == set(c.name for c in mol.chains)
# first transform is identity
numpy.testing.assert_allclose(assembly.transforms[0],
numpy.identity(4))
# second transform's rotation is unitary
rot = assembly.transforms[1][:3,:3]
numpy.testing.assert_allclose(rot.dot(rot.T),
numpy.identity(3))
@pytest.mark.parametrize('key', 'mmcif pdb'.split())
def test_1kbu_assembly_build(key, request):
asym = request.getfixturevalue('%s_1kbu' % key)
original = mdt.Molecule(asym)
assembly = asym.properties.bioassemblies['1']
rot = assembly.transforms[1][:3,:3]
move = assembly.transforms[1][:3,3] * u.angstrom
mol = mdt.build_assembly(asym, 1)
assert mol.num_chains == 2 * asym.num_chains
# test that original is unaffected
assert original.is_identical(asym)
testchain = assembly.chains[0]
new_chain_pos = mol.chains[testchain].positions.T.ldot(rot).T + move[None, :]
numpy.testing.assert_allclose(new_chain_pos.defunits_value(),
mol.chains[asym.num_chains].positions.defunits_value())
@pytest.mark.parametrize('fmt', 'smiles pdb mol2 sdf inchi mmcif pkl'.split())
def test_topology_preserved_in_serialization(bipyridine_smiles, fmt):
""" Test that bond topology is preserved even if it doesn't make sense from distances
"""
if fmt != 'pkl':
pytest.xfail("We are currently unable to get an unambiguous representation of a molecular "
"sructure with ANY current file formats or parsers.")
mol = bipyridine_smiles.copy() # don't screw up the fixture object
mol.bond_graph[mol.atoms[3]][mol.atoms[5]] = 3
mol.bond_graph[mol.atoms[5]][mol.atoms[3]] = 3
mol.atoms[3].x += 10.0 * u.angstrom
newmol = mdt.read(mol.write(format=fmt), format=fmt)
assert mol.same_bonds(newmol, verbose=True)
def test_write_traj(h2_trajectory, tmpdir):
path = os.path.join(str(tmpdir), 'traj.xyz')
h2_trajectory.write(path)
assert int(subprocess.check_output(['wc', '-l', path]).split()[0]) == (
(h2_trajectory.mol.num_atoms+2) * h2_trajectory.num_frames)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/object_fixtures.py | .py | 3,903 | 162 | """
This module is mostly _fixtures_ - functions that create various objects for downstream testing.
There are a few tests here too, mostly to make sure the objects are created correctly in the first
place.
"""
import collections
import numpy as np
import pytest
import moldesign as mdt
from .. import units as u
from .. import utils
from .molecule_fixtures import *
registered_types = {key:val[:] for key,val in molecule_standards.items()}
__all__ = ['registered_types']
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
__all__.append(func.__name__)
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
######################################
# Various python objects
TESTDICT = collections.OrderedDict((('a', 'b'),
('c', 3),
('d', 'e'),
('a', 1),
(3, 35)))
@typedfixture('pickleable')
def dotdict():
dd = utils.DotDict(TESTDICT)
return dd
# Some objects with units
@typedfixture('pickleable')
def list_of_units():
return [1.0 * u.angstrom, 1.0 * u.nm, 1.0 * u.a0]
@typedfixture('pickleable', 'equality')
def simple_unit_array():
return np.array([1.0, -2.0, 3.5]) * u.angstrom
@typedfixture('pickleable', 'equality')
def unit_number():
return 391.23948 * u.ureg.kg * u.angstrom / u.alpha
######################################
# Atom objects
@typedfixture('atom')
def carbon_atom():
atom1 = mdt.Atom('C')
return atom1
def test_carbon_atom(carbon_atom):
assert carbon_atom.symbol == 'C'
assert carbon_atom.mass == 12.0 * u.amu
@typedfixture('atom')
def carbon_copy(carbon_atom):
atoms = carbon_atom.copy()
return atoms
######################################
# Hydrogen-related objects
@typedfixture('molecule')
def h2_harmonic(h2):
mol = h2
SPRING_CONSTANT = 1.0 * u.kcalpermol / (u.angstrom ** 2)
model = mdt.models.HarmonicOscillator(k=SPRING_CONSTANT)
integrator = mdt.integrators.VelocityVerlet(timestep=0.5*u.fs, frame_interval=30)
mol.set_energy_model(model)
mol.set_integrator(integrator)
return mol
@typedfixture('pickleable')
def atom_bond_graph(h2):
return h2.bond_graph[h2.atoms[0]]
@typedfixture('pickleable')
def mol_bond_graph(h2):
return h2.bond_graph
@typedfixture('pickleable')
def mol_wfn(h2_rhf_sto3g):
return h2_rhf_sto3g.copy().wfn
@typedfixture('pickleable')
def mol_properties(h2_rhf_sto3g):
return h2_rhf_sto3g.copy().properties
@typedfixture('trajectory')
def h2_trajectory(h2_harmonic):
mol = h2_harmonic
mol.atoms[0].x = 1.0 * u.angstrom
mol.momenta *= 0.0
traj = mol.run(500)
return traj
@typedfixture('molecule')
def h2_traj_tempmol(h2_trajectory):
return h2_trajectory._tempmol
@typedfixture('molecule')
def h2_harmonic_copy(h2_harmonic):
return mdt.Molecule(h2_harmonic)
@typedfixture('submolecule')
def copy_atoms_from_h2_harmonic(h2_harmonic):
atoms = h2_harmonic.atoms.copy()
return atoms
@typedfixture('molecule')
def h2_harmonic_thats_been_copied(h2_harmonic):
temp = mdt.Molecule(h2_harmonic)
return h2_harmonic
@typedfixture('submolecule')
def h2_harmonic_atoms(h2_harmonic):
return h2_harmonic.atoms
moldesign_objects = (registered_types['molecule'] +
registered_types['submolecule'] +
registered_types['trajectory'] +
registered_types['atom'])
pickleable = registered_types['pickleable'] + moldesign_objects
__all__.extend(['moldesign_objects', 'pickleable'])
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_gaussian_math.py | .py | 17,426 | 519 | """ Tests internal math routines
"""
import random
import itertools
import numpy as np
import pytest
import moldesign
from moldesign import units as u
from moldesign.mathutils import spherical_harmonics as harmonics
from . import helpers
from .molecule_fixtures import *
registered_types = {}
__PYTEST_MARK__ = ['math', 'gaussians']
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@pytest.fixture
def std_1d_gaussian():
g = moldesign.orbitals.gaussians.Gaussian([0.0]*u.angstrom,
1.0/u.angstrom ** 2)
return g
@typedfixture('basis_fn')
def std_3d_gaussian():
g = moldesign.orbitals.gaussians.Gaussian([0.0, 0.0, 0.0]*u.angstrom,
1.0/u.angstrom ** 2)
return g
@typedfixture('basis_fn')
def cartesian_3d_gaussian():
g = moldesign.orbitals.CartesianGaussian(
center=[random.random() for i in range(3)]*u.angstrom,
powers=[1, 3, 0],
alpha=1.1/u.angstrom ** 2,
coeff=1.0)
return g
@typedfixture('basis_fn')
def spherical_3d_gaussian():
g = moldesign.orbitals.SphericalGaussian(
center=[random.random() for i in range(3)]*u.angstrom,
l=3, m=-2,
alpha=1.1/u.angstrom ** 2,
coeff=1.0)
return g
@pytest.mark.parametrize('objkey', ['std_1d_gaussian','std_3d_gaussian'])
@pytest.mark.screening
def test_gaussian_integral_and_dimensionality(objkey, request):
g = request.getfixturevalue(objkey)
assert g.ndim == len(g.center)
intval = g.integral
expectval = g.coeff*(np.pi/g.alpha) ** (g.ndim/2.0)
_assert_almost_equal(intval,
expectval,
decimal=10)
@pytest.fixture
def linear_combination():
return _make_rando_linear_combination(True)
def _make_rando_gaussian(withunits=True):
if withunits:
length = u.angstrom
else:
length = 1.0
return moldesign.orbitals.Gaussian((np.random.rand(3)-0.5)*1.0 * length,
(random.random()*5)/(length ** 2),
coeff=random.random())
def _make_rando_cartesian_gaussian(powers, withunits=True):
if withunits:
length = u.angstrom
else:
length = 1.0
return moldesign.orbitals.CartesianGaussian((np.random.rand(3)-0.5)*1.0 * length,
(random.random()*5)/(length ** 2),
powers=powers,
coeff=random.random())
def _make_rando_spherical_gaussian(l,m, withunits=True):
if withunits:
length = u.angstrom
else:
length = 1.0
return moldesign.orbitals.SphericalGaussian((np.random.rand(3)-0.5)*1.0 * length,
(random.random()*5)/(length ** 2),
l,m,
coeff=random.random())
def _make_rando_linear_combination(withunits=True):
gaussians = []
if withunits:
length = u.angstrom
else:
length = 1.0
center = (np.random.rand(3)-0.5)*1.0 * length
for pwr in [(0,0,0), (1,1,1), (3,2,1)]:
gaussians.append(
moldesign.orbitals.CartesianGaussian(
center=center,
powers=pwr,
alpha=(10.0 * (random.random()+3))/(length**2),
coeff=1/(np.sqrt(3.0))))
lc = moldesign.orbitals.PrimitiveSum(gaussians)
lc.ndims = 3 # so it works with the test suite
return lc
@pytest.mark.parametrize('withunits', [True, False], ids=['quantity','number'])
def test_numerical_vs_analytical_overlap_gauss(withunits):
p1 = _make_rando_gaussian(withunits)
p2 = _make_rando_gaussian(withunits)
_assert_numerical_analytical_overlaps_match(p1, p2)
@pytest.mark.parametrize('withunits', [True, False], ids=['quantity','number'])
def test_numerical_vs_analytical_overlap_cartesian(withunits):
p1 = _make_rando_cartesian_gaussian((1,2,3), withunits)
p2 = _make_rando_cartesian_gaussian((1,0,1), withunits)
_assert_numerical_analytical_overlaps_match(p1, p2)
@pytest.mark.parametrize('withunits', [True, False], ids=['quantity','number'])
def test_numerical_vs_analytical_overlap_spherical(withunits):
p1 = _make_rando_spherical_gaussian(1,-1, withunits)
p2 = _make_rando_spherical_gaussian(2,0, withunits)
_assert_numerical_analytical_overlaps_match(p1, p2)
@pytest.mark.parametrize('withunits', [True, False], ids=['quantity','number'])
def test_numerical_vs_analytical_overlap_linear_combination(withunits):
p1 = _make_rando_linear_combination(withunits)
p2 = _make_rando_linear_combination(withunits)
_assert_numerical_analytical_overlaps_match(p1, p2)
def _assert_numerical_analytical_overlaps_match(g1, g2):
olap = g1.overlap(g2)
try:
prod = g1*g2
except NotImplementedError:
assert isinstance(g1, moldesign.orbitals.SphericalGaussian)
assert isinstance(g2, moldesign.orbitals.SphericalGaussian)
else:
helpers.assert_almost_equal(prod.integral, olap)
def assert_with_resolution(npoints):
allpoints, grid = helpers.generate_grid(g1, g2, npoints)
with np.errstate(under='ignore'):
prodvals = g1(allpoints) * g2(allpoints)
numsum = prodvals.sum() * grid.dx * grid.dy * grid.dz
helpers.assert_almost_equal(numsum, olap, decimal=4)
# If numerical isn't equal to analytical, try again with higher resolution
# to make sure the failure isn't due to a sparse grid:
try:
assert_with_resolution(64)
except AssertionError:
pass
else:
return
try:
assert_with_resolution(128)
except AssertionError:
pass
else:
return
assert_with_resolution(256)
@pytest.mark.parametrize('withunits', [False, True])
def test_gaussian_multiplication_amplitudes(withunits):
g1 = _make_rando_gaussian(withunits)
g2 = _make_rando_gaussian(withunits)
_assert_same_function_values(g1, g2, withunits)
# parameterizations across a sample of cartesian gaussians
test_powers = ((0,0,0), (1,0,0), (0,1,0), (0,0,1), (2,0,0), (1,1,1), (2,0,2), (4,1,1))
cartesian_test_suite = list(itertools.product(test_powers, test_powers, [True, False]))
cartesian_test_ids = ['[%d%d%d]*[%d%d%d]/%s' % (p[0] + p[1] + ('units' if p[2] else 'c-num',))
for p in cartesian_test_suite]
@pytest.mark.parametrize('p1,p2,withunits',
cartesian_test_suite,
ids=cartesian_test_ids)
def test_cartesian_gaussian_multiplication_amplitudes(p1, p2, withunits):
""" Tests that ``g1(x) * g2(x) == (g1 * g2)(x)``
"""
g1 = _make_rando_cartesian_gaussian(p1, withunits)
g2 = _make_rando_cartesian_gaussian(p2, withunits)
_assert_same_function_values(g1, g2, withunits)
def _assert_same_function_values(g1, g2, withunits):
testcoords = 6.0*(np.random.rand(50, 3)-0.5)
if withunits:
testcoords = testcoords*u.angstrom
g1g2 = g1*g2
gvals = g1g2(testcoords)
g1vals = g1(testcoords)
g2vals = g2(testcoords)
prodvals = g1vals*g2vals
helpers.assert_almost_equal(prodvals, gvals)
def test_initial_gaussian_normalization_gaussian():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
g2 = moldesign.orbitals.Gaussian(center, exp, normalized=True)
helpers.assert_almost_equal(1.0, _numerical_norm(g2), decimal=3)
helpers.assert_almost_equal(1.0, g2.norm)
def test_initial_gaussian_normalization_with_prefactor():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
g1 = moldesign.orbitals.Gaussian(center, exp, coeff=3.0*u.angstrom, normalized=True)
helpers.assert_almost_equal(3.0*u.angstrom, _numerical_norm(g1), decimal=3)
helpers.assert_almost_equal(3.0*u.angstrom, g1.norm)
def test_initial_normalization_cartesian():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
for powers in itertools.product(range(4), range(4), range(4)):
g2 = moldesign.orbitals.CartesianGaussian(center, exp, powers, normalized=True)
helpers.assert_almost_equal(1.0, _numerical_norm(g2), decimal=3)
helpers.assert_almost_equal(1.0, g2.norm)
def test_initial_normalization_cartesian_with_prefactor():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
for powers in itertools.product(range(4), range(4), range(4)):
g1 = moldesign.orbitals.CartesianGaussian(center, exp, powers, coeff=3.0, normalized=True)
helpers.assert_almost_equal(3.0, _numerical_norm(g1), decimal=3)
helpers.assert_almost_equal(3.0, g1.norm)
def test_initial_normalization_spherical():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
for l in range(5):
for m in range(-l, l+1):
g2 = moldesign.orbitals.SphericalGaussian(center, exp, l, m, normalized=True)
helpers.assert_almost_equal(1.0, _numerical_norm(g2), decimal=3)
helpers.assert_almost_equal(1.0, g2.norm)
def test_initial_normalization_spherical_with_prefactor():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
for l in range(5):
for m in range(-l, l+1):
g1 = moldesign.orbitals.SphericalGaussian(center, exp, l, m,
coeff=3.0 * u.angstrom, normalized=True)
helpers.assert_almost_equal(3.0 * u.angstrom, _numerical_norm(g1), decimal=3)
helpers.assert_almost_equal(3.0 * u.angstrom, g1.norm)
def _numerical_norm(g):
allpoints, grid = helpers.generate_grid(g)
with np.errstate(under='ignore'):
vals = g(allpoints)
numnorm = np.sqrt(grid.dx * grid.dy * grid.dz * (vals**2).sum())
return numnorm
@pytest.mark.parametrize('objkey', registered_types['basis_fn'])
def test_gaussian_function_values(objkey, request):
g = request.getfixturevalue(objkey)
for idim in range(g.ndims):
coord = g.center.copy()
randoffset = 4.0 * (random.random() - 0.5) * g.alpha**-0.5
coord[idim] += randoffset
funcval = _gfuncval(g, coord)
retval = g(coord)
_assert_almost_equal(funcval, retval)
@pytest.mark.parametrize('objkey', registered_types['basis_fn'])
def test_vectorized_gaussian_function_evaluations(objkey, request):
g = request.getfixturevalue(objkey)
coords = np.zeros((5, g.ndims)) * g.center.units
for i in range(5):
coords[i] = g.center
randoffset = 4.0 * (random.random() - 0.5) * g.alpha**-0.5
idim = random.randrange(g.ndims)
coords[i, idim] += randoffset
vector_results = g(coords)
expected = u.array([g(c) for c in coords])
if vector_results.dimensionless:
vector_results = vector_results._magnitude
_assert_almost_equal(vector_results, expected, decimal=8)
@pytest.mark.parametrize('objkey', registered_types['basis_fn'] + ['linear_combination'])
def test_gaussian_str_and_repr_works(objkey, request):
g1 = request.getfixturevalue(objkey)
str(g1)
repr(g1)
@pytest.mark.parametrize('objkey', registered_types['basis_fn'])
def test_normalized_gaussian_self_overlap_is_unity(objkey, request):
g1 = request.getfixturevalue(objkey)
g2 = g1.copy()
g1.coeff = -10.0
g2.coeff = 12341.1832
olap = g1.overlap(g2, normalized=True)
assert abs(-1.0 - olap) < 1e-12
g1.coeff = 10.0
olap = g1.overlap(g2, normalized=True)
assert abs(1.0 - olap) < 1e-12
@pytest.mark.parametrize('objkey', registered_types['basis_fn'])
def test_normalization(objkey, request):
g1 = request.getfixturevalue(objkey)
oldnorm = g1.norm
g1.coeff = (random.random() - 0.5) * 428.23
try:
assert g1.norm != oldnorm
except u.DimensionalityError:
pass # this is a reasonable thing to happen too
g1.normalize()
assert abs(g1.norm - 1.0) < 1e-12
def test_linear_combination_normalization(linear_combination):
g1 = linear_combination
oldnorm = g1.norm
prefactor = (random.random() - 0.5) * 428.23
for prim in g1:
prim.coeff *= prefactor
try:
assert g1.norm != oldnorm
except u.DimensionalityError:
pass # this is a reasonable thing to happen too
g1.normalize()
assert abs(g1.norm - 1.0) < 1e-12
def _gfuncval(g, coord):
r = g.center - coord
if len(coord.shape) > 1:
r2 = np.sum(r**2, axis=1)
else:
r2 = np.sum(r**2)
fv = g.coeff * np.exp(-g.alpha * r2)
if isinstance(g, moldesign.orbitals.SphericalGaussian):
fv *= r2**(g.l/2.0) * harmonics.Y(g.l, g.m)(coord - g.center)
elif isinstance(g, moldesign.orbitals.CartesianGaussian): # assume cartesian
for r, r0, pow in zip(coord, g.center, g.powers):
if pow != 0:
fv *= (r-r0)**pow
return fv
def _assert_almost_equal(a, b, *args, **kwargs):
a_is_quantity = hasattr(a,'units')
b_is_quantity = hasattr(b,'units')
if not (a_is_quantity or b_is_quantity):
return np.testing.assert_almost_equal(a, b,
*args, **kwargs)
else:
assert a_is_quantity and b_is_quantity
units = a.units
return np.testing.assert_almost_equal(a.value_in(units),
b.value_in(units),
*args, **kwargs)
def test_convert_cartesian_label_to_array_of_integer_powers():
from moldesign.orbitals.gaussians import cart_to_powers
assert cart_to_powers('y') == [0, 1, 0]
assert cart_to_powers('xxyz') == [2, 1, 1]
assert cart_to_powers('zx^3') == [3,0,1]
@pytest.mark.parametrize('key', registered_types['basis_fn'] + ['linear_combination'])
def test_numerical_vs_analytical_norm(key, request):
g = request.getfixturevalue(key)
numnorm = _numerical_norm(g)
helpers.assert_almost_equal(g.norm, numnorm)
@pytest.mark.screening
def test_s_orbitals_equivalent_among_gaussian_types():
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
g_bare = moldesign.orbitals.Gaussian(center, exp)
g_cart = moldesign.orbitals.CartesianGaussian(center, exp, [0,0,0])
g_sphr = moldesign.orbitals.SphericalGaussian(center, exp, 0, 0)
for gauss in (g_bare, g_cart, g_sphr):
# normalize to amplitude of 1.0 at center
gauss.coeff = gauss.coeff / gauss(center)
assert gauss(center) == 1.0
_assert_orbitals_equivalent(g_bare, g_cart)
_assert_orbitals_equivalent(g_bare, g_sphr)
# real spherical harmonics that can be represented as a single cartesian term:
LM_TO_CART = {(1,-1): (0,1,0),
(1,0): (0,0,1),
(1,1): (1,0,0),
(2,-2): (1,1,0),
(2,-1): (0,1,1),
(2,1): (1,0,1),
(3,-2): (1,1,1)}
@pytest.mark.parametrize('lm,powers',
LM_TO_CART.items(),
ids=['lm:%d,%d, xyz:%d%d%d' % (args[0] + args[1])
for args in LM_TO_CART.items()])
def test_orbitals_same_in_cartesian_and_spherical(lm, powers):
center = np.random.rand(3) * u.angstrom
exp = 5.12 / u.angstrom**2
g_cart = moldesign.orbitals.CartesianGaussian(center, exp, powers)
g_sphr = moldesign.orbitals.SphericalGaussian(center, exp, *lm)
_assert_orbitals_equivalent(g_cart, g_sphr)
@pytest.mark.parametrize('l', range(4), ids=lambda x:'l=%s' % x)
def test_spherical_to_cartesian(l):
for m in range(-l,l+1):
center = np.random.rand(3)*u.angstrom
exp = random.random()*2.0/u.angstrom ** 2
bf = moldesign.orbitals.SphericalGaussian(center, exp, l, m, normalized=True)
_assert_orbitals_equivalent(bf, bf.to_cart())
def _assert_orbitals_equivalent(g1, g2):
helpers.assert_almost_equal(g1.norm,
g2.norm)
testcoords = 6.0*(np.random.rand(50, 3)-0.5)*u.angstrom
helpers.assert_almost_equal(g1(testcoords),
g2(testcoords))
def test_pyscf_and_mdt_norms_are_the_same(h2_rhf_augccpvdz):
mol = h2_rhf_augccpvdz
basis = mol.wfn.aobasis
for bf in basis:
assert abs(bf.norm - 1.0) < 1e-12
def test_pyscf_and_mdt_overlaps_are_the_same(h2_rhf_augccpvdz):
mol = h2_rhf_augccpvdz
basis = mol.wfn.aobasis
calc_overlap_mat = []
for i in range(len(basis)):
calc_overlap_mat.append(
[basis[i].overlap(basis[j]) for j in range(len(basis))]
)
overlaps = u.array(calc_overlap_mat)
assert isinstance(overlaps, np.ndarray) or overlaps.units == u.dimensionless
np.testing.assert_allclose(mol.wfn.aobasis.overlaps,
overlaps,
atol=5.0e-7)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_openmm_xface.py | .py | 7,917 | 234 | import random
from itertools import product
import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from moldesign.compute import packages
from . import helpers
from .molecule_fixtures import *
# TODO: remove constraints from dynamics parameters - they should only live in the constraints array
TESTSYTEMS = ['small_mol', 'protein', 'protein_custom_constraints', 'protein_freeze_hbonds']
INTEGRATORS = ['verlet', 'langevin']
missing_openmm = not packages.openmm.is_installed()
@pytest.fixture
def protein(protein_default_amber_forcefield):
mol = protein_default_amber_forcefield
mol.energy_model.params.compute_platform = 'cpu'
mol.energy_model.params.num_cpus = 1
mol.minimize(force_tolerance=0.5*u.eV/u.angstrom) # perform a very partial minimization
return mol
@pytest.fixture
def small_mol(mol_with_gast_params):
mol = mol_with_gast_params
mol.energy_model.params.compute_platform = 'cpu'
mol.energy_model.params.num_cpus = 1
mol.minimize(force_tolerance=0.5*u.eV/u.angstrom) # perform a very partial minimization
return mol
@pytest.fixture
def protein_custom_constraints(protein):
# constrains distance between first and last c-alpha carbons plus position of c-alpha in PHE58
mol = protein
mol.constrain_distance(mol.chains['X'].n_terminal['CA'],
mol.chains['X'].c_terminal['CA'])
mol.constrain_atom(mol.chains['X'].residues['PHE58']['CA'])
return mol
@pytest.fixture
def protein_freeze_hbonds(protein):
# constrains distance between first and last c-alpha carbons plus position of c-alpha in PHE58
mol = protein
mol.constrain_hbonds()
return mol
INTEGRATOR_PARAMS = dict(timestep=1.0 * u.fs,
constrain_hbonds=False,
constrain_water=False)
@pytest.fixture
def langevin():
return mdt.integrators.OpenMMLangevin(frame_interval=500,
**INTEGRATOR_PARAMS)
@pytest.fixture
def verlet():
return mdt.integrators.OpenMMVerlet(frame_interval=250*u.fs,
**INTEGRATOR_PARAMS)
@pytest.mark.parametrize('objkey', TESTSYTEMS)
def test_forces_and_energy_were_calculated(objkey, request):
mol = request.getfixturevalue(objkey)
energy = mol.calculate_potential_energy()
forces = mol.calculate_forces()
assert forces.shape == mol.positions.shape
@pytest.mark.skipif(mdt.compute.packages.openmm.force_remote,
reason="Numerical derivatives need to be parallelized, "
"otherwise this takes too long")
@pytest.mark.parametrize('objkey', TESTSYTEMS)
def test_analytical_vs_numerical_forces(objkey, request):
mol = request.getfixturevalue(objkey)
if mol.num_atoms > 20:
atoms = random.sample(mol.atoms, 20)
else:
atoms = mol.atoms
atom_indices = [atom.index for atom in atoms]
anagrad = -mol.calculate_forces()[atom_indices]
numgrad = helpers.num_grad(mol,
mol.calculate_potential_energy,
atoms=atoms,
step=0.005*u.angstrom)
assert (anagrad-numgrad).norm()/(3.0*len(atoms)) <= 5.0e-4 * u.eV / u.angstrom
@pytest.mark.parametrize('objkey', TESTSYTEMS)
def test_minimization_reduces_energy(objkey, request):
mol = request.getfixturevalue(objkey)
mol.positions += 0.01 * u.angstrom * np.random.rand(mol.num_atoms, 3)
p0 = mol.positions.copy()
e0 = mol.calculate_potential_energy()
traj = mol.minimize()
if mol.constraints:
pytest.xfail("This will fail until we replace minimizer with a CustomIntegrator")
helpers.assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.parametrize('systemkey,integratorkey', product(TESTSYTEMS, INTEGRATORS))
def test_openmm_dynamics(systemkey, integratorkey, request):
mol = request.getfixturevalue(systemkey)
mol.set_integrator(request.getfixturevalue(integratorkey))
mol.integrator.prep()
if not missing_openmm:
assert mol.integrator.sim.system is mol.energy_model.sim.system
initially_satisfied_constraints = all(c.satisfied() for c in mol.constraints)
p0 = mol.positions.copy()
t0 = mol.time
traj = mol.run(2.0 * u.ps)
# Basic dynamics and constraint sanity checks:
helpers.assert_something_resembling_dynamics_happened(traj, mol, p0, t0, 2.0*u.ps)
if 'temperature' in mol.integrator.params:
temp = mol.integrator.params.temperature
if mol.num_atoms > 50:
assert (temp / 2.0 <= traj.kinetic_temperature[-1] <= 500 * u.kelvin)
else: # small molecules have a big range, just a very loose sanity check here
assert mol.kinetic_temperature > temp / 10.0
else: # Assume constant energy dynamics (may need to check explicitly in future)
energy = traj.potential_energy+traj.kinetic_energy
if initially_satisfied_constraints:
compareframe = 0
else:
compareframe = 1
assert abs(energy[compareframe]-energy[-1]) <= 0.01*mol.num_atoms*u.kcalpermol
def test_cleared_constraints_are_no_longer_applied(protein_custom_constraints, langevin):
mol = protein_custom_constraints
langevin.frame_interval = 500
t0 = mol.time
p0 = mol.positions.copy()
mol.set_integrator(langevin)
traj = mol.run(2.0 * u.ps)
helpers.assert_something_resembling_dynamics_happened(traj, mol, p0, t0, 2*u.ps)
for constraint in mol.constraints:
assert constraint.satisfied()
oldconstraints = mol.constraints[:]
assert len(mol.constraints) > 0
mol.clear_constraints()
assert len(mol.constraints) == 0
t1 = mol.time
p1 = mol.positions.copy()
traj = mol.run(2.0 * u.ps)
for constraint in oldconstraints:
assert not constraint.satisfied() # it would be very very unlikely, I think
helpers.assert_something_resembling_dynamics_happened(traj, mol, p1, t1, 2*u.ps)
@pytest.mark.parametrize('integkey', INTEGRATORS)
@pytest.mark.screening
def test_unsupported_constraint_types(protein, integkey, request):
integrator = request.getfixturevalue(integkey)
protein.set_integrator(integrator)
if not missing_openmm:
assert protein.energy_model._prepped
protein.constrain_dihedral(*protein.atoms[:4])
if not missing_openmm:
assert not protein.energy_model._prepped
protein.calculate(use_cache=False) # this should work, because there's no motion invovled
with pytest.raises(mdt.exceptions.NotSupportedError):
traj = protein.run(1.0*u.ps)
t0 = protein.time
p0 = protein.positions.copy()
protein.clear_constraints()
traj = protein.run(1.0*u.ps) # should NOT raise a fuss now
helpers.assert_something_resembling_dynamics_happened(traj, protein, p0, t0, 1.0*u.ps)
protein.constrain_angle(*protein.atoms[:3])
with pytest.raises(mdt.exceptions.NotSupportedError):
protein.run(1.0*u.ps)
@pytest.mark.parametrize('integkey', INTEGRATORS)
def test_fallback_to_builtin_minimizer_for_arbitrary_constraints(small_mol, integkey, request):
mol = small_mol
mol.positions += 0.01 * u.angstrom * np.random.rand(mol.num_atoms, 3)
assert len(mol.constraints) == 0
mol.set_integrator(request.getfixturevalue(integkey))
mol.constrain_angle(*mol.atoms[:3])
assert len(mol.constraints) == 1
p0 = mol.positions.copy()
e0 = mol.calculate_potential_energy()
traj = mol.minimize()
helpers.assert_something_resembling_minimization_happened(p0, e0, traj, mol)
@pytest.mark.skipif(missing_openmm, reason='OpenMM not installed')
def test_list_platforms(): # doesn't do much right now
platforms = mdt.interfaces.openmm.list_openmmplatforms()
print('Found platforms %d: ', (len(platforms), platforms))
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_qmmm.py | .py | 2,650 | 103 | import pytest
import moldesign as mdt
from moldesign import units as u
from . import helpers
# Tests:
# 1. internal bonds on QM region are removed in all cases
# 2. wavefunction is perturbed for electrostatic embedding
# 3.
@pytest.fixture
def h2params():
mol = mdt.from_smiles('[H][H]')
mol.atoms[0].name = 'HA'
mol.atoms[1].name = 'HB'
mol.residues[0].name = 'H2'
params = mdt.create_ff_parameters(mol, charges='gasteiger')
return mol, params
@pytest.fixture(scope='function')
def h2_h2_with_ff(h2params):
ma, params = h2params
ma.residues[0].resname = 'UNL'
ma.atoms[0].name = 'HA'
ma.atoms[1].name = 'HB'
list(ma.bonds)[0].align('x')
mb = ma.copy()
mb.translate([0.0, 2.0, 0.0]*u.angstrom)
mol = ma.combine(mb)
params.assign(mol)
return mol
@pytest.fixture
def h2_mm(h2params):
mol, params = h2params
params.assign(mol)
mol.set_energy_model(mdt.models.OpenMMPotential)
return mol
@pytest.fixture
def h2_qm(h2params):
mol, params = h2params
mol.set_energy_model(mdt.models.RHF, basis='sto-3g')
return mol
@pytest.fixture
def h2_h2_mm(h2_h2_with_ff):
h2_h2_with_ff.set_energy_model(mdt.models.OpenMMPotential)
return h2_h2_with_ff
@pytest.fixture
def h2_h2_rhf(h2_h2_with_ff):
h2_h2_with_ff.set_energy_model(mdt.models.RHF, basis='sto-3g')
return h2_h2_with_ff
@pytest.fixture
def h2_h2_mechanical_embedding_rhf(h2_h2_with_ff):
mol = h2_h2_with_ff
mol.set_energy_model(mdt.models.MechanicalEmbeddingQMMM,
qm_atom_indices=[0, 1],
qm_model=mdt.models.RHF(basis='sto-3g'),
mm_model=mdt.models.OpenMMPotential)
return mol
@pytest.fixture
def h2_h2_mechanical_embedding_zeroqm(h2_h2_with_ff):
mol = h2_h2_with_ff
mol.set_energy_model(mdt.models.MechanicalEmbeddingQMMM,
qm_atom_indices=[0, 1],
qm_model=helpers.ZeroEnergy,
mm_model=mdt.models.OpenMMPotential)
return mol
def test_mechanical_embedding_wfn(h2_h2_mechanical_embedding_rhf):
mol = h2_h2_mechanical_embedding_rhf
mol.calculate()
qmprops = mol.properties.qmprops
mmprops = mol.properties.mmprops
h2_qm = mdt.Molecule(mol.residues[0])
h2_qm.set_energy_model(mdt.models.RHF, basis='sto-3g')
h2_qm.calculate()
assert abs(h2_qm.potential_energy - qmprops.potential_energy) < 1e-8 * u.hartree
helpers.assert_almost_equal(h2_qm.wfn.fock_ao, qmprops.wfn.fock_ao)
assert qmprops.potential_energy + mmprops.potential_energy == mol.potential_energy
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_constraints.py | .py | 9,496 | 293 | """ Tests constraint routines
"""
from builtins import range
import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from .molecule_fixtures import *
from . import helpers
registered_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@pytest.fixture
def four_particle_45_twist():
mol = helpers._make_mol_with_n_hydrogens(4)
mol.positions = u.nm*[[0.1, 0.0, -0.5],
[0.0, 0.0, -0.5],
[0.0, 0.0, 0.5],
[0.2, -0.2, 0.5]]
for iatom in range(3):
mol.atoms[iatom].bond_to(mol.atoms[iatom+1], 1)
return mol
@typedfixture('constraint')
def dihedral_constraint_satisfied(four_particle_45_twist):
mol = four_particle_45_twist
c = mol.constrain_dihedral(*mol.atoms)
return mol, c
@typedfixture('constraint')
def dihedral_constraint_unsatisfied(dihedral_constraint_satisfied):
mol, c = dihedral_constraint_satisfied
mol.atoms[0].z += 0.1*u.angstrom
mol.atoms[1].x += -1.0 * u.angstrom
mol.atoms[2].z -= -0.6 * u.angstrom
return mol, c
@typedfixture('constraint')
def angle_constraint_satisfied(four_particle_45_twist):
mol = four_particle_45_twist
c = mol.constrain_angle(*mol.atoms[:3])
return mol, c
@typedfixture('constraint')
def angle_constraint_unsatisfied(angle_constraint_satisfied):
mol, c = angle_constraint_satisfied
mol.atoms[1].x += -1.0 * u.angstrom
mol.atoms[2].z -= -0.6 * u.angstrom
return mol, c
@typedfixture('constraint')
def distance_constraint_satisfied(four_particle_45_twist):
mol = four_particle_45_twist
c = mol.constrain_distance(mol.atoms[1], mol.atoms[2])
return mol, c
@typedfixture('constraint')
def distance_constraint_unsatisfied(distance_constraint_satisfied):
mol, c = distance_constraint_satisfied
mol.atoms[1].x += -1.0 * u.angstrom
mol.atoms[2].z -= -0.6 * u.angstrom
return mol, c
@typedfixture('constraint')
def atom_position_constraint_unsatisfied(four_particle_45_twist):
mol = four_particle_45_twist
c = mol.constrain_atom(mol.atoms[2])
mol.atoms[2].x += 1.0*u.angstrom # the gradient is singular when exactly satisfied
return mol, c
@typedfixture('constraint')
def atom_coordinate_constraint_satisfied(four_particle_45_twist):
mol = four_particle_45_twist
c = mdt.geom.FixedCoordinate(mol.atoms[3], vector=np.array([1,1,-1]))
return mol, c
@typedfixture('constraint')
def angle_constraint_unsatisfied(atom_coordinate_constraint_satisfied):
mol, c = atom_coordinate_constraint_satisfied
mol.atoms[3].x += -1.0 * u.angstrom
mol.atoms[3].y -= -1.0 * u.angstrom
return mol, c
@pytest.mark.screening
def test_distance_constraint(distance_constraint_satisfied):
mol, c = distance_constraint_satisfied
# satisfied
np.testing.assert_allclose(c.current().value_in(u.nm),
1.0)
assert c.satisfied()
assert abs(c.error().value_in(u.nm)) <= 1e-10
# unsatisfied
mol.atoms[1].z = -0.6 * u.nm
assert not c.satisfied()
assert abs(c.error().value_in(u.nm) - 0.1) <= 1e-10
@pytest.mark.parametrize('objkey', registered_types['constraint'])
def test_constraint_gradient(objkey, request):
mol, c = request.getfixturevalue(objkey)
calc_grad = c.gradient()
num_grad = helpers.num_grad(mol, c.error)
np.testing.assert_allclose(num_grad.defunits_value(),
calc_grad.defunits_value(),
atol=5.0*helpers.DEFSTEP.defunits_value())
@pytest.mark.screening
def test_dihedral_constraint_errors(four_particle_45_twist):
mol = four_particle_45_twist
constraint = mol.constrain_dihedral(*mol.atoms)
assert constraint.error() == 0.0
assert constraint.satisfied()
constraint.value = 30.0 * u.degrees
np.testing.assert_allclose(constraint.error().value_in(u.degrees), 15.0)
assert not constraint.satisfied()
constraint.value = 60.0 * u.degrees
np.testing.assert_allclose(constraint.error().value_in(u.degrees), -15.0)
assert not constraint.satisfied()
def test_dihedral_constraint_errors_at_0(four_particle_45_twist):
mol = four_particle_45_twist
mol.atoms[3].position = [0.1, 0.0, 0.5] * u.angstrom
constraint = mol.constrain_dihedral(*mol.atoms)
assert constraint.error() == 0.0
assert constraint.satisfied()
for angle in (0, -10, 10, 90, -90) * u.degrees:
constraint.value = angle
np.testing.assert_allclose(constraint.error().value_in(u.degrees), -angle.magnitude)
def test_cannot_add_duplicate_constraints(mol_with_zerocharge_params):
mol = mol_with_zerocharge_params
mol.constrain_distance(*mol.atoms[:2])
mol.constrain_angle(*mol.atoms[:3])
mol.constrain_dihedral(*mol.atoms[:4])
mol.constrain_atom(mol.atoms[0])
mol.constrain_hbonds()
# Failure on adding duplicates
with pytest.raises(KeyError):
mol.constrain_distance(*mol.atoms[:2])
with pytest.raises(KeyError):
mol.constrain_angle(*mol.atoms[:3])
with pytest.raises(KeyError):
mol.constrain_dihedral(*mol.atoms[:4])
with pytest.raises(KeyError):
mol.constrain_atom(mol.atoms[0])
with pytest.raises(KeyError):
mol.constrain_hbonds()
# These should be ok
mol.constrain_distance(*mol.atoms[1:3])
mol.constrain_angle(*mol.atoms[1:4])
mol.constrain_dihedral(*mol.atoms[1:5])
mol.constrain_atom(mol.atoms[1])
def test_degrees_of_freedom_with_constraints(benzene, h2):
water = mdt.from_smiles('[OH2]')
water.residues[0].resname = 'HOH'
benzene.residues[0].resname = 'UNL'
h2.residues[0].resname = 'H2'
mol = benzene.combine(h2, water, water)
assert mol.num_atoms == 20 # assert I can count
assert mol.dynamic_dof == 3 * mol.num_atoms
full_dof = mol.dynamic_dof
def _constrain_direction():
c = mdt.geom.constraints.FixedCoordinate(mol.atoms[0], np.array([0.0, 0, 1.0]))
mol.constraints.append(c)
for constrainer, num_dof, args in ((mol.constrain_distance, 1, mol.atoms[:2]),
(mol.constrain_angle, 1, mol.atoms[:3]),
(mol.constrain_dihedral, 1, mol.atoms[:4]),
(mol.constrain_atom, 3, mol.atoms[:1]),
(mol.constrain_hbonds, 11, [True]),
(_constrain_direction, 1, [])):
constrainer(*args)
assert mol.dynamic_dof == full_dof-num_dof
mol.clear_constraints()
assert mol.dynamic_dof == full_dof
def test_degrees_of_freedom_with_integrator_constraints(benzene):
water = mdt.from_smiles('[OH2]')
water.residues[0].resname = 'HOH'
mol = benzene.combine(water)
full_dof = mol.dynamic_dof
assert full_dof == 3 * mol.num_atoms
mol.set_energy_model(mdt.models.OpenMMPotential)
mol.set_integrator(mdt.integrators.OpenMMLangevin)
mol.integrator.params.remove_translation = False
mol.integrator.params.remove_rotation = False
mol.integrator.params.constrain_hbonds = False
mol.integrator.params.constrain_water = False
assert mol.dynamic_dof == full_dof
mol.integrator.params.constrain_hbonds = True
mol.integrator.params.constrain_water = False
assert mol.dynamic_dof == full_dof - 8
mol.integrator.params.constrain_hbonds = False
mol.integrator.params.constrain_water = True
assert mol.dynamic_dof == full_dof - 3
mol.integrator.params.constrain_hbonds = True
mol.integrator.params.constrain_water = True
assert mol.dynamic_dof == full_dof - 9
mol.clear_constraints() # does nothing, constraints are in the integrator
assert mol.dynamic_dof == full_dof - 9
mol.integrator.params.constrain_hbonds = False
mol.integrator.params.constrain_water = False
assert mol.dynamic_dof == full_dof
mol.integrator.params.remove_translation = True
mol.integrator.params.remove_rotation = True
mol.integrator.params.constrain_hbonds = True
mol.integrator.params.constrain_water = True
assert mol.dynamic_dof == full_dof - 9 - 6
def test_degrees_of_freedom_with_integrator_reorientation(pdb3aid):
mol = pdb3aid
full_dof = mol.dynamic_dof
mol.set_energy_model(mdt.models.OpenMMPotential)
mol.set_integrator(mdt.integrators.OpenMMLangevin)
mol.integrator.params.remove_translation = False
mol.integrator.params.remove_rotation = False
mol.integrator.params.constrain_hbonds = False
mol.integrator.params.constrain_water = False
assert mol.dynamic_dof == full_dof
mol.integrator.params.remove_translation = False
mol.integrator.params.remove_rotation = True
assert mol.dynamic_dof == full_dof - 3
mol.integrator.params.remove_translation = True
mol.integrator.params.remove_rotation = False
assert mol.dynamic_dof == full_dof - 3
mol.integrator.params.remove_translation = True
mol.integrator.params.remove_rotation = True
assert mol.dynamic_dof == full_dof - 6
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_protein_primary_structure.py | .py | 8,144 | 256 | """ Tests introspection and methods for protein primary structure
"""
import itertools
import pytest
import moldesign as mdt
from moldesign import units as u
from .helpers import get_data_path
fixture_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
fixture_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@typedfixture('3AID', 'protein')
def protease_pdb():
return mdt.read(get_data_path('3aid.pdb.gz'))
@typedfixture('3AID', 'protein')
def protease_cif():
return mdt.read(get_data_path('3aid.cif.bz2'))
def test_chain_types(protease_pdb):
assert protease_pdb.chains['A'].type == 'protein'
assert protease_pdb.chains['B'].type == 'protein'
def test_chain_iterators(protease_pdb):
waters = list(protease_pdb.chains['A'].solvent_residues)
waternames = [water.name for water in waters]
assert waternames == ['HOH402', 'HOH403', 'HOH405', 'HOH406', 'HOH410']
ligands = list(protease_pdb.chains['A'].unclassified_residues)
assert len(ligands) == 1
assert ligands[0].name == 'ARQ401'
assert protease_pdb.chains['A'].get_ligand() == ligands[0]
water_chainb = list(protease_pdb.chains['B'].solvent_residues)
waternames_b = [water.name for water in water_chainb]
assert waternames_b == ['HOH407', 'HOH408', 'HOH409']
def test_3aid_cif_chains(protease_cif):
mol = protease_cif
assert len(mol.chains) == 5
assert mol.chains['A'].num_residues == mol.chains['B'].num_residues == 99
assert mol.chains['C'].num_residues == 1
assert mol.chains['C'].type == mol.chains['C'].residues[0].type == 'unknown'
assert mol.chains['D'].type == mol.chains['D'].type == 'water'
def test_3aid_cif_separate_waters(protease_cif):
mol = protease_cif
assert mol.chains['D'].num_residues == 5
assert mol.chains['E'].num_residues == 3
@pytest.mark.parametrize('fixture', fixture_types['3AID'])
def test_3aid_chain_properties(fixture, request):
mol = request.getfixturevalue(fixture)
for chainid in 'AB':
c = mol.chains[chainid]
assert c.n_terminal == c.residues['PRO1']
assert c.c_terminal == c.residues['PHE99']
assert c.type == 'protein'
@pytest.mark.parametrize('fixture', fixture_types['3AID'])
def test_3aid_primary_structure_access_methods(fixture, request):
mol = request.getfixturevalue(fixture)
a1 = mol.chains['A'].residues['GLN2'].atoms['CB']
assert a1 is mol.atoms[a1.index]
assert a1 is mol.chains['A'].residues.GLN2.atoms.CB
assert a1 in mol.chains['A'].residues.GLN2
assert 'GLN2' in mol.chains['A']
assert hasattr(mol.chains['A'].residues.GLN2.atoms, 'CB')
@pytest.mark.parametrize('fixture', fixture_types['3AID'])
def test_3aid_atom_selection(fixture, request):
mol = request.getfixturevalue(fixture)
a1 = mol.chains['A'].residues['GLN2'].atoms['CB']
a2 = mol.chains['B'].residues['LYS20'].atoms['O']
assert abs(a1.distance(a2) - 27.206*u.angstrom) < 0.001 * u.angstrom
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_chain_lookup_by_name_and_index(fixture, request):
mol = request.getfixturevalue(fixture)
for ic, chain in enumerate(mol.chains):
assert mol.chains[chain.index] is chain
assert mol.chains[chain.name] is chain
assert mol.chains[ic] is chain
# assert getattr(mol.chains, chain.name) is chain # this functionality disabled for now, possibly forever
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_residue_lookup_by_name_and_index(fixture, request):
mol = request.getfixturevalue(fixture)
for chain in mol.chains:
for ires, residue in enumerate(chain.residues):
assert mol.residues[residue.index] is residue
assert chain[residue.name] is residue
assert chain[ires] is residue
# assert getattr(chain, residue.name) is residue # this functionality disabled for now, possibly forever
assert chain.residues[residue.name] is residue
assert chain.residues[ires] is residue
assert getattr(chain.residues, residue.name) is residue
assert residue.chain is chain
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_atom_lookup_by_name_and_index(fixture, request):
mol = request.getfixturevalue(fixture)
for residue in mol.residues:
for iatom, atom in enumerate(residue.atoms):
assert residue[atom.name] is atom
assert residue[iatom] is atom
# assert getattr(residue,atom.name) is atom # this functionality disabled for now, possibly forever
assert residue.atoms[atom.name] is atom
assert residue.atoms[iatom] is atom
assert getattr(residue.atoms, atom.name) is atom
assert mol.atoms[atom.index] is atom
assert atom.chain is residue.chain
assert atom.residue is residue
@pytest.mark.parametrize('fixture', fixture_types['protein'])
@pytest.mark.screening
def test_protein_residue_iteration(fixture, request):
mol = request.getfixturevalue(fixture)
assert mol.chains['A'].type == 'protein'
firstres = mol.chains['A'].residues[0]
for res in mol.chains['A']:
if res.type == 'protein':
lastres = res
lr = firstres
for res in mol.chains['A'][1:]:
if res is lastres:
break
assert res.prev_residue is lr
assert lr.next_residue is res
lr = res
lastseq = -1
for ires, res in enumerate(mol.chains['A'].polymer_residues):
if ires == 0:
assert res is firstres
assert res.pdbindex > lastseq
lastseq = res.pdbindex
assert res is lastres
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_protein_residue_terminals(fixture, request):
mol = request.getfixturevalue(fixture)
assert mol.chains['A'].type == 'protein'
firstres = mol.chains['A'].residues[0]
for res in mol.chains['A']:
if res.type == 'protein':
lastres = res
assert firstres.is_n_terminal
assert lastres.is_c_terminal
assert mol.chains['A'].n_terminal is firstres
assert mol.chains['A'].c_terminal is lastres
for res in mol.chains['A'][1:]:
if res is lastres:
break
assert not res.is_n_terminal
assert not res.is_c_terminal
with pytest.raises(StopIteration):
firstres.prev_residue
with pytest.raises(StopIteration):
lastres.next_residue
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_molecule_links(fixture, request):
mol = request.getfixturevalue(fixture)
for obj in itertools.chain(mol.atoms, mol.residues, mol.chains):
assert obj.molecule is mol
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_chains_iterate_in_order(fixture, request):
mol = request.getfixturevalue(fixture)
_iter_index_order_tester(mol.chains)
@pytest.mark.parametrize('fixture', fixture_types['protein'])
def test_residues_iterate_in_order(fixture, request):
mol = request.getfixturevalue(fixture)
_iter_index_order_tester(mol.residues)
for chain in mol.chains:
_iter_index_order_tester(chain.residues)
@pytest.mark.parametrize('fixture', fixture_types['protein'])
@pytest.mark.screening
def test_atoms_iterate_in_order(fixture, request):
mol = request.getfixturevalue(fixture)
_iter_index_order_tester(mol.atoms)
for chain in mol.chains:
_iter_index_order_tester(chain.atoms)
for residue in mol.residues:
_iter_index_order_tester(residue.atoms)
def _iter_index_order_tester(iterable):
iterator = iter(iterable)
lastitem = next(iterator)
for item in iterator:
assert item.index > lastitem.index
lastitem = item
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_molecules.py | .py | 11,254 | 364 | """ Test various functionalities around data structure consistency
"""
import pickle
from past.builtins import basestring
import pytest
import numpy as np
from moldesign import units as u
import moldesign as mdt
from .object_fixtures import *
from .molecule_fixtures import *
from . import helpers
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
def test_h2_protected_atom_arrays(h2):
atom1, atom2 = h2.atoms
with pytest.raises(TypeError):
atom1.position = 'airplane'
with pytest.raises(u.DimensionalityError):
atom1.momentum = 3.0 * u.femtoseconds
with pytest.raises(ValueError):
atom2.position = np.array([1.0, 2.0]) * u.angstrom
atom2.position = 4.0 * u.ureg.meters
assert atom2.x == atom2.y == atom2.z == 4.0 * u.ureg.meters
def test_h2_hierarchy(h2):
assert len(h2.residues) == 1
assert len(h2.chains) == 1
chain = next(iter(h2.chains))
res = next(iter(h2.residues))
atom1, atom2 = h2.atoms
assert h2 == atom1.molecule == atom2.molecule == chain.molecule == res.molecule
assert chain == atom1.chain == atom2.chain
assert res == atom1.residue == atom2.residue
def test_h2_array_link(h2):
atom1, atom2 = h2.atoms
atom2.momentum[1] = 3.0*u.default.momentum
h2.positions[0, 1] = 0.1*u.angstrom
assert atom1.index == 0 and atom2.index == 1
assert atom1.y == 0.1*u.angstrom
assert h2.momenta[1, 1] == 3.0*u.default.momentum
assert h2.atoms[1].py == 3.0*u.default.momentum
def test_benzene_orbital_numbers(benzene):
assert benzene.num_electrons == 42
assert benzene.homo == 20
assert benzene.lumo == 21
def test_h2_set_coord_slices(h2):
mol = h2.copy()
mol.positions[:] = np.zeros((2,3)) * u.angstrom
assert (mol.positions == np.zeros((2,3)) * u.angstrom).all()
mol.momenta[0:2,1:3] = np.ones((2,2)) * u.default.momentum
assert (mol.momenta[0:2, 1:3] == np.ones((2,2)) * u.default.momentum).all()
@pytest.mark.screening
def test_h2_harmonic_oscillator(h2_harmonic):
mol = h2_harmonic
atoms = h2_harmonic.atoms
atoms[0].x = -1.0*u.angstrom
atoms[1].x = 0.0*u.angstrom
atoms[1].y = 0.3 * u.angstrom
e1 = mol.calc_potential_energy()
f1 = mol.forces[0,0]
atoms[0].x = 1.0*u.angstrom
f2 = mol.calc_forces()[0,0]
e2 = mol.potential_energy
assert e1 == e2 == 0.5*u.kcalpermol
force_units = u.kcalpermol/u.angstrom
assert abs(f1 + f2).value_in(force_units) < 1e-14
assert abs(f1 - 1.0*force_units).value_in(force_units) < 1e-14
def test_h2_cache_flush(h2_harmonic):
h2 = h2_harmonic
pe = h2.calc_potential_energy()
f = h2.forces
h2.atoms[0].x += 0.1285*u.angstrom
pe2 = h2.calc_potential_energy()
f2 = h2.forces
assert pe != pe2
assert not np.array_equal(f, f2)
def test_h2_not_calculated_yet(h2_harmonic):
h2_harmonic.calculate()
h2_harmonic.atoms[1].x += 0.3*u.angstrom
with pytest.raises(mdt.NotCalculatedError):
h2_harmonic.forces
with pytest.raises(mdt.NotCalculatedError):
h2_harmonic.potential_energy
def h2_properties_raises_not_calculated_yet(h2_harmonic):
h2_harmonic.calculate()
h2_harmonic.atoms[1].x += 0.3*u.angstrom
with pytest.raises(mdt.NotCalculatedError):
h2_harmonic.properties.forces
with pytest.raises(mdt.NotCalculatedError):
h2_harmonic.properties.potential_energy
@pytest.mark.screening
def test_h2_calculation_caching(h2_harmonic):
h2 = h2_harmonic
h2.properties = mdt.MolecularProperties(h2)
true_energy = h2.calc_potential_energy()
assert 'potential_energy' in h2.properties
assert 'forces' in h2.properties
h2.potential_energy
h2.forces
h2.properties['potential_energy'] = 'banana'
assert h2.potential_energy == h2.calc_potential_energy() == 'banana'
props = h2.calculate()
assert props.potential_energy == h2.potential_energy == h2.calc_potential_energy() == 'banana'
props2 = h2.calculate(use_cache=False)
assert props2.potential_energy == h2.potential_energy == true_energy
assert h2.calc_potential_energy() == true_energy
def test_h2_traj_energies(h2_trajectory):
traj = h2_trajectory
assert (np.abs(traj.positions[0,0]) <= 1.0 * u.angstrom).all()
assert (traj.potential_energy <= 4.0 * u.kcalpermol).all()
@pytest.mark.parametrize('molkey', registered_types['molecule'])
@pytest.mark.screening
def test_molecule_atom_hierarchy(molkey, request):
mol = request.getfixturevalue(molkey)
mol._atom_consistency_check()
@pytest.mark.parametrize('molkey', registered_types['molecule'])
def test_molecule_residue_hierarchy(molkey, request):
mol = request.getfixturevalue(molkey)
mol._residue_consistency_check()
@pytest.mark.parametrize('molkey', registered_types['molecule'])
def test_molecule_chain_hierarchy(molkey, request):
mol = request.getfixturevalue(molkey)
mol._chain_consistency_check()
@pytest.mark.parametrize('molkey', registered_types['molecule'])
def test_molecule_bonds(molkey, request):
mol = request.getfixturevalue(molkey)
mol._bond_consistency_check()
@pytest.mark.parametrize('molkey', registered_types['molecule'])
def test_molecule_types(molkey, request):
mol = request.getfixturevalue(molkey)
assert issubclass(type(mol.atoms), mdt.AtomList)
for atom in mol.atoms:
assert issubclass(type(atom), mdt.Atom)
for residue in mol.residues:
assert issubclass(type(residue), mdt.Residue)
def test_degrees_of_freedom(benzene):
assert benzene.dynamic_dof == 36
@pytest.mark.parametrize('objkey', registered_types['equality'])
def test_pickled_equality(objkey, request):
obj = request.getfixturevalue(objkey)
for iprotocol in helpers.PICKLE_PROTOCOLS:
x = pickle.dumps(obj, protocol=iprotocol)
y = pickle.loads(x)
assert type(y) == type(obj)
try:
assert y == obj
except ValueError:
assert (y == obj).all()
def test_h2_positions(h2):
atom1, atom2 = h2.atoms
assert (atom1.position == np.array([0.5, 0.0, 0.0]) * u.angstrom).all()
assert atom2.x == -0.25 * u.angstrom
assert atom1.distance(atom2) == 0.75 * u.angstrom
def test_h2(h2):
mol = h2
assert mol.num_atoms == 2
assert mol.atoms[0].symbol == mol.atoms[1].symbol == 'H'
def test_3aid(pdb3aid):
mol = pdb3aid
assert len(mol.chains) == 2
def test_3aid_ligand_search(pdb3aid):
mol = pdb3aid
unknown = mol.chains['A'](type='unknown')
proteina = mol.chains['A'](type='protein')
proteinb = mol.chains['B'](type='protein')
assert len(unknown) == 1
assert len(proteina) == len(proteinb) == 99
def test_ligand3aid(ligand3aid):
mol = ligand3aid
assert len(mol.chains) == 1
assert len(mol.residues) == 1
def test_nucleic_build(nucleic):
mol = nucleic
assert mol.num_chains == 2
assert mol.num_residues == 8
assert mol.chains[0] is mol.chains['A']
assert mol.chains[1] is mol.chains['B']
assert len(mol.chains[0].residues) == len(mol.chains[1].residues) == 4
def test_h2_trajectory(h2_trajectory):
"""
Check if the trajectory is the sine wave that we expect
"""
traj = h2_trajectory
mol = traj.mol
k = mol.energy_model.params.k
period = 2*u.pi*np.sqrt(mol.atoms[0].mass/k)
for frame in traj.frames:
period_progress = (frame.time % period) / period
if period_progress < 0.1 or period_progress > 0.9:
# check for expected peaks of sine wave
assert frame.positions[0, 0] > 0.1 * u.angstrom
elif 0.4 < period_progress < 0.6:
# check for expected troughs of sine wave
assert frame.positions[0, 0] < -0.1 * u.angstrom
@pytest.mark.parametrize('molkey', ['nucleic', 'pdb3aid', 'h2', 'mol_with_zerocharge_params'])
@pytest.mark.screening
def test_markdown_reprs_work(molkey, request):
# Not bothering to test the content, just want to make sure there's no error
mol = request.getfixturevalue(molkey)
assert isinstance(mol._repr_markdown_(), basestring)
assert isinstance(mol.atoms[0]._repr_markdown_(), basestring)
assert isinstance(mol.residues[0]._repr_markdown_(), basestring)
def test_dna_and_hydrogen_are_different(nucleic, h2):
assert not nucleic.same_topology(h2)
assert not nucleic.is_identical(h2)
def test_attribute_error_without_simulation_setup(h2):
with pytest.raises(AttributeError):
h2.calculate()
with pytest.raises(AttributeError):
h2.minimize()
with pytest.raises(AttributeError):
h2.run(500)
def test_changing_momenta_and_positions_makes_mols_different(nucleic):
n = nucleic.copy()
assert nucleic.same_topology(n)
assert nucleic.is_identical(n)
n.positions[3] += 0.1 * u.angstrom
assert nucleic.same_topology(n)
assert not nucleic.is_identical(n, verbose=True)
n.positions = nucleic.positions
assert nucleic.is_identical(n)
n.momenta[3] += 5.0 * u.default.momentum
assert not nucleic.is_identical(n, verbose=True)
assert nucleic.same_topology(n, verbose=True)
n.momenta = nucleic.momenta
assert nucleic.is_identical(n, verbose=True)
assert nucleic.same_topology(n, verbose=True)
def test_changing_residue_name_makes_mols_different(nucleic):
n = nucleic.copy()
assert nucleic.is_identical(n, verbose=True)
n.residues[0].resname = 'abc'
n.residues[0].name = 'abc1'
assert not nucleic.is_identical(n, verbose=True)
def test_changing_residue_name_makes_mols_different(nucleic):
n = nucleic.copy()
assert nucleic.is_identical(n, verbose=True)
n.atoms[3].atnum = 5
assert not nucleic.is_identical(n, verbose=True)
assert not nucleic.same_topology(n, verbose=True)
def test_changing_bonds_makes_mols_different(nucleic):
n = nucleic.copy()
assert nucleic.is_identical(n, verbose=True)
atom1 = n.atoms[3]
atom2 = n.atoms[134]
n.bond_graph[atom1][atom2] = n.bond_graph[atom2][atom1] = 1
assert not nucleic.is_identical(n, verbose=True)
assert not nucleic.same_topology(n, verbose=True)
def test_charge_from_number(h2):
h2plus = mdt.Molecule(h2, charge=1)
assert h2plus.charge == 1 * u.q_e
h2plus.charge = 2 * u.q_e
assert h2plus.charge == 2 * u.q_e
h2plus.charge = 3
assert h2plus.charge == 3 * u.q_e
def test_energy_model_charges(h2):
h2.charge = 1 * u.q_e
assert h2.charge == 1 * u.q_e
h2.set_energy_model(mdt.models.OpenMMPotential)
assert h2.energy_model.params.charge == 1 * u.q_e
h2.set_energy_model(mdt.models.OpenMMPotential, charge=3*u.q_e)
# TODO: test for warning here as well
assert h2.energy_model.params.charge == 3 * u.q_e
def test_initialization_charges():
a1 = mdt.Atom('Na', formal_charge=-1)
mol = mdt.Molecule([a1])
assert mol.charge == -1 * u.q_e
with pytest.raises(TypeError):
mdt.Atom('H', charge=3) # it needs to be "formal_charge" to distinguish from partial charge
m2 = mdt.Molecule([a1], charge=-1)
assert m2.charge == -1 * u.q_e
m2 = mdt.Molecule([a1], charge=-3*u.q_e)
# TODO: test for warning
assert m2.charge == -3 * u.q_e
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/helpers.py | .py | 8,008 | 249 | import io
from future.standard_library import install_aliases
install_aliases()
from builtins import range
from future.utils import PY2
import pytest
import os
import socket
import numpy as np
import moldesign as mdt
from moldesign import units as u
DEFSTEP = 0.000005*u.angstrom
def get_data_path(f):
"""
Returns path to a file in the ``moldesign/_tests/data/`` directory.
"""
return os.path.join(mdt.data.PACKAGEPATH, '_tests', 'data', f)
def num_grad(mol, fn, step=DEFSTEP, atoms=None, fnargs=None, fnkwargs=None):
""" Calculate the finite-difference gradient of a function
"""
grad = None
origpos = mol.positions.copy()
if fnargs is None:
fnargs = tuple()
if fnkwargs is None:
fnkwargs = dict()
if atoms is None:
atoms = mol.atoms
for iatom, atom in enumerate(atoms):
for idim in range(3):
atom.position[idim] += step
vplus = fn(*fnargs, **fnkwargs)
atom.position[idim] -= 2.0 * step
vminus = fn(*fnargs, **fnkwargs)
mol.positions = origpos # reset positions
if grad is None:
grad = np.zeros((len(atoms), 3)) * vplus.units/mol.positions.units
grad[iatom, idim] = (vplus - vminus) / (2.0*step)
return grad
ENERGY_TOLERANCE = 1e-8 * u.hartree
def _make_mol_with_n_hydrogens(n):
return mdt.Molecule([mdt.Atom('H') for i in range(n)])
def native_str_buffer(*args, **kwargs):
if PY2:
return io.BytesIO(*args, **kwargs)
else:
return io.StringIO(*args, **kwargs)
if PY2:
PICKLE_PROTOCOLS = list(range(3))
else:
PICKLE_PROTOCOLS = list(range(5))
class ZeroEnergy(mdt.models.base.EnergyModelBase):
""" All 0, all the time
"""
def prep(self):
pass
def calculate(self):
return dict(potential_energy=0.0*u.default.energy,
forces=np.zeros(self.mol.positions.shape)*u.default.force)
def _internet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
FROM https://stackoverflow.com/a/33117579/1958900
"""
try:
socket.setdefaulttimeout(timeout)
try:
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
except OSError:
return False
return True
except Exception as ex:
print(ex.message)
return False
INTERNET_ON = _internet()
def assert_something_resembling_minimization_happened(p0, e0, traj, mol):
""" Raises assertion error if results do not correspond to a successful optimization
Args:
p0 (Array[length]): initial position array
e0 (Scalar[energy]): initial energy
traj (moldesign.Trajectory): trajectory created from minimization
mol (moldesign.Molecule): state of molecule AFTER minimization
Returns:
"""
# Use assert_almost_equal to account for small numerical differences in
# convergence noise, serialization methods, etc.
import scipy.optimize.optimize
assert traj.num_frames > 1
assert_almost_equal(traj.potential_energy[0],
e0, decimal=9)
assert_almost_equal(traj.potential_energy[-1],
mol.potential_energy, decimal=9)
assert traj.potential_energy[-1] < e0
assert (traj.positions[0] == p0).all()
assert (traj.positions[-1] != p0).any()
assert (traj.positions[-1] == mol.positions).all()
recalc = mol.calculate_potential_energy(usecache=False)
assert (recalc - traj.potential_energy[-1]) < 1.0e-8 * u.hartree
scipyresult = getattr(traj, 'info', None)
if isinstance(scipyresult, scipy.optimize.optimize.OptimizeResult):
np.testing.assert_allclose(scipyresult.x,
mol.positions.defunits_value().flat)
assert_almost_equal(scipyresult.fun,
mol.potential_energy.defunits_value())
if mol.constraints or mol.energy_model.params.get('constrain_hbonds', False):
assert_constraints_satisfied(traj, p0, mol)
def assert_something_resembling_dynamics_happened(traj, mol, p0, t0, duration):
""" Checks that dynamics routines have produced a consistent trajectory
"""
frame_interval = mol.integrator.params.frame_interval
timestep = mol.integrator.params.timestep
epsilon_t = 1e-5 * timestep # numerical noise in time
if isinstance(frame_interval, int):
frame_interval *= mol.integrator.params.timestep
assert mol is traj.mol
assert traj.time[0] == t0
assert mol.time == traj.time[-1]
assert_almost_equal(traj.positions[-1], mol.positions)
# Energy test is not exact due to some non-deterministic kernels (e.g., OpenMM CPU model)
# Note: this is WAY too loose right now ...
assert abs(traj.potential_energy[-1] - mol.calculate_potential_energy()) < 1e-5 * u.eV
# lower precision for first step due to noise from single-precision positions (i.e. OpenMM CPU)
assert_almost_equal(traj.positions[0], p0, decimal=5)
lasttime = -np.inf * u.fs
expected_end = t0 + duration
for istep, step in enumerate(traj):
assert istep < len(traj) # I certainly hope so!
assert step.time > lasttime
if istep == len(traj) - 1:
# last frame - it just needs
assert step.time >= expected_end - epsilon_t
break
elif istep != 0:
assert (step.time - lasttime - frame_interval) < epsilon_t
lasttime = step.time
# If frame_interval doesn't divide duration exactly, it's permitted to go beyond duration
assert duration <= mol.time - traj.time[0] + epsilon_t
assert mol.time - traj.time[0] < duration + frame_interval + epsilon_t
if mol.constraints or mol.energy_model.params.get('constrain_hbonds', False):
assert_constraints_satisfied(traj, p0, mol, rigorous_constraints=True)
def assert_constraints_satisfied(traj, p0, mol, rigorous_constraints=False):
""" Checks that constraints were satisfied during molecular motion
"""
# TODO: check water rigidity, if called for
if mol.integrator is not None and mol.integrator.params.get('constrain_hbonds', False):
check_hbonds = True
assert mdt.geom.HBondsConstraint(mol).satisfied() # not sure what tolerance should be here
else:
check_hbonds = False
for constraint in mol.constraints:
assert constraint.satisfied()
if rigorous_constraints:
testmol = mol.copy()
if check_hbonds:
hbonds = mdt.HBondsConstraint(testmol)
for frame in traj.frames[1:]: # ok if starting positions don't obey constraints
testmol.positions = frame.positions
for constraint in testmol.constraints:
assert constraint.satisfied()
if check_hbonds:
assert hbonds.satisfied()
def assert_almost_equal(actual, desired, **kwargs):
units = mdt.units.get_units(actual)
np.testing.assert_almost_equal(units.value_of(actual),
units.value_of(desired),
**kwargs)
requires_internet_connection = pytest.mark.skipif(not INTERNET_ON,
reason='Network connection timed out')
""" Decorator to disable tests that need internet if we can't connect to the network """
def generate_grid(g, g2=None, npoints=64):
from moldesign import mathutils
if g2 is None: g2 = g
if not hasattr(g, 'alpha'):
alpha = min(min(p.alpha for p in g), min(p.alpha for p in g2))
else:
alpha = min(g.alpha, g2.alpha)
width = np.sqrt(1.0/alpha)
ranges = np.ones((3, 2))*5.0*width
ranges[:, 0] *= -1
ranges += ((g.center + g2.center)/2.0)[:, None]
grid = mathutils.VolumetricGrid(*ranges, npoints=npoints)
allpoints = grid.allpoints()
return allpoints, grid
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_copies.py | .py | 10,165 | 282 | from builtins import zip
import itertools
import numpy as np
import pytest
import moldesign as mdt
from moldesign import units as u
from .molecule_fixtures import *
from .object_fixtures import *
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
def test_carbon_copy(carbon_copy, carbon_atom):
atom = carbon_copy
assert atom.symbol == carbon_atom.symbol
assert atom.mass == carbon_atom.mass
assert atom.bond_graph == {}
@pytest.mark.screening
def test_copy_breaks_link(h2):
h2copy = mdt.Molecule(h2)
h2.atoms[0].y = 4.0 * u.bohr
assert h2copy.atoms[0].y == 0.0 * u.angstrom
np.testing.assert_almost_equal(h2.positions[0,1].value_in(u.bohr),
4.0, 7)
assert h2copy.positions[0, 1] == 0.0 * u.bohr
h2copy.momenta[1, 0] = 2.0 * u.default.momentum
np.testing.assert_almost_equal(h2copy.atoms[1].px.value_in(u.default.momentum),
2.0, 7)
assert h2.momenta[1, 0] == 0.0 * u.default.momentum
assert h2.atoms[1].px == 0.0 * u.default.momentum
def test_h2_harmonic_copy(h2_harmonic_copy, h2_harmonic):
mol = h2_harmonic_copy
assert mol.energy_model is mol.integrator is None
for name in 'num_atoms num_residues positions momenta'.split():
try:
assert getattr(h2_harmonic_copy, name) == getattr(h2_harmonic, name)
except ValueError:
assert (getattr(h2_harmonic_copy, name) == getattr(h2_harmonic, name)).all()
assert mol.atoms[0].bond_graph[mol.atoms[1]] == 1
assert mol.atoms[1].bond_graph[mol.atoms[0]] == 1
@pytest.mark.screening
def test_copying_doesnt_corrupt_original_h2_harmonic(h2_harmonic):
mol = h2_harmonic
integ = mol.integrator
model = mol.energy_model
residue = mol.residues[0]
chain = list(mol.chains)[0]
m2 = mdt.Molecule(mol)
assert integ is mol.integrator
assert model is mol.energy_model
assert len(mol.chains) == 1
assert len(mol.residues) == 1
assert residue == mol.residues[0]
assert chain == list(mol.chains)[0]
def test_atoms_copied_from_h2_harmonic(copy_atoms_from_h2_harmonic, h2_harmonic):
atoms = copy_atoms_from_h2_harmonic
atom = atoms[0]
assert atom.molecule is None
assert atom.residue is not h2_harmonic.atoms[0].residue
assert atom.chain is not h2_harmonic.atoms[0].chain
assert atoms[0].residue is atoms[1].residue
assert atoms[0].chain is atoms[1].chain
@pytest.mark.parametrize('fixture_key',
registered_types['molecule'] + registered_types['submolecule'])
def test_copy_atoms(fixture_key, request):
oldobj = request.getfixturevalue(fixture_key)
oldatoms = oldobj.atoms
atoms = oldatoms.copy_atoms()
assert isinstance(atoms, mdt.AtomList)
assert_atom_copy_integrity(atoms, oldatoms)
@pytest.mark.parametrize('fixture_key',
registered_types['molecule'] + registered_types['submolecule'])
def test_copy_atoms_in_containers(fixture_key, request):
oldobj = request.getfixturevalue(fixture_key)
if isinstance(oldobj, mdt.molecules.ChildList):
pytest.xfail("We haven't defined the behavior for copying ChildLists yet")
newobj = oldobj.copy()
assert newobj.__class__ is oldobj.__class__
assert_atom_copy_integrity(newobj.atoms, oldobj.atoms)
def assert_atom_copy_integrity(atoms, oldatoms):
newmol = atoms[0].molecule
assert len(atoms) == len(oldatoms)
for oldatom, atom in itertools.zip_longest(oldatoms, atoms):
assert oldatom.name == atom.name
assert oldatom.atnum == atom.atnum
assert oldatom.mass == atom.mass
assert (oldatom.position == atom.position).all()
assert (oldatom.velocity == atom.velocity).all()
atom.x += 1.0 * u.angstrom
assert all((oldatom.position == atom.position) == [False, True, True])
atom.px += 1.0 * u.angstrom * u.amu / u.fs
assert all((oldatom.momentum == atom.momentum) == [False, True, True])
assert oldatom.residue is not atom.residue
assert oldatom.residue.name == atom.residue.name
assert oldatom.chain is not atom.chain
assert oldatom.chain.name == atom.chain.name
assert (oldatom.molecule is atom.molecule is None) or (oldatom.molecule is not atom.molecule)
assert atom.molecule is newmol # might be None
if oldatom.residue is not None:
assert atom.residue.molecule is newmol
assert atom in atom.residue
assert atom.residue[atom.name] is atom
if oldatom.chain is not None:
assert atom.chain.molecule is newmol
assert atom in atom.chain.atoms
assert atom.residue in atom.chain
assert atom.chain[atom.residue.name] is atom.residue
if newmol is not None:
assert atom.residue is newmol.residues[atom.residue.index]
assert atom.chain is newmol.chains[atom.chain.index]
assert atom is newmol.atoms[atom.index]
@pytest.mark.parametrize('fixture_key', moldesign_objects)
def test_copied_types(fixture_key, request):
obj = request.getfixturevalue(fixture_key)
if isinstance(obj, mdt.molecules.ChildList):
pytest.xfail("We haven't defined the behavior for copying ChildLists yet")
objcopy = obj.copy()
assert obj.__class__ is objcopy.__class__
if not (isinstance(obj, mdt.Trajectory) or isinstance(obj, mdt.Atom)):
atomcopy = obj.copy_atoms()
assert isinstance(atomcopy, mdt.AtomList)
assert len(atomcopy) == obj.num_atoms
@pytest.mark.parametrize('fixture_key', registered_types['molecule'])
def test_molecule_copy(fixture_key, request):
mol = request.getfixturevalue(fixture_key)
newmol = mol.copy()
assert mol.name in newmol.name
assert mol.energy_model == newmol.energy_model
assert mol.integrator == newmol.integrator
@pytest.mark.parametrize('fixturename', 'pdb3aid h2'.split())
def test_molecular_combination_chains(request, fixturename):
mol = request.getfixturevalue(fixturename)
m2 = mol.copy()
newmol = mol.combine(m2)
assert newmol.num_chains == 2*mol.num_chains
assert len(set(chain for chain in newmol.chains)) == newmol.num_chains
_assert_unique_chainids(newmol)
def _assert_unique_chainids(mol):
chain_names = set()
for chain in mol.chains:
assert chain.name == chain.pdbindex
assert chain.name not in chain_names
chain_names.add(chain.name)
def test_chain_rename(pdb3aid):
res1 = mdt.Molecule(pdb3aid.residues[3])
res2 = mdt.Molecule(pdb3aid.residues[4])
newmol = mdt.Molecule([res1, res2])
assert newmol.num_chains == 2
assert newmol.num_residues == 2
assert newmol.residues[0].name == res1.residues[0].name
assert newmol.residues[1].name == res2.residues[0].name
assert newmol.chains[0].name == 'A'
assert newmol.chains[1].name == 'B'
@pytest.mark.parametrize('molkey', ["cached_mol_parameterized_with_zeros",
"cached_protein_with_default_amber_ff"])
def test_forcefield_copied_with_molecule(molkey, request):
mol = request.getfixturevalue(molkey)
m2 = mol.copy()
assert isinstance(m2.ff, mol.ff.__class__)
assert isinstance(m2.ff.parmed_obj, mol.ff.parmed_obj.__class__)
assert m2.ff.parmed_obj is not mol.ff.parmed_obj
p1 = m2.ff.parmed_obj
p2 = m2.ff.parmed_obj
assert m2.ff.parmed_obj.LJ_depth == mol.ff.parmed_obj.LJ_depth
assert p1.bond_types == p2.bond_types
assert p1.angle_types == p2.angle_types
assert p1.dihedral_types == p2.dihedral_types
assert p1.improper_types == p2.improper_types
def test_constraints_copied_with_molecule(mol_with_zerocharge_params):
mol = mol_with_zerocharge_params
mol.constrain_distance(*mol.atoms[:2])
mol.constrain_angle(*mol.atoms[:3])
mol.constrain_dihedral(*mol.atoms[:4])
mol.constrain_atom(mol.atoms[0])
mol.constrain_hbonds()
mcpy = mol.copy()
assert isinstance(mcpy.constraints, mol.constraints.__class__)
assert mcpy.constraints[0].desc == 'distance'
assert mcpy.constraints[1].desc == 'angle'
assert mcpy.constraints[2].desc == 'dihedral'
assert mcpy.constraints[3].desc == 'position'
assert mcpy.constraints[4].desc == 'hbonds'
for constraint in mcpy.constraints:
assert constraint.mol is mcpy
if constraint.desc != 'hbonds':
for atom in constraint.atoms:
assert atom.molecule is mcpy
def test_properties_copied_with_molecule(cached_h2_rhf_sto3g):
original = cached_h2_rhf_sto3g
assert original.potential_energy is not None # sanity check
mol = cached_h2_rhf_sto3g.copy()
assert mol is not original
assert mol.properties is not original.properties
for prop, val in original.properties.items():
assert prop in mol.properties
if isinstance(val, (u.MdtQuantity, np.ndarray)) and getattr(val, 'shape', False):
assert (mol.properties[prop] == val).all()
assert mol.properties[prop] is not val
elif isinstance(val, (str, int, float, mdt.molecules.AtomicProperties)):
assert mol.properties[prop] == val
else: # otherwise, just make sure it's not the original
assert mol.properties[prop] is not val
def test_wfn_copied_with_molecule(cached_h2_rhf_sto3g):
original = cached_h2_rhf_sto3g
assert original.wfn is not None # sanity check
mol = original.copy()
assert mol.wfn is not None
# should be completely equal
assert (mol.wfn.aobasis.fock == original.wfn.aobasis.fock).all()
# but different objects
assert mol.wfn.aobasis.fock is not original.wfn.aobasis.fock
def test_wfn_copy(cached_h2_rhf_sto3g):
original = cached_h2_rhf_sto3g
wfn = original.wfn.copy()
assert wfn.mol is original
assert wfn is not original.wfn
# should be completely equal
assert (wfn.aobasis.fock == original.wfn.aobasis.fock).all()
# but different objects
assert wfn.aobasis.fock is not original.wfn.aobasis.fock | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_cli.py | .py | 2,358 | 82 | from __future__ import print_function
import subprocess
import os
import pytest
import moldesign as mdt
from moldesign.external import pathlib
__PYTEST_MARK__ = 'io'
@pytest.fixture
def example_path(tmpdir):
path = pathlib.Path(str(tmpdir))
subprocess.check_call('python -m moldesign copyexamples',
shell=True,
cwd=str(path))
return path
@pytest.mark.screening
def test_exampled_copied(example_path):
path = example_path
assert (path / 'moldesign-examples').is_dir()
with (path / 'moldesign-examples' / '.mdtversion').open('r') as verfile:
assert verfile.read().strip() == mdt.__version__
def test_no_overwrite_examples(example_path):
path = example_path
try:
subprocess.check_call('python -m moldesign copyexamples',
shell=True,
cwd=str(path))
except subprocess.CalledProcessError as err:
assert err.returncode == 200
else:
assert False, "Expected CalledProcessError"
def test_example_version_warning(tmpdir):
path = example_path(tmpdir) # call this directly because we mangle the test dir version
with (path / 'moldesign-examples' / '.mdtversion').open('w') as verfile:
verfile.write(u'0.1.0')
try:
subprocess.check_call('python -m moldesign copyexamples',
shell=True,
cwd=str(path))
except subprocess.CalledProcessError as err:
assert err.returncode == 201
else:
assert False, "Expected CalledProcessError"
def test_version_command():
ver = subprocess.check_output('python -m moldesign version'.split()).splitlines()[-1]
assert ver.decode('ascii') == mdt.__version__
def test_dumpenv_command():
# just test that it doesn't error
subprocess.check_call('python -m moldesign dumpenv'.split())
def test_print_environment():
# just test that it still works
mdt.data.print_environment()
def test_config_command(tmpdir):
tempconfpath = os.path.join(str(tmpdir), 'moldesign.yml')
with open(tempconfpath, 'w') as tempfile:
print('devmode: True\nx: y', file=tempfile)
# just test that it doesn't error
subprocess.check_call(['python', '-m', 'moldesign', '--config-file', tempconfpath, 'config'])
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_atom_containers.py | .py | 9,183 | 287 | from builtins import range
import itertools
import random
import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from . import helpers
from .molecule_fixtures import pdb3aid, ethylene_waterbox_2na_2cl
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
registered_types = {}
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
@typedfixture('container')
def protein():
return mdt.read(helpers.get_data_path('3aid.pdb.gz'))
@pytest.fixture
def atom(protein):
return random.choice(protein.atoms)
@typedfixture('container')
def chain(protein):
return random.choice(protein.chains)
@typedfixture('container')
def residue(protein):
return random.choice(protein.residues)
@typedfixture('container')
def atomlist(protein):
return mdt.AtomList(random.sample(protein.atoms, 10))
@typedfixture('container')
def small_molecule():
return mdt.from_smiles('c1ccccc1')
def test_self_distances_are_0(protein):
res = protein.residues[0]
assert protein.distance(protein.atoms[0]) == 0.0
assert protein.residues[0].distance(protein) == 0.0
assert protein.atoms[0].distance(protein.atoms[0]) == 0.0
assert res.distance(res) == 0.0
assert res.distance(res.chain) == 0.0
def test_distance_is_minimum_pairwise(protein):
res1 = protein.residues[0]
res2 = protein.residues[2]
assert res1.distance(res2) == _get_minimum_pairwise(res1, res2)
assert res1.distance(res2.atoms[3]) == _get_minimum_pairwise(res1,
mdt.AtomList([res2.atoms[3]]))
@pytest.mark.parametrize(['f1', 'f2'],
itertools.product(registered_types['container'],
registered_types['container']))
def test_pairwise_distance_arrays(f1, f2, request):
o1 = request.getfixturevalue(f1)
o2 = request.getfixturevalue(f2)
if isinstance(o1, mdt.Atom):
array = np.array([o1.calc_distance(o2)])
else:
array = o1.calc_distance_array(o2)
if o1.num_atoms * o2.num_atoms > 250: # stochastically test larger matrices
pairs = ((random.randrange(0, o1.num_atoms), random.randrange(0, o2.num_atoms))
for i in range(250))
else:
pairs = itertools.product(range(o1.num_atoms), range(o2.num_atoms))
for iatom, jatom in pairs:
assert o1.atoms[iatom].distance(o2.atoms[jatom]) == array[iatom, jatom]
@pytest.mark.parametrize('fixturename', registered_types['container'])
def test_center_of_mass_movement(fixturename, request):
obj = request.getfixturevalue(fixturename)
origpos = obj.positions.copy()
obj.positions -= obj.center_of_mass
np.testing.assert_allclose(obj.center_of_mass,
np.zeros(3),
atol=1e-10)
obj.translate([1.0, 2.0, 3.0] * u.angstrom)
np.testing.assert_allclose(obj.center_of_mass,
[1.0, 2.0, 3.0]*u.angstrom)
obj.rotate(90 * u.degrees, [0,0,1])
np.testing.assert_allclose(obj.center_of_mass,
[1.0, 2.0, 3.0]*u.angstrom)
obj.rotate(90 * u.degrees, [0,0,1], center=[0,0,0]*u.angstrom)
np.testing.assert_allclose(obj.center_of_mass,
[-2.0, 1.0, 3.0]*u.angstrom)
obj.positions = origpos
@pytest.mark.parametrize('fixturename', registered_types['container'])
def test_container_properties(fixturename, request):
obj = request.getfixturevalue(fixturename)
assert obj.mass == sum([atom.mass for atom in obj.atoms])
np.testing.assert_array_equal(obj.positions.defunits(),
u.array([atom.position for atom in obj.atoms]).defunits())
assert obj.num_atoms == len(obj.atoms)
@pytest.mark.parametrize('fixturename', registered_types['container'])
def test_position_links(fixturename, request):
obj = request.getfixturevalue(fixturename)
np.testing.assert_array_equal(obj.positions[0, :],
obj.atoms[0].position)
obj.positions[0, :] *= 2.0
np.testing.assert_array_equal(obj.positions[0, :],
obj.atoms[0].position)
def _get_minimum_pairwise(group1, group2):
mindist = np.inf * u.angstrom
for a1, a2 in itertools.product(group1.atoms, group2.atoms):
distance = (a1.position-a2.position).norm()
mindist = min(distance, mindist)
return mindist
@pytest.mark.parametrize('fixturename', ['atom', 'residue', 'atomlist', 'small_molecule'])
def test_atoms_within(fixturename, request):
obj = request.getfixturevalue(fixturename)
if fixturename == 'atom':
myatoms = {obj}
mol = obj.molecule
else:
myatoms = set(obj.atoms)
mol = obj.atoms[0].molecule
assert len(obj.atoms_within(0.0*u.angstrom)) == 0
within5 = set(obj.atoms_within(5.0*u.angstrom))
within5_self = set(obj.atoms_within(5.0*u.angstrom, include_self=True))
assert myatoms.issubset(within5_self)
assert within5.union(myatoms) == within5_self
for atom in mol.atoms:
if atom in myatoms:
assert atom not in within5
elif atom.distance(obj) <= 5.0*u.angstrom:
assert atom in within5
else:
assert atom not in within5
@pytest.mark.parametrize('fixturename', ['atom', 'residue', 'atomlist'])
@pytest.mark.screening
def test_residues_within(fixturename, request):
obj = request.getfixturevalue(fixturename)
if fixturename == 'atom':
mol = obj.molecule
else:
mol = obj.atoms[0].molecule
assert len(obj.residues_within(0.0*u.angstrom)) == 0
within5 = set(obj.residues_within(5.0*u.angstrom))
within5_self = set(obj.residues_within(5.0*u.angstrom, include_self=True))
if fixturename == 'residue':
assert within5.union([obj]) == within5_self
else:
assert within5 == within5_self
for residue in mol.residues:
if residue == obj:
assert residue in within5_self
assert residue not in within5
elif residue.distance(obj) <= 5.0*u.angstrom:
assert residue in within5
else:
assert residue not in within5
def test_setlike_atomlist_methods(protein):
l1 = protein.atoms[:10]
assert isinstance(l1, mdt.AtomList)
l2 = protein.atoms[5:15]
assert l1.union(l2) == protein.atoms[:15]
assert l2.union(l1) == protein.atoms[5:15] + protein.atoms[:5]
interx = l1.intersection(l2)
assert interx == protein.atoms[5:10]
assert l2.intersection(l1) == interx
assert l1 - l2 == protein.atoms[:5]
assert l2 - l1 == protein.atoms[10:15]
assert (l1 + l2).unique() == protein.atoms[:15]
@pytest.mark.screening
def test_get_atoms(protein):
protein_atoms = set(protein.get_atoms('protein'))
water_atoms = set(protein.get_atoms('water'))
carbon_atoms = set(protein.get_atoms(symbol='C'))
gly_alpha_carbons = set(protein.get_atoms(resname='GLY', name='CA'))
for atom in protein.atoms:
assert (atom.residue.type == 'protein') == (atom in protein_atoms)
assert (atom.residue.resname == 'HOH') == (atom in water_atoms)
assert (atom.atnum == 6) == (atom in carbon_atoms)
assert (atom.name == 'CA' and atom.residue.resname == 'GLY') == (
atom in gly_alpha_carbons)
def test_get_atoms_keywords(ethylene_waterbox_2na_2cl):
mol = ethylene_waterbox_2na_2cl
with pytest.raises(ValueError):
mol.get_atoms('arglebargle')
with pytest.raises(ValueError):
mol.get_atoms('ions') # it's "ion" only (for now)
ions = mol.get_atoms('ion')
assert ions.num_atoms == 4
for ion in ions:
assert ion.residue.resname in ('NA','CL') and ion.name in ('Na','Cl')
waters = mol.get_atoms('water')
for w in waters:
assert w.residue.resname == 'HOH'
solute = mol.get_atoms('unknown')
assert len(solute) == 6
assert len(waters) + len(ions) + len(solute) == mol.num_atoms
def test_get_residues_in_molecule(pdb3aid):
mol = pdb3aid
waters = mol.get_residues(type='water')
assert set(waters) == set(res for res in mol.residues if res.resname == 'HOH')
def test_get_residues_in_chain(pdb3aid):
mol = pdb3aid
chain = mol.chains['A']
waters = chain.get_residues(type='water')
assert set(waters) == set(res for res in mol.chains['A'].residues if res.resname == 'HOH')
def test_get_residues_two_parameters(pdb3aid):
mol = pdb3aid
alas = mol.chains['B'].get_residues(resname='ALA')
assert set(alas) == set(res for res in mol.chains['B'].residues if res.resname == 'ALA')
ala2 = mol.get_residues(resname='ALA', chain='B')
assert set(ala2) == set(alas)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_wfn.py | .py | 3,128 | 78 | import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from moldesign.interfaces.pyscf_interface import basis_values
from .molecule_fixtures import *
from . import helpers
__PYTEST_MARK__ = 'wfn'
TESTSYSTEMS = ['h2_rhf_augccpvdz', 'h2_rhf_sto3g', 'acetylene_dft_631g']
def test_pyscf_orbital_grid_works(h2_rhf_augccpvdz):
""" Tests the basic input/output of the pyscf basis_values function
Doesn't actually test the values directly - just that the answers are mathematically consistent
"""
mol = h2_rhf_augccpvdz
wfn = mol.wfn
nbasis = len(wfn.aobasis)
coords = u.array([mol.com,
np.zeros(3)*u.angstrom,
10.0 * np.ones(3) * u.angstrom,
np.ones(3)*u.nm])
# First - check that the shape is appropriate if called without orbital coefficients
values_nocoeffs = basis_values(mol, wfn.aobasis, coords)
assert values_nocoeffs.shape == (len(coords), nbasis)
assert (values_nocoeffs[-1] == values_nocoeffs[-2]).all() # these 2 coordinates are the same
# Second - explicitly send orbital coefficients for first 2 basis functions
coeffs = np.zeros((2, nbasis))
coeffs[:2, :2] = np.identity(2)
vals_b0 = basis_values(mol, wfn.aobasis, coords, coeffs=coeffs)
assert vals_b0.shape == (len(coords), len(coeffs))
np.testing.assert_allclose(values_nocoeffs[:,:2], vals_b0)
# Third - send symmetric and anti-symmetric combinations of basis functions and check answers
plusminus = np.zeros((2, nbasis))
plusminus[:2, :2] = 1.0 / np.sqrt(2)
plusminus[1,1] = -1.0 / np.sqrt(2)
vals_plusminus = basis_values(mol, wfn.aobasis, coords, coeffs=plusminus)
assert vals_plusminus.shape == (len(coords), len(coeffs))
helpers.assert_almost_equal(vals_plusminus[:,0],
(vals_b0[:,0] + vals_b0[:,1])/np.sqrt(2))
helpers.assert_almost_equal(vals_plusminus[:,1],
(vals_b0[:,0] - vals_b0[:,1])/np.sqrt(2))
@pytest.mark.parametrize('molkey', TESTSYSTEMS)
def test_basis_function_3d_grids_same_in_pyscf_and_mdt(molkey, request):
mol = request.getfixturevalue(molkey)
randocoords = 6.0 * u.angstrom * (np.random.rand(200, 3) - 0.5)
pyscf_vals = basis_values(mol, mol.wfn.aobasis, randocoords)
with np.errstate(under='ignore'):
mdt_vals = mol.wfn.aobasis(randocoords)
helpers.assert_almost_equal(mdt_vals, pyscf_vals, decimal=5)
@pytest.mark.parametrize('molkey', ['h2_rhf_augccpvdz', 'h2_rhf_sto3g'])
@pytest.mark.screening
def test_pyscf_basis_function_space_integral_normalized(molkey, request):
mol = request.getfixturevalue(molkey)
grid = mdt.mathutils.padded_grid(mol.positions, 8.0 * u.angstrom, npoints=150)
points = grid.allpoints()
pyscf_vals = basis_values(mol, mol.wfn.aobasis, points)
assert pyscf_vals.shape == (len(points), len(mol.wfn.aobasis))
pyscf_normsqr = (pyscf_vals ** 2).sum(axis=0) * grid.dx * grid.dy * grid.dz
helpers.assert_almost_equal(pyscf_normsqr, 1.0,
decimal=4)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_config.py | .py | 3,146 | 105 | import os
import yaml
import pytest
import moldesign as mdt
from moldesign.compute import packages
from .molecule_fixtures import *
__PYTEST_MARK__ = ['internal', 'config']
# mark all tests in this module with this label (see ./conftest.py)
@pytest.fixture(scope='function')
def tempconfigfile(tmpdir):
tmpdir = str(tmpdir)
path = os.path.join(tmpdir, 'moldesign.yml')
oldenviron = os.environ.get('MOLDESIGN_CONFIG', None)
os.environ['MOLDESIGN_CONFIG'] = path
with open(path, 'w') as cfile:
cfile.write('devmode: true')
yield path
if oldenviron is not None:
os.environ['MOLDESIGN_CONFIG'] = oldenviron
else:
os.environ.pop('MOLDESIGN_CONFIG')
clean_config()
def clean_config():
mdt.compute.config.clear()
mdt.compute.init_config()
def test_write_conf(tempconfigfile):
mdt.compute.update_saved_config(run_local={'nwchem':True, 'opsin':True})
mdt.compute.update_saved_config(run_remote={'openmm':True}, run_local={'nwchem':False})
mdt.compute.update_saved_config(devmode=True)
with open(tempconfigfile, 'r') as conffile:
data = yaml.load(conffile)
assert data['run_local'] == {'nwchem':False, 'opsin':True}
assert data['run_remote'] == {'openmm':True}
assert data['devmode']
@pytest.fixture
def disconnect_docker():
oldhost = mdt.compute.config.default_docker_host
mdt.compute.config.default_docker_host = '000.111:333'
yield
mdt.compute.config.default_docker_host = oldhost
mdt.compute.compute.default_engine = None
def test_docker_connection_failure(disconnect_docker):
with pytest.raises(mdt.exceptions.DockerError):
mdt.compute.reset_compute_engine()
@pytest.mark.skipif(not packages.openbabel.is_installed(),
reason='Only run if openbabel is present locally')
def test_set_docker_python(tempconfigfile):
njob = mdt._njobs
g1 = mdt.from_smiles('CC')
assert mdt._njobs == njob
mdt.compute.update_saved_config(run_remote={'openbabel':True})
clean_config()
g2 = mdt.from_smiles('CC')
assert mdt._njobs == njob + 1
def test_docker_image_strings(tempconfigfile):
mdt.compute.config.devmode = True
assert mdt.compute.get_image_path('blah') == 'blah:dev'
assert mdt.compute.get_image_path('a/b') == 'a/b:dev'
mdt.compute.config.devmode = False
mdt.compute.config.default_repository = 'myrepo/thing:'
mdt.compute.config.default_version_tag = 'tagtag'
assert mdt.compute.get_image_path('blah') == 'myrepo/thing:blah-tagtag'
mdt.compute.config.default_repository = 'myrepo/thing'
mdt.compute.config.default_version_tag = 'tagtag'
assert mdt.compute.get_image_path('blah') == 'myrepo/thing/blah:tagtag'
mdt.compute.config.default_repository = 'myrepo/thing/'
assert mdt.compute.get_image_path('blah') == 'myrepo/thing/blah:tagtag'
def test_nbmolviz_errors(ethylene):
""" These should always raise importerrors because we're not running in Jupyter
"""
with pytest.raises(ImportError):
mdt.widgets.BondSelector()
with pytest.raises(ImportError):
ethylene.draw()
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_symmetry.py | .py | 5,256 | 189 | import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from moldesign.external import transformations
from .molecule_fixtures import *
@pytest.fixture
def linear():
expected = {'C1': 1,
'Cinf_v': 1}
a1 = mdt.Atom(1)
a1.position = [-1, 0, 0] * u.angstrom
a2 = mdt.Atom(2)
a2.position = [1, 0, 0] * u.angstrom
return mdt.Molecule([a1, a2], name='linear_h2'), expected, True
@pytest.fixture
def linear_inversion(linear):
mol = linear[0].copy()
expected = {'C1': 1,
'Cinf_v': 1,
'Cs': 1,
'Ci': 1}
mol.atoms[0].atnum = mol.atoms[1].atnum
mol.atoms[0].mass = mol.atoms[1].mass
return mol, expected, True
@pytest.fixture
def planar():
expected = {'C1': 1,
'Cs': 1}
a1 = mdt.Atom(1)
a1.position = [-1, 0, 0] * u.angstrom
a2 = mdt.Atom(2)
a2.position = [0.9, 0.2, 0] * u.angstrom
a3 = mdt.Atom(3)
a3.position = [-0.9, 3.2, 0] * u.angstrom
return mdt.Molecule([a1, a2, a3], name='planar_h3'), expected, True
@pytest.fixture
def almost_planar(planar):
atoms = planar[0].atoms
atoms.append(mdt.Atom(4))
atoms[-1].position = [0, 0, 0.005] * u.angstrom
return mdt.Molecule(atoms, name='almost_planar')
def test_approximate_symmetry(almost_planar):
symmetries = mdt.get_symmetry(almost_planar)
assert symmetries.rms > 0
assert len(symmetries.exact) == 1
assert symmetries.exact[0].symbol == 'C1'
assert len(symmetries.approximate) == 1
assert symmetries.approximate[0].symbol == 'Cs'
@pytest.mark.screening
def test_symmetrizer(almost_planar):
mol = almost_planar.copy()
symmetries = mdt.get_symmetry(almost_planar)
cs = symmetries.groups['Cs'][0]
mol.positions = symmetries.get_symmetrized_coords(cs)
newsymm = mdt.get_symmetry(mol)
assert len(newsymm.exact) == 2
assert len(newsymm.approximate) == 0
@pytest.fixture
def benz(benzene):
# Note: we're counting on the geometry generation algorithm to give proper symmetries
expected = {'C1': 1,
'C6': 1,
'C2': 7,
'C3': 1,
'Ci': 1,
'Cs': 7,
'S6': 1,
'S3': 1}
return benzene, expected, False
@pytest.mark.parametrize('fixturename', 'linear linear_inversion planar benz'.split())
def test_expected_symmetries(fixturename, request):
mol, expected, allexact = request.getfixturevalue(fixturename)
symmetries = mdt.get_symmetry(mol)
if allexact:
assert abs(symmetries.rms) <= 1e-10 * u.angstrom
found = {}
for elem in symmetries.elems:
if elem.symbol not in found:
found[elem.symbol] = 0
found[elem.symbol] += 1
if allexact:
assert abs(elem.csm) <= 1e-10 * u.angstrom
assert abs(elem.max_diff) <= 1e-10 * u.angstrom
positions = symmetries.orientation.copy()
transformed = positions.dot(elem.matrix)
assert_isomorphic(mol, positions, transformed, elem.max_diff)
# check that transformation matrix is unitary
assert_identity_matrix(elem.matrix.dot(elem.matrix.T))
# check matrix transform properties
if elem.symbol == 'C1':
assert_identity_matrix(elem.matrix)
elif elem.symbol == 'Cs':
assert_reflection_matrix(elem.matrix)
elif elem.symbol == 'Ci':
assert_identity_matrix(-1 * elem.matrix)
elif len(elem.symbol) == 2 and elem.symbol[0] == 'C' and elem.symbol[1].isdigit():
nfold = int(elem.symbol[1])
assert_rotation_matrix(elem.matrix, (360.0*u.degrees)/nfold)
assert expected == found
def assert_identity_matrix(mat):
np.testing.assert_allclose(mat, np.identity(3), atol=1e-10)
def assert_reflection_matrix(mat):
mat4 = _asmat4(mat)
try:
transformations.reflection_from_matrix(mat4)
except ValueError:
assert False, 'not a reflection matrix'
def assert_rotation_matrix(mat, angle=None):
mat4 = _asmat4(mat)
try:
theta, direc, point = transformations.rotation_from_matrix(mat4)
except ValueError:
assert False, 'not a rotation matrix'
else:
assert (point[:3] == 0).all() # would be WEIRD if this fails
if angle is not None:
assert abs(angle.value_in(u.radian) - abs(theta)) <= 1e-6
def assert_isomorphic(mol, transformed, positions, maxdiff):
if maxdiff == 0.0:
tolerance = 1.0e-4 * u.angstrom
else:
tolerance = maxdiff * 4
tol2 = tolerance ** 2
available = {atom: pos for atom, pos in zip(mol.atoms, positions)}
for atom, newpos in zip(mol.atoms, transformed):
closest_atom = None
closest = np.inf * u.angstrom**2
for availatom, pos in available.items():
dist2 = np.sum((pos-newpos)**2)
if dist2 < closest:
closest_atom = availatom
closest = dist2
assert atom.atnum == closest_atom.atnum
assert atom.mass == closest_atom.mass
assert closest <= tol2
def _asmat4(mat):
mat4 = np.identity(4)
mat4[:3,:3] = mat
return mat4 | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_atom_bond_computed_properties.py | .py | 2,315 | 72 | import pytest
import moldesign as mdt
from moldesign import units as u
from .molecule_fixtures import *
from . import helpers
def test_forcefield_atom_term_access(protein_default_amber_forcefield):
mol = protein_default_amber_forcefield
for atom in mol.atoms:
assert atom.ff.ljepsilon.dimensionality == u.kcalpermol.dimensionality
assert atom.ff.ljsigma.dimensionality == u.angstrom.dimensionality
assert atom.ff.partial_charge.dimensionality == u.q_e.dimensionality
assert atom.ff.pmdobj.idx == atom.index
assert atom.ff.pmdobj.element == atom.atnum
@pytest.mark.screening
def test_forcefield_bond_term_access(protein_default_amber_forcefield):
mol = protein_default_amber_forcefield
for bond in mol.bonds:
assert bond.ff.equilibrium_length.dimensionality == u.angstrom.dimensionality
assert bond.ff.force_constant.dimensionality == (u.kcalpermol/u.angstrom).dimensionality
pmdobj = bond.ff.pmdobj
pmdatoms = sorted((pmdobj.atom1, pmdobj.atom2), key=lambda x:x.idx)
assert (pmdatoms[0].idx, pmdatoms[1].idx) == (bond.a1.index, bond.a2.index)
assert (pmdatoms[0].element, pmdatoms[1].element) == (bond.a1.atnum, bond.a2.atnum)
def test_atom_basis_function_returns_none_if_no_wfn(h2):
for atom in h2.atoms:
assert atom.basis_functions is None
def test_atom_ffterms_returns_none_if_no_ff(h2):
for atom in h2.atoms:
assert atom.ff is None
def test_bond_ffterms_returns_none_if_no_ff(h2):
for bond in h2.bonds:
assert bond.ff is None
def test_basis_function_atom_access(h2_rhf_sto3g):
mol = h2_rhf_sto3g
for atom in mol.atoms:
assert len(atom.basis_functions) == 1 # good ol' sto-3g
assert len(atom.basis_functions[0].primitives) == 3
@pytest.mark.screening
def test_atom_property_access_to_mulliken_charges(h2_rhf_sto3g):
mol = h2_rhf_sto3g
for atom in mol.atoms:
assert abs(atom.properties.mulliken) <= 1e-5 * u.q_e
def test_atomic_forces(h2_rhf_sto3g):
mol = h2_rhf_sto3g
helpers.assert_almost_equal(mol.atoms[0].force, -mol.atoms[1].force)
def test_atom_properties_are_empty_dict_if_nothings_computed(h2):
empty = mdt.utils.DotDict()
for atom in h2.atoms:
assert atom.properties == empty
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_mathutils.py | .py | 7,600 | 253 | import itertools
import pytest
import numpy as np
from moldesign import mathutils
from moldesign import units as u
from moldesign.mathutils import spherical_harmonics as sh
from . import helpers
__PYTEST_MARK__ = ['internal', 'math', 'mathutils']
CONSTRUCTORS = []
IDS = []
# Couldn't figure out a way to do this with fixtures ...
def constructor(f):
def wrapper():
arr, norm = f()
return arr * 3.0 * u.nm, norm * 3.0 * u.nm
wrapper.__name__ = f.__name__ + '_quantity'
CONSTRUCTORS.append(f)
IDS.append(f.__name__)
CONSTRUCTORS.append(wrapper)
IDS.append(wrapper.__name__)
return wrapper
@constructor
def zeros():
return np.zeros(3), 0.0
@constructor
def ones():
return np.ones(3), np.sqrt(3)
@constructor
def y_unit_vector():
v = np.zeros(3)
v[1] = 1.0
return v, 1.0
@constructor
def list_of_vectors():
return np.array(TESTARRAY), np.array(TESTARRAY_NORMS)
@pytest.mark.parametrize('setupfn', CONSTRUCTORS, ids=IDS)
def test_norm(setupfn):
arr, expected_norm = setupfn()
n = mathutils.norm(arr)
helpers.assert_almost_equal(n, expected_norm)
@pytest.mark.parametrize('setupfn', CONSTRUCTORS, ids=IDS)
def test_normalized(setupfn):
arr, expected_norm = setupfn()
vectorized = len(arr.shape) > 1
normed = mathutils.normalized(arr)
if not vectorized:
arr, expected_norm, normed = [arr], [expected_norm], [normed]
for v, n, unitvec in zip(arr, expected_norm, normed):
if n != 0:
helpers.assert_almost_equal(unitvec, v/n)
@pytest.mark.parametrize('setupfn', CONSTRUCTORS, ids=IDS)
@pytest.mark.screening
def test_perpendicular(setupfn):
arr, expected_norm = setupfn()
vectorized = len(arr.shape) > 1
normvecs = mathutils.normalized(arr)
perpvecs = mathutils.perpendicular(arr)
assert isinstance(perpvecs, np.ndarray)
assert not hasattr(perpvecs, 'units')
# test that vectors are indeed perpendicular
if vectorized:
assert (np.abs((normvecs * perpvecs).sum(axis=1)) < 1e-12).all()
else:
assert abs(perpvecs.dot(normvecs)) < 1e-12
# test that they are unit vectors (or 0 if the input vector is zero)
if not vectorized:
arr = [arr]
perpvecs = [perpvecs]
expected_norm = [expected_norm]
for i, (vec, perpvec) in enumerate(zip(arr, perpvecs)):
if expected_norm[i] == 0.0:
assert mathutils.norm(perpvec) < 1e-12
else:
assert np.abs(1.0 - mathutils.norm(perpvec)) < 1e-12
def test_spherical_angles():
assert sh.cart_to_polar_angles(np.zeros(3)) == (0.0, 0.0)
oneangles = sh.cart_to_polar_angles(np.array([1.0, 0.0, 1.0]))
np.testing.assert_allclose(np.array(oneangles),
np.array([np.pi/4, 0.0]))
oneangles = sh.cart_to_polar_angles(np.array([0.0, 1.0, 1.0]))
np.testing.assert_allclose(np.array(oneangles),
np.array([np.pi/4, np.pi/2.0]))
np.testing.assert_allclose(np.array(sh.cart_to_polar_angles(RANDARRAY)),
np.array(RAND_ARRAY_ANGLES).T)
@pytest.mark.parametrize('shell', range(4))
def test_cart_and_spherical_equivalence(shell):
l = shell
testpoints = (np.random.rand(10, 3)-0.5)*10.0
for m in range(-l,l+1):
real_y = sh.Y(l, m)
cart_y = sh.SPHERE_TO_CART[l,m]
# single point
np.testing.assert_allclose(real_y(testpoints[0]),
cart_y(testpoints[0]),
err_msg="Failed at %s" % ((l,m),))
# vectorized
np.testing.assert_allclose(real_y(testpoints),
cart_y(testpoints),
err_msg="Failed at %s" % ((l,m),))
@pytest.mark.parametrize('l1,m1,l2,m2',
[(0,0,0,0),
(1,0,1,0),
(3,-2,2,-1),
(1,0,1,1),
(1,-1,1,1),
(10,5,10,5)])
def test_spherical_harmonics_orthonormal(l1, m1, l2, m2):
y1 = sh.Y(l1, m1)
y2 = sh.Y(l2, m2)
NPHI = 1000
NTHETA = 700
thetas = np.linspace(0, np.pi, num=NTHETA)
dtheta = np.pi/NTHETA
phis = np.linspace(0, 2.0 * np.pi, num=NPHI)
cosphi = np.cos(phis)
sinphi = np.sin(phis)
dphi = 2.0 * np.pi/NPHI
phibuffer = np.zeros((NPHI, 3))
integ = 0.0
for theta in thetas:
sintheta = np.sin(theta)
phibuffer[:,0] = cosphi * sintheta
phibuffer[:,1] = sinphi * sintheta
phibuffer[:,2] = np.cos(theta)
values = y1(phibuffer) * y2(phibuffer)
integ += dphi * dtheta * sintheta * values.sum()
if l1 == l2 and m1 == m2:
assert abs(integ - 1.0) < 1e-2
else:
assert abs(integ) < 1e-2
@pytest.fixture
def ndarray_ranges():
ranges = np.array([[1,4],
[10, 40],
[100, 400]])
return ranges
@pytest.fixture
def ranges_with_units(ndarray_ranges):
return ndarray_ranges * u.angstrom
@pytest.mark.parametrize('key', ['ndarray_ranges', 'ranges_with_units'])
def test_volumetric_grid_point_list(key, request):
ranges = request.getfixturevalue(key)
grid = mathutils.VolumetricGrid(*ranges, xpoints=3, ypoints=4, zpoints=5)
assert (grid.xpoints, grid.ypoints, grid.zpoints) == (3,4,5)
pl = list(grid.iter_points())
pa = grid.allpoints()
assert (u.array(pl) == pa).all()
for i in range(3):
assert pa[:,i].min() == ranges[i][0]
assert pa[:,i].max() == ranges[i][1]
assert grid.npoints == 3*4*5
assert len(pl) == grid.npoints
for idim in range(3):
for ipoint in range(1,grid.points[idim]):
helpers.assert_almost_equal(grid.spaces[idim][ipoint] - grid.spaces[idim][ipoint-1],
grid.deltas[idim])
@pytest.mark.parametrize('key', ['ndarray_ranges', 'ranges_with_units'])
def test_volumetric_iteration(key, request):
ranges = request.getfixturevalue(key)
grid = mathutils.VolumetricGrid(*ranges, npoints=4)
grid_iterator = grid.iter_points()
assert (grid.xpoints, grid.ypoints, grid.zpoints) == (4,4,4)
assert grid.npoints == 4**3
for ix,x in enumerate(grid.xspace):
for iy, y in enumerate(grid.yspace):
for iz, z in enumerate(grid.zspace):
gridpoint = next(grid_iterator)
if ix == iy == iz == 0:
assert (gridpoint == grid.origin).all()
assert x == gridpoint[0]
assert y == gridpoint[1]
assert z == gridpoint[2]
RANDARRAY = np.array([[ 0.03047527, -4.49249374, 5.83154878],
[-7.38885486, 8.30076569, -7.97671261],
[ 6.79409582, -4.07664079, 8.45983794],
[-4.25045695, 0.03411114, 9.02986275]])
RAND_ARRAY_ANGLES = [(0.656426762, -1.564012833),
(2.1933588598416, 2.2981378887583),
(0.75266068344496, -0.54043933754409),
(0.43995560467481, 3.1335675381452)]
TESTARRAY = [[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[0.0, 0.0, 0.0],
[1.0, -1.0, 1.0],
[2.0, 2.0, 2.0],
[0.57735027, 0.57735027, -0.57735027],
[0.70710678, 0.70710678, 0.],
[0.0, -1.0, 1.0]]
TESTARRAY_NORMS = [1.0, 1.0, 1.0, 0.0, np.sqrt(3), np.sqrt(12.0), 1.0, 1.0, np.sqrt(2)]
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_pdbfixer_xface.py | .py | 6,277 | 157 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import moldesign as mdt
from moldesign import units as u
from .helpers import get_data_path
import pytest
from .molecule_fixtures import *
def test_inchain_residue_mutation_in_protein(pdb3aid):
_mutate_and_check(pdb3aid, 3, 'ALA',
{'C', 'CA', 'CB', 'HA', 'HB1', 'HB2', 'HB3', 'HN2', 'N', 'O'})
def test_nterm_residue_mutate_protein(pdb3aid):
_mutate_and_check(pdb3aid, 0, 'MET',
{'CE', 'HE1', 'C', 'N', 'HA', 'HB2', 'HE3', 'HG2', 'CG', 'CA', 'HG3',
'O', 'HB3', 'HN2', 'CB', 'HE2'})
def test_cterm_residue_mutate_protein(pdb3aid):
cterm = pdb3aid.chains['A'].c_terminal
_mutate_and_check(pdb3aid, cterm.index, 'LEU',
{'HD11', 'HD23', 'C', 'N', 'HD22', 'HA', 'HB2', 'CG', 'CA', 'CD2', 'HD21',
'O', 'CD1', 'HD12', 'HB3', 'HN2', 'HD13', 'CB', 'HG'})
def _mutate_and_check(mol, residx, resname, allatoms):
newmol = mdt.mutate_residues(mol, {mol.residues[residx]: resname})
assert newmol.num_chains == mol.num_chains
assert mol.num_residues == newmol.num_residues
foundnew = False
for i, (res, newres) in enumerate(zip(mol.residues, newmol.residues)):
if i == residx:
foundnew = True
assert newres.resname == resname
assert newres.name == resname+str(newres.pdbindex)
atomnames = set(atom.name for atom in newres)
assert len(atomnames) == newres.num_atoms
assert atomnames.issubset(allatoms)
else:
assert res.name == newres.name
assert res.num_atoms == newres.num_atoms
for oldatom, newatom in zip(res, newres):
assert oldatom.name == newatom.name
assert oldatom.atnum == newatom.atnum
if not foundnew:
assert oldatom.pdbindex == newatom.pdbindex
def test_mutate_docstring_dict_example(pdb3aid):
mol = pdb3aid
assert mol.residues[5].resname != 'ALA'
mut = mdt.mutate_residues(mol, {mol.residues[5]: 'ALA'}) # mutate residue 5 to ALA
assert mut.residues[5].resname == 'ALA'
def test_mutation_nomenclature_string_only(pdb3aid):
mol = pdb3aid
res25 = mol.get_residues(pdbindex=25)
assert len(res25) == 2
assert [r.resname for r in res25] == ['ASP', 'ASP']
mut = mdt.mutate_residues(mol, 'D25M') # Mutate ALA43 to MET43
assert mut.get_residues()
mut25 = mut.get_residues(pdbindex=25)
assert len(mut25) == 2
assert [r.resname for r in mut25] == ['MET', 'MET']
def test_mutation_topology(pdb1yu8):
""" Test the topology of the backbone atoms for a mutated molecule. """
molecule = pdb1yu8
mutation_residues = ["X.13G"]
mutated_molecule = mdt.mutate_residues(molecule, mutation_residues)
# Check that the number of bonds for backbone atoms match.
for res, mut_res in zip(molecule.residues, mutated_molecule.residues):
if not res.backbone:
continue
for atom in res.backbone:
bonds = [bond for bond in molecule.bond_graph[atom] if bond.name in res.backbone]
mut_atom = mutated_molecule.chains["X"].residues[mut_res.name].atoms[atom.name]
mut_bonds = mutated_molecule.bond_graph[mut_atom]
mut_bonds = [bond for bond in mutated_molecule.bond_graph[mut_atom] \
if bond.name in mut_res.backbone]
assert len(bonds) == len(mut_bonds)
@pytest.mark.screening
def test_multiple_mutations(pdb3aid):
mol = pdb3aid
mut = mdt.mutate_residues(mol, ['A.2S', 'B.3S']) # Mutate Chain A res 2 and B 3 to SER
assert [r.resname for r in mut.chains['A'].get_residues(pdbindex=2)] == ['SER']
assert [r.resname for r in mut.chains['B'].get_residues(pdbindex=3)] == ['SER']
def test_solvate_small_molecule_boxsize(benzene):
newmol = mdt.add_water(benzene, min_box_size=15.0*u.angstrom)
assert newmol.num_atoms > 50 # who knows how many? more than benzene though
def test_seawater_solvation_small_molecule(benzene):
newmol = mdt.add_water(benzene,
min_box_size=20.0*u.angstrom,
ion_concentration=0.6*u.molar)
assert newmol.num_atoms > 50 # who knows how many? more than benzene though
assert len(newmol.get_atoms(name='Cl')) == 3 # TODO: check that this is correct molarity
assert len(newmol.get_atoms(name='Na')) == 3 # TODO: check that this is correct molarity
@pytest.mark.screening
def test_solvation_alternative_ions(benzene):
newmol = mdt.add_water(benzene,
min_box_size=20.0*u.angstrom,
ion_concentration=0.6*u.molar,
positive_ion='Rb',
negative_ion='I')
assert newmol.num_atoms > 50 # who knows how many? more than benzene though
assert len(newmol.get_atoms(name='Rb')) == 3 # TODO: check that this is correct molarity
assert len(newmol.get_atoms(name='I')) == 3 # TODO: check that this is correct molarity
def test_solvate_protein_padding(pdb1yu8):
newmol = mdt.add_water(pdb1yu8, padding=5.0*u.angstrom)
assert newmol.num_atoms > pdb1yu8.num_atoms
oldmol = mdt.Molecule(newmol.residues[:pdb1yu8.num_residues])
assert oldmol.same_topology(pdb1yu8, verbose=True)
np.testing.assert_allclose(pdb1yu8.positions.value_in(u.angstrom),
oldmol.positions.value_in(u.angstrom),
atol=1e-3)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_geometry.py | .py | 12,247 | 340 | """ Tests geometry routines
"""
from builtins import range
import random
import itertools
import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from . import helpers
registered_types = {}
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
# TODO: automated method testing based on its metadata - i.e. test to make sure parameters are
# honored, test that it calcultes what it says it does, test that properties have the right
# units and array shapes, etc.
# step for numerical derivative testing
def typedfixture(*types, **kwargs):
"""This is a decorator that lets us associate fixtures with one or more arbitrary types.
We'll later use this type to determine what tests to run on the result"""
def fixture_wrapper(func):
for t in types:
registered_types.setdefault(t, []).append(func.__name__)
return pytest.fixture(**kwargs)(func)
return fixture_wrapper
def _make_mol_with_n_hydrogens(n):
return mdt.Molecule([mdt.Atom('H') for i in range(n)])
def _apply_random_offsets(mol, idim):
mol.positions[:, idim] += (random.random()-0.5)*100.0*u.angstrom
@typedfixture('atomcontainer', scope='function')
def three_particle_right_angle():
mol = _make_mol_with_n_hydrogens(3)
mol.atoms[0].x = 1.0 * u.angstrom
mol.atoms[2].y = 1.0 * u.angstrom
for idim in range(3):
_apply_random_offsets(mol, idim)
return mol
@typedfixture('atomcontainer', scope='function')
def four_particle_45_twist():
mol = _make_mol_with_n_hydrogens(4)
mol.positions = u.nm*[[0.1, 0.0, -0.5],
[0.0, 0.0, -0.5],
[0.0, 0.0, 0.5],
[0.2, -0.2, 0.5]]
for idim in range(3):
_apply_random_offsets(mol, idim)
for iatom in range(3):
mol.atoms[iatom].bond_to(mol.atoms[iatom+1], 1)
return mol
########################
# Dihedrals #
########################
def test_dihedral_measure(four_particle_45_twist):
mol = four_particle_45_twist
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms).value_in(u.degrees),
45.0,
decimal=8)
def test_dihedral_two_atom_selection(four_particle_45_twist):
mol = four_particle_45_twist
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms[1:3]).value_in(u.degrees),
45.0,
decimal=8)
with pytest.raises(ValueError): # raises exception because it's not part of a dihedral
mdt.dihedral(mol.atoms[0], mol.atoms[1])
def test_set_dihedral(four_particle_45_twist):
mol = four_particle_45_twist
mdt.set_dihedral(mol.atoms[0], mol.atoms[1], mol.atoms[2], mol.atoms[3], 10.0 * u.degrees)
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms).value_in(u.degrees),
10.0,
decimal=8)
@pytest.mark.screening
def test_set_dihedral_sign_convention(four_particle_45_twist):
mol = four_particle_45_twist
mdt.set_dihedral(mol.atoms[0], mol.atoms[1], mol.atoms[2], mol.atoms[3], -23.0 * u.degrees)
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms).value_in(u.degrees),
337.0,
decimal=8)
def test_set_dihedral_two_atom_selection(four_particle_45_twist):
mol = four_particle_45_twist
mdt.set_dihedral(mol.atoms[1], mol.atoms[2], 10.0 * u.degrees)
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms).value_in(u.degrees),
10.0,
decimal=8)
with pytest.raises(ValueError): # raises exception because it's not part of a dihedral
mdt.set_dihedral(mol.atoms[0], mol.atoms[1], 5.0 * u.degrees)
def test_set_dihedral_bond_no_adjust(four_particle_45_twist):
mol = four_particle_45_twist
bond = mdt.Bond(mol.atoms[1], mol.atoms[2])
mdt.set_dihedral(bond, 10.0 * u.degrees, adjustmol=False)
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms).value_in(u.degrees),
10.0,
decimal=8)
def test_dihedral_sign_convention(four_particle_45_twist):
mol = four_particle_45_twist
mol.atoms[-1].y += 0.4 * u.nm
np.testing.assert_almost_equal(mdt.dihedral(*mol.atoms).value_in(u.degrees),
315.0,
decimal=8)
# TODO: test behavior at discontinuities (180, -180)
@pytest.mark.screening
def test_dihedral_gradient(four_particle_45_twist):
mol = four_particle_45_twist
dihe = mdt.DihedralMonitor(*mol.atoms)
calc_grad = dihe.gradient()
num_grad = helpers.num_grad(mol, lambda: dihe.value)
np.testing.assert_allclose(calc_grad.defunits_value(),
num_grad.defunits_value(),
atol=5.0*helpers.DEFSTEP.defunits_value())
def test_dihedral_gradient_sign_convention(four_particle_45_twist):
mol = four_particle_45_twist
mol.atoms[-1].y += 0.4 * u.nm
dihe = mdt.DihedralMonitor(*mol.atoms)
calc_grad = dihe.gradient()
num_grad = helpers.num_grad(mol, lambda: dihe.value)
np.testing.assert_allclose(calc_grad,
num_grad,
atol=5.0*helpers.DEFSTEP.defunits_value())
########################
# Angles #
########################
def test_angle_measure(three_particle_right_angle):
mol = three_particle_right_angle
np.testing.assert_almost_equal(mdt.angle(*mol.atoms).value_in(u.degrees),
90.0,
decimal=8)
@pytest.mark.screening
def test_angle_gradient(three_particle_right_angle):
mol = three_particle_right_angle
ang = mdt.AngleMonitor(*mol.atoms)
assert abs(ang.value.value_in(u.degrees) - 90.0) <= 1.0e-8
calc_grad = ang.gradient()
num_grad = helpers.num_grad(mol, lambda:ang.value)
np.testing.assert_allclose(calc_grad.defunits_value(),
num_grad.defunits_value(),
atol=5.0*helpers.DEFSTEP.defunits_value())
def test_set_angle_with_monitor(three_particle_right_angle):
mol = three_particle_right_angle
ang = mdt.AngleMonitor(*mol.atoms)
ang.value = 45 * u.degrees
assert abs(mdt.angle(*mol.atoms) - (45 * u.degrees)) < 0.1 * u.degrees
def test_set_angle_noadjust(four_particle_45_twist):
mol = four_particle_45_twist
assert mdt.angle(*mol.atoms[:3]) == 90.0 * u.degrees
final = 45 * u.degrees
origpos = mol.positions.copy()
mdt.set_angle(mol.atoms[0], mol.atoms[1], mol.atoms[2], final, adjustmol=False)
assert abs(mdt.angle(*mol.atoms[:3]) - final) < 0.1 * u.degrees
assert (mol.positions[-1] == origpos[-1]).all()
########################
# Distances #
########################
def test_distance_array(three_particle_right_angle):
mol = three_particle_right_angle
desired_distance_array = u.angstrom*[[0.0, 1.0, np.sqrt(2)],
[1.0, 0.0, 1.0],
[np.sqrt(2), 1.0, 0.0]]
distance_array = mol.calc_distance_array()
np.testing.assert_allclose(distance_array,
desired_distance_array,
atol=1e-8)
def test_set_distance_and_adjust(four_particle_45_twist):
mol = four_particle_45_twist
origpos = mol.positions.copy()
distance = mdt.DistanceMonitor(mol.atoms[1], mol.atoms[2])
olddist = distance.value
distance.value *= 2.0
displacement = np.sqrt(((origpos[0] - mol.positions[0])**2).sum()) + \
np.sqrt(((origpos[-1] - mol.positions[-1])**2).sum())
assert abs(mdt.distance(mol.atoms[1], mol.atoms[2]) - 2.0*olddist) <= 1e-9 * u.angstrom
assert abs(displacement - olddist) < 1.0e-9 * u.angstrom
def test_set_distance_noadjust(four_particle_45_twist):
mol = four_particle_45_twist
origpos = mol.positions.copy()
olddist = mdt.distance(mol.atoms[1], mol.atoms[2])
mdt.set_distance(mol.atoms[1], mol.atoms[2], 2.0 * olddist, adjustmol=False)
assert abs(mdt.distance(mol.atoms[1], mol.atoms[2]) - 2.0*olddist) <= 1e-9 * u.angstrom
assert (origpos[0] == mol.positions[0]).all() and (origpos[-1] == mol.positions[-1]).all()
@pytest.mark.parametrize('objkey', registered_types['atomcontainer'])
def test_atomic_distance_measures_are_consistent(objkey, request):
mol = request.getfixturevalue(objkey)
distance_array = mol.calc_distance_array()
for i, j in itertools.product(range(3), range(3)):
ai, aj = mol.atoms[i], mol.atoms[j]
assert ai.distance(aj) == distance_array[i, j]
assert mdt.distance(ai, aj) == distance_array[i, j]
np.testing.assert_almost_equal(np.sum((ai.position - aj.position)**2).defunits_value(),
(distance_array[i, j]**2).defunits_value(),
decimal=10)
def test_center_of_mass(four_particle_45_twist):
mol = four_particle_45_twist
mol.positions = u.nm*[[0.1, 0.0, -0.5],
[0.0, 0.0, -0.5],
[0.0, 0.0, 0.5],
[0.2, -0.2, 0.5]]
desired_com_angstroms = np.array([0.1+0.2, -0.2, 0.0]) * 10.0 / 4.0
np.testing.assert_almost_equal(mol.center_of_mass.defunits_value(),
desired_com_angstroms)
mol.atoms[0].mass = 5.0 * u.ureg.kilograms
mol.atoms[1].mass = 10.0 * u.ureg.kilograms
mol.atoms[2].mass = 5.0 * u.ureg.kilograms
mol.atoms[3].mass = 10.0 * u.ureg.kilograms
desired_com_angstroms = np.array([0.1+0.4, -0.4, 0.0]) * 10.0 / 6.0
np.testing.assert_almost_equal(mol.center_of_mass.defunits_value(),
desired_com_angstroms)
def test_set_center_of_mass(four_particle_45_twist):
# reset COM
four_particle_45_twist.com = [0, 0, 0] * u.angstrom
np.testing.assert_almost_equal(four_particle_45_twist.com.value_in(u.angstrom),
([0, 0, 0] * u.angstrom).value_in(u.angstrom))
# set it to its current position
four_particle_45_twist.com = [0, 0, 0] * u.angstrom
np.testing.assert_almost_equal(four_particle_45_twist.com.value_in(u.angstrom),
([0, 0, 0] * u.angstrom).value_in(u.angstrom))
# move COM elsewhere
four_particle_45_twist.com = [10, 0, -10] * u.angstrom
np.testing.assert_almost_equal(four_particle_45_twist.com.value_in(u.angstrom),
([10, 0, -10] * u.angstrom).value_in(u.angstrom))
def test_distance_gradient(three_particle_right_angle):
mol = three_particle_right_angle
dist = mdt.DistanceMonitor(*mol.atoms[:2])
assert dist.value == mol.atoms[0].distance(mol.atoms[1])
calc_grad = dist.gradient()
num_grad = helpers.num_grad(mol, lambda:dist.value)
np.testing.assert_allclose(calc_grad.defunits_value(),
num_grad.defunits_value(),
atol=5.0*helpers.DEFSTEP.defunits_value())
#########################
# Utilities #
#########################
def test_sub_angles():
from moldesign.geom import sub_angles
np.testing.assert_allclose(sub_angles(np.pi*u.radian, np.pi/2.0*u.radian),
np.pi/2.0 * u.radian)
np.testing.assert_allclose(sub_angles(360*u.degrees, 179*u.degrees),
-179*u.degrees)
np.testing.assert_allclose(sub_angles(360*u.degrees, 3*u.degrees),
-3*u.degrees)
np.testing.assert_allclose(sub_angles(720*u.degrees, -360*u.degrees),
0*u.degrees)
np.testing.assert_allclose(sub_angles(180*u.degrees, 270*u.degrees),
-90*u.degrees)
np.testing.assert_allclose(sub_angles(270*u.degrees, 0*u.degrees),
-90*u.degrees)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_units.py | .py | 11,253 | 327 | """ Tests the unit system
"""
import pytest
import numpy as np
from moldesign import units
from moldesign import units as u
# mark all tests in this module with these label (see ./conftest.py)
__PYTEST_MARK__ = ['internal', 'units']
@pytest.mark.screening
def test_scalar_comparison_dimensionality_errors():
with pytest.raises(units.DimensionalityError):
x = 1.0 * units.angstrom == 1.0*units.ureg.kilograms
with pytest.raises(units.DimensionalityError):
y = 1.0 * units.fs < 1.0 * units.ureg.meter
with pytest.raises(units.DimensionalityError):
z = 1.0 * units.ureg.hectare >= 1.0 * units.ureg.astronomical_unit
@pytest.mark.screening
def test_array_comparison_dimensionality_errors():
mylist = [0.0, -1.0, 1.0]
with pytest.raises(units.DimensionalityError):
x = mylist * units.angstrom == mylist*units.ureg.kilograms
with pytest.raises(units.DimensionalityError):
y = mylist * units.fs < mylist * units.ureg.meter
with pytest.raises(units.DimensionalityError):
z = mylist * units.ureg.hectare >= mylist * units.ureg.astronomical_unit
@pytest.mark.screening
def test_addition_dimensionality_errors():
with pytest.raises(units.DimensionalityError):
x = 1.0 * units.angstrom + 1.0*units.ureg.kilograms
with pytest.raises(units.DimensionalityError):
y = 1.0 * units.fs - 1.0 * units.ureg.meter
@pytest.mark.screening
def test_compatible_units_comparison():
num = 1.0*units.angstrom
assert abs(num-0.1*units.nm) < 1.0e-15 * units.angstrom
assert 1.0 * units.ureg.meter > 123456.0 * units.nm
def test_default_units():
assert units.default.length == units.angstrom
assert units.default.mass == units.amu
assert units.default.energy == units.eV
@pytest.fixture
def si_units():
system = units.UnitSystem(length=u.ureg.meters, mass=u.ureg.kg,
time=u.ureg.seconds, energy=u.ureg.joules)
return system
@pytest.mark.parametrize(['dimension', 'expected', 'weird_units'],
[['length', u.ureg.meters, u.ureg.lightyear],
['mass', u.ureg.kg, u.ureg.stone],
['time', u.ureg.seconds, u.ureg.year],
['momentum', u.ureg.kg * u.ureg.meter / u.ureg.second,
u.ureg.lightyear * u.ureg.stone / u.ureg.year],
['force', u.ureg.joule / u.ureg.meter, u.ureg.force_ton],
['energy', u.ureg.joule, u.ureg.horsepower * u.ureg.seconds]],
ids='length mass time momentum force energy'.split())
def test_si_unit_system(si_units, dimension, expected, weird_units):
assert getattr(si_units, dimension) == expected
default_unit = getattr(u.default, dimension)
my_quantity = 3.141 * default_unit
si_quantity = si_units.convert(my_quantity)
assert my_quantity.units != expected
assert si_quantity.units == expected
assert u.default.convert(abs(my_quantity - si_quantity)) < 1e-15 * default_unit
setattr(si_units, dimension, weird_units)
assert getattr(si_units, dimension) == weird_units
weird_quantity = si_units.convert(my_quantity)
assert abs(my_quantity-weird_quantity) < 1e-15 * default_unit
assert weird_quantity.units == weird_units
@pytest.mark.screening
def test_default_unit_conversions():
my_list = [1.0*units.angstrom, 1.0*units.nm, 1.0*units.a0]
my_array = units.array(my_list).defunits()
assert my_array.get_units() == units.default.convert(my_array).get_units()
result = my_array.value_in(units.nm)
np.testing.assert_almost_equal(result[0], 0.1, 9)
np.testing.assert_almost_equal(result[1], 1.0, 9)
np.testing.assert_almost_equal(result[2], 0.05291772, 7)
def test_dimensional_array_from_mixed_data():
data = [np.arange(3) * u.angstrom,
[1.0 * u.nm, 1.0 * u.nm**2/u.angstrom, 3.0*u.ureg.km],
[1,1,1] * u.bohr]
arr = u.array(data)
bohr_in_ang = (1.0 * u.bohr).value_in(u.angstrom)
expected = u.angstrom * [[0,1,2],
[10.0, 100.0, 3.0e13],
[bohr_in_ang, bohr_in_ang, bohr_in_ang]]
np.testing.assert_allclose(arr, expected)
assert isinstance(arr, units.MdtQuantity)
def test_dimensionless_array_from_mixed_data():
data = [np.arange(3),
[1.0 * u.dimensionless, 1.0 * u.nm/u.angstrom, 3.0],
[1,1,1] * u.ureg.kg / u.ureg.g]
arr = u.array(data)
np.testing.assert_allclose(arr,
np.array([[0,1,2],
[1,10,3],
[1000,1000,1000]],dtype='float') )
assert isinstance(arr, np.ndarray)
def test_inconsistent_array_units_raises_dimensionality_error():
with pytest.raises(units.DimensionalityError):
u.array([[1,2,3] * u.angstrom, [3*u.bohr, 4*u.eV, 5*u.bohr]])
def test_mixed_units_and_nonunits_raises_dimensionality_error():
with pytest.raises(units.DimensionalityError):
u.array([[1,2,3] * u.angstrom, [3*u.bohr, 4, 5*u.bohr]])
def test_no_nonsquare_arrays():
with pytest.raises(ValueError):
u.array([[1,2],[3]])
def test_scalar_comparisons_to_zero_ignore_units():
num = 1.0*units.angstrom
assert num > 0.0
assert num > 0.0 * units.angstrom
assert num > 0.0 * units.nm
with pytest.raises(units.DimensionalityError):
num > 0.0 * units.fs
def test_array_comparisons_to_zero_ignore_units():
num = [1, -2, 0]*units.angstrom
assert ((num > 0) == [True, False, False]).all()
assert ((num == 0) == [False, False, True]).all()
def test_dimensionless_array_operations():
arr = np.arange(5) * units.ureg.dimensionless
assert (arr == [0, 1, 2, 3, 4]).all()
arr[1:5] = [100, 101, 102, 103]
assert (arr == [0, 100, 101, 102, 103]).all()
assert arr[4].units == units.ureg.dimensionless
assert arr[:3].units == units.ureg.dimensionless
def test_dimensionless_array_unit_checks():
arr = np.arange(5) * units.ureg.dimensionless
with pytest.raises(units.DimensionalityError):
arr[0] = 5.0 * units.angstrom
with pytest.raises(units.DimensionalityError):
arr[:] = np.arange(5, 10) * units.angstrom
arr[:] = np.arange(5, 10)
assert (arr == np.arange(5, 10)).all()
arr[:] = np.arange(10, 15) * units.ureg.dimensionless
assert (arr == np.arange(10, 15)).all()
@pytest.mark.screening
def test_array_unit_checks():
arr = np.arange(5) * units.ureg.nm / units.ureg.fs
with pytest.raises(units.DimensionalityError):
arr[0] = 5.0 * units.angstrom
with pytest.raises(units.DimensionalityError):
arr[3] = 5.0
with pytest.raises(units.DimensionalityError):
arr[:] = np.arange(5, 10) * units.fs
arr[2:3] = np.arange(5, 6) * units.ureg.angstrom / units.ureg.fs
np.testing.assert_allclose(arr[2:3].magnitude,
np.arange(5, 6)/10.0)
arr[:] = np.arange(10, 15) * units.ureg.micrometers / units.ureg.picoseconds
np.testing.assert_allclose(arr.magnitude,
np.arange(10, 15))
@pytest.mark.parametrize(['a1','a2'],
((np.ones(3), np.ones(3)*10/10),
(np.ones(3), u.array(np.ones(3))),
(np.ones(3)*u.nm, 10.0*np.ones(3)*u.angstrom),
(np.ones((3,3)) * u.nm / u.angstrom, np.ones(3) * 10)),
ids="numpy-numpy numpy-dimensionless nm-angstrom nm/angstrom-numpy".split()
)
def test_array_almost_equal_returns_true(a1, a2):
assert u.arrays_almost_equal(a1, a2)
assert u.arrays_almost_equal(a2, a1)
@pytest.mark.parametrize(['a1','a2'],
((np.ones(3), np.ones(3)*10/10 * u.eV),
(np.ones(3)*u.nm, 10.0*np.ones(3)*u.dalton),
(u.array(np.ones(3)), np.ones(3) * u.kcalpermol)),
ids="numpy-ev nm-dalton dimensionless-kcalpermole".split()
)
def test_array_almost_equal_raises_dimensionality_error(a1, a2):
with pytest.raises(u.DimensionalityError):
u.arrays_almost_equal(a1, a2)
with pytest.raises(u.DimensionalityError):
u.arrays_almost_equal(a2, a1)
@pytest.mark.screening
def test_default_unit_conversions():
assert abs(10.0 - (1.0*units.nm).defunits_value()) < 1e-10
assert abs(1000.0 - (1.0*units.ps).defunits_value()) < 1e-10
assert abs(1.0 - 6.022140857e23/((1.0*units.ureg.grams).defunits_value())) < 1e-6
assert abs(103.642685491 - (1.0*units.angstrom**2*units.dalton/units.fs**2).defunits_value()
) < 1e-7
def test_getunits_doctests():
assert units.get_units(1.0*units.angstrom) == units.MdtUnit('angstrom')
assert units.get_units(np.array([1.0, 2, 3.0])) == units.MdtUnit('dimensionless')
assert units.get_units([[1.0*units.dalton, 3.0*units.eV],
['a'], 'gorilla']) == units.MdtUnit('amu')
@pytest.mark.screening
def test_setitem_from_quantity():
myarray = np.arange(100) * u.angstrom
with pytest.raises(u.DimensionalityError):
myarray[:10] = np.arange(10)
myarray[11] = 5.0 * u.ureg.meters
myarray[:10] = np.arange(10) * u.nm
for i in range(10):
assert myarray[i].units == u.angstrom
assert abs(myarray[i].magnitude - i*10) < 1e-14
assert myarray[11].units == u.angstrom
assert abs(myarray[11].magnitude - (5.0*u.ureg.meters).value_in(u.angstrom)) < 1e-14
assert myarray.units == u.angstrom
@pytest.mark.screening
def test_setitem_from_list_of_quantities():
myarray = np.arange(100) * u.angstrom
myarray[:10] = list(np.arange(10) * u.nm)
for i in range(10):
assert myarray[i].units == u.angstrom
assert abs(myarray[i].magnitude - i*10) < 1e-14 * u.angstrom
def test_setitem_slice_dimensionless():
myarray = np.arange(100) * u.ureg.dimensionless
assert isinstance(myarray, u.MdtQuantity)
myarray[:10] = np.arange(10)
assert myarray.units == u.ureg.dimensionless
assert (myarray[:10] == np.arange(10)).all()
@pytest.fixture
def make_test_matrices():
randommatrix = np.random.rand(10,7)
randomvector = np.random.rand(10)
unitmatrix = randommatrix * u.kcalpermol
unitvector = randomvector * u.angstrom
expected_matvec_product = randomvector.dot(randommatrix)
return unitvector, unitmatrix, expected_matvec_product
def self_dot(a, b):
return a.dot(b)
def self_ldot(a,b):
return b.ldot(a)
def unit_dot(a,b):
return u.dot(a, b)
MATRIX_MATHS = [self_dot, self_ldot, unit_dot]
@pytest.mark.parametrize('testfun', MATRIX_MATHS, ids=[x.__name__ for x in MATRIX_MATHS])
@pytest.mark.screening
def test_matrix_math_with_units(make_test_matrices, testfun):
unitvector, unitmatrix, expected_matvec_product = make_test_matrices
result = testfun(unitvector, unitmatrix)
assert result.units == u.kcalpermol * u.angstrom
np.testing.assert_array_almost_equal(expected_matvec_product,
result.magnitude, decimal=12)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_imports.py | .py | 646 | 28 | import pytest
import sys
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
@pytest.mark.tryfirst
def test_lazy_imports():
import moldesign
for mod in 'simtk simtk.openmm pyscf pdbfixer scipy':
assert mod not in sys.modules
def test_package_install_check():
import moldesign as mdt
from moldesign.compute import packages
try:
from simtk import openmm
except ImportError:
assert not packages.openmm.is_installed()
else:
assert packages.openmm.is_installed()
assert packages.openmm.installed_version() == openmm.__version__
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_atoms.py | .py | 7,153 | 254 | import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from .molecule_fixtures import *
from . import helpers
__PYTEST_MARK__ = 'internal'
def test_create_atom_with_element_as_name():
he_plus = mdt.Atom("He", position=np.ones(3) * u.nm, formal_charge=1*u.q_e)
assert he_plus.atomic_number == 2
helpers.assert_almost_equal(he_plus.position, 10 * np.ones(3) * u.angstrom)
assert he_plus.name == 'He'
assert he_plus.element == 'He'
assert he_plus.formal_charge == 1 * u.q_e
def test_create_atom_with_uppercase_element():
cl_minus = mdt.Atom("CL2", element='CL', formal_charge=-1)
assert cl_minus.formal_charge == -1 * u.q_e
assert cl_minus.atnum == 17
assert cl_minus.name == 'CL2'
assert cl_minus.element == 'Cl'
def test_create_atom_with_unrelated_name():
carbon_named_bob = mdt.Atom("bob", element='c')
assert carbon_named_bob.name == 'bob'
assert carbon_named_bob.atnum == 6
assert carbon_named_bob.element == 'C'
def test_create_atom_with_element_name_as_first_char():
carbon_alpha = mdt.Atom('ca')
assert carbon_alpha.name == 'ca'
assert carbon_alpha.atnum == 6
assert carbon_alpha.element == 'C'
def test_create_atom_with_atomic_number():
h = mdt.Atom('ca', atnum=1)
assert h.atnum == 1
assert h.element == 'H'
assert h.name == 'ca'
with pytest.raises(AssertionError):
mdt.Atom('ca', atnum=1, element='He')
def test_add_atom(h2):
newatom = mdt.Atom('Xe')
h2.add_atom(newatom)
assert newatom in h2.atoms
assert h2.num_atoms == 3
assert h2.num_residues == 1
assert h2.num_chains == 1
assert newatom.residue is h2.residues[0]
assert newatom.chain is h2.chains[0]
def test_add_already_owned_atoms(h2):
h2cpy = h2.copy()
h2cpy.translate([10, 11, 12] * u.angstrom)
h2.add_atoms(h2cpy.atoms)
assert h2.num_atoms == 4
assert h2cpy.num_atoms == 2
for atom in h2cpy.atoms:
assert atom.molecule is h2cpy
assert atom.residue is h2cpy.residues[0]
assert atom.chain is h2cpy.chains[0]
for newatom in h2.atoms[2:]:
assert newatom.molecule is h2
assert newatom.residue is h2.residues[1]
assert newatom.chain is h2.chains[1]
helpers.assert_almost_equal(h2.positions[2:],
h2cpy.positions)
def test_atom_shortstr_3aid(pdb3aid):
assert pdb3aid.atoms[10]._shortstr() == 'CA #10 in A.GLN2'
def test_atom_shortstr_benzene(benzene):
for atom in benzene.atoms:
assert atom._shortstr() == '%s #%s' % (atom.name, atom.index)
def test_atom_bond_iterators(benzene):
atom = benzene.atoms[0]
assert atom.atnum == 6 # sanity check
atombonds = benzene.bond_graph[atom]
assert set(atom.bonded_atoms) == set(atombonds.keys())
assert atom.bond_graph == atombonds
assert len(atom.heavy_bonds) == 2
heavybonds = sorted(atom.heavy_bonds, key=lambda x:x.order)
assert len(heavybonds) == 2
assert heavybonds[0].order == 1 and heavybonds[1].order == 2
assert len(atom.bonds) == 3
hbond, csingle, cdouble = False, False, False
for bond in atom.bonds:
assert bond.a1 is atom # since "atom" has the lowest index, it's always a1
assert bond.partner(atom) is bond.a2
if bond.a2.atnum == 1:
assert hbond is False
hbond = True
assert bond.order == 1
assert len(bond.a2.heavy_bonds) == 0
else:
assert bond.a2.atnum == 6
if bond.order == 1:
assert csingle is False
csingle = True
assert bond == heavybonds[0]
else:
assert cdouble is False
cdouble = True
assert bond.order == 2
assert bond == heavybonds[1]
assert hbond and csingle and cdouble
def test_atom_bond_to(pdb3aid):
mol = pdb3aid
a1, a2 = mol.atoms[3], mol.atoms[321] # arbitrary atom indices
mol.ff = 'arglebargle' # changing topology should reset this
nbonds = mol.num_bonds
assert a1 not in mol.bond_graph[a2]
a1.bond_to(a2, 3)
assert mol.num_bonds == nbonds + 1
assert mol.ff is None
assert_consistent_bond(mol, a1, a2, 3)
def test_delete_bond_with_atoms(pdb3aid):
mol = pdb3aid
a1 = mol.atoms[35] # arbitrary atom
mol.ff = 'arglebargle' # changing topology should reset this
nbonds = mol.num_bonds
a2 = a1.bonded_atoms[-1]
mol.delete_bond(a1, a2)
assert mol.num_bonds == nbonds - 1
assert_not_bonded(mol, a1, a2)
def test_delete_bond(pdb3aid):
mol = pdb3aid
a1 = mol.atoms[89] # arbitrary atom
mol.ff = 'arglebargle' # changing topology should reset this
nbonds = mol.num_bonds
a2 = a1.bonded_atoms[-1]
bond = mdt.Bond(a1, a2)
mol.delete_bond(bond)
assert mol.num_bonds == nbonds - 1
assert_not_bonded(mol, a1, a2)
def test_bond_object_automatically_associates_with_molecule(pdb3aid):
mol = pdb3aid
a1 = mol.atoms[511] # arbitrary atom
bond_from_atom = a1.bonds[-1]
a2 = bond_from_atom.partner(a1)
created_bond = mdt.Bond(a2, a1)
assert created_bond == bond_from_atom
assert created_bond.order == mol.bond_graph[a1][a2]
assert bond_from_atom.order == mol.bond_graph[a1][a2]
assert created_bond.molecule is mol
assert bond_from_atom.molecule is mol
def test_change_bond_order_with_bond_object(pdb3aid):
mol = pdb3aid
a1 = mol.atoms[511] # arbitrary atom
bond = a1.bonds[-1]
a2 = bond.partner(a1)
other_bond_object = mdt.Bond(a1, a2)
oldorder = bond.order
assert oldorder == other_bond_object.order
assert a1.bond_graph[a2] == oldorder
# First raise the order
bond.order += 1
assert_consistent_bond(mol, a1, a2, oldorder+1)
# Now delete the bond by setting it to None
bond.order = None
assert_not_bonded(mol, a1, a2)
def test_bond_object_for_unbonded_atoms(pdb3aid):
mol = pdb3aid
a1 = mol.atoms[1]
a2 = mol.atoms[-10]
bond = mdt.Bond(a1, a2)
assert bond.order is None
bond.order = 2
assert_consistent_bond(mol, a1, a2, 2)
def assert_not_bonded(mol, a1, a2):
assert mol.ff is None
assert a1 not in a2.bond_graph
assert a1 not in a2.bonded_atoms
assert a2 not in a1.bond_graph
assert a2 not in a1.bonded_atoms
assert a2 not in mol.bond_graph[a1]
assert a1 not in mol.bond_graph[a2]
def assert_consistent_bond(mol, a1, a2, order):
assert a1 in a2.bond_graph
assert a2 in a1.bond_graph
_unique_bond_check(a1, a2, order)
_unique_bond_check(a2, a1, order)
assert a1.bond_graph[a2] == a2.bond_graph[a1] == order
assert mol.bond_graph[a1][a2] == mol.bond_graph[a2][a1] == order
def _unique_bond_check(a1, a2, order):
found = False
for bond in a1.bonds:
if bond.partner(a1) is a2:
assert not found, '%s appeared twice' % bond
assert bond.order == order
found = True
if a1.num_bonds > 0 and not found:
assert False, "bond not found in atom.bonds"
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_qm_xfaces.py | .py | 4,712 | 139 | """ Tests basic QM functionality and data structures
"""
import itertools
import pytest
import numpy as np
import moldesign as mdt
from moldesign import units as u
from . import helpers
from .molecule_fixtures import *
# TODO: automated method testing based on its metadata - i.e. test to make sure parameters are
# honored, test that it calcultes what it says it does, test that properties have the right
# units and array shapes, etc.
# Note that this is an incomplete set of models
models_to_test = list(itertools.product((mdt.models.NWChemQM, mdt.models.PySCFPotential),
'sto-3g 6-31g'.split(),
'rhf rks mp2'.split()))
model_ids = ['/'.join((model.__name__, theory, basis)) for (model, theory, basis) in models_to_test]
TESTSET = ['h2', 'small_molecule', 'benzene']
@pytest.fixture(params=models_to_test, ids=model_ids, scope='function')
def h2_with_model(request, h2):
model, basis, theory = request.param
if model is mdt.models.NWChemQM and theory == 'mp2':
pytest.xfail('Not implemented')
h2.set_energy_model(model, basis=basis, theory=theory)
return h2
def test_minimization_trajectory(h2):
mol = h2
h2.set_energy_model(mdt.models.PySCFPotential, basis='sto-3g', theory='rks')
assert 'potential_energy' not in mol.properties
e1 = mol.calculate_potential_energy()
p1 = mol.positions.copy()
traj = mol.minimize()
helpers.assert_something_resembling_minimization_happened(p1, e1, traj, mol)
@pytest.mark.parametrize('objkey', TESTSET)
def test_pyscf_rhf_sto3g_properties(objkey, request):
mol = request.getfixturevalue(objkey)
mol.set_energy_model(mdt.models.PySCFPotential, basis='sto-3g', theory='rhf')
mol.calculate()
assert 'potential_energy' in mol.properties
assert 'wfn' in mol.properties
assert 'canonical' in mol.wfn.orbitals
assert 'atomic' in mol.wfn.orbitals
assert mol.wfn.num_electrons == sum([atom.atnum for atom in mol.atoms]) \
- mol.charge.value_in(u.q_e)
@pytest.mark.parametrize('objkey', TESTSET)
def test_pyscf_rhf_sto3g_matrices(objkey, request):
mol = request.getfixturevalue(objkey)
mol.set_energy_model(mdt.models.PySCFPotential, basis='sto-3g', theory='rhf')
mol.calculate()
basis = mol.wfn.aobasis
canonical = mol.wfn.orbitals.canonical
assert (mol.wfn.aobasis.fock == mol.wfn.fock_ao).all()
assert (mol.wfn.orbitals.atomic.coeffs == np.identity(mol.wfn.nbasis)).all()
np.testing.assert_allclose(canonical.to_ao(canonical.fock), mol.wfn.fock_ao, atol=1.e-9)
np.testing.assert_allclose(canonical.from_ao(basis.overlaps), canonical.overlaps, atol=1.e-9)
def test_pyscf_casscf(h2):
h2.set_energy_model(mdt.models.PySCFPotential,
theory='casscf',
active_electrons=2, active_orbitals=2,
state_average=3, basis='sto-3g')
h2.calculate()
# TODO: actually test results
def test_pyscf_casci(h2):
pytest.xfail("CASCI interface doesn't yet work")
h2.set_energy_model(mdt.models.PySCFPotential,
theory='casci',
active_electrons=2, active_orbitals=2, basis='6-31g')
h2.calculate()
# TODO: actually test results
@pytest.mark.parametrize('objkey', TESTSET)
def test_pyscf_rhf_sto3g_forces(objkey, request):
mol = request.getfixturevalue(objkey)
mol.set_energy_model(mdt.models.PySCFPotential, basis='sto-3g', theory='rhf')
forces = mol.calc_forces()
assert forces.shape == (mol.num_atoms, 3)
def test_calc_eri_tensor(h2):
h2.set_energy_model(mdt.models.PySCFPotential, basis='sto-3g', theory='rhf')
h2.calculate()
eris = h2.wfn.aobasis.calc_eris()
assert eris[0,0, 1,1] == eris[1,1, 0,0]
assert eris[1,0, 0,1] == eris[0,1, 0,1]
assert eris.nbasis == 2
with pytest.raises(IndexError):
eris[0,1,2,1]
@pytest.mark.screening
def test_aobasis(h2_rhf_sto3g):
# it's sto-3g, so structure is simple
aobasis = h2_rhf_sto3g.wfn.aobasis
assert aobasis.basisname == 'sto-3g'
assert (aobasis.coeffs == np.identity(2)).all()
np.testing.assert_allclose(aobasis.fock, aobasis.fock.T)
assert (aobasis.energies == aobasis.fock.diagonal()).all()
assert aobasis.fock.dimensionality == u.eV.dimensionality
for orb in h2_rhf_sto3g.wfn.aobasis:
assert orb.aotype == '1s'
assert orb.orbtype == 's'
assert len(orb.primitives) == 3
assert (orb.n, orb.m, orb.l) == (1, 0, 0)
assert isinstance(orb.name, str)
# todo: deal with other shells, cartesian vs. spherical
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/conftest.py | .py | 541 | 20 |
def pytest_itemcollected(item):
marks = getattr(item.module, '__PYTEST_MARK__', None)
if marks is None:
return
if isinstance(marks, str):
marks = [marks]
for mark in marks:
item.add_marker(mark)
# TODO: nicer output strings for git commit status
# see https://docs.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures
#@pytest.hookimpl(tryfirst=True, hookwrapper=True)
#def pytest_runtest_makereport(item, call):i
# pass
# Also possibly useful: item.add_report_section
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_tests/test_alignments.py | .py | 5,314 | 149 | import random
import numpy as np
import pytest
import moldesign as mdt
from moldesign import geom
from moldesign.mathutils import normalized
from moldesign import units as u
from .molecule_fixtures import *
from .helpers import assert_almost_equal
__PYTEST_MARK__ = 'internal' # mark all tests in this module with this label (see ./conftest.py)
def test_bond_alignment_on_axis(benzene):
mol = benzene.copy()
directions = ['x', 'y', 'z',
[1,2,3.0],
[0,1,0],
[0.1, 0.1, 0.1] * u.angstrom]
for i, dir in enumerate(directions):
bond = mdt.Bond(*random.sample(mol.atoms, 2))
center = (i % 2) == 0.0
bond.align(dir, centered=center)
if center:
np.testing.assert_allclose(bond.midpoint, np.zeros(3),
atol=1.e-12)
np.testing.assert_allclose(bond.a1.position.defunits_value(),
-bond.a2.position.defunits_value(),
atol=1e-10)
if isinstance(dir, str):
if dir == 'x':
d = np.array([1.0, 0, 0])
elif dir == 'y':
d = np.array([0.0, 1.0, 0.0])
elif dir == 'z':
d = np.array([0.0, 0.0, 1.0])
else:
raise WtfError()
else:
d = normalized(u.array(dir))
newvec = (bond.a2.position - bond.a1.position).normalized()
assert abs(1.0 - d.dot(newvec)) < 1e-10
def test_align_two_bonds(benzene, h2):
h2 = h2.copy()
alignbond = list(h2.bonds)[0]
one_was_different = False
for targetbond in benzene.bonds:
# sanity checks before we start:
assert not np.allclose(alignbond.midpoint.defunits_value(),
targetbond.midpoint.defunits_value())
vec1, vec2 = (normalized(b.a2.position - b.a1.position)
for b in (alignbond, targetbond))
one_was_different = (one_was_different or vec1.dot(vec2) < 0.8)
alignbond.align(targetbond)
np.testing.assert_allclose(alignbond.midpoint, targetbond.midpoint)
vec1, vec2 = (normalized(b.a2.position - b.a1.position)
for b in (alignbond, targetbond))
assert (1.0 - vec1.dot(vec2)) < 1e-8
@pytest.mark.parametrize('fixturename', 'ligand3aid pdb3aid benzene small_molecule pdb1yu8'.split())
def test_pmi_is_orthonormal(request, fixturename):
# test a bunch of molecules
mol = request.getfixturevalue(fixturename).copy()
pmi = geom.alignment.PrincipalMomentsOfInertia(mol)
for ivec in range(3):
assert abs(1.0 - mdt.mathutils.norm(pmi.evecs[ivec])) < 1e-12
for jvec in range(ivec+1, 3):
assert abs(pmi.evecs[ivec].dot(pmi.evecs[jvec])) < 1e-12
@pytest.mark.parametrize('fixturename', 'ligand3aid pdb3aid benzene small_molecule pdb1yu8'.split())
def test_pmi_translational_rotational_invariance(request, fixturename):
# currently only test the eigenvalues
mol = request.getfixturevalue(fixturename).copy()
pmi = geom.alignment.PrincipalMomentsOfInertia(mol)
_randomize_orientation(mol)
pmi2 = geom.alignment.PrincipalMomentsOfInertia(mol)
assert_almost_equal(pmi.moments, pmi2.moments)
def _randomize_orientation(mol):
translation = 10.0*(np.random.rand(3)-0.5)*u.angstrom
mol.translate(translation)
axis = [random.uniform(-1.0, 1.0),
random.uniform(-1.0, 1.0),
random.uniform(0.4, 1.0)] # make sure to rotate off of x-axis
mol.rotate(axis=axis, angle=random.randrange(15.0, 170.0) * u.degrees)
@pytest.mark.screening
def test_pmi_reorientation_on_linear_molecule():
# note that this will fail if the generated polymer is not perfectly linear
mol = mdt.from_smiles('C#CC#CC#C')
original_distmat = mol.calc_distance_array().defunits_value()
for i in range(5):
_randomize_orientation(mol)
# calculate PMI and reorient
pmi = geom.alignment.PrincipalMomentsOfInertia(mol)
pmi.reorient(mol)
# Check that everything lies along the z-axis
np.testing.assert_allclose(mol.positions[:,:2], 0.0, atol=1e-12)
# Check that distance matrix was unchanged under the transformation
newdistmat = mol.calc_distance_array()
np.testing.assert_allclose(newdistmat.defunits_value(),
original_distmat)
def test_pmi_reorientation_on_benzene(benzene):
# note that this will fail if the generated polymer is not perfectly linear
mol = benzene.copy()
original_distmat = mol.calc_distance_array().defunits_value()
for i in range(5):
_randomize_orientation(mol)
# calculate PMI and reorient
pmi = geom.alignment.PrincipalMomentsOfInertia(mol)
pmi.reorient(mol)
# Check that molecule is _roughly_ in x-y plane
np.testing.assert_allclose(mol.positions[:,0].value_in(u.angstrom), 0.0,
atol=0.1)
# Check that distance matrix was unchanged under the transformation
newdistmat = mol.calc_distance_array()
np.testing.assert_allclose(newdistmat.defunits_value(),
original_distmat)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/monitor.py | .py | 4,421 | 135 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import moldesign as mdt
from . import toplevel
from . import constraints, grads, coords, setcoord
class Monitor(object):
def __init__(self, *atoms):
if len(atoms) != self.NUM_ATOMS:
raise ValueError('%s requires %d atoms, but %d passed' %
(type(self), self.NUM_ATOMS, len(atoms)))
self.atoms = atoms
@property
def value(self):
return self.GETTER(*self.atoms)
@value.setter
def value(self, val):
args = self.atoms + (val,)
self.SETTER(*args)
def gradient(self):
return grads._atom_grad_to_mol_grad(self.atoms, self.GRAD(*self.atoms))
@property
def ffterm(self):
""" mdt.forcefields.ForceFieldTerm: term associated with this quantity
Raises:
ValueError: if this quantity is not associated with a molecule or a forcefield
"""
mol = self.atoms[0].molecule
for atom in self.atoms[1:]:
if atom.molecule is not mol:
raise ValueError('These atoms are not part of the same molecule')
return mol.ff.get_term(*self.atoms)
@mdt.utils.kwargs_from(constraints.GeometryConstraint)
def constrain(self, **kwargs):
""" Constrain this coordinate.
This will add a new item to the parent molecule's constraint list.
Args:
**kwargs (dict): kwargs for constraints.GeometryConstraint
Returns:
constraints.GeometryConstraint: the constraint object
"""
c = self.CONSTRAINT(*self.atoms, **kwargs)
mol = self.atoms[0].molecule
for atom in mol.atoms[1:]:
if atom.molecule is not mol:
raise ValueError("Can't create constraint; atoms are not part of the same Molecule")
mol.constraints.append(c)
mol._reset_methods()
return c
def __call__(self, obj):
""" Calculate this value for the given trajectory
Args:
obj (mdt.Molecule or mdt.Trajectory): molecule or trajectory to measure
Returns:
moldesign.units.Quantity: this coordinate's value (for a molecule), or a list of values
(for a trajectory)
Note:
Atoms are identified by their index only; the atoms defined in the Monitor must have
the same indices as those in the passed object
"""
return self.GETTER(*(obj.atoms[a.index] for a in self.atoms))
def __str__(self):
return '%s: %s' % (type(self).__name__, self.value)
def __repr__(self):
return '<%s for atoms %s: %s>' % (type(self).__name__,
','.join(str(atom.index) for atom in self.atoms),
self.value)
@toplevel
class DistanceMonitor(Monitor):
NUM_ATOMS = 2
GETTER = staticmethod(coords.distance)
SETTER = staticmethod(setcoord.set_distance)
GRAD = staticmethod(grads.distance_gradient)
CONSTRAINT = constraints.DistanceConstraint
@toplevel
class AngleMonitor(Monitor):
NUM_ATOMS = 3
GETTER = staticmethod(coords.angle)
SETTER = staticmethod(setcoord.set_angle)
GRAD = staticmethod(grads.angle_gradient)
CONSTRAINT = constraints.AngleConstraint
@toplevel
class DihedralMonitor(Monitor):
def __init__(self, *atoms):
if len(atoms) in (1, 2):
atoms = coords._infer_dihedral(*atoms)
super().__init__(*atoms)
NUM_ATOMS = 4
GETTER = staticmethod(coords.dihedral)
SETTER = staticmethod(setcoord.set_dihedral)
GRAD = staticmethod(grads.dihedral_gradient)
CONSTRAINT = constraints.DihedralConstraint
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/symmetry.py | .py | 6,506 | 170 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import moldesign as mdt
from moldesign import units as u
from moldesign.external import transformations as trns
from moldesign.interfaces import symmol_interface as smi
from . import __all__ as __toplevel__
get_symmetry = smi.run_symmol
__toplevel__.append('get_symmetry')
class SymmetryElement(object):
"""
Represents an basic, origin-centered symmetry operation: an identity operation (C1/E),
inversion center (Ci),
mirror plane (Cs), rotation axis (C2,C3,...), or
improper rotation (S4, S6, ...)
Attributes:
mol (moldesign.Molecule): molecule this symmetry describes
idx (int): symmetry index
symbol (str): Schoenflies symbol
matrix (np.array): symmetry transformation
csm (mdt.units.MdtQuantity): mean-squared-distance to this symmetry group (i.e.,
0 if this symmetry is exact)
max_diff (mdt.unitsMdtQuantity): maximum distance of any one atom to this symmetry group
"""
def __init__(self, mol, idx, symbol, matrix, csm, max_diff):
self.mol = mol
self.symbol = symbol
self.matrix = matrix
self.mol = mol
self.csm = csm
self.max_diff = max_diff
self.idx = idx
def __str__(self):
return 'SymmetryElement %s, error=%s' % (self.symbol, self.csm)
def __repr__(self):
return '<%s>' % self
def get_axis(self):
"""
Returns normal of the plane for Cs or axis of rotation for a Cn
:param symm_elem: symmetry element (with attributes 'symbol' and 'matrix')
:return: array of shape (3,)
"""
mat = np.identity(4)
mat[:3, :3] = self.matrix
symbol = self.symbol
if symbol == 'Cs':
point, normal = trns.reflection_from_matrix(mat)
assert np.allclose(point[:3], np.zeros(3))
return normal
elif symbol[0] == 'C' and symbol[-1].isdigit():
angle, normal, point = trns.rotation_from_matrix(mat)
assert np.allclose(point[:3], np.zeros(3))
return normal
elif symbol[0] == 'S' and symbol[-1].isdigit():
normal = improper_axis_from_matrix(self.matrix)
return normal
else:
raise ValueError('Unrecognized symmetry type %s' % self.symbol)
class MolecularSymmetry(object):
def __init__(self, mol, symbol, rms,
orientation, elems,
_job=None):
self.mol = mol
self.symbol = symbol
self.rms = rms
self.orientation = mdt.utils.if_not_none(orientation, mol.positions)
self.elems = mdt.utils.if_not_none(elems, [])
self.groups = mdt.utils.Categorizer(lambda x:x.symbol, self.elems)
self._job = _job
@property
def exact(self):
""" List[SymmetryElement]: Exact symmetry elements
"""
return [elem for elem in self.elems if elem.max_diff == 0.0]
@property
def approximate(self):
""" List[SymmetryElement]: Approximate symmetry elements
"""
return [elem for elem in self.elems if elem.max_diff != 0.0]
def __str__(self):
return '%d symmetry element%s' % (len(self.elems), 's' if len(self.elems) != 1 else '')
def __repr__(self):
return '%s of molecule %s' % (self, self.mol.name)
def get_symmetrized_coords(self, elem):
"""
Symmetrize the molecule based on the symmetry operation
This will work as long as the symmetry operation brings each atom closest to a symmetry relation.
"""
import scipy.spatial.distance
# First, apply the transformation
oriented_coords = self.orientation
transformed_coords = self.orientation.T.ldot(elem.matrix).T
# Next, calculate the correspondence between the untransformed and transformed atoms
align_to_transform = {} # map between the original positions and their transformed positions
transform_to_align = {} # inverse
byelement = mdt.utils.Categorizer(lambda x: x.element, self.mol.atoms)
for elemname, atoms in byelement.items():
indices = np.array([atom.index for atom in atoms])
atoms_aligned = oriented_coords[indices].defunits_value()
atoms_transformed = transformed_coords[indices].defunits_value()
distances = scipy.spatial.distance.cdist(atoms_aligned, atoms_transformed)
for a_idx, t_idx in enumerate(distances.argmin(axis=0)):
align_to_transform[indices[a_idx]] = indices[t_idx]
for t_idx, a_idx in enumerate(distances.argmin(axis=1)):
transform_to_align[indices[t_idx]] = indices[a_idx]
# Make the positions exactly symmetric by averaging them
pos = np.zeros(transformed_coords.shape) * u.default.length
for align_atom, transform_atom in align_to_transform.items():
assert transform_to_align[transform_atom] == align_atom, \
'Molecule is too far from this symmetry to symmetrize'
pos[transform_atom] = (oriented_coords[transform_atom] +
transformed_coords[align_atom]) / 2.0
return pos
def improper_axis_from_matrix(matrix):
"""
Return rotation angle and axis / mirror plane normal from improper rotation matrix.
"""
R = np.array(matrix, dtype=np.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
w, W = np.linalg.eig(R33.T)
i = np.where(abs(np.real(w) + 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue -1")
direction = np.real(W[:, i[-1]]).squeeze()
return direction
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/coords.py | .py | 6,226 | 202 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from .. import units as u
from .. import mathutils
from . import toplevel
@toplevel
def distance(a1, a2):
""" Return distance between two atoms
Args:
a1,a2 (mdt.Atom): the two atoms
Returns:
u.Scalar[length]: the distance
"""
diffvec = a1.position - a2.position
dim = len(diffvec.shape)
if dim == 1:
return np.sqrt(diffvec.dot(diffvec))
else:
assert dim == 2
return np.sqrt((diffvec*diffvec).sum(axis=1))
@toplevel
def angle(a1, a2, a3):
""" The angle between bonds a2-a1 and a2-a3
Args:
a1,a2,a3 (mdt.Atom): the atoms describing the angle
Returns:
u.Scalar[length]: the distance
"""
r21 = (a1.position - a2.position).defunits_value() # remove units immediately to improve speed
r23 = (a3.position - a2.position).defunits_value()
return mathutils.alignment_rotation(r21, r23)[0]
def _join_bonds(b1, b2):
""" Return a1, a2, a3, where a2 is the atom shared by both bonds
"""
try:
a3 = b2.partner(b1.a2)
except ValueError:
return b1.a2, b1.a1, b2.partner(b1.a1)
else:
return b1.a1, b1.a2, a3
@toplevel
def dihedral(a1, a2=None, a3=None, a4=None):
"""Twist angle of bonds a1-a2 and a4-a3 around around the central bond a2-a3
Can be called as ``dihedral(a1, a2, a3, a4)``
OR ``dihedral(a2, a2)``
OR ``dihedral(bond)``
Args:
a1 (mdt.Bond): the central bond in the dihedral. OR
a1,a2 (mdt.Atom): the atoms describing the dihedral
a3,a4 (mdt.Atom): (optional) if not passed, ``a1`` and ``a2`` will be treated as the
central atoms in this bond, and a3 and a4 will be inferred.
Returns:
(units.Scalar[angle]): angle - [0, 2 pi) radians
"""
if a3 is a4 is None: # infer the first and last atoms
a1, a2, a3, a4 = _infer_dihedral(a1, a2)
r21 = (a1.position - a2.position).defunits_value() # remove units immediately to improve speed
r34 = (a4.position - a3.position).defunits_value()
dim = len(r21.shape)
center_bond = (a2.position - a3.position).defunits_value()
plane_normal = mathutils.normalized(center_bond)
if dim == 1:
r21_proj = r21 - plane_normal * r21.dot(plane_normal)
r34_proj = r34 - plane_normal * r34.dot(plane_normal)
else:
assert dim == 2
r21_proj = r21 - plane_normal * (r21*plane_normal).sum(axis=1)[:, None]
r34_proj = r34 - plane_normal * (r34*plane_normal).sum(axis=1)[:, None]
va = mathutils.normalized(r21_proj)
vb = mathutils.normalized(r34_proj)
if dim == 1:
costheta = np.dot(va, vb)
if np.allclose(costheta, 1.0):
return 0.0 * u.radians
elif np.allclose(costheta, -1.0):
return u.pi * u.radians
else:
costheta = (va*vb).sum(axis=1)
abstheta = mathutils.safe_arccos(costheta)
cross = np.cross(va, vb)
if dim == 1:
theta = abstheta * np.sign(np.dot(cross, plane_normal))
else:
theta = abstheta * np.sign((cross*plane_normal).sum(axis=1))
return (theta * u.radians) % (2.0 * u.pi * u.radians)
@toplevel
def nonplanar_bend_angle(a1, a2=None, a3=None, a4=None):
""" Calculates the pyramidalization of a 4-atom system
"Pyramidalization" is the out of plane bending around a trivalent center (usually an
sp2 carbon). This routine calculates it as the angle between two planes. The two planes
are defined by:
1) the three substituents of a tri-valent central atom
2) the central atom and its two single-bonded constituents
Can be called as ``pyramidalization(central_atom)`` in an sp2 system
OR ``pyramidalization(double_bond, single_bond1, single_bond2)``
OR ``pyramidalization(a1, a2, a3, a4)`` where the atoms, in order are
1. a1 - the central atom
2. a2 - the doubly bonded neighbors
3. a3 - one of the singly-bonded neighbors
4. a4 - the other singly-bonded neighbor
Returns:
(units.Scalar[angle]): angle - [0, 2 pi) radians
"""
raise NotImplementedError()
def _infer_dihedral(a2, a3=None):
""" Given two atoms defining the central bond in a dihedral, pick the first and last atoms
in a heuristic way (see :meth:`_pick_atom`) to get a unique-ish definition.
"""
if a3 is None: # assume bond-like
bond = a2
a2, a3 = bond.a1, bond.a2
a1 = _pick_atom(a2, a3)
a4 = _pick_atom(a3, a2)
return a1, a2, a3, a4
def _pick_atom(atom, nbr):
""" Pick an atom bonded to ``atom`` that:
A) is not nbr
B) has the largest atomic number
C) has the lowest index
This gives us a unique definition for dihedrals when only passing 2 atoms
"""
newat = None
if hasattr(atom, 'traj'):
istraj = True
traj = atom.traj
atom = atom.real_atom
nbr = nbr.real_atom
else:
istraj = False
for bond in atom.bonds:
pt = bond.partner(atom)
if pt == nbr:
continue
elif newat is None:
newat = pt
elif newat.atnum < pt.atnum:
newat = pt
elif newat.atnum == pt.atnum and newat.index > pt.index:
newat = pt
if newat is None:
raise ValueError('%s is not part of a dihedral' % atom)
if istraj:
newat = traj.atoms[newat.index]
return newat
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/setcoord.py | .py | 7,516 | 196 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import moldesign as mdt
import moldesign.molecules.atomcollections
from moldesign import external
from moldesign.mathutils import sub_angles, apply_4x4_transform
from . import toplevel, angle, dihedral
from .coords import _infer_dihedral
@toplevel
def set_distance(a1, a2, newlength, adjustmol=True):
""" Set the distance between two atoms. They will be adjusted along the vector separating them.
If the two atoms are A) bonded, B) not part of the same ring system, and C) ``adjustmol`` is
True, then the entire molecule's positions will be modified as well
Args:
a1,a2 (mdt.Atom): atoms to adjust
newlength (u.Scalar[length]): new length to set
adjustmol (bool): Adjust all atoms on either side of this bond?
"""
#TODO: lots of room for optimization here
if adjustmol:
assert a1.molecule is not None
assert a1.molecule == a2.molecule
vec = a1.position - a2.position
dist = np.sqrt(vec.dot(vec))
direction = (vec / dist)
delta = newlength - dist
if np.abs(delta) < 1.0e-5 * delta.get_units(): return
if not adjustmol:
a1.position += direction * delta / 2.0
a2.position -= direction * delta / 2.0
else:
mol = a1.molecule
indices, sign = _get_fragment_indices(mol, a1, a2)
mol.positions[indices] += delta*direction*sign
@toplevel
def set_angle(a1, a2, a3, theta, adjustmol=True):
""" Set the angle between bonds a1-a2 and a3-a2. The atoms will be adjusted along the
gradient of the angle.
If ``adjustmol`` is True and the topology is unambiguous, then the entire molecule's positions
will be modified as well
Args:
a1,a2,a3 (mdt.Atom): atoms to adjust
theta (u.Scalar[angle]): new angle to set
adjustmol (bool): Adjust all atoms on either side of this bond?
"""
# TODO: deal with co-linear a1, a2, a3 - the rotation axis is ill-defined in this case \
# (require an axis to be specified)
# TODO: weakly cache the rotation axis so that users can set angle to 0 or 180 without losing the axis
current = angle(a1, a2, a3)
rotation = sub_angles(current, theta)
if abs(rotation) < 1.0e-6: return
axis = np.cross(a1.position - a2.position, a3.position - a2.position) # do vecs need to be normalized?
if not adjustmol:
rotmat_l = external.transformations.rotation_matrix(rotation / 2.0, axis, a2.position)
rotmat_r = external.transformations.rotation_matrix(-rotation / 2.0, axis, a2.position)
a1.position = apply_4x4_transform(rotmat_l, a1.position)
a3.position = apply_4x4_transform(rotmat_r, a3.position)
else:
mol = a2.molecule
indices, sign = _get_fragment_indices(mol, a1, a2)
rotmat = external.transformations.rotation_matrix(rotation, axis*sign, a2.position)
mol.positions[indices] = apply_4x4_transform(rotmat, mol.positions[indices])
@toplevel
def set_dihedral(a1, a2=None, a3=None, a4=None, theta=None, adjustmol=True):
""" Set the twist angle of atoms a1 and a4 around the central bond a2-a3. The atoms will be
adjusted along the gradient of the angle.
Can be called as ``set_dihedral(a1, a2, a3, a4, theta, adjustmol=True)``
OR ``set_dihedral(a2, a2, theta, adjustmol=True)``
OR ``set_dihedral(bond, theta, adjustmol=True)``
If ``adjustmol`` is True and the topology is unambiguous, then the entire molecule's positions
will be modified as well
Args:
a1 (mdt.Bond): central bond in dihedral
a1,a2 (mdt.Atom): atoms around central bond in dihedral
a3, a4 (mdt.Atom):
theta (u.Scalar[angle]): new angle to set
adjustmol (bool): Adjust all atoms on either side of this bond?
"""
# TODO: deal with co-linear a1/a4, a2, a3 - the angle is ill-defined \
# (should just an arbitrary axis normal to the central bond)
if a4 is None:
if isinstance(a1, mdt.Bond):
if theta is None:
theta = a2
a1, a2 = a1.a1, a1.a2
if a3 is not None and theta is None:
theta, a3 = a3, theta
elif a3 is not None or a4 is not None or theta is None:
raise ValueError('Invalid number of arguments for set_dihedral')
a1, a2, a3, a4 = _infer_dihedral(a1, a2)
current = dihedral(a1, a2, a3, a4)
rotation = sub_angles(theta, current)
if abs(rotation) < 1.0e-6: return
axis = a2.position - a3.position
if not adjustmol:
rotmat_l = external.transformations.rotation_matrix((-rotation / 2.0), axis, a3.position)
rotmat_r = external.transformations.rotation_matrix((rotation / 2.0), axis, a3.position)
a1.position = apply_4x4_transform(rotmat_l, a1.position)
a4.position = apply_4x4_transform(rotmat_r, a4.position)
else:
mol = a2.molecule
indices, sign = _get_fragment_indices(mol, a3, a2)
rotmat = external.transformations.rotation_matrix(rotation, axis*sign, a3.position)
mol.positions[indices] = apply_4x4_transform(rotmat, mol.positions[indices])
def _get_fragment(mol, a1, a2):
"""
Given a pair of atoms a1 and a2, return two fragments, one composed of all atoms on a1's
side of the molecule, the other composed of all atoms on a2's side of the molecule.
This won't work if a1 and a2 are in a cycle.
"""
# DFS for a1's side of the bond. To prevent visiting a2, we mark it as visited at the start
visited = set([a2])
def dfs_dive(atom):
visited.add(atom)
for nbr in atom.bond_graph:
if nbr is a2 and atom is not a1:
raise ValueError("a1 and a2 are in a cyclic moiety")
if nbr not in visited:
dfs_dive(nbr)
dfs_dive(a1)
visited.remove(a2)
result = moldesign.molecules.atomcollections.AtomList(visited)
return result
def _get_fragment_indices(mol, a1, a2):
key = (mol, a1, a2)
if key in _get_fragment_indices.cache:
return _get_fragment_indices.cache[key]
# Try to get the smaller fragment ... a bit hacky right now
try: frag1 = _get_fragment(mol, a1, a2)
except ValueError:
frag1 = None
try: frag2 = _get_fragment(mol, a2, a1)
except ValueError:
if frag1 is None: raise
else:
frag = frag1
sign = 1.0
else:
if frag1 is None or len(frag1) > len(frag2):
frag = frag2
sign = -1.0
else:
frag = frag1
sign = 1.0
indices = [atom.index for atom in frag]
result = np.array(indices)
_get_fragment_indices.cache[key] = (result, sign)
return result, sign
_get_fragment_indices.cache = {}
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/grads.py | .py | 3,592 | 118 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from moldesign import units as u
from moldesign.mathutils import normalized
from . import toplevel, angle
@toplevel
def distance_gradient(a1, a2):
r""" Gradient of the distance between two atoms,
.. math::
\frac{\partial \mathbf{R}_1}{\partial \mathbf{r}} ||\mathbf{R}_1 - \mathbf{R}_2|| =
\frac{\mathbf{R}_1 - \mathbf{R}_2}{||\mathbf{R}_1 - \mathbf{R}_2||}
Args:
a1,a2 (mdt.Atom): the two atoms
Returns:
Tuple[u.Vector[length], u.Vector[length]]: (gradient w.r.t. first atom, gradient w.r.t.
second atom)
"""
d = normalized(a1.position-a2.position) * u.ureg.dimensionless
return d, -d
@toplevel
def angle_gradient(a1, a2, a3):
r"""Gradient of the angle between bonds a2-a1 and a2-a3
.. math::
\nabla \theta_{ijkl} = \frac{\partial \theta_{ijkl}}{\partial \mathbf R}
Args:
a1,a2,a3 (mdt.Atom): the atoms describing the vector
References:
https://salilab.org/modeller/9v6/manual/node436.html
"""
theta = angle(a1, a2, a3)
costheta = np.cos(theta)
p = np.power(1.0 - costheta**2, -0.5)
vij = a1.position - a2.position
vkj = a3.position - a2.position
rij = np.sqrt(vij.dot(vij))
rkj = np.sqrt(vkj.dot(vkj))
eij = vij/rij
ekj = vkj/rkj
vec1 = p * (eij * costheta - ekj) / rij
vec3 = p * (ekj * costheta - eij) / rkj
vec2 = -vec1 - vec3
return vec1, vec2, vec3
@toplevel
def dihedral_gradient(a1, a2, a3, a4):
r""" Cartesian gradient of a dihedral coordinate,
.. math::
\nabla \theta_{ijkl} = \frac{\partial \theta_{ijkl}}{\partial \mathbf R}
Args:
a1,a2,a3,a4 (mdt.Atom): the atoms describing the dihedral
References:
https://salilab.org/modeller/9v6/manual/node436.html
"""
vij = a1.position - a2.position
vkj = a3.position - a2.position
vkl = a3.position - a4.position
vmj = vij.cross(vkj)
vnk = vkj.cross(vkl)
rkj = np.sqrt(vkj.dot(vkj))
rmj = np.sqrt(vmj.dot(vmj))
rnk = np.sqrt(vnk.dot(vnk))
pijkj = vij.dot(vkj) / (rkj**2)
pklkj = vkl.dot(vkj) / (rkj**2)
vec1 = rkj * vmj / (rmj**2)
vec4 = -rkj * vnk / (rnk**2)
vec2 = vec1 * (pijkj - 1.0) - vec4 * pklkj
vec3 = vec4 * (pklkj - 1.0) - vec1 * pijkj
return -vec1 * u.radians, -vec2 * u.radians, -vec3 * u.radians, -vec4 * u.radians
def _atom_grad_to_mol_grad(atoms, grads):
""" Convert list of gradients on atoms to a full-dimensional Nx3 gradient list (with 0s for
uninvolved atoms)
"""
m = atoms[0].molecule
if len(grads) != len(atoms):
raise ValueError('Number of gradients does not match number of atoms')
mol_grad = np.zeros((m.num_atoms, 3))*grads[0].get_units()
for v, a in zip(grads, atoms):
mol_grad[a.index] = v
return mol_grad
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/__init__.py | .py | 262 | 14 | def toplevel(o):
__all__.append(o.__name__)
return o
__all__ = []
from .coords import *
from .grads import *
from .setcoord import *
from .constraints import *
from .symmetry import *
from .monitor import *
from .shake import *
from .alignment import *
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/shake.py | .py | 3,447 | 103 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import moldesign as mdt
from moldesign import units as u
# TODO: create dynamics wrapper that uses timestep to explicitly calculate constraint forces
def shake_positions(mol, prev_positions, max_cycles=100, use_masses=True, constraints=None):
""" Satisfy all molecular constraints using the SHAKE algorithm
Args:
mol (moldesign.Molecule): molecule with unsatisfied constraints
prev_positions (mdt.units.Array[length]): positions prior to move
max_cycles (int): halt and raise an exception after this many cycles
constraints (List[moldesign.geom.GeometryConstraint]): list of constraints (optional;
uses mol.constraints if not provided)
Note:
This algorithm does badly if constraint function gradients go to 0.
References:
R. Elber, A. Ruymgaart, B. Hess: SHAKE Parallelization.
Eur Phys J Spec Top. 2011 Nov 1; 200(1): 211.
doi:10.1140/epjst/e2011-01525-9
"""
if constraints is None:
constraints = mdt.geom.get_base_constraints(mol.constraints)
# ---array shapes---
# prevgrad, currgrad: (num_constr, 3N)
# values: (num_constr,)
# A: (num_constr, num_constr)
# multipliers: (num_constr, )
# delta: (3N,)
curr = mol.positions.copy()
prev = prev_positions.copy()
mol.positions = prev
prevgrad = np.array([_clean_grad_array(c.gradient()) for c in constraints])
mol.positions = curr
if use_masses:
dim_masses = mol.dim_masses
else:
dim_masses = np.ones((mol.num_atoms, 3)) * u.default.mass
flat_masses = dim_masses.defunits_value().flatten()
for i in range(max_cycles):
for c in mol.constraints:
if not c.satisfied():
break
else:
return # e.g., we're done
# Get constraint derivatives
# Note: we remove units here because pint does not handle arrays with heterogeneous units
values = np.array([c.error().defunits_value() for c in constraints])
currgrad = np.array([_clean_grad_array(c.gradient()) for c in constraints])
A = np.dot(currgrad/flat_masses, prevgrad.T)
multipliers = np.linalg.solve(A, values)
# reapply units and adjust positions
delta = multipliers.dot(prevgrad).reshape(mol.num_atoms, 3) * (
u.default.mass * u.default.length)
mol.positions -= delta/dim_masses
else:
raise mdt.ConvergenceFailure('SHAKE did not converge after %d iterations'%
max_cycles)
def _clean_grad_array(a):
""" Remove units and flatten array
"""
return a.defunits_value().flatten()
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/alignment.py | .py | 3,682 | 103 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from .. import units as u
from ..mathutils import Eigenspace
from .. import utils
@utils.exports
class PrincipalMomentsOfInertia(Eigenspace):
""" Calculates the moments of inertia of a molecule at a given position
Notes:
This object is NOT updated if the initializing molecule's positions change.
This allows it to be used to reorient other molecules into the same coordinate system
Args:
mol (moldesign.Molecule): molecule to calculate PMIs for
mass_centered (bool): calculate PMIs relative to molecule's center of mass (default: True)
Attributes:
axes (List[Vector[len=3]]]): principal rotation axes
moments (Vector[length**2 * mass, len=3]): rotational inertias for the three axes
"""
def __init__(self, mol, mass_centered=True):
from scipy.linalg import eig
inertia_tensor, com = get_inertia_tensor(mol, mass_centered=mass_centered)
evals, evecs = eig(inertia_tensor.defunits_value()) # strip units before going to scipy
evals = evals*u.default.mass*u.default.length ** 2 # reapply units to evals
assert (abs(evecs.imag) < 1e-12).all() # hopefully everything is real?
assert (abs(evals.imag) < 1e-12 * evals.units).all()
super().__init__(evals.real, evecs.T)
self._com = com
self.sort()
@property
def moments(self):
return self.evals
@property
def axes(self):
return self.evecs
def reorient(self, mol):
""" Rotates molecular coordinates into the PMI coordinate system
The molecule will be translated (if necessary), then rotated so that x lies along PMI 1,
y along PMI 2, and z along PMI 3.
Args:
mol (moldesign.Molecule): molecule to re-orient - its current positinos will be changed
"""
if self._com is not None:
mol.com -= self._com
mol.positions = self.transform(mol.positions)
@utils.exports
def get_inertia_tensor(mol, mass_centered=True):
""" Calculates the moment of inertia for a molecule
Args:
mol (moldesign.Molecule): calculate the inertia tensor of this molecule
mass_centered (bool): if True, calcualte tensor relative to molecule's center of mass. If
False, calculate it relative to the current origin.
Returns:
Matrix[mass*length*length]: moment of inertia tensor
"""
inertia_tensor = np.zeros((3,3)) * u.default.mass * u.default.length**2
com = mol.com if mass_centered else None
pos = mol.positions
if mass_centered:
pos = pos - mol.com
for i in range(3):
inertia_tensor[i,i] = (mol.masses * (pos[:,i-1]**2 + pos[:,i-2]**2)).sum()
for j in range(i+1,3):
di = (mol.masses * pos[:,i] * pos[:,j]).sum()
inertia_tensor[i,j] = -di
inertia_tensor[j,i] = -di
return inertia_tensor, com | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/geom/constraints.py | .py | 13,871 | 401 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import moldesign as mdt
from .. import units as u
from ..mathutils import *
from .coords import *
from .grads import *
from .grads import _atom_grad_to_mol_grad
DIST_TOLERANCE = 1.0e-5 * u.angstrom
DIST_FORCE_CONSTANT = 1000.0 * u.kcalpermol / (u.angstrom**2)
ANGLE_TOLERANCE = 1.0e-2 * u.degrees
ANGLE_FORCE_CONSTANT = 1500.0 * u.kcalpermol / (u.radians**2)
class GeometryConstraint(object):
""" Base class - Keeps track of a 3D geometry constraint.
The constraint is satisfied when self.current() == self.value
Args:
atoms (List[mdt.Atom]): atoms involved
value (u.Scalar): constrain the coordinate to this value
tolerance (u.Scalar): absolute tolerance (for iterative constraint enforcement)
force_constant (u.Scalar[force]): optional, only for minimizations and/or use in
restraints)
"""
desc = 'base constraint' # use this to identify the constraint in interfaces
dof = 1 # number of degrees of freedom constrained (so that we can properly calculate temperature)
def __init__(self, atoms, value=None, tolerance=None, force_constant=None):
self.atoms = mdt.AtomList(atoms)
self.mol = self.atoms[0].molecule
self.tolerance = tolerance
self.force_constant = force_constant
for atom in self.atoms:
assert atom.molecule is self.mol
self.value = mdt.utils.if_not_none(value, self.current())
def copy(self, mol=None):
""" Copy this constraint, optionally relinking to a new molecule
Args:
mol (moldesign.Molecule): optional new molecule to track.
Returns:
GeometryConstraint: new constraint instance
"""
if mol is None:
mol = self.mol
newatoms = [mol.atoms[atom.index] for atom in self.atoms]
# Note: this is the call signature for most subclasses, different than this base class's
return self.__class__(*newatoms,
value=self.value, tolerance=self.tolerance,
force_constant=self.force_constant)
def current(self):
"""
Return the current value of the constrained quantity
"""
raise NotImplementedError()
def gradient(self):
r"""
Return the gradient of the constrained quantity
Requires that self.atomgrad be implemented (or otherwise provided)
Must return an MdtQuantity object, even if dimensionless
.. math::
\nabla G(\mathbf r)
"""
return _atom_grad_to_mol_grad(self.atoms, self.atomgrad(*self.atoms))
def satisfied(self):
"""
Returns:
bool: True if this constraint is satisfied to within tolerance
"""
return abs(self.error()) <= self.tolerance
def restraint_penalty(self):
"""
Returns:
u.Scalar[energy]: energy penalty for restraints
"""
return 0.5 * self.force_constant * self.error()**2
def restraint_penalty_force(self):
"""
Returns:
u.Vector[energy]: forces from restraint
"""
return -self.force_constant * self.gradient() * self.error()
def error(self):
"""
Returns:
u.Scalar: deviation of current geometry from the constraint
"""
return self.current() - self.value
def __repr__(self):
return '<{cls.__name__}{self.atoms}:value={self.value})>'.format(
cls=self.__class__, self=self)
def __str__(self):
return 'Constraint: {self.desc}({atoms}) -> {self.value})>'.format(
atoms=','.join([a.name for a in self.atoms]), self=self)
def _constraintsig(self):
""" Returns a unique key that lets us figure out if we have duplicate or conflicting
constraints
"""
return tuple([self.desc] + [atom.index for atom in self.atoms])
class DistanceConstraint(GeometryConstraint):
desc = 'distance'
atomgrad = staticmethod(distance_gradient)
dof = 1
def __init__(self, atom1, atom2, value=None,
tolerance=DIST_TOLERANCE, force_constant=DIST_FORCE_CONSTANT):
self.a1 = atom1
self.a2 = atom2
super().__init__([atom1, atom2], value=value,
tolerance=tolerance, force_constant=force_constant)
def current(self):
return self.a1.distance(self.a2)
current.__doc__ = GeometryConstraint.current.__doc__
class AngleConstraint(GeometryConstraint):
desc = 'angle'
atomgrad = staticmethod(angle_gradient)
dof = 1
def __init__(self, atom1, atom2, atom3, value=None,
tolerance=ANGLE_TOLERANCE, force_constant=ANGLE_FORCE_CONSTANT):
self.a1 = atom1
self.a2 = atom2
self.a3 = atom3
super().__init__([atom1, atom2, atom3], value=value,
tolerance=tolerance, force_constant=force_constant)
def current(self):
return angle(*self.atoms)
current.__doc__ = GeometryConstraint.current.__doc__
def error(self):
return sub_angles(self.current(), self.value)
error.__doc__ = GeometryConstraint.error.__doc__
class DihedralConstraint(GeometryConstraint):
desc = 'dihedral'
atomgrad = staticmethod(dihedral_gradient)
dof = 1
def __init__(self, atom1, atom2, atom3, atom4, value=None,
tolerance=ANGLE_TOLERANCE, force_constant=ANGLE_FORCE_CONSTANT):
self.a1 = atom1
self.a2 = atom2
self.a3 = atom3
self.a4 = atom4
super().__init__([atom1, atom2, atom3, atom4], value=value,
tolerance=tolerance, force_constant=force_constant)
def current(self):
return dihedral(*self.atoms)
current.__doc__ = GeometryConstraint.current.__doc__
def error(self):
return sub_angles(self.current(), self.value)
error.__doc__ = GeometryConstraint.error.__doc__
class FixedPosition(GeometryConstraint):
"""Fixes a single atom at a given location
Note:
The gradient of this function is singular and discontinuous when the constraint is satisfied,
leading to poor results in iterative methods such as SHAKE.
In such cases, this constraint should be automatically replaced with three
:class:`FixedCoordinate` constraints on the atom's x, y, and z coordinates.
"""
desc = 'position'
dof = 3
def __init__(self, atom, value=None,
tolerance=DIST_TOLERANCE, force_constant=DIST_FORCE_CONSTANT):
self.atom = atom
if value is None:
self.value = mdt.utils.if_not_none(value, atom.position.copy())
else:
self.value = value.copy()
super().__init__([atom], value=self.value,
tolerance=tolerance, force_constant=force_constant)
def current(self):
return self.atom.position
current.__doc__ = GeometryConstraint.current.__doc__
def error(self):
diff = self.atom.position - self.value
return np.sqrt(diff.dot(diff))
error.__doc__ = GeometryConstraint.error.__doc__
def decompose(self):
""" Decompose this 3-d constraint into 3 1-dimensional constraints
Single-DOF holonomic constraints tend to be much better behaved mathematically and
are thus easier for optimizers to handle.
"""
for i in range(3):
vec = np.zeros(3)
vec[i] = 1.0
yield FixedCoordinate(self.atom, vec, value=self.value[i])
def atomgrad(self, atom=None):
"""
Note:
For numerical reasons, this returns a vector in the [1,1,1] direction if the
constraint is exactly met
Returns:
u.Vector[length]: unit vector from the constraint location to the atom's actual
location (len=3)
"""
if atom: assert atom is self.atom
diff = self.atom.position - self.value
grad = normalized(diff)
if (grad == np.zeros(3)).all():
grad[:] = np.ones(3) / np.sqrt(3)
return [grad] * u.dimensionless
class HBondsConstraint(GeometryConstraint):
""" Constrains the lengths of all bonds involving hydrogen.
By default, the lengths will be constrained to their forcefield equilibrium values.
They can also be constrained to their current values by setting ``usecurrent=True``
Args:
mol (moldesign.Molecule): Constrain all h-bonds in this molecule
usecurrent (bool): if False (default), set the constraint values to their forcefield
equilibrium values (this will fail if no forcefield is assigned). If True, constrain
the hydrogen bonds at the current values.
Raises:
AttributeError: if usecurrent=False but no forcefield is assigned
"""
desc = 'hbonds'
def __init__(self, mol, usecurrent=False):
self.mol = mol
self.bonds = []
self.subconstraints = []
for bond in self.mol.bonds:
if bond.a1.atnum == 1 or bond.a2.atnum == 1:
self.bonds.append(bond)
if usecurrent:
l = bond.length
else:
l = bond.ff.equilibrium_length
self.subconstraints.append(DistanceConstraint(bond.a1, bond.a2, value=l))
self.values = [c.current() for c in self.subconstraints]
def copy(self, mol=None):
if mol is None:
return super().copy()
else:
return self.__class__(mol)
@property
def tolerance(self):
return len(self.bonds) * DIST_TOLERANCE**2
def __repr__(self):
return '<%s for %s>' % (self.__class__.__name__, self.mol)
def __str__(self):
return 'Constraint: All h-bond lengths in %s)>' % self.mol
def _constraintsig(self):
""" Returns a unique key that lets us figure out if we have duplicate or conflicting
constraints
"""
return self.desc
@property
def dof(self):
return len(self.bonds)
def current(self):
""" Current value of this constraint function. Equivalent to ``self.error()`` here.
Returns:
Scalar[length**2]: sum of errors squared
"""
return sum(distconst.error()**2 for distconst in self.subconstraints)
current.__doc__ = GeometryConstraint.current.__doc__
error = current # same thing here
def gradient(self):
""" Current value of this constraint function. Equivalent to ``self.error()`` here.
Returns:
Vector[length, shape=(*,3)]: gradient of self.error()
"""
grad = np.zeros((self.mol.num_atoms, 3)) * u.default.length
for constraint in self.subconstraints:
grad += 2.0 * constraint.gradient() * constraint.error()
return grad
def decompose(self):
""" Decompose this constraint into a list of bond-length constraints
"""
return self.subconstraints
class FixedCoordinate(GeometryConstraint):
"""Fixes a single, linear degree of freedom for an atom, so that it's constrained to a plane.
Args:
atom (moldesign.Atom): atom to constrain
vector (np.ndarray): direction to constrain
value (units.Scalar[length]): constraint value (i.e., we constrain the dot product of the
atom's position and the normalized direction vector to be this value)
"""
desc = 'coordinate'
dof = 1
def __init__(self, atom, vector, value=None,
tolerance=DIST_TOLERANCE, force_constant=DIST_FORCE_CONSTANT):
self.atom = atom
self.vector = normalized(vector)
if value is None:
self.value = mdt.utils.if_not_none(value, self.current())
else:
self.value = value.copy()
super().__init__([atom], value=self.value,
tolerance=tolerance, force_constant=force_constant)
def copy(self, mol=None):
""" Copy this constraint, optionally relinking to a new molecule
Args:
mol (moldesign.Molecule): optional new molecule to track.
Returns:
GeometryConstraint: new constraint instance
"""
if mol is None:
mol = self.mol
newatom = mol.atoms[self.atom.index]
return self.__class__(newatom, self.vector.copy(),
value=self.value, tolerance=self.tolerance,
force_constant=self.force_constant)
def current(self):
return self.atom.position.dot(self.vector)
current.__doc__ = GeometryConstraint.current.__doc__
def atomgrad(self, atom=None):
return [self.vector] * u.ureg.dimensionless
def _constraintsig(self):
return super()._constraintsig() + tuple(self.vector)
def get_base_constraints(constraintlist):
constraints = []
for c in constraintlist:
if hasattr(c, 'decompose'):
constraints.extend(c.decompose())
else:
constraints.append(c)
return constraints
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_static_data/apply_copyright.sh | .sh | 729 | 22 | #!/bin/bash
for file in `grep -L "Copyright 2016 Autodesk Inc." *.py`; do
mv $file{.bak}
cat > $file <<EOF
# Copyright 2016 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
EOF
cat $file.bak >> $file
done
| Shell |
3D | Autodesk/molecular-design-toolkit | moldesign/_static_data/scripts/generate_residue_templates.py | .py | 857 | 27 | #!/usr/bin/env python
""" A short script that assembles reasonable template geometries for standard amino acids
and DNA bases
"""
import moldesign as mdt
import json
protein = mdt.from_pdb('4F0A')
dna = mdt.build_bdna('ACTGAA')
residues = {}
for chain in list(protein.chains.values()) + list(dna.chains.values()):
for residue in chain:
if residue.type not in ('dna', 'protein'): continue
if residue.type == 'dna' and (residue.is_5prime_end or residue.is_3prime_end):
continue
if residue.type == 'protein' and (residue.is_c_terminal or residue.is_n_terminal):
continue
residues[residue.resname] = mdt.clean_pdb(mdt.Molecule(residue))
residue_pdb = {k: m.write(format='pdb') for k,m in residues.items()}
with open('residue_templates.json', 'w') as outfile:
json.dump(residue_pdb, outfile)
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/_static_data/scripts/generate_residue_data.py | .py | 4,363 | 137 | #!/usr/bin/env python
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Generates a residue database for MDT from the PDB Chemical Component Dictionary
Due to its size, we generate a dbm database that can be accessed without loading the whole thing
into memory.
"""
from __future__ import print_function
from builtins import zip
import collections
import itertools
import sys
import os
sys.path.insert(0, '..')
from moldesign import utils
# to install mmCif: pip install git+git://github.com/glenveegee/PDBeCIF
from mmCif.mmcifIO import CifFileReader
ORDERS = dict(SING=1, DOUB=2, TRIP=3)
DBNAME = 'chemical_components'
def bond_data(data):
if '_chem_comp_bond' not in data:
return {}
bonds = collections.OrderedDict()
bond_data = data['_chem_comp_bond']
if type(bond_data['atom_id_1']) == str: # there's just one bond
a1 = bond_data['atom_id_1']
a2 = bond_data['atom_id_2']
order = ORDERS[bond_data['value_order']]
bonds[a1] = {a2: order}
bonds[a2] = {a1: order}
else:
for a1, a2, order in zip(bond_data['atom_id_1'],
bond_data['atom_id_2'],
bond_data['value_order']):
bonds.setdefault(a1, {})[a2] = ORDERS[order]
bonds.setdefault(a2, {})[a1] = ORDERS[order]
return bonds
ATOMFIELDS = ['symbol', 'formal_charge']
def atom_data(data):
atomdata = data['_chem_comp_atom']
atoms = collections.OrderedDict()
if isinstance(atomdata['atom_id'], list):
atom_ids = atomdata['atom_id']
atom_charges = atomdata['charge']
atom_symbols = atomdata['type_symbol']
else:
atom_ids = [atomdata['atom_id']]
atom_charges = [atomdata['charge']]
atom_symbols = [atomdata['type_symbol']]
for id, charge, symbol in zip(atom_ids, atom_charges, atom_symbols):
atoms[id] = [symbol, int(charge)]
return atoms
def download_ccd():
os.system('wget -N ftp://ftp.wwpdb.org/pub/pdb/data/monomers/aa-variants-v1.cif.gz')
os.system('wget -N ftp://ftp.wwpdb.org/pub/pdb/data/monomers/components.cif.gz')
os.system('gunzip -v -f -k components.cif.gz aa-variants-v1.cif.gz')
RESFIELDS = ['name', 'type', 'atoms', 'bonds']
def read_ccd():
print('Reading components.cif ...')
sys.stdout.flush()
components = CifFileReader()
all_residues = components.read('components.cif')
print('Reading aa-variants-v1.cif ...')
amino_variants = components.read('aa-variants-v1.cif')
return itertools.chain(iter(all_residues.items()), iter(amino_variants.items()))
def store_residue(resname, data, db):
try:
record = [data['_chem_comp']['name'],
data['_chem_comp']['type'],
atom_data(data),
bond_data(data)]
except (KeyError, ValueError) as exc:
print('\nFAILED for residue %s: %s'%(resname, exc))
else:
db[resname] = record
print(resname, end=' ')
sys.stdout.flush()
def main():
print('This program regenerates the `%s` database using the "Chemical Component ' % DBNAME)
print('Dictionary" and "Protonation Variants Dictionary" from http://www.wwpdb.org/data/ccd')
if len(sys.argv) > 1 and sys.argv[1] == '--download':
print('Downloading newest CCD files ...\n')
download_ccd()
else:
print('Using cached download (run with "--download" to download a new version)')
residues = read_ccd()
db = utils.CompressedJsonDbm(DBNAME, 'n')
db['__FIELDS__'] = {'ATOMFIELDS': ATOMFIELDS,
'RESFIELDS': RESFIELDS}
for resname, data in residues:
store_residue(resname, data, db)
print('\nCreated db "%s" (%d records)' % (DBNAME, len(db)))
db.close()
if __name__ == '__main__':
main()
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/data/chemical_components.py | .py | 2,262 | 69 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module provides access to the chemical component database, which is stored in
``moldesign/_static_data/chemical_components``
and can be re-generated by running
``cd moldesign/_static_data/ && scripts/generate_residue_data.py --download``
"""
import os
from . import PACKAGEPATH
from moldesign import utils
class _DatabaseEntry(object):
""" Maps into a field stored in the database
"""
def __init__(self, hostdb, keyname):
self.hostdb = hostdb
self.keyname = keyname
self.index = self.hostdb['__FIELDS__']['RESFIELDS'].index(keyname)
def __repr__(self):
return '<Chemical component dictionary: "%s" entries>' % self.keyname
def __getitem__(self, item):
return self.hostdb[item][self.index]
__contains__ = utils.Alias('hostdb.__contains__')
def keys(self):
for key in self.hostdb.keys():
if key == '__FIELDS__':
continue
yield key
def items(self):
for key in self:
yield key, self[key]
__iter__ = keys
# This is a very big dict, so we load it as a compressed database
_bondfilename = os.path.join(PACKAGEPATH, '_static_data', 'chemical_components')
CCD_DATABASE = utils.CompressedJsonDbm(_bondfilename, 'r', dbm=utils.ReadOnlyDumb)
RESIDUE_BONDS = _DatabaseEntry(CCD_DATABASE, 'bonds')
RESIDUE_ATOMS = _DatabaseEntry(CCD_DATABASE, 'atoms')
RESIDUE_CCD_NAMES = _DatabaseEntry(CCD_DATABASE, 'name')
RESIDUE_CCD_TYPES = _DatabaseEntry(CCD_DATABASE, 'type')
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/data/__init__.py | .py | 121 | 5 | from .data import *
from .atomic import *
from .biochemical import *
from .chemical_components import *
from .ff import * | Python |
3D | Autodesk/molecular-design-toolkit | moldesign/data/atomic.py | .py | 1,571 | 45 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import yaml
from moldesign import units as u
from . import PACKAGEPATH
__all__ = 'ATOMIC_MASSES ATOMIC_NUMBERS ELEMENTS SYMBOLS'.split()
with open(os.path.join(PACKAGEPATH, '_static_data', 'nist_atomic.yml'), 'r') as ymlfile:
isotopes = yaml.load(ymlfile)
ATOMIC_NUMBERS = {record[0]['symbol']: atnum for atnum, record in isotopes.items()}
ELEMENTS = {val: key for key, val in ATOMIC_NUMBERS.items()}
SYMBOLS = ELEMENTS
# Isotopic masses for the most abundant species of each element
# from https://www.ncsu.edu/chemistry/msf/pdf/IsotopicMass_NaturalAbundance.pdf
ATOMIC_MASSES = {atnum: records[0]['mass']*u.amu for atnum, records in isotopes.items()}
for atnum, mass in list(ATOMIC_MASSES.items()):
ATOMIC_MASSES[ELEMENTS[atnum]] = mass # index by atnum and symbol
ATOMIC_MASSES[-1] = -1.0*u.amu
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/data/ff.py | .py | 1,287 | 39 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import yaml
from . import PACKAGEPATH
from ..utils import exports_names
exports_names('AMBER_DEFAULT', 'AMBER_LEAPRC', 'AMBER_SYSTEM')
AMBER_DEFAULT = ('GLYCAM_06j-1', 'tip3p', 'gaff2', 'lipid14', 'OL15', 'OL3', 'ff14SB')
with open(os.path.join(PACKAGEPATH, '_static_data', 'amber_ffs.yml'), 'r') as _ambfile:
ambff = yaml.load(_ambfile)
AMBER_LEAPRC = {}
AMBER_SYSTEM = {}
for system, ffs in list(ambff.items()):
for ff, leaprc in list(ffs.items()):
AMBER_LEAPRC[ff] = leaprc
AMBER_SYSTEM[ff] = system
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/data/data.py | .py | 2,786 | 86 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import json
import moldesign as mdt
from .. import units as u
PACKAGEPATH = os.path.abspath(os.path.dirname(mdt.__file__))
class CyclicList(list):
def __getitem__(self, item):
return super().__getitem__(item % len(self))
COLOR_LIST = ['lightgreen', 'lightblue', 'lightgrey',
'yellow', 'orange', 'purple', 'IndianRed',
'PaleTurquoise', 'OldLace', 'Thistle', 'pink']
DEFAULT_FORCE_TOLERANCE = (0.0001 * u.hartree / u.bohr).defunits() # taken from GAMESS OPTTOL keyword
# Precompute odd factorial values (N!!)
ODD_FACTORIAL = {0: 1} # by convention
_ofact = 1
for _i in range(1, 20, 2):
_ofact *= _i
ODD_FACTORIAL[_i] = float(_ofact)
def print_environment():
"""For reporting bugs - spits out the user's environment"""
import sys
version = {}
for pkg in 'moldesign IPython ipywidgets jupyter matplotlib numpy docker pyccc distutils' \
'nbmolviz jupyter_client jupyter_core pint Bio openbabel simtk pyscf pip setuptools'\
.split():
try:
module = __import__(pkg)
except ImportError as e:
version[pkg] = str(e)
else:
try:
version[pkg] = module.__version__
except AttributeError as e:
version[pkg] = str(e)
env = {'platform': sys.platform,
'version': sys.version,
'prefix': sys.prefix}
try:
import platform
env['machine'] = platform.machine()
env['linux'] = platform.linux_distribution()
env['mac'] = platform.mac_ver()
env['windows'] = platform.win32_ver()
env['impl'] = platform.python_implementation()
env['arch'] = platform.architecture()
env['system'] = platform.system()
env['python_build'] = platform.python_build()
env['platform_version'] = platform.version()
except Exception as e:
env['platform_exception'] = str(e)
print(json.dumps({'env': env,
'versions': version}))
| Python |
3D | Autodesk/molecular-design-toolkit | moldesign/data/biochemical.py | .py | 4,255 | 145 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TODO: synchronize this with the Chemical Component Dictionary
BASES = 'C T G U A I'.split()
ALL_BASES = BASES+['%s5'%_b for _b in BASES]+['%s3'%_b for _b in BASES]
DBASES = ['D%s'%_b for _b in ALL_BASES]
RBASES = ['R%s'%_b for _b in ALL_BASES]
# Add terminal base names (sometimes used by forcefields)
for _nucleic_list in DBASES, RBASES:
for _base in list(_nucleic_list):
_nucleic_list.append(_base+'3')
_nucleic_list.append(_base+'5')
BACKBONES = {'dna': set(("P OP1 OP2 O5' O4' C5' C4' C3' O3' C2' C1' H1' H2'' H2' H3' H4' H5' H5'' "
"HO5' HO3'").split()),
'protein': set("N CA C O OXT H HA HA2 HA3 H2 H3".split())}
RESIDUE_ONE_LETTER = dict(ALA="A", ASX="B", CYS="C", ASP="D",
GLU="E", PHE="F", GLY="G", HIS="H", ILE="I",
LYS="K", LEU="L", MET="M", ASN="N", PRO="P",
GLN="Q", ARG="R", SER="S", THR="T", VAL="V",
TRP="W", XAA="X", TYR="Y", GLX="Z")
RESIDUE_CODE_TO_NAME = {v:k for k,v in RESIDUE_ONE_LETTER.items()}
BIOPOLYMER_TYPES = set('dna rna protein'.split())
CHAIN_MONOMER_NAMES = {'dna': 'dna base',
'protein': 'amino acid',
'unkonwn': 'small molecule',
'water': 'water',
'solvent': 'solvent',
'ion': 'ion'}
AMINO_NAMES = {
"ALA": "Alanine",
"ARG": "Arginine",
"ASN": "Asparagine",
"ASP": "Aspartic acid",
"ASX": "ASP/ASN ambiguous",
"CYS": "Cysteine",
"CYX": "Cystine",
"CYM": "Cysteine anion",
"GLN": "Glutamine",
"GLU": "Glutamic acid",
"GLX": "GLU/GLN ambiguous",
"GLY": "Glycine",
"HIS": "Histidine",
"HIE": "Histidine epsilon tautomer",
"HID": "Histidine delta tautomer",
"HIP": "Histidine ion",
"ILE": "Isoleucine",
"LEU": "Leucine",
"LYS": "Lysine",
"MET": "Methionine",
"PHE": "Phenylalanine",
"PRO": "Proline",
"SER": "Serine",
"THR": "Threonine",
"TRP": "Tryptophan",
"TYR": "Tyrosine",
"VAL": "Valine",
"UNK": "Undetermined"}
NUCLEIC_NAMES = {
'A': 'Adenine',
'C': 'Cytosine',
'G': 'Guanine',
'I': 'Inosine', # TODO: verify this one
'T': 'Thymine',
'U': 'Uracil'}
IONS = {'NA': 'Na+',
'K': 'K+',
'MG': 'Mg+2',
'CA': 'Ca+2',
'F': 'F-',
'CL': 'Cl-',
'BR': 'Br-',
'I': 'I-'}
RESTYPES = dict(
protein=set(AMINO_NAMES),
water={'HOH', 'H2O'},
solvent=set(),
dna=set(DBASES),
rna=set(RBASES),
unknown=set(),
ion=set(IONS))
def _make_residue_type_dict():
rdt = {None: 'placeholder'}
for typename, namelist in RESTYPES.items():
for resname in namelist:
rdt[resname] = typename
return rdt
RESIDUE_TYPES = _make_residue_type_dict()
def _make_residue_description_dict():
rd = dict(AMINO_NAMES)
for base, name in AMINO_NAMES.items():
rd['N'+name] = name+' (N-terminal)'
rd['C'+name] = name+' (C-terminal)'
rd.update(NUCLEIC_NAMES)
for base, name in NUCLEIC_NAMES.items():
rd['D'+base] = name+" (DNA)"
rd['D'+base+'5'] = name+" (DNA, 5'-end)"
rd['D'+base+'3'] = name+" (DNA, 3'-end)"
rd['R'+base] = name+" (RNA)"
rd['R'+base+'5'] = name+" (RNA, 5'-end)"
rd['R'+base+'3'] = name+" (RNA, 3'-end)"
return rd
RESIDUE_DESCRIPTIONS = _make_residue_description_dict()
| Python |
3D | Autodesk/molecular-design-toolkit | docs/generate_package_api.py | .py | 4,738 | 157 | #!/usr/bin/env python
""" Auto-generate rst files for the MDT API.
This is more or less our customized replacement for sphinx-apidoc. The goal here is to
organize the auto-generated API documentation in a more user-focused way - to clearly group
the classes and functions exposed by various parts of the MDT *runtime* API.
"""
import os
import types
import collections
SubMod = collections.namedtuple('MDTSubModule', 'modname name toplevel')
SUBMODULES = [SubMod('geom', 'Geometry', True),
SubMod('widgets', 'Widgets', False),
SubMod('tools', 'Tools', True),
SubMod('models', 'Energy models', False),
SubMod('integrators', 'Integrators', False),
SubMod('data', 'Data', False)]
DOCPATH = '_mdt_api'
IGNORES = set(('toplevel exports __builtins__ __file__ __name__ __package__ __path__ __module__ '
'__all__').split())
def main():
if not os.path.exists(DOCPATH):
os.mkdir(DOCPATH)
for m in SUBMODULES:
rstfile = os.path.join(DOCPATH, 'moldesign.%s.rst' % m.modname)
with open(rstfile, 'w') as outfile:
print >> outfile, document_module(m)
print ' %s' % rstfile
def document_module(submod):
""" Create a string with appropriate Autodoc directives for a given submodule
Args:
submod (SubMod): description of the submodule
Returns:
str: RST file content
"""
module = getattr(moldesign, submod.modname)
moddoc, mod_members, allnames = get_module_members(module, submod)
docname = '%s API' % submod.name
output = ['='*len(docname), docname, '='*len(docname), '']
sections = collections.OrderedDict([('Classes', []),
('Functions', []),
('Data', []),
('Unexported API', [])
])
if moddoc is not None:
output.extend([moddoc, ''])
for attrname, attr in mod_members:
if submod.toplevel and attrname in allnames:
path = 'moldesign'
else:
path = 'moldesign.%s' % submod.modname
directive = get_autodoc_directive(attr, attrname, path)
if submod.toplevel and attrname not in allnames:
sections['Unexported API'].extend(directive)
elif isinstance(attr, type):
sections['Classes'].extend(directive)
elif isinstance(attr, types.FunctionType):
sections['Functions'].extend(directive)
else:
sections['Data'].extend(directive)
for key, lines in sections.iteritems():
if not lines: continue
output.extend([key, '='*len(key), ''])
output.extend(lines)
return '\n'.join(output)
def get_module_members(module, submod):
""" Make a list of the attributes to document for this module
Returns:
(str): docstring for the module (or None if it doesn't have one)
List[(str, object)]: list of tuples of the form (attribute name, attribute reference)
set(str): list of attribute names in the __all__ variables
"""
attrnames = dir(module)
mod_members = []
for attrname in attrnames:
if attrname in IGNORES: continue
attr = getattr(module, attrname)
if isinstance(attr, types.ModuleType): continue
if attrname == '__doc__':
moddoc = attr
continue
else:
mod_members.append((attrname, attr))
mod_members.sort()
if hasattr(module, '__all__') and submod.toplevel:
allnames = set(module.__all__)
else:
allnames = set(attrnames)
return moddoc, mod_members, allnames
def get_autodoc_directive(attr, attrname, path):
""" Create autodoc directive for a given object in the module
Returns:
List[str]: list of lines (to be joined via ``'\n'.join()``)
"""
attrdocname = '``%s`` %s'%(attrname, _obj_description(attr))
directive = [attrdocname,
'-'*len(attrdocname), '',
'.. %s:: %s.%s'%(_autorst(attr), path, attrname)]
if isinstance(attr, type):
directive.append(' :members:\n :undoc-members:\n :show-inheritance:')
directive.append('')
return directive
def _obj_description(o):
if isinstance(o, type):
return 'class'
elif isinstance(o, types.FunctionType):
return 'function'
else:
return ''
def _autorst(o):
if isinstance(o, type):
return 'autoclass'
elif isinstance(o, types.FunctionType):
return 'autofunction'
else:
return 'autoattribute'
if __name__ == '__main__':
import moldesign
main() | Python |
3D | Autodesk/molecular-design-toolkit | docs/autogen_api.sh | .sh | 70 | 5 | #!/bin/bash
sphinx-apidoc -M -o _moldesign_api ../moldesign --force
| Shell |
3D | Autodesk/molecular-design-toolkit | docs/conf.py | .py | 10,517 | 320 | # -*- coding: utf-8 -*-
#
# Molecular Design Toolkit documentation build configuration file, created by
# sphinx-quickstart on Mon Apr 18 11:27:36 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
os.environ['SPHINX_IS_BUILDING_DOCS'] = "1"
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
mathjax_path = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# 1.3 = napoleon integration = google-style docstrings
needs_sphinx = '1.3'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autosummary',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
'sphinx.ext.githubpages']
# def skip(app, what, name, obj, skip, options):
# print options
# if name == "__init__":
# return False
# return skip
#
#
# def setup(app):
# app.connect("autodoc-skip-member", skip)
autoclass_content = 'class'
autodoc_member_order = 'alphabetical'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Molecular Design Toolkit'
copyright = u'2016 Autodesk Research'
author = u'Aaron Virshup, Dion Amago, Justin McCandless, Malte Tinnus (Bio/Nano Research Group, Autodesk)'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
import moldesign
# The short X.Y version.
version = '0.7.3'
# The full version, including alpha/beta/rc tags.
release = '0.7.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#html_title = u'Molecular Design Toolkit v.2'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['img']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'moldesign-doc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'MolecularDesignToolkit.tex', u'Molecular Design Toolkit Documentation',
u'Aaron Virshup, BioNano Research Group, Autodesk', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'moleculardesigntoolkit', u'Molecular Design Toolkit Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'MolecularDesignToolkit', u'Molecular Design Toolkit Documentation',
author, 'MolecularDesignToolkit', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
| Python |
3D | Autodesk/molecular-design-toolkit | deployment/test-version-number.sh | .sh | 436 | 23 | #!/usr/bin/env bash
set -e
if [ -z "${CI_BRANCH}" ]; then
echo "Error: env var CI_BRANCH not set"
exit 1
fi
pyversion=$(python -m moldesign version | tail -n 1)
echo "Expecting moldesign==${CI_BRANCH}"
echo "Found moldesign==${pyversion}"
if [ "${pyversion}" == "${CI_BRANCH}" ]; then
echo "All good"
exit 0
else
echo "Error: moldesign package version '${pyversion}' differs from its Git tag '${CI_BRANCH}'"
exit 1
fi
| Shell |
3D | Autodesk/molecular-design-toolkit | deployment/push-coverage.sh | .sh | 383 | 13 | #!/usr/bin/env bash
# combines coverage from all test environments and pushes it to coveralls.io
set -e
mkdir -p /opt/reports/env-coverage
if $(cp /opt/reports/env-coverage/coverage.* /opt/reports/); then
coverage combine /opt/reports/coverage.*
coveralls || echo "Failed to upload coverage to coveralls.io"
else
echo "No coverage files found, skipping coveralls upload"
fi
| Shell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.