v6.0.0 docs — cloud-only, subscription (fullrmc.com). Free download: v4.1.1.

fullrmc.OptimizationEngine module

fullrmc.OptimizationEngine.get_sites_symmetry_fit(OP)

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

Parameters:
  1. OP (CrystalOptimizer): the crystal optimizer instance whose current unitcell box coordinates must be fitted back onto its original sites symmetry

Returns:
  1. 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']
fullrmc.OptimizationEngine.get_delta_limits_chain(name, value, defaultDelta, defaultLimits, maxDelta=(None, None), maxLimits=(None, None), _fixLimits=True)

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.

Parameters:
  1. name (str): parameter name used in raised errors and warnings

  2. value (bool, str, number, list, tuple, dict): the raw parameter value to parse

  3. defaultDelta (list, tuple): default (lower, upper) delta bounds used when value is True or only a chain/deltas is missing

  4. defaultLimits (list, tuple): default (lower, upper) limits used when value does not explicitly define limits

  5. maxDelta (tuple): (lower, upper) maximum allowed delta bounds. None means no bound enforced on that side

  6. maxLimits (tuple): (lower, upper) maximum allowed limits bounds. None means no bound enforced on that side

  7. _fixLimits (boolean): if True, out of bound values are silently clipped and logged instead of raising an assertion error

Returns:
  1. value (list): normalized [lower, upper] delta bounds

  2. chain (None, str): chain name if given, None otherwise

  3. limits (list): normalized [lower, upper] limits

class fullrmc.OptimizationEngine.ChainedAtomsOptimizerGenerator(OP, chain, indexes, mgType, *args, **kwargs)

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))))
optimize_code(v_index, indent=1)

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.

Parameters:
  1. v_index (int): index of the first free optimization variable to allocate for this chain’s move

  2. indent (int): indentation level (multiplied by 4 spaces) to apply to the generated code block

Returns:
  1. v_index (int): updated variable index after allocating this chain’s variables

  2. code (str): the generated optimization code snippet(s), as returned by the underlying per-move-type generator

update_code(uv_index, indent=1)

Generate the update source code snippet applying this chain’s selected move type result back onto the engine’s box coordinates.

Parameters:
  1. uv_index (int): index of the first free update variable to allocate for this chain’s move

  2. indent (int): indentation level (multiplied by 4 spaces) to apply to the generated code block

Returns:
  1. uv_index (int): updated variable index after allocating this chain’s variables

  2. code (str): the generated update code snippet, as returned by the underlying per-move-type generator

fullrmc.OptimizationEngine.create_optimization_code(OP, siteIndexes=False, atomIndexes=False, atomChains=False, scale=False, resolution=False, qmax=False, thermals=False, delta1=False, delta2=False, qbroad=False, ax=False, ay=False, az=False, bx=False, by=False, bz=False, cx=False, cy=False, cz=False, atomsWeight=False, pairsWeight=False, defaultLimits=None)

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.

Parameters:
  1. OP (CrystalOptimizer, StochasticEngineOptimizer): the optimizer instance whose structure and/or experimental constraint corrections are being wired into optimization variables

  2. 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

  3. atomIndexes (boolean, list): individual unitcell atom indexes (P1, no symmetry) whose position is optimized independently. Same True/False/list format as siteIndexes

  4. 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)

  5. scale (boolean, number, tuple, dict): experimental constraint scale factor optimization definition

  6. resolution (boolean, number, tuple, dict): instrument resolution correction optimization definition

  7. qmax (boolean, number, tuple, dict): Qmax correction optimization definition

  8. thermals (boolean, number, tuple, dict): isotropic thermal (Debye-Waller) vibration correction factors optimization definition

  9. delta1 (boolean, number, tuple, dict): anisotropic thermal vibration correction ‘delta1’ parameter optimization definition

  10. delta2 (boolean, number, tuple, dict): anisotropic thermal vibration correction ‘delta2’ parameter optimization definition

  11. qbroad (boolean, number, tuple, dict): anisotropic thermal vibration correction ‘qbroad’ parameter optimization definition

  12. 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

  13. atomsWeight (boolean, number, tuple, dict): per-element or per-atom scattering weighting corrections optimization definition

  14. pairsWeight (boolean, number, tuple, dict): per-atom-pair partial scattering weighting corrections optimization definition

  15. defaultLimits (None, dict): optional overrides of the default (None, None) limits used for any of the above named optimization targets, keyed by parameter name

Returns:
  1. 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

  2. updCode (str): source code defining update_function(result, OP, FLOAT_TYPE, PRECISION) which applies an accepted solver result back onto OP and its engine

  3. deltas (list): per optimization variable raw delta bounds

  4. bounds (list): per optimization variable (lower, upper) solver bounds

  5. limits (list): per optimization variable physical value limits

  6. x0 (list): per optimization variable initial value

  7. varTypes (list): per optimization variable category string, one of 'symmetry', 'site', 'atom', 'chainedAtom', 'scale', 'resolution', 'thermal', 'qmax', 'atomsWeight' or 'pairsWeight'

  8. varNames (list): per optimization variable name or grouping label used while generating optCode and updCode

  9. parameters (dict): the normalized input parameters as given to this function, keyed by parameter name

class fullrmc.OptimizationEngine.CrystalOptimizer(name=None, path=None, _maxUnitcellSize=5000)

Bases: object

This is the main implementation to perform PDF-GUI like structure refinement using differential evolution and normal stochastic refinement

Parameters:
  1. 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()
property maxUnitcellSize

Allowed maximum unitcell size

property originalStructure

Main structure dictionary information

property optimizedStructure

Optimized structure dictionary built from the current engine’s box coordinates, expressed in the unitcell referential.

Returns:
  1. 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)

property optimizedParameters

get refined structure parameters

property name

Optimizer user defined name

property path

optimizer parent engine path

property sitesSymmetryFit

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_minimum_needed_supercell(maxDist=None, tolerance=1, _bc=None)

Get needed supercell size to cover maxDist

Parameters:
  1. maxDist (None, number): If None, experimental data maximum R-range will be used

  2. tolerance (number): tolerance in R above maxDist. If maxDist is not None, tolerance will be ignored

  3. _bc (None, PeriodicBoundaries): internal flag. Boundary conditions to compute the minimum supercell against. If None, the optimizer’s own unitcell boundary conditions are used

Returns:
  1. supercell (list): supercell size along a, b, and c

get_pdb(supercell=(1, 1, 1), contiguous=False, _optimizedStructure=True)

Get pdb of optimized structure

Parameters:
  1. supercell (tuple): defines how big of a supercell is needed

  2. contiguous (boolean): get contiguous molecules if molecules are defined

  3. _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

Returns:
  1. pdb (pdbparser.pdbparser): the pdb instance

set_name(name)

User defined optimizer name

Parameters:
  1. name (str): optimizer name

set_path(path)

Set engine path

Parameters:
  1. path (str): engine path

reset()

Reset optimizer by removing any optimized structure

set_structure(cif, scaleup, supercell, optimizationDistance=None, redefinitions=False, distances=False, bonds=False, angles=False, dihedrals=False, impropers=False)

Set optimization structure

Parameters:
  1. 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

  2. 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.

  3. 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

  4. 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

  5. redefinitions (None, dict): kwargs used to call set_stucture_redefinitions method and redefine structure atoms and molecules

  6. distances (False, number, tuple, dict): distances rigid constraint definition forwarded as is to set_distances_constraint(). False disables the constraint

  7. bonds (False, number, tuple, dict): bonds rigid constraint definition forwarded as is to set_bonds_constraint(). False disables the constraint

  8. angles (False, number, tuple, dict): angles rigid constraint definition forwarded as is to set_angles_constraint(). False disables the constraint

  9. dihedrals (False, number, tuple, dict): dihedrals rigid constraint definition forwarded as is to set_dihedrals_constraint(). False disables the constraint

  10. impropers (False, number, tuple, dict): impropers rigid constraint definition forwarded as is to set_impropers_constraint(). False disables the constraint

set_stucture_redefinitions(_resetConstraints=True, _raise=False, **kwargs)

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

Parameters:
  1. _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

  2. _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

  3. **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)
Returns:
  1. 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_box_coordinates(boxCoords, indexes=None, inUnicellBoxReferential=True, _recompute=True)

Set unitcell atoms coordinates

Parameters:
  1. 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.

  2. indexes (None, list,tuple): atoms indexes in unitcell. If None, all unitcell atoms are updated.

  3. inUnicellBoxReferential (bool): whether given box coordinates are in unitcell box coordinates referential.

  4. _recompute (boolean): internal flag. If True, recompute the experimental constraint data after updating the coordinates

set_unitcell_sites_position(sites=None, _recompute=True)

Set unitcell atoms coordinates given sites

Parameters:
  1. sites (None, dictionary): sites atom position. If None, original sites positions will be restored

  2. _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, _recompute=True)

Set unitcell boundary conditions

Parameters:
  1. 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.

  2. _recompute (boolean): internal flag. If True, recompute the experimental constraint data after updating the boundary conditions

set_parameters(**params)

Given parameters set and update structure

Returns:
  1. data (dict): constraint data dictionary

  2. total (numpy.ndarray): constraint total pair distribution function

  3. standardError (float): constraint standard error

set_optimization_distance(value, _keepAtomsPositions=True, _force=False, _recompute=True)

Set optimization distance

Parameters:
  1. value (bool, number): the optimization distance. If a number is given, the supercell will be automatically recomputed to cover at least this distance.

  2. _keepAtomsPositions (boolean): internal flag. If True, preserve the current atoms box coordinates across the supercell rebuild triggered by this distance change

  3. _force (boolean): internal flag. If True, apply the change even if value already equals the current optimizationDistance

  4. _recompute (boolean): internal flag. If True, recompute the experimental constraint data after applying the change

Returns:
  1. result (boolean): whether optimization distance was reset or not

set_supercell(supercell, _keepAtomsPositions=True, _force=False, _recompute=True)

Reset structure supercell

Parameters:
  1. supercell (int, list, tuple): supercell along x,y and z

  2. _keepAtomsPositions (boolean): internal flag. If True, preserve the current atoms box coordinates across the supercell rebuild

  3. _force (boolean): internal flag. If True, apply the change even if supercell already equals the current supercell

  4. _recompute (boolean): internal flag. If True, recompute the experimental constraint data after applying the change

Returns:
  1. result (boolean): whether supercell was reset or not

set_scaleup(scaleup, _keepAtomsPositions=True, _force=False, _recompute=True)

Reset structure scaleup

Parameters:
  1. scaleup (int, list, tuple): scaleup along x,y and z used to create a bigger unitcell from the main unitcell

  2. _keepAtomsPositions (boolean): internal flag, currently not implemented and forced to False regardless of the given value

  3. _force (boolean): internal flag. If True, apply the change even if scaleup already equals the current scaleup

  4. _recompute (boolean): internal flag. If True, recompute the experimental constraint data after applying the change

Returns:
  1. result (boolean): whether scaleup was reset or not

reset_structure()

Reset structure to the original atoms coordinates as given in CIF file

Returns:
  1. result (boolean): whether the structure was actually reset, as returned by the underlying set_supercell() or set_optimization_distance() call

set_distances_constraint(distances=(0.8, 1.5))

Set distance constraint definition

Parameters:
  1. 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_bonds_constraint(bonds=None)

Set atomic bonds constraint definition

Parameters:
  1. bonds (None, dictionary): atomic bonds definition.

set_angles_constraint(angles=None)

Set atomic angles constraint definition

Parameters:
  1. angles (None, dictionary): atomic angles definition

set_dihedrals_constraint(dihedrals=None)

Set atomic dihedral angles constraint definition

Parameters:
  1. dihedrals (None, dictionary): atomic dihedral angles definition
    1. First atom index of the first plane.

    2. Second atom index of the first plane and first atom index of the second plane.

    3. Third atom index of the first plane and second atom index of the second plane.

    4. Fourth atom index of the second plane.

set_impropers_constraint(impropers=None)

Set atomic improper angles constraint definition

Parameters:
  1. impropers (None, dictionary): atomic improper angles definition
    1. item 1: angle improper atom by type (must be given)

    2. item 2: angle plane ‘o’ origin atom by type (must be given)

    3. item 3: angle plane ‘x’ atom by type used to calculated ‘Ox’ vector (must be given)

    4. item 4: angle plane ‘y’ atom by type used to calculated ‘Oy’ vector (must be given)

    5. item 5: angle lower bound in degrees (must be given)

    6. item 6: angle upper bound in degrees (must be given)

set_pair_distribution_constraint(**params)

Add pair distribution constraint

Parameters:
  1. params (dict): Any set of parameters used to instanciate fullrmc.Constraint.PairDistributionConstraints.PairDistributionConstraint

Returns:
  1. constraint (PairDistributionConstraint): the created and attached experimental constraint instance

set_pair_correlation_constraint(**params)

Add pair correlation constraint

Parameters:
  1. params (dict): Any set of parameters used to instanciate fullrmc.Constraint.PairCorrelationConstraints.PairCorrelationConstraint

Returns:
  1. constraint (PairCorrelationConstraint): the created and attached experimental constraint instance

set_radial_distribution_constraint(**params)

Add radial distribution constraint

Parameters:
  1. params (dict): Any set of parameters used to instanciate fullrmc.Constraint.RadialDistributionConstraints.RadialDistributionConstraint

Returns:
  1. constraint (RadialDistributionConstraint): the created and attached experimental constraint instance

set_structure_factor_constraint(sfType=None, **params)

Add structure factor constraint

Parameters:
  1. sfType (None, string): Structure factor constraint type. If None, StructureFactorConstraint is used. If ‘reduced’, ReducedStructureFactorConstraint is used. If ‘normalized’, NormalizedStructureFactorConstraint is used.

  2. params (dict): Any set of parameters used to instanciate fullrmc.Constraint.StructureFactorConstraints.StructureFactorConstraint

Returns:
  1. constraint (StructureFactorConstraint, ReducedStructureFactorConstraint, NormalizedStructureFactorConstraint): the created and attached experimental constraint instance, its exact type depending on sfType

get_experimental_constraint_standard_error()

Get distance constraint standard error.

Returns:
  1. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

get_distances_computation(dataDict=False)

Get distance constraint computation result.

Parameters:
  1. dataDict (boolean): If true, data will be transformed to full format

Returns:
  1. distances (None, numpy.ndarray): distances computed array

  2. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

get_distances_standard_error()

Get bonds constraint standard error.

Returns:
  1. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

plot_distances_constraint(data=None, *args, **kwargs)

Plot distances constraint computation result as a pie chart of per-definition standard errors.

Parameters:
  1. data (None, dict): Pre-computed distances data as returned by get_distances_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine

Returns:
  1. figure (matplotlib.figure.Figure): the plotted figure

  2. axes (matplotlib.axes.Axes): the plot axes

  3. data (dict): the distances data used for plotting

export_distances_constraint(fileName=None, data=None, *args, **kwargs)

Export distances constraint computation result to a delimited text file.

Parameters:
  1. fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk

  2. data (None, dict): Pre-computed distances data as returned by get_distances_computation() with dataDict=True. Computed automatically if None

  3. *args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine

Returns:
  1. lines (str): the exported data formatted as text

get_distances_summary(data=None, *args, **kwargs)

Get distances constraint per-definition statistical summary.

Parameters:
  1. data (None, dict): Pre-computed distances data as returned by get_distances_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine

Returns:
  1. summary (dict): per definition dictionary of count, error_count, total_error, mean, median, stddev, minimum and maximum values

get_bonds_computation(dataDict=False)

Get bonds constraint standard error.

Parameters:
  1. dataDict (boolean): If true, data will be transformed to full format

Returns:
  1. bonds (None, numpy.ndarray): bonds computed array

  2. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

get_bonds_standard_error()

Get bonds constraint standard error.

Returns:
  1. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

plot_bonds_constraint(data=None, *args, **kwargs)

Plot bonds constraint computation result as a pie chart of per-definition standard errors.

Parameters:
  1. data (None, dict): Pre-computed bonds data as returned by get_bonds_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine

Returns:
  1. figure (matplotlib.figure.Figure): the plotted figure

  2. axes (matplotlib.axes.Axes): the plot axes

  3. data (dict): the bonds data used for plotting

export_bonds_constraint(fileName=None, data=None, *args, **kwargs)

Export bonds constraint computation result to a delimited text file.

Parameters:
  1. fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk

  2. data (None, dict): Pre-computed bonds data as returned by get_bonds_computation() with dataDict=True. Computed automatically if None

  3. *args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine

Returns:
  1. lines (str): the exported data formatted as text

get_bonds_summary(data=None, *args, **kwargs)

Get bonds constraint per-definition statistical summary.

Parameters:
  1. data (None, dict): Pre-computed bonds data as returned by get_bonds_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine

Returns:
  1. summary (dict): per definition dictionary of count, error_count, total_error, mean, median, stddev, minimum and maximum values

get_angles_computation(dataDict=False)

Get angles constraint computation result

Parameters:
  1. dataDict (boolean): If true, data will be transformed to full format

Returns:
  1. angles (None, numpy.ndarray): angles computed array

  2. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

get_angles_standard_error()

Get angles constraint standard error.

Returns:
  1. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

plot_angles_constraint(data=None, *args, **kwargs)

Plot angles constraint computation result as a pie chart of per-definition standard errors.

Parameters:
  1. data (None, dict): Pre-computed angles data as returned by get_angles_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine

Returns:
  1. figure (matplotlib.figure.Figure): the plotted figure

  2. axes (matplotlib.axes.Axes): the plot axes

  3. data (dict): the angles data used for plotting

export_angles_constraint(fileName=None, data=None, *args, **kwargs)

Export angles constraint computation result to a delimited text file.

Parameters:
  1. fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk

  2. data (None, dict): Pre-computed angles data as returned by get_angles_computation() with dataDict=True. Computed automatically if None

  3. *args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine

Returns:
  1. lines (str): the exported data formatted as text

get_angles_summary(data=None, *args, **kwargs)

Get angles constraint per-definition statistical summary.

Parameters:
  1. data (None, dict): Pre-computed angles data as returned by get_angles_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine

Returns:
  1. summary (dict): per definition dictionary of count, error_count, total_error, mean, median, stddev, minimum and maximum values

get_dihedrals_computation(dataDict=False)

Get dihedrals constraint computation result

Parameters:
  1. dataDict (boolean): If true, data will be transformed to full format

Returns:
  1. angles (None, numpy.ndarray): angles computed array

  2. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

get_dihedrals_standard_error()

Get dihedrals constraint standard error.

Returns:
  1. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

plot_dihedrals_constraint(data=None, *args, **kwargs)

Plot dihedrals constraint computation result as a pie chart of per-definition standard errors.

Parameters:
  1. data (None, dict): Pre-computed dihedrals data as returned by get_dihedrals_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine

Returns:
  1. figure (matplotlib.figure.Figure): the plotted figure

  2. axes (matplotlib.axes.Axes): the plot axes

  3. data (dict): the dihedrals data used for plotting

export_dihedrals_constraint(fileName=None, data=None, *args, **kwargs)

Export dihedrals constraint computation result to a delimited text file.

Parameters:
  1. fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk

  2. data (None, dict): Pre-computed dihedrals data as returned by get_dihedrals_computation() with dataDict=True. Computed automatically if None

  3. *args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine

Returns:
  1. lines (str): the exported data formatted as text

get_dihedrals_summary(data=None, *args, **kwargs)

Get dihedrals constraint per-definition statistical summary.

Parameters:
  1. data (None, dict): Pre-computed dihedrals data as returned by get_dihedrals_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine

Returns:
  1. summary (dict): per definition dictionary of count, error_count, total_error, mean, median, stddev, minimum and maximum values

get_impropers_computation(dataDict=False)

Get impropers constraint computation result

Parameters:
  1. dataDict (boolean): If true, data will be transformed to full format

Returns:
  1. angles (None, numpy.ndarray): improper angles computed array

  2. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

get_impropers_standard_error()

Get impropers constraint standard error.

Returns:
  1. standardError (None, number): distance constraint total standard error. If structure or constraint are not defined, None is returned

plot_impropers_constraint(data=None, *args, **kwargs)

Plot impropers constraint computation result as a pie chart of per-definition standard errors.

Parameters:
  1. data (None, dict): Pre-computed impropers data as returned by get_impropers_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional plotting arguments forwarded to the internal rigid constraint plotting routine

Returns:
  1. figure (matplotlib.figure.Figure): the plotted figure

  2. axes (matplotlib.axes.Axes): the plot axes

  3. data (dict): the impropers data used for plotting

export_impropers_constraint(fileName=None, data=None, *args, **kwargs)

Export impropers constraint computation result to a delimited text file.

Parameters:
  1. fileName (None, str): output file path. If None, data is only formatted and returned, nothing is written to disk

  2. data (None, dict): Pre-computed impropers data as returned by get_impropers_computation() with dataDict=True. Computed automatically if None

  3. *args, **kwargs: additional arguments forwarded to the internal rigid constraint export routine

Returns:
  1. lines (str): the exported data formatted as text

get_impropers_summary(data=None, *args, **kwargs)

Get impropers constraint per-definition statistical summary.

Parameters:
  1. data (None, dict): Pre-computed impropers data as returned by get_impropers_computation() with dataDict=True. Computed automatically if None

  2. *args, **kwargs: additional arguments forwarded to the internal rigid constraint summary routine

Returns:
  1. summary (dict): per definition dictionary of count, error_count, total_error, mean, median, stddev, minimum and maximum values

run_optimization(siteIndexes=False, atomIndexes=False, atomChains=False, scale=False, resolution=False, qmax=False, thermals=False, delta1=False, delta2=False, qbroad=False, ax=False, ay=False, az=False, bx=False, by=False, bz=False, cx=False, cy=False, cz=False, atomsWeight=False, pairsWeight=False, setResultParams=False, locker=None, functionName='optimize_structure', _lockerPopMessages=True, *args, **kwargs)

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.

Parameters:
  1. siteIndexes (boolean, list): crystal sites position optimization definition, mutually exclusive with atomIndexes and atomChains

  2. atomIndexes (boolean, list): individual atoms position optimization definition, mutually exclusive with siteIndexes and atomChains

  3. atomChains (bool, dict): rigid chains of atoms optimization definition, mutually exclusive with siteIndexes and atomIndexes

  4. scale (boolean, list): experimental constraint scale factor optimization definition

  5. resolution (boolean, list): instrument resolution correction optimization definition

  6. qmax (boolean, list): Qmax correction optimization definition

  7. thermals (boolean, list): isotropic thermal vibration correction factors optimization definition

  8. delta1 (boolean, list): anisotropic thermal vibration ‘delta1’ parameter optimization definition

  9. delta2 (boolean, list): anisotropic thermal vibration ‘delta2’ parameter optimization definition

  10. qbroad (boolean, list): anisotropic thermal vibration ‘qbroad’ parameter optimization definition

  11. ax (boolean, list): unitcell basis vector a’s x component optimization definition

  12. ay (boolean, list): unitcell basis vector a’s y component optimization definition

  13. az (boolean, list): unitcell basis vector a’s z component optimization definition

  14. bx (boolean, list): unitcell basis vector b’s x component optimization definition

  15. by (boolean, list): unitcell basis vector b’s y component optimization definition

  16. bz (boolean, list): unitcell basis vector b’s z component optimization definition

  17. cx (boolean, list): unitcell basis vector c’s x component optimization definition

  18. cy (boolean, list): unitcell basis vector c’s y component optimization definition

  19. cz (boolean, list): unitcell basis vector c’s z component optimization definition

  20. atomsWeight (boolean, list): per-element or per-atom scattering weighting corrections optimization definition

  21. pairsWeight (boolean, list): per-atom-pair partial scattering weighting corrections optimization definition

  22. 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()

  23. locker (None, pylocker.ServerLocker): optional locker instance used to intercept user stop messages ('stop_optimizing', 'stop_optimizing_all') while the solver is running

  24. functionName (str): label identifying this optimization run, embedded in the generated optimization code for logging and debugging purposes

  25. _lockerPopMessages (boolean): internal flag. If True, pop and discard any pending stop messages from locker before starting this optimization run

  26. *args, **kwargs: other arguments or keywords arguments that will be fed to the differential evolution algorithm

Returns:
  1. result (dict): the final optimization result

set_optimization_result(stdErrDiffThreshold=0.001, _force=False, _logData=True)

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.

Parameters:
  1. stdErrDiffThreshold (None, number): minimum required standard error decrease (start - end) for the result to be applied. None disables this check

  2. _force (boolean): if True, bypass the standard error increase/threshold checks and apply the result anyway

  3. _logData (boolean): if True, log a detailed summary of the updated structure and refined parameters

class fullrmc.OptimizationEngine.StochasticEngineOptimizer(engine, name=None)

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

Parameters:
  1. engine (fullrmc.Engine.Engine): fullrmc stochastic engine instance

  2. name (str): optimizer name

property engine

Optimizer fullrmc stochastic engine

property name

Optimizer user defined name

set_engine(engine)

Set the fullrmc stochastic engine this optimizer operates on.

Parameters:
  1. engine (fullrmc.Engine.Engine): the stochastic engine instance to attach to this optimizer

remove_constraint()

Detach the currently set experimental and engine constraints, resetting them so they can be repopulated at runtime.

set_name(name)

User defined optimizer name

Parameters:
  1. name (str): optimizer name

run_optimization_cycle(constraint, cycle=None, ncycles=5, locker=None, setResultParams=True, solverParams=None, _lockerPopMessages=True)

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.

Parameters:
  1. constraint (Constraint): the experimental constraint to optimize, forwarded to every run_optimization() call

  2. 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

  3. ncycles (int): number of times the whole cycle sequence is repeated

  4. 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

  5. setResultParams (boolean, None, dict): forwarded as is to every run_optimization() call to control automatic set_optimization_result() calls

  6. 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

  7. _lockerPopMessages (boolean): internal flag forwarded to every run_optimization() call

Returns:
  1. summary (list): list of deep copies of this optimizer’s optimization result dictionary, one per executed optimization step across all cycles

run_optimization(constraint, reset=False, scale=False, resolution=False, qmax=False, thermals=False, delta1=False, delta2=False, qbroad=False, atomsWeight=False, pairsWeight=False, setResultParams=True, locker=None, functionName='optimize_constraint', _lockerPopMessages=True, *args, **kwargs)

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.

Parameters:
  1. constraint (Constraint): the experimental constraint to optimize

  2. reset (boolean): whether to reset the experimental constraint prior to optimizing

  3. scale (boolean, list): experimental constraint scale factor optimization definition

  4. resolution (boolean, list): instrument resolution correction optimization definition

  5. qmax (boolean, list): Qmax correction optimization definition

  6. thermals (boolean, list): isotropic thermal vibration correction factors optimization definition

  7. delta1 (boolean, list): anisotropic thermal vibration ‘delta1’ parameter optimization definition

  8. delta2 (boolean, list): anisotropic thermal vibration ‘delta2’ parameter optimization definition

  9. qbroad (boolean, list): anisotropic thermal vibration ‘qbroad’ parameter optimization definition

  10. atomsWeight (boolean, list): per-element or per-atom scattering weighting corrections optimization definition

  11. pairsWeight (boolean, list): per-atom-pair partial scattering weighting corrections optimization definition

  12. 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()

  13. locker (None, pylocker.ServerLocker): optional locker instance used to intercept user stop messages ('stop_optimizing', 'stop_optimizing_all') while the solver is running

  14. functionName (str): label identifying this optimization run, embedded in the generated optimization code for logging and debugging purposes

  15. _lockerPopMessages (boolean): internal flag. If True, pop and discard any pending stop messages from locker before starting this optimization run

  16. *args, **kwargs: other arguments or keywords arguments that will be fed to the differential evolution algorithm

Returns:
  1. result (dict): the final optimization result

set_optimization_result(stdErrDiffThreshold=1e-06, updateEngineConstraint=True, _force=False, _logData=True)

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.

Parameters:
  1. stdErrDiffThreshold (None, number): minimum required standard error decrease (start - end) for the result to be applied. None disables this check

  2. updateEngineConstraint (boolean): if True, also push the refined corrections onto the live engine constraint so subsequent engine computations reflect them

  3. _force (boolean): if True, bypass the standard error increase/threshold checks and apply the result anyway

  4. _logData (boolean): if True, log a detailed summary of the refined parameters

Returns:
  1. success (boolean): False if the result was not applied for any of the reasons above, True otherwise

Previous topic

fullrmc.Globals module

Next topic

fullrmc.SystemBuilderUtils module