Given a CrystalOptimizer atoms position being optimized independently, the system’s symmetry will be reduced to P1. This function can be used to get the best fit of the current structure to original symmetry and hence getting a sitesSymmetry solution
OP (CrystalOptimizer): the crystal optimizer instance whose current unitcell box coordinates must be fitted back onto its original sites symmetry
result (collections.OrderedDict): dictionary mapping every
sites-symmetry key to a fit dictionary with keys 'xyz'
(fitted x, y, z symmetry expressions or values), 'site_atoms'
(the site’s symmetry-equivalent atoms), 'symmetry_rank'
(rank of the fitted symmetry, 0 to 3), 'fitted' (boolean,
whether a least-squares solution was found), 'box_residuals'
and 'real_residuals' (per atom residual arrays in box and
real coordinates) and 'box_absolute_total_error' and
'real_absolute_total_error' (summed absolute residuals)
result = get_sites_symmetry_fit(OP=OP)
# get sites symmetry from result
sites = OrderedDict()
for ssk in result:
v = result[ssk]
k = (ssk[0],ssk[1],v['xyz'])
sites[k] = v['site_atoms']
Parse and normalize a user given delta/limits/chain optimization
parameter definition into a consistent (value, chain, limits) form.
The input value can be given in multiple flexible forms: a boolean,
a chain name string, a single number, a list/tuple of 2 to 5 items or
a dictionary with 'deltas', 'limits' and 'chain' keys. This
function validates and clips it against the allowed maxDelta and
maxLimits bounds.
name (str): parameter name used in raised errors and warnings
value (bool, str, number, list, tuple, dict): the raw parameter value to parse
defaultDelta (list, tuple): default (lower, upper) delta bounds
used when value is True or only a chain/deltas is missing
defaultLimits (list, tuple): default (lower, upper) limits
used when value does not explicitly define limits
maxDelta (tuple): (lower, upper) maximum allowed delta bounds. None means no bound enforced on that side
maxLimits (tuple): (lower, upper) maximum allowed limits bounds. None means no bound enforced on that side
_fixLimits (boolean): if True, out of bound values are silently clipped and logged instead of raising an assertion error
value (list): normalized [lower, upper] delta bounds
chain (None, str): chain name if given, None otherwise
limits (list): normalized [lower, upper] limits
Bases: object
Generate optimization and update source code for a chain of atoms that must move together as a rigid unit, using one of the supported move types: random walk, random translation, translation along an axis, translation along a symmetry axis, translation in a plane, or random rotation.
An instance is built per chain by create_optimization_code() and
exposes optimize_code() and update_code() which delegate
to the private generator matching the chain’s mgType.
###############################################################
####################### TEST CHAINED MOVE #####################
path = '/Users/bachiraoun/Desktop/tylenol/Monoclinic_acetaminophen.cif'
rdfp = '/Users/bachiraoun/Desktop/tylenol/tylenol.rdf'
# create engine
E = fullrmc.Engine(path='/Users/bachiraoun/Desktop/test.stc', freshStart=True)
#E.read_cif_set_pdb(path)
E.save()
E.optimizer_add_configuration('test')
E.optimizer_set_used_configuration('test')
#E.remove_optimization('test')
E.optimizer_set_structure(cif=path,
scaleup=(1,1,1),
supercell=(5,5,5))
self = OP = E.optimizer
E.optimizer_set_experimental_constraint(experimentalData=rdfp)
self.experimentalConstraint._ExperimentalConstraint__scaleFactor = 0.017627664
E.optimizer_set_distances_constraint(distances=(0.8,1.6))
redef = {'M0': [[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76],
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77],
[2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62, 66, 70, 74, 78],
[3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75, 79]]}
E.optimizer_set_stucture_redefinitions(moleculesDefinition=redef)
######## TEST
atomChainsRot = {}
atomChainsTrs = {}
atomChainsTra = {}
atomChainsTrp = {}
atomChainsTrsym = {}
for atIdx, molIdx in enumerate(E.optimizer.unitcellMoleculesIndex):
ad = atomChainsRot.setdefault(str(molIdx), {'indexes':[], 'generator_type':'random_rotation'})
ad['indexes'].append(atIdx)
ad = atomChainsTrs.setdefault(str(molIdx), {'indexes':[], 'generator_type':'random_translation'})
ad['indexes'].append(atIdx)
ad = atomChainsTra.setdefault(str(molIdx), {'indexes':[], 'generator_type':'translation_along_axis'})
ad['indexes'].append(atIdx)
ad = atomChainsTrp.setdefault(str(molIdx), {'indexes':[], 'generator_type':'translation_in_plane'})
ad['indexes'].append(atIdx)
ad = atomChainsTrsym.setdefault(str(molIdx), {'indexes':[], 'generator_type':'translation_along_symmetry_axis'})
ad['indexes'].append(atIdx)
BCOORDS = np.copy(OP.engine.boxCoordinates)
for _ in range(100):
### random translation
#E.optimizer_run_optimization(atomChains=atomChainsTrs)
#E.optimizer_set_optimization_result(_logData=False)
### random rotation
#E.optimizer_run_optimization(atomChains=atomChainsRot)
#E.optimizer_set_optimization_result(_logData=False)
### translation along axis
#E.optimizer_run_optimization(atomChains=atomChainsTra)
#E.optimizer_set_optimization_result(_logData=False)
### translation in plane
#E.optimizer_run_optimization(atomChains=atomChainsTrp)
#E.optimizer_set_optimization_result(_logData=False)
### translation along symmetry
E.optimizer_run_optimization(atomChains=atomChainsTrsym)
E.optimizer_set_optimization_result(_logData=False)
################
basisVectors = OP.unitcellBC.get_vectors().astype(FLOAT_TYPE)
boxCoords = np.copy(OP.engine.boxCoordinates[OP.unitcellIndexes])
ucBoxCoords = OP.unitcellBC.real_to_box_array( OP.engine.boundaryConditions.box_to_real_array(boxCoords) ).astype(FLOAT_TYPE)
d = unitcell_distances(boxCoords = ucBoxCoords,
basisVectors = basisVectors,
indexes0 = OP.distancesConstraint["indexes0"],
indexes1 = OP.distancesConstraint["indexes1"],
lowerBound = OP.distancesConstraint["lowerBound"],
upperBound = OP.distancesConstraint["upperBound"])[0]
diff = BCOORDS-OP.engine.boxCoordinates
print("--------------> "+str(d)+" "+str(np.sum(np.abs(diff))))
Generate the optimization source code snippet for this chain’s
selected move type (random walk, random/along-axis/in-plane/along-
symmetry-axis translation, or random rotation), as chosen at
construction time via mgType.
v_index (int): index of the first free optimization variable to allocate for this chain’s move
indent (int): indentation level (multiplied by 4 spaces) to apply to the generated code block
v_index (int): updated variable index after allocating this chain’s variables
code (str): the generated optimization code snippet(s), as returned by the underlying per-move-type generator
Generate the update source code snippet applying this chain’s selected move type result back onto the engine’s box coordinates.
uv_index (int): index of the first free update variable to allocate for this chain’s move
indent (int): indentation level (multiplied by 4 spaces) to apply to the generated code block
uv_index (int): updated variable index after allocating this chain’s variables
code (str): the generated update code snippet, as returned by the underlying per-move-type generator
Create structure optimization and update code.
Builds two dynamically compiled Python source snippets, one that
computes a trial move for every requested optimization target
(optimize_function) and one that applies an accepted solver
result back onto OP and its engine (update_function), along
with the initial values, bounds and limits needed to drive a
differential evolution style solver.
Position related parameters (siteIndexes, atomIndexes and
atomChains) are mutually exclusive: only one of them may be given
at a time. All correction-like parameters (scale, resolution,
qmax, thermals, delta1, delta2, qbroad, symmetry
ax…``cz``, atomsWeight and pairsWeight) share the same
flexible value format handled by get_delta_limits_chain():
False disables the target, True uses its default delta, and a
number, tuple or dict can be given to set custom delta bounds,
limits and/or a shared optimization “chain” name.
OP (CrystalOptimizer, StochasticEngineOptimizer): the optimizer instance whose structure and/or experimental constraint corrections are being wired into optimization variables
siteIndexes (boolean, list): crystal sites (symmetry
equivalent atom groups) whose xyz position is optimized
independently. If False, disabled. If True, all sites are
optimized using the default (-0.1, 0.1) delta on each axis.
If a list, items are site indexes or tuples of
(index, deltaX, deltaY, deltaZ) where each delta follows
the get_delta_limits_chain() value format
atomIndexes (boolean, list): individual unitcell atom indexes
(P1, no symmetry) whose position is optimized independently.
Same True/False/list format as siteIndexes
atomChains (boolean, dict): group atoms into named rigid
chains that move together via a
ChainedAtomsOptimizerGenerator. If True, all
unitcell atoms are optimized as a single chain using random
translation. If a dict, keys are chain names and values are
dictionaries with 'indexes' (atom indexes list),
'generator_type' (move type string: 'random_walk',
'random_translation', 'translation_along_axis',
'translation_along_symmetry_axis',
'translation_in_plane' or 'random_rotation') and
'kwargs' (generator specific keyword arguments)
scale (boolean, number, tuple, dict): experimental constraint scale factor optimization definition
resolution (boolean, number, tuple, dict): instrument resolution correction optimization definition
qmax (boolean, number, tuple, dict): Qmax correction optimization definition
thermals (boolean, number, tuple, dict): isotropic thermal (Debye-Waller) vibration correction factors optimization definition
delta1 (boolean, number, tuple, dict): anisotropic thermal vibration correction ‘delta1’ parameter optimization definition
delta2 (boolean, number, tuple, dict): anisotropic thermal vibration correction ‘delta2’ parameter optimization definition
qbroad (boolean, number, tuple, dict): anisotropic thermal vibration correction ‘qbroad’ parameter optimization definition
ax, ay, az, bx, by, bz, cx, cy, cz (boolean, number, tuple, dict): the nine components of the unitcell’s a, b and c basis vectors, each independently optimizable, allowing symmetry-constrained unitcell parameters refinement
atomsWeight (boolean, number, tuple, dict): per-element or per-atom scattering weighting corrections optimization definition
pairsWeight (boolean, number, tuple, dict): per-atom-pair partial scattering weighting corrections optimization definition
defaultLimits (None, dict): optional overrides of the default
(None, None) limits used for any of the above named
optimization targets, keyed by parameter name
optCode (str): source code defining
optimize_function(v, OP, startStruStdError, startStdError, FLOAT_TYPE, PRECISION)
which computes a trial move and its resulting standard error
for a given solver variables vector v
updCode (str): source code defining
update_function(result, OP, FLOAT_TYPE, PRECISION) which
applies an accepted solver result back onto OP and its
engine
deltas (list): per optimization variable raw delta bounds
bounds (list): per optimization variable (lower, upper) solver bounds
limits (list): per optimization variable physical value limits
x0 (list): per optimization variable initial value
varTypes (list): per optimization variable category string,
one of 'symmetry', 'site', 'atom',
'chainedAtom', 'scale', 'resolution',
'thermal', 'qmax', 'atomsWeight' or
'pairsWeight'
varNames (list): per optimization variable name or grouping
label used while generating optCode and updCode
parameters (dict): the normalized input parameters as given to this function, keyed by parameter name
Bases: object
This is the main implementation to perform PDF-GUI like structure refinement using differential evolution and normal stochastic refinement
name (string): optimizer user defined name
# import fullrmc's InterceptHook
from fullrmc import Engine
# create engine
E = fullrmc.Engine(path='/path/to/engine.stc', freshStart=True)
E.save()
# add optimization
E.optimizer_add_configuration('test')
# use optimizastion
E.optimizer_set_used_configuration('test')
# add structure to used optimization
cif = {'symOps': [('x', 'y', 'z'), ('-x', '-y', '-z'), ('-x', '-y', 'z'),
('x', 'y', '-z'), ('-x', 'y', '-z'), ('x', '-y', 'z'),
('x', '-y', '-z'), ('-x', 'y', 'z'), ('z', 'x', 'y'),
('-z', '-x', '-y'), ('z', '-x', '-y'), ('-z', 'x', 'y'),
('-z', '-x', 'y'), ('z', 'x', '-y'), ('-z', 'x', '-y'),
('z', '-x', 'y'), ('y', 'z', 'x'), ('-y', '-z', '-x'),
('-y', 'z', '-x'), ('y', '-z', 'x'), ('y', '-z', '-x'),
('-y', 'z', 'x'), ('-y', '-z', 'x'), ('y', 'z', '-x'),
('y', 'x', '-z'), ('-y', '-x', 'z'), ('-y', '-x', '-z'),
('y', 'x', 'z'), ('y', '-x', 'z'), ('-y', 'x', '-z'),
('-y', 'x', 'z'), ('y', '-x', '-z'), ('x', 'z', '-y'),
('-x', '-z', 'y'), ('-x', 'z', 'y'), ('x', '-z', '-y'),
('-x', '-z', '-y'), ('x', 'z', 'y'), ('x', '-z', 'y'),
('-x', 'z', '-y'), ('z', 'y', '-x'), ('-z', '-y', 'x'),
('z', '-y', 'x'), ('-z', 'y', '-x'), ('-z', 'y', 'x'),
('z', '-y', '-x'), ('-z', '-y', '-x'), ('z', 'y', 'x')],
'atoms': [('Ba', 'Ba', 0.0, 0.0, 0.0, 1.0),
('Ti', 'Ti', 0.5, 0.5, 0.5, 1.0),
('O', 'O', 0.5, 0.5, 0.0, 1.0)],
'unitcellBC': [[4.0075, 0.0, 0.0],
[0.0, 4.0075, 0.0],
[0.0, 0.0, 4.0075]]
}
E.optimizer_set_structure(cif=cif, scaleup=None, supercell=(20, 20, 20))
# add experimental pdf constraint
E.optimizer_set_experimental_constraint(experimentalData='/path/to/pdf.dat')
# add distance constraint
E.optimizer_set_distances_constraint(distances=1.5)
# optimize structure
for cycle in range(5):
print("-----------------\nCYCLE {c}\n-----------------".format(c=cycle))
# scale and resolution
E.optimizer_run(scale=True, resolution=True)
E.optimizer_set_optimization_result()
# atom positions
E.optimizer_run(atomIndexes=True)
E.optimizer_set_optimization_result()
# thermals
E.optimizer_run(thermals=True)
E.optimizer_set_optimization_result()
# qmax
E.optimizer_run(qmax=True)
E.optimizer_set_optimization_result()
# symmetry x axis
E.optimizer_run(ax=True,ay=True,az=True)
E.optimizer_set_optimization_result()
# symmetry y axis
E.optimizer_run(bx=True,by=True,bz=True)
E.optimizer_set_optimization_result()
# symmetry z axis
E.optimizer_run(cx=True,cy=True,cz=True)
E.optimizer_set_optimization_result()
# anisotropic thermals
E.optimizer_run(delta1=True,delta2=True,qbroad=True)
E.optimizer_set_optimization_result()
Allowed maximum unitcell size
Main structure dictionary information
Optimized structure dictionary built from the current engine’s box coordinates, expressed in the unitcell referential.
optimizedStructure (None, dict): None if no engine is set,
otherwise a dictionary with keys 'symOps' (identity
symmetry operation, P1), 'unitcellBC' (unitcell basis
vectors as list of lists) and 'atoms' (list of
(element, name, x, y, z) tuples in the unitcell box
referential)
get refined structure parameters
Optimizer user defined name
optimizer parent engine path
Get sites symmetry best fit. When atoms are optimized independently system’s symmetry reduces to P1. This will get the best fit of the system’s symmetry to the one of the original system
Get needed supercell size to cover maxDist
maxDist (None, number): If None, experimental data maximum R-range will be used
tolerance (number): tolerance in R above maxDist. If maxDist is not None, tolerance will be ignored
_bc (None, PeriodicBoundaries): internal flag. Boundary conditions to compute the minimum supercell against. If None, the optimizer’s own unitcell boundary conditions are used
supercell (list): supercell size along a, b, and c
Get pdb of optimized structure
supercell (tuple): defines how big of a supercell is needed
contiguous (boolean): get contiguous molecules if molecules are defined
_optimizedStructure (boolean, dict): internal flag. If a
dict is given, it is used directly as the structure to
build the pdb from. If True, the current
optimizedStructure is used. If False, the original
(pre-optimization) structure is used instead
pdb (pdbparser.pdbparser): the pdb instance
User defined optimizer name
name (str): optimizer name
Set engine path
path (str): engine path
Reset optimizer by removing any optimized structure
Set optimization structure
cif (string, dict, CrystalMaker): cif CrystalMaker structure. If string is given it must point to a cif file path. If a dict is given, it will be used to build an initital structure using pdbparser CrystalBuilder
scaleup (None, tuple): if given this will be used to create a bigger unitcell from the main unitcell. This can be used to refine more complex structures where inter-unitcells anisotropic correlations are present. The new constructed unitcell will be used later in the supercell creation.
supercell (None, tuple): defines how big of a supercell is needed. if None supercell will be automatically computed used optimizationDistance or currently defined supercell will be used and if both failed, (10,10,10) will be used
optimizationDistance (None, bool, number): set optimization distance so supercell will be computed automatically. If None, optimizationDistance value won’t be changed. If False, given supercell will be used. If True, supercell will be automatically re-computed according to experimental data maximum distance If number, this will be the maximum distance
redefinitions (None, dict): kwargs used to call set_stucture_redefinitions method and redefine structure atoms and molecules
distances (False, number, tuple, dict): distances rigid
constraint definition forwarded as is to
set_distances_constraint(). False disables the
constraint
bonds (False, number, tuple, dict): bonds rigid constraint
definition forwarded as is to set_bonds_constraint().
False disables the constraint
angles (False, number, tuple, dict): angles rigid
constraint definition forwarded as is to
set_angles_constraint(). False disables the
constraint
dihedrals (False, number, tuple, dict): dihedrals rigid
constraint definition forwarded as is to
set_dihedrals_constraint(). False disables the
constraint
impropers (False, number, tuple, dict): impropers rigid
constraint definition forwarded as is to
set_impropers_constraint(). False disables the
constraint
Set structure re-definitions. Used keyword arguments are ‘atomsName’, ‘moleculesName’, ‘moleculesIndex’ and values must be lists of the same length as unitcell number of atoms. ‘moleculesDefinition’ is another kwarg that can be given and this must be a dictionary of molecules name as keys and valuesare list of lists of atom indexes per molecule. All other kwargs will be stored but ignored
_resetConstraints (boolean): internal flag. If True, also reset the bonds, angles, dihedrals and impropers rigid constraints definitions after redefining the structure. The distances constraint is always reset regardless of this flag
_raise (boolean): internal flag. If True, raise an exception when the given redefinitions are invalid instead of logging a warning and keeping the previous definitions
**kwargs: redefinition keyword arguments as described above
# import Collection
from fullrmc.Core import Collection
# get unitcell coordinates
basisVectors = self.maker.unitcellBC.get_vectors().astype(np.float32)
boxCoords = np.array(self.maker.unitcellAttributes['boxCoords'], dtype=np.float32)
elements = self.maker.unitcellAttributes['elements']
names = self.maker.unitcellAttributes['names']
# create elements index
elementsLUT = {}
for el in sorted(set(elements)):
elementsLUT[el] = len(elementsLUT)
elementsIndex = np.array([elementsLUT[el] for el in elements], dtype=np.int32)
# create bonds matrix
bonds = np.zeros( (len(elementsLUT), len(elementsLUT)), dtype=np.float32 )
for el1 in elementsLUT:
idx1 = elementsLUT[el1]
for el2 in elementsLUT:
idx2 = elementsLUT[el2]
bonds[idx1,idx2] = Collection.get_bond_length(el1, el2)
# get molecules
bondAtoms,molecules, moleculesByKey = Collection.parse_molecules_from_box_of_atoms(boxCoords=boxCoords,
basisVectors=basisVectors,
elementsIndex=elementsIndex,
bonds=bonds,
maxBonds = 4,
ncores = 1)
# recreate molecules
moleculesIndex = [0]*len(elements)
moleculesName = ['mol']*len(elements)
atomsName = list(names)
namesLUT = {}
molNameIndex = 0
molIdx = 0
for k in moleculesByKey:
mols = moleculesByKey[k]
molNm = 'M%i'%molNameIndex
molNameIndex += 1
indexes = sorted(mols[0][None])
newNames = []
for i in indexes:
el = elements[i]
_ = namesLUT.setdefault(el, -1)
namesLUT[el] += 1
newNames.append('%s%s'%(el, namesLUT[el]))
for m in mols:
indexes = sorted(m[None])
for idx, i in enumerate(indexes):
moleculesName[i] = molNm
moleculesIndex[i] = molIdx
atomsName[i] = newNames[idx]
molIdx += 1
self.set_stucture_redefinitions(unitcellAtomsName = atomsName,
unitcellMoleculesIndex = moleculesIndex,
unitcellMoleculesName = moleculesName)
redefinitions (None, dict): None if no kwargs were given,
otherwise a dictionary with keys 'unitcellAtomsName',
'unitcellMoleculesName' and 'unitcellMoleculesIndex'
reflecting the currently applied redefinitions, whether or
not the given kwargs were successfully applied
Set unitcell atoms coordinates
boxCoords (numpy.ndarray): unitcell atoms box coordinates. Given array must have the shape of (n,3) where n equals to number of atoms in unitcell is indexes is None or the same length of indexes list.
indexes (None, list,tuple): atoms indexes in unitcell. If None, all unitcell atoms are updated.
inUnicellBoxReferential (bool): whether given box coordinates are in unitcell box coordinates referential.
_recompute (boolean): internal flag. If True, recompute the experimental constraint data after updating the coordinates
Set unitcell atoms coordinates given sites
sites (None, dictionary): sites atom position. If None, original sites positions will be restored
_recompute (boolean): internal flag. If True, recompute the experimental constraint data after updating the sites positions
sites = {(0, 'Ba', (0.0, 0.0, 0.0)): [(0, ('x', 'y', 'z'))],
(1, 'Ti', (0.5, 0.5, 0.5)): [(1, ('x', 'y', 'z'))],
(2, 'O', (0.479, 0.522, -0.0145)): [(2, ('x', 'y', 'z')), (3, ('z', 'x', 'y')), (4, ('y', 'z', 'x'))]}
self.set_unitcell_sites_position(sites=sites)
Set unitcell boundary conditions
boundaryConditions (PeriodicBoundaries, numpy.ndarray, number): The unitcell new boundary conditions. If numpy.ndarray is given, it must be pass-able to a PeriodicBoundaries instance. Normally any real numpy.ndarray of shape (1,), (3,1), (9,1), (3,3) is allowed. If number is given, it’s like a numpy.ndarray of shape (1,), it is assumed as a cubic box of box length equal to number.
_recompute (boolean): internal flag. If True, recompute the experimental constraint data after updating the boundary conditions
Given parameters set and update structure
data (dict): constraint data dictionary
total (numpy.ndarray): constraint total pair distribution function
standardError (float): constraint standard error
Set optimization distance
value (bool, number): the optimization distance. If a number is given, the supercell will be automatically recomputed to cover at least this distance.
_keepAtomsPositions (boolean): internal flag. If True, preserve the current atoms box coordinates across the supercell rebuild triggered by this distance change
_force (boolean): internal flag. If True, apply the change
even if value already equals the current
optimizationDistance
_recompute (boolean): internal flag. If True, recompute the experimental constraint data after applying the change
result (boolean): whether optimization distance was reset or not
Reset structure supercell
supercell (int, list, tuple): supercell along x,y and z
_keepAtomsPositions (boolean): internal flag. If True, preserve the current atoms box coordinates across the supercell rebuild
_force (boolean): internal flag. If True, apply the change
even if supercell already equals the current supercell
_recompute (boolean): internal flag. If True, recompute the experimental constraint data after applying the change
result (boolean): whether supercell was reset or not
Reset structure scaleup
scaleup (int, list, tuple): scaleup along x,y and z used to create a bigger unitcell from the main unitcell
_keepAtomsPositions (boolean): internal flag, currently not implemented and forced to False regardless of the given value
_force (boolean): internal flag. If True, apply the change
even if scaleup already equals the current scaleup
_recompute (boolean): internal flag. If True, recompute the experimental constraint data after applying the change
result (boolean): whether scaleup was reset or not
Reset structure to the original atoms coordinates as given in CIF file
result (boolean): whether the structure was actually reset,
as returned by the underlying set_supercell() or
set_optimization_distance() call
Set distance constraint definition
distances (None, number, tuple, dictionary): atoms distances constraint definition. If number, it will be set for all atoms ‘inter’ If tuple, it must contain 2 numbers to set for all atoms respectively in ‘intra’ and ‘inter’
Set atomic bonds constraint definition
bonds (None, dictionary): atomic bonds definition.
Set atomic angles constraint definition
angles (None, dictionary): atomic angles definition
Set atomic dihedral angles constraint definition
First atom index of the first plane.
Second atom index of the first plane and first atom index of the second plane.
Third atom index of the first plane and second atom index of the second plane.
Fourth atom index of the second plane.
Set atomic improper angles constraint definition
item 1: angle improper atom by type (must be given)
item 2: angle plane ‘o’ origin atom by type (must be given)
item 3: angle plane ‘x’ atom by type used to calculated ‘Ox’ vector (must be given)
item 4: angle plane ‘y’ atom by type used to calculated ‘Oy’ vector (must be given)
item 5: angle lower bound in degrees (must be given)
item 6: angle upper bound in degrees (must be given)
Add pair distribution constraint
params (dict): Any set of parameters used to instanciate fullrmc.Constraint.PairDistributionConstraints.PairDistributionConstraint
constraint (PairDistributionConstraint): the created and attached experimental constraint instance
Add pair correlation constraint
params (dict): Any set of parameters used to instanciate fullrmc.Constraint.PairCorrelationConstraints.PairCorrelationConstraint
constraint (PairCorrelationConstraint): the created and attached experimental constraint instance
Add radial distribution constraint
params (dict): Any set of parameters used to instanciate fullrmc.Constraint.RadialDistributionConstraints.RadialDistributionConstraint
constraint (RadialDistributionConstraint): the created and attached experimental constraint instance
Add structure factor constraint
sfType (None, string): Structure factor constraint type. If None, StructureFactorConstraint is used. If ‘reduced’, ReducedStructureFactorConstraint is used. If ‘normalized’, NormalizedStructureFactorConstraint is used.
params (dict): Any set of parameters used to instanciate fullrmc.Constraint.StructureFactorConstraints.StructureFactorConstraint
constraint (StructureFactorConstraint, ReducedStructureFactorConstraint,
NormalizedStructureFactorConstraint): the created and
attached experimental constraint instance, its exact type
depending on sfType
Get distance constraint standard error.
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Get distance constraint computation result.
dataDict (boolean): If true, data will be transformed to full format
distances (None, numpy.ndarray): distances computed array
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Get bonds constraint standard error.
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Plot distances constraint computation result as a pie chart of per-definition standard errors.
data (None, dict): Pre-computed distances data as returned
by get_distances_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine
figure (matplotlib.figure.Figure): the plotted figure
axes (matplotlib.axes.Axes): the plot axes
data (dict): the distances data used for plotting
Export distances constraint computation result to a delimited text file.
fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk
data (None, dict): Pre-computed distances data as returned
by get_distances_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine
lines (str): the exported data formatted as text
Get distances constraint per-definition statistical summary.
data (None, dict): Pre-computed distances data as returned
by get_distances_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine
summary (dict): per definition dictionary of count,
error_count, total_error, mean, median,
stddev, minimum and maximum values
Get bonds constraint standard error.
dataDict (boolean): If true, data will be transformed to full format
bonds (None, numpy.ndarray): bonds computed array
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Get bonds constraint standard error.
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Plot bonds constraint computation result as a pie chart of per-definition standard errors.
data (None, dict): Pre-computed bonds data as returned
by get_bonds_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine
figure (matplotlib.figure.Figure): the plotted figure
axes (matplotlib.axes.Axes): the plot axes
data (dict): the bonds data used for plotting
Export bonds constraint computation result to a delimited text file.
fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk
data (None, dict): Pre-computed bonds data as returned
by get_bonds_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine
lines (str): the exported data formatted as text
Get bonds constraint per-definition statistical summary.
data (None, dict): Pre-computed bonds data as returned
by get_bonds_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine
summary (dict): per definition dictionary of count,
error_count, total_error, mean, median,
stddev, minimum and maximum values
Get angles constraint computation result
dataDict (boolean): If true, data will be transformed to full format
angles (None, numpy.ndarray): angles computed array
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Get angles constraint standard error.
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Plot angles constraint computation result as a pie chart of per-definition standard errors.
data (None, dict): Pre-computed angles data as returned
by get_angles_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine
figure (matplotlib.figure.Figure): the plotted figure
axes (matplotlib.axes.Axes): the plot axes
data (dict): the angles data used for plotting
Export angles constraint computation result to a delimited text file.
fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk
data (None, dict): Pre-computed angles data as returned
by get_angles_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine
lines (str): the exported data formatted as text
Get angles constraint per-definition statistical summary.
data (None, dict): Pre-computed angles data as returned
by get_angles_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine
summary (dict): per definition dictionary of count,
error_count, total_error, mean, median,
stddev, minimum and maximum values
Get dihedrals constraint computation result
dataDict (boolean): If true, data will be transformed to full format
angles (None, numpy.ndarray): angles computed array
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Get dihedrals constraint standard error.
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Plot dihedrals constraint computation result as a pie chart of per-definition standard errors.
data (None, dict): Pre-computed dihedrals data as returned
by get_dihedrals_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine
figure (matplotlib.figure.Figure): the plotted figure
axes (matplotlib.axes.Axes): the plot axes
data (dict): the dihedrals data used for plotting
Export dihedrals constraint computation result to a delimited text file.
fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk
data (None, dict): Pre-computed dihedrals data as returned
by get_dihedrals_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine
lines (str): the exported data formatted as text
Get dihedrals constraint per-definition statistical summary.
data (None, dict): Pre-computed dihedrals data as returned
by get_dihedrals_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine
summary (dict): per definition dictionary of count,
error_count, total_error, mean, median,
stddev, minimum and maximum values
Get impropers constraint computation result
dataDict (boolean): If true, data will be transformed to full format
angles (None, numpy.ndarray): improper angles computed array
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Get impropers constraint standard error.
standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned
Plot impropers constraint computation result as a pie chart of per-definition standard errors.
data (None, dict): Pre-computed impropers data as returned
by get_impropers_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine
figure (matplotlib.figure.Figure): the plotted figure
axes (matplotlib.axes.Axes): the plot axes
data (dict): the impropers data used for plotting
Export impropers constraint computation result to a delimited text file.
fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk
data (None, dict): Pre-computed impropers data as returned
by get_impropers_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine
lines (str): the exported data formatted as text
Get impropers constraint per-definition statistical summary.
data (None, dict): Pre-computed impropers data as returned
by get_impropers_computation() with dataDict=True.
Computed automatically if None
*args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine
summary (dict): per definition dictionary of count,
error_count, total_error, mean, median,
stddev, minimum and maximum values
Run configuration optimization
Optimization target parameters (siteIndexes through
pairsWeight) share the exact same value format and meaning
as their namesakes in create_optimization_code(); see that
function’s docstring for full details.
siteIndexes (boolean, list): crystal sites position
optimization definition, mutually exclusive with
atomIndexes and atomChains
atomIndexes (boolean, list): individual atoms position
optimization definition, mutually exclusive with
siteIndexes and atomChains
atomChains (bool, dict): rigid chains of atoms
optimization definition, mutually exclusive with
siteIndexes and atomIndexes
scale (boolean, list): experimental constraint scale factor optimization definition
resolution (boolean, list): instrument resolution correction optimization definition
qmax (boolean, list): Qmax correction optimization definition
thermals (boolean, list): isotropic thermal vibration correction factors optimization definition
delta1 (boolean, list): anisotropic thermal vibration ‘delta1’ parameter optimization definition
delta2 (boolean, list): anisotropic thermal vibration ‘delta2’ parameter optimization definition
qbroad (boolean, list): anisotropic thermal vibration ‘qbroad’ parameter optimization definition
ax (boolean, list): unitcell basis vector a’s x component optimization definition
ay (boolean, list): unitcell basis vector a’s y component optimization definition
az (boolean, list): unitcell basis vector a’s z component optimization definition
bx (boolean, list): unitcell basis vector b’s x component optimization definition
by (boolean, list): unitcell basis vector b’s y component optimization definition
bz (boolean, list): unitcell basis vector b’s z component optimization definition
cx (boolean, list): unitcell basis vector c’s x component optimization definition
cy (boolean, list): unitcell basis vector c’s y component optimization definition
cz (boolean, list): unitcell basis vector c’s z component optimization definition
atomsWeight (boolean, list): per-element or per-atom scattering weighting corrections optimization definition
pairsWeight (boolean, list): per-atom-pair partial scattering weighting corrections optimization definition
setResultParams (boolean, None, dict): whether and how to
automatically call set_optimization_result() upon
completion. False disables the automatic call. True or
None uses default parameters. A number is used as
stdErrDiffThreshold. A dict is forwarded as keyword
arguments to set_optimization_result()
locker (None, pylocker.ServerLocker): optional locker
instance used to intercept user stop messages
('stop_optimizing', 'stop_optimizing_all') while
the solver is running
functionName (str): label identifying this optimization run, embedded in the generated optimization code for logging and debugging purposes
_lockerPopMessages (boolean): internal flag. If True, pop
and discard any pending stop messages from locker
before starting this optimization run
*args, **kwargs: other arguments or keywords arguments that will be fed to the differential evolution algorithm
result (dict): the final optimization result
Update the optimizer’s structure and experimental constraint
with the latest run_optimization() result, provided it
actually improved the standard error.
The update is refused (with a logged warning, no exception) when
no optimization ran yet, the run was unsuccessful, the result was
already applied ('set' flag True), the final standard error
could not be computed, the error increased, or the improvement did
not exceed stdErrDiffThreshold.
stdErrDiffThreshold (None, number): minimum required
standard error decrease (start - end) for the result to
be applied. None disables this check
_force (boolean): if True, bypass the standard error increase/threshold checks and apply the result anyway
_logData (boolean): if True, log a detailed summary of the updated structure and refined parameters
Bases: object
Stochastic engine optimizer. This can be used to optimized certain optimizable parameters of an engine such as an experimental constraint scaleFactor, isotropic and anisotropic thermal vibration coefficients, experimental q_max and experimental resolution correction
engine (fullrmc.Engine.Engine): fullrmc stochastic engine instance
name (str): optimizer name
Optimizer fullrmc stochastic engine
Optimizer user defined name
Set the fullrmc stochastic engine this optimizer operates on.
engine (fullrmc.Engine.Engine): the stochastic engine instance to attach to this optimizer
Detach the currently set experimental and engine constraints, resetting them so they can be repopulated at runtime.
User defined optimizer name
name (str): optimizer name
Run one or more cycles of optimization, where a cycle is an
ordered sequence of run_optimization() calls, each
targeting a different combination of correction parameters
(e.g. scale alone, then scale+resolution, then thermal
vibrations, etc). This progressively refines the experimental
constraint corrections rather than optimizing everything at once.
constraint (Constraint): the experimental constraint to
optimize, forwarded to every run_optimization() call
cycle (None, str, dict, list): the cycle definition. If
None, a default 10-step cycle progressively refining
scale, resolution, qmax and isotropic/anisotropic thermal
vibrations is used. If a string, it is used as
{cycle:True}, a single step targeting only that named
parameter. If a dict, it is used as a single optimization
step (kwargs forwarded to run_optimization()). If a
list, it must be a list of such dictionaries, one per
step, executed in order
ncycles (int): number of times the whole cycle sequence is repeated
locker (None, pylocker.ServerLocker): optional locker
instance used to intercept user stop messages
('stop_optimizing', 'stop_optimizing_all',
'stop_optimizing_cycle', 'stop_optimizing_function')
while cycling
setResultParams (boolean, None, dict): forwarded as is to
every run_optimization() call to control automatic
set_optimization_result() calls
solverParams (None, dict): differential evolution solver
keyword arguments (e.g. 'popsize', 'maxiter',
'mutationScaleFactor', 'crossoverRate', 'tol',
'atol', 'patience') merged into every step and
forwarded to run_optimization(). If None, a default
parameters dict is used
_lockerPopMessages (boolean): internal flag forwarded to
every run_optimization() call
summary (list): list of deep copies of this optimizer’s
optimization result dictionary, one per executed
optimization step across all cycles
Run configuration optimization
Optimization target parameters (scale through
pairsWeight) share the exact same value format and meaning
as their namesakes in create_optimization_code(); see that
function’s docstring for full details.
constraint (Constraint): the experimental constraint to optimize
reset (boolean): whether to reset the experimental constraint prior to optimizing
scale (boolean, list): experimental constraint scale factor optimization definition
resolution (boolean, list): instrument resolution correction optimization definition
qmax (boolean, list): Qmax correction optimization definition
thermals (boolean, list): isotropic thermal vibration correction factors optimization definition
delta1 (boolean, list): anisotropic thermal vibration ‘delta1’ parameter optimization definition
delta2 (boolean, list): anisotropic thermal vibration ‘delta2’ parameter optimization definition
qbroad (boolean, list): anisotropic thermal vibration ‘qbroad’ parameter optimization definition
atomsWeight (boolean, list): per-element or per-atom scattering weighting corrections optimization definition
pairsWeight (boolean, list): per-atom-pair partial scattering weighting corrections optimization definition
setResultParams (boolean, None, dict): whether and how to
automatically call set_optimization_result() upon
completion. False disables the automatic call. True
computes a default stdErrDiffThreshold. A number is
used directly as stdErrDiffThreshold. A dict is
forwarded as keyword arguments to
set_optimization_result()
locker (None, pylocker.ServerLocker): optional locker
instance used to intercept user stop messages
('stop_optimizing', 'stop_optimizing_all') while
the solver is running
functionName (str): label identifying this optimization run, embedded in the generated optimization code for logging and debugging purposes
_lockerPopMessages (boolean): internal flag. If True, pop
and discard any pending stop messages from locker
before starting this optimization run
*args, **kwargs: other arguments or keywords arguments that will be fed to the differential evolution algorithm
result (dict): the final optimization result
Update the optimizer’s experimental constraint (and optionally
the engine’s live constraint) with the latest
run_optimization() result, provided it actually improved the
standard error.
The update is refused (with a logged warning, returning False)
when no optimization ran yet, the run was unsuccessful, the result
was already applied ('set' flag True), the final standard
error could not be computed, the error increased, or the
improvement did not exceed stdErrDiffThreshold.
stdErrDiffThreshold (None, number): minimum required
standard error decrease (start - end) for the result to
be applied. None disables this check
updateEngineConstraint (boolean): if True, also push the refined corrections onto the live engine constraint so subsequent engine computations reflect them
_force (boolean): if True, bypass the standard error increase/threshold checks and apply the result anyway
_logData (boolean): if True, log a detailed summary of the refined parameters
success (boolean): False if the result was not applied for any of the reasons above, True otherwise