Constraint contains parent classes for all constraints. A Constraint is used to set certain rules for the stochastic engine to evolve the atomic system. Therefore it has become possible to fully customize and set any possibly imaginable rule.

random() -> x in the interval [0, 1).
Bases: ListenerBase
A constraint is used to direct the evolution of the atomic configuration towards the desired and most meaningful one.
Design pattern implementation. Subclasses must overload this classmethod to build and return a new constraint instance from stored parameters.
params (dict): The constraint’s stored parameters used to rebuild the instance.
engine (Engine): The engine instance the constraint will be bound to.
args (tuple): Additional positional arguments.
kwargs (dict): Additional keyword arguments.
Design pattern implementation.
For general constraints no nanoscopic parameters are needed.
parameters (None): Always None for the base Constraint class.
Design pattern implementation. Subclasses must overload this method to update the constraint’s internal state from params.
params (dict): The new parameters to update the constraint with.
Get update parameters that can be used to update this constraint to the given one
constraint (dict, Constraint): Given constraint parameters of constraint instance of the same type as this constraint
parameters (dict): Update parameters
Constraint unique ID create at instantiation time.
constraintId (string): The constraint’s unique id (its listenerId).
Constraints unique name in engine given when added to engine.
constraintName (string): The constraint’s name.
Stochastic fullrmc’s engine instance.
engine (None, Engine): The bound engine instance, or None if not yet added to an engine.
Get used frame in engine. If None then engine is not defined yet.
usedFrame (None, string): The engine’s currently used frame.
Computation cost number.
computationCost (number): The constraint’s computation cost.
Constraint’s state.
state (object): The constraint’s current internal state marker.
Constraint’s number of tried moves.
tried (integer): The number of tried moves.
Constraint’s number of accepted moves.
accepted (integer): The number of accepted moves.
Constraint’s used flag. Defines whether constraint is used in the stochastic engine at runtime or set inactive.
used (boolean): Whether the constraint is active.
Constraint’s variance used in the stochastic engine at runtime to calculate the total constraint’s standard error.
variance (number): The constraint’s variance.
Listener data.
listenerData (object): The constraint’s listener data.
Optimization parameters.
optimizationParameters (object): The constraint’s optimization parameters.
Constraint’s weight (1./variance) used in the stochastic engine at runtime to calculate the total constraint’s standard error.
constraintWeight (number): The constraint’s weight.
Constraint’s standard error value.
standardError (number): The constraint’s standard error.
Constraint’s original data calculated upon initialization.
originalData (object): The constraint’s original data.
Constraint’s current calculated data.
data (object): The constraint’s current data.
Constraint’s current calculated data before last move.
activeAtomsDataBeforeMove (object): The data before the last move.
Constraint’s current calculated data after last move.
activeAtomsDataAfterMove (object): The data after the last move.
Constraint’s current calculated StandardError after last move.
afterMoveStandardError (number): The standard error after the last move.
Constraint’s current calculated data after amputation.
amputationData (object): The data after amputation.
Constraint’s current calculated StandardError after amputation.
amputationStandardError (number): The standard error after amputation.
Design pattern implementation. In this case it’s always 1.
mesoscopicWeight (FLOAT_TYPE): Always 1.
Design pattern implementation. In this case it’s always 0.
mesoscopicPrior (FLOAT_TYPE): Always 0.
Design pattern implementation. In this case it’s always None.
nanoscopicData (None): Always None.
Get whether constraint is already in defined and added to engine. It can be the same exact instance or a repository pulled instance of the same constraintId
engine (stochastic fullrmc engine): Engine instance.
result (boolean): Whether constraint exists in engine.
Set constraint’s variance that is used in the computation of the total stochastic engine standard error.
value (number): Any positive non zero number.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.
Set constraint’s computation cost value. This is used at stochastic engine runtime to minimize computations and enhance performance by computing less costly constraints first. At every step, constraints will be computed in order starting from the less to the most computationally costly. Therefore upon rejection of a step because of an unsatisfactory rigid constraint, the left un-computed constraints at this step are guaranteed to be the most time coslty ones.
value (number): computation cost.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.
Set used flag.
value (boolean): True to use this constraint in stochastic engine runtime.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, all other multiframe subframes will be targeted if constraints is ExperimentalConstraint.
Set constraint’s state. When constraint’s state and stochastic engine’s state don’t match, constraint’s data must be re-calculated.
value (object): Constraint state value.
Set constraint’s number of tried moves.
value (integer): Constraint tried moves value.
Increment number of tried moves.
Set constraint’s number of accepted moves.
value (integer): Constraint’s number of accepted moves.
Increment constraint’s number of accepted moves.
Set constraint’s standardError value.
value (number): standard error value.
Set constraint’s data value.
value (number): constraint’s data.
Set constraint’s before move happens active atoms data value.
value (number): Data value.
Set constraint’s after move happens active atoms data value.
value (number): data value.
Set constraint’s standard error value after move happens.
value (number): standard error value.
Set constraint’s after amputation data.
value (number): data value.
Set constraint’s standardError after amputation.
value (number): standard error value.
Reset constraint.
reinitialize (boolean): If set to True, it will override the rest of the flags and will completely reinitialize the constraint.
flags (boolean): Reset the state, tried and accepted flags of the constraint.
data (boolean): Reset the constraints computed data.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
Compute and set constraint’s standard error by calling compute_standard_error method and passing constraint’s data.
Get a dictionary look up table of constraint’s properties
frame (string): frame to pull and build contraint data. It can be a traditional frame, a multiframe or a subframe
frameDataLUT (dictionary): properties value look up table. Keys are described herein. All keys start with ‘frames-’ and values are list of properties for every and each frame.
frames-name: list of all frames name
frames-mesoscopic_weight: list of all frames weight
frames-number_of_removed_atoms: list of number of removed atoms from each frame
frames-constraint: list of constraint copy
frames-data: list of constraint data
frames-standard_error: list of all frames standard error
Design pattern implementation.
Design pattern implementation.
Design pattern implementation.
Design pattern implementation.
Design pattern implementation. Subclasses must overload this method to compute constraint data before atoms are moved.
realIndexes (numpy.ndarray): Group real atoms indexes.
relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to compute constraint data after atoms are moved.
realIndexes (numpy.ndarray): Group real atoms indexes.
relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.
movedBoxCoordinates (numpy.ndarray): The new moved atoms coordinates in box coordinates system.
Design pattern implementation. Subclasses must overload this method to accept a previously computed move.
realIndexes (numpy.ndarray): Group real atoms indexes.
relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to reject a previously computed move.
realIndexes (numpy.ndarray): Group real atoms indexes.
relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to compute constraint data as if a single atom was amputated (removed) from the system.
realIndex (numpy.ndarray): The atom real index.
relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to compute constraint data as if a single atom was inserted into the system.
realIndex (numpy.ndarray): The atom real index.
relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to accept a previously computed amputation.
realIndex (numpy.ndarray): The atom real index.
relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to reject a previously computed amputation.
realIndex (numpy.ndarray): The atom real index.
relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to accept a previously computed insertion.
realIndex (numpy.ndarray): The atom real index.
relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.
Design pattern implementation. Subclasses must overload this method to reject a previously computed insertion.
realIndex (numpy.ndarray): The atom real index.
relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.
Export constraint data to text file or to an archive of files.
fileName (path): full file name and path.
frame (None, string): frame name to export data from. If multiframe is given, multiple files will be created with subframe name appended to the end.
format (string): string format to export the data. format is as follows (%[flag]width[.precision]specifier)
delimiter (string): String or character separating columns.
comments (string): String that will be prepended to the header.
lines (string): The exported data as a single string, also written to fileName if fileName is not None.
Plot constraint data. This can be overloaded in children classes.
frame (None, string): The frame name to plot. If None, used frame will be plotted.
axes (None, matplotlib Axes): matplotlib Axes instance to plot in. If None is given a new plot figure will be created.
figureAxesNCols (None, int): number of columns in figure to create axes in multi-axes figures. If None, number of columns will be automatically set.
subAdParams (None, dict): matplotlib.artist.Artist.subplots_adjust parameters subplots adjust parameters.
dataParams (None, dict): constraint data plotting parameters
xlabelParams (None, dict): matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): matplotlib.axes.Axes.set_ylabel parameters.
legendParams (None, dict):matplotlib.axes.Axes.legend parameters.
xticksParams (None, dict):matplotlib.axes.Axes.set_xticklabels parameters.
yticksParams (None, dict):matplotlib.axes.Axes.set_yticklabels parameters.
shareX (boolean): Whether all axes in a multi-axes figure should share the same x axis.
shareY (boolean): Whether all axes in a multi-axes figure should share the same y axis.
titleParams (None, boolean, string, dict): axes title. If None or False are given, no title will be set. It True, default title wille be given. If dict, it must have the key ‘label’ and all other arguments are used for ‘matplotlib.axes.Axes.set_title’ method.
gridParams (None, dict): matplotlib.axes.Axes.grid parameters
tightLayout (boolean): whether to call figure tight_layout method
show (boolean): Whether to render and show figure before returning.
_frameDataLUT: for internal use only
figure (matplotlib Figure): matplotlib used figure.
axes (matplotlib Axes): matplotlib used axes.
frameDataLUT (dict): the frame data LUT
Bases: object
Base implementation to be used along with experimental constraints that need any type of histogram corrections.
thermalCorrections (None, number, dict): Atomic thermal vibration parameters that will be used to correct for partials histogram peaks broadening. If None is given, no correction will be made. If number is given, it will be used as the thermal vibration coefficient for all elements pair. If dictionary is given, it can then include any of ‘set_thermal_corrections’ method parameters
qmaxCorrections (None, number, dict): Experimental real space atomic distribution is obtained by a Fourier transform of the reduced structure factor F(q). However, the experimental q range is limited by a certain maximum measurable value \(Q_{max}\). Theoretically, this is similar to multiplying an infinite q range F(q) with a Heaviside step function cutting off at \(Q_{max}\). Fourier transforming this multiplied step function from the reciprocal to real space will result in a convolution with sine cardinal function defined as \(sinc(Q_{max}r)\). If None is given, no \(Q_{max}\) correction will be made. If a number is given, it will be considered the experimental \(Q_{max}\) in \(\AA^{-1}\). If a dictionary is given, it can then include any of ‘set_qmax_corrections’ method parameters.
resolutionCorrections (None, number, dict): Experimental resolution correction \((Q_{damp})\) which will correct for intensity damping due to limited experimental resolution. It’s defined using a typical exponential decay function given as a guassian \(G_{damp}=e^{-0.5\sigma_{g}^2r^2}\) or a lorentzian \(L_{damp}=e^{-0.5\sigma_{l}r}\).
If None is given, no resolution correction will be performed.
If number is given, it is then the guassian function that will be considered \(G_{damp}=e^{-0.5\sigma_{g}^2r^2}\) and the value is \(\sigma_{g}\) value.
If dict is given, it can contain either ‘q_damp’ which is equivalent to ‘sigma_g’ key corresponding to \(\sigma_{g}\) or ‘sigma_l’ key corresponding to \(\sigma_{l}\) and the values are respectively corresponding to \(e^{-0.5\sigma_{g}^2r^2}`and :math:`L_{damp}=e^{-0.5\sigma_{l}r}\).
The bigger \(Q_{damp}\) (\(\sigma_{l}\) ,:math:sigma_{g}) value is the stronger the damp will be at higher \(r\) values
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('BaTiO3.pdb')
# create and add constraint
PDC = PairDistributionConstraint(experimentalData="pdf.dat",
weighting="atomicNumber",
thermalCorrections={'factors': {('Ba', 'Ba'): 0.004, ('Ba', 'O'): 0.01,
('Ba', 'Ti'): 0.01, ('O', 'O'): 0.004,
('O', 'Ti'): 0.01, ('Ti', 'Ti'): 0.004},
'defaultFactor': 0.01, 'broadening': 1.5},
resolutionCorrections={'sigma_g':0.047},
qmaxCorrections={'qmax': 30.0, 'rWidth': 1.0}
)
ENGINE.add_constraints(PDC)
Atomic thermal vibration broadening correction parameters.
thermalCorrections (dict): The thermal corrections parameters.
Atomic thermal vibration broadening correction arrays.
thermalArrays (None, dict): The thermal correction arrays.
Experimental \(Q_{max}\) cutoff correction parameters.
qmaxCorrections (dict): The qmax corrections parameters.
Experimental \(Q_{max}\) cutoff correction array.
qmaxArray (None, numpy.ndarray): The qmax correction array.
Experimental resolution correction parameters.
resolutionCorrections (None, dict): The resolution corrections parameters.
Experimental resolution correction array.
resolutionArray (None, numpy.ndarray): The resolution correction array.
Get histogram parameters.
histogramParameters (None, dict): The histogram parameters.
Get default parameters for optimization.
engine (None, Engine): The stochastic engine used to resolve the frame category and repository. If None, no frame-specific resolution is performed.
frame (None, str): stochastic engine frame. If None, engine used frame will be set
defaults (None, dict): Optional dictionary of default values overriding the built-in template defaults.
params (dict): The optimization parameters template dictionary.
create optimization step parameters template
parameters (None, dict): starting parameters dictionary. If None, optimizationParameters will be used
template (dict): optimization template dictionary
# import fullrmc modules
from fullrmc import OptimizationEngine
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('BaTiO3.pdb')
PDC = PairDistributionConstraint(experimentalData="pdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PDC)
# create optimizer
SEO = OptimizationEngine.StochasticEngineOptimizer(engine=ENGINE)
# create optimization parameters from template
parameters = PDC.get_optimization_parameters_template(engine=ENGINE)
template = PDC.get_optimization_step_parameters_template(parameters=parameters)
scale = template.get('scale', False)
resolution = template.get('resolution', False)
qmax = template.get('qmax', False)
thermals = template.get('thermals', False)
delta1 = template.get('delta1', False)
delta2 = template.get('delta2', False)
qbroad = template.get('qbroad', False)
# run optimization
kwargs = parameters.get('solver',{})
SEO.run_optimization(constraint=PDC, reset=False,
## corrections
scale=scale, resolution=resolution, qmax=qmax,
## thermal vibtations
thermals=thermals, delta1=delta1, delta2=delta2, qbroad=qbroad,
## set results parameters
setResultParams=True,
functionName='my_function',
## differential evolution args and kwargs
**kwargs)
create optimization cycle parameters template
parameters (None, dict): starting parameters dictionary. If None, optimizationParameters will be used
template (dict): optimization template dictionary
# import fullrmc modules
from fullrmc import OptimizationEngine
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('BaTiO3.pdb')
PDC = PairDistributionConstraint(experimentalData="pdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PDC)
# create optimizer
SEO = OptimizationEngine.StochasticEngineOptimizer(engine=ENGINE)
# create optimization parameters from template
parameters = PDC.optimizationParameters
template = PDC.get_optimization_cycle_parameters_template(parameters)
# run optimization cycle
SEO.run_optimization_cycle(constraint=PDC,
cycle=template,
ncycles=parameters.get('ncycles',5),
setResultParams=True,
solverParams=parameters.get('solver',{})
)
Run a single optimization step given parameters
parameters (None, dict): dictionary of optimization parameters. If None, constraint optimizationParameters will be used
name (str): optimization step name. This is used for logging purposes
locker (None, object): Optional repository locker to use while dumping optimization data. If None, the engine’s repository locker will be used when available.
_save (bool): Internal fullrmc flag controlling whether the optimization results are dumped to the repository. End users should not need to alter this.
optimizer (StochasticEngineOptimizer): the used StochasticEngineOptimizer instance
summary (list): optimization summary dictionary as a single list item
Run optimization cycle of steps given parameters
cycle (None, list): list of optimization step parameters dictionaries defining the optimization cycle. If None, get_optimization_cycle_parameters_template will be used to build it.
ncycles (None, integer): Number of cycles to run. If None, constraint optimizationParameters ‘ncycles’ value will be used, defaulting to 1.
locker (None, object): Optional repository locker to use while dumping optimization data. If None, the engine’s repository locker will be used when available.
_save (bool): Internal fullrmc flag controlling whether the optimization results are dumped to the repository. End users should not need to alter this.
optimizer (StochasticEngineOptimizer): the used StochasticEngineOptimizer instance
summary (list): list of cycles results
set corrections optimization parameters
parameters (None, dict): the optimization parameters dictionary.
frame (None, str): stochastic engine frame. If None is given, stochastic engine used frame will be used. If multiframe is given, parameters will be set to all subframes
Set isotropic or anisotropic thermal vibrations parameters that will be used to simulate partial pair distribution peaks broadening. \(\sigma_{ij}^{2}=<u^{2}>\) factors given in \(\AA^{2}\), are the mean square deviation of atoms and they are directly related to the so called Debye-Waller according to the following formula \(B=8\pi^{2}<u^{2}>\)
factors (None, bool, number, dict): element pairs thermal isotropic mean square deviation factors \(\sigma_{ij}^{2}\) in \(\AA^{2}\).
If True is given, previously set factors will be used, if the latter is None then no histogram correction will be performed.
If False is given, no histogram correction will be performed.
If number is given, it will be used to set all element pairs isotropic mean square deviation factor.
If a dictionary is given, it must include all element pairs as tuples. Missing elements will be automatically set to given default isotropic factor. Missing pairs factors will be computed as the average of given seperate elements isotropic coefficient.
Anisotropic pairs factor can be given by providing additional \(\delta_{1}\), \(\delta_{2}\) and \(Q_{broad}\). values along with the isotropic factor. The adopted anisotropic factor follows the following formula (C. L. Farrow et al. J. Phys.: Condens. Mat. 19, 335219 (2007)): \(\sigma_{ij}\sqrt{1-\frac{\delta_{1}}{r_{ij}}-\frac{\delta_{2}}{r_{ij}^{2}}+Q_{broad}^{2}r_{ij}^{2}}\)
Isotropic thermal factor is a special case of the general anisotropic factor formula when \(\delta_{1}\), \(\delta_{2}\) and \(Q_{broad}\) are equal to 0.
defaultFactor (None, number): elements default isotropic mean square deviation factor value. If None is given, previously set value will be used
delta1 (number): default delta1 parameter for all atom pairs as defined in the anisotropic formula
delta2 (number): default delta2 parameter for all atom pairs as defined in the anisotropic formula
qbroad (number): default qbroad parameter for all atom pairs as defined in the anisotropic formula
broadening (None, number): number of minimum standard deviations (coefficient) to consider while setting the extent of the thermal corrections. If None is given, previously set value will be used
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('BaTiO3.pdb')
# create and add constraint
PDC = PairDistributionConstraint(experimentalData="pdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PDC)
PDC.set_thermal_corrections(factors={('Ba', 'Ba'): 0.004, ('Ba', 'O'): 0.01,
('Ba', 'Ti'): 0.01, ('O', 'O'): 0.004,
('O', 'Ti'): 0.01,
# set anisotropic for ('Ti', 'Ti') pairs
('Ti', 'Ti'): {'factor':0.04,
'delta1':4.678,
'delta2':-13.977,
'qbroad':0.0754},},
defaultFactor=0.01,
broadening= 1.5 )
Set the experimental resolution correction \((Q_{damp})\) which will correct for intensity damping due to limited experimental resolution. Resolution damping is defined using a typical exponential decay function given as a guassian \(G_{damp}=e^{-0.5\sigma_{g}^2r^2}\) or a lorentzian \(L_{damp}=e^{-0.5\sigma_{l}r}\)
value (None,boolean,number,dict): The limited resolution damping \(\sigma_{g}\) or \(\sigma_{l}\) value. If True is given, previously set value will be used, if the latter is None then no resolution correction will be performed.
If False or None is given, no resolution correction will be performed.
If number is given, it is then the guassian function that will be considered \(G_{damp}=e^{-0.5\sigma_{g}^2r^2}\) and the value is \(\sigma_{g}\) value.
If dict is given, it can contain either ‘q_damp’ which is equivalent to ‘sigma_g’ key corresponding to \(\sigma_{g}\) or ‘sigma_l’ key corresponding to \(\sigma_{l}\) and the values are respectively corresponding to \(e^{-0.5\sigma_{g}^2r^2}`and :math:`L_{damp}=e^{-0.5\sigma_{l}r}\).
The bigger \(Q_{damp}\) (\(\sigma_{l}\) ,:math:sigma_{g}) value is the stronger the damp will be at higher \(r\) values
\(\sigma_{g}\) or \(\sigma_{l}\) values for resolution damping are in general computed using a standard crystaline material (silicon standard). Using the standard material, \(\sigma_{g}\) or \(\sigma_{l}\) values are approximated by fitting the exponential decay function to reproduce the intensity damping that is due to the limited experimental resolution at high R range.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('BaTiO3.pdb')
# create and add constraint
PDC = PairDistributionConstraint(experimentalData="pdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PDC)
PDC.set_resolution_corrections({'sigma_g':0.047})
Set t:math:Q_{max} corrections parameters
qmax (None, bool, number): \(Q_{max}\) value. If True is given, previously set \(Q_{max}\) will be used, if the latter is None then no \(Q_{max}\) will be performed.
If False is given, no \(Q_{max}\) correction will be performed.
If number is given, it should be the experimental \(Q_{max}\).
rWidth (None, bool, number): The real space r width to consider in \(S(r)=sinc(Q_{max}r)=sin(Q_{max}r)/Q_{max}r)r\). If True is given, previously set rWidth will be used.
If False or None is given, dr will be computed as \(2\pi/Q_{max}\). If number is given, it will be the r width value.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('BaTiO3.pdb')
# create and add constraint
PDC = PairDistributionConstraint(experimentalData="pdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PDC)
PDC.set_qmax_corrections(qmax=30.0, rWidth=1.0)
Bases: object
Base implementation to be used in constraints that need atoms pair weighting
weighting (string): The elements weighting scheme. It must be any atomic attribute (atomicNumber, neutronCohb, neutronIncohb, neutronCohXs, neutronIncohXs, atomicWeight, covalentRadius) defined in pdbparser database. In case of xrays or neutrons experimental weights, one can simply set weighting to ‘xrays’ or ‘neutrons’ and the value will be automatically adjusted to respectively ‘atomicNumber’ and ‘neutronCohb’. If attribute values are missing in the pdbparser database, atomic weights must be given in atomsWeight dictionary argument.
atomsWeight (None, dict): Atoms weight dictionary where keys are atoms element and values are custom weights. If None is given or partially given, missing elements weighting will be fully set given weighting scheme.
pairsWeight (None, dict): Atom pairs weight. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2. Customizing pairs weight is needed for differential or resonant experimental setups. If el1 weighting or atomWeigth value is x and el2 value is y then (el1,el2) pair value weight is x*y.
custPartScatteringPower (None, dict): Atom pairs scattering power. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2.
Elements pairs.
elementsPairs (list): List of element pair tuples.
Elements weighting definition.
weighting (string): The elements weighting scheme name.
Customized atoms weight.
atomsWeight (None, dict): The customized atoms weight dict.
Customized atom pairs weight.
pairsWeight (None, dict): The customized atom pairs weight dict.
Partials distribution scattering power.
partialsScatteringPower (dict): The partials scattering power dictionary.
Custom partials distribution scattering power.
customPartialsScatteringPower (None, dict): The custom partials scattering power dictionary.
Alias to customPartialsScatteringPower.
custPartScatteringPower (None, dict): The custom partials scattering power dictionary.
Elements weights and partials scattering power for given weighting without applying user defined atomsWeight and pairsWeight.
elementsWeight (None, dict): The computed elements weight dictionary, or None if engine is not set.
pairScattPower (None, dict): The computed pairs scattering power dictionary, or None if engine is not set.
Elements and pairs weights scattering power after applying user defined atomsWeight and pairsWeight.
elementsSP (None, dict): The elements scattering power dictionary, or None if engine or elementsPairs are not set.
pairsSP (None, dict): The pairs scattering power dictionary, or None if engine or elementsPairs are not set.
Set elements weighting. It must be a valid entry of pdbparser atom’s database.
weighting (string): The elements weighting scheme. It must be any atomic attribute (atomicNumber, neutronCohb, neutronIncohb, neutronCohXs, neutronIncohXs, atomicWeight, covalentRadius) defined in pdbparser database. In case of xrays or neutrons experimental weights, one can simply set weighting to ‘xrays’ or ‘neutrons’ and the value will be automatically adjusted to respectively ‘atomicNumber’ and ‘neutronCohb’. If attribute values are missing in the pdbparser database, atomic weights must be given in atomsWeight dictionary argument.
Custom set atoms weight. This is the way to customize setting atoms weights different than the given weighting scheme.
atomsWeight (None, dict): Atoms weight dictionary where keys are atoms element and values are custom weights. If None is given or partially given, missing elements weighting will be fully set given weighting scheme.
pairsWeight (None, dict): Atom pairs weight. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2. Customizing pairs weight is needed for differential or resonant experimental setups. If el1 weighting or atomWeigth value is x and el2 value is y then (el1,el2) pair value weight is x*y.
custPartScatteringPower (None, dict): Atom pairs scattering power. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
Bases: Constraint
Experimental constraint is any constraint related to experimental data.
engine (None, fullrmc.Engine): Constraint’s stochastic engine.
experimentalData (numpy.ndarray, string): Experimental data given as numpy.ndarray or string path to load data using numpy.loadtxt method.
dataWeights (None, numpy.ndarray): Weights array of the same number of points of experimentalData used in the constraint’s standard error computation. Therefore particular fitting emphasis can be put on different data points that might be considered as more or less important in order to get a reasonable and plausible modal.
If None is given, all data points are considered of the same importance in the computation of the constraint’s standard error.
If numpy.ndarray is given, all weights must be positive and all zeros weighted data points won’t contribute to the total constraint’s standard error. At least a single weight point is required to be non-zeros and the weights array will be automatically scaled upon setting such as the sum of all the weights is equal to the number of data points.
scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.
adjustScaleFactor (None, list, tuple, dict): Used to adjust fit or guess the best scale factor during stochastic engine runtime.
If None, default value {‘update’:10, ‘minimum’:0.8, ‘maximum’:1.2, ‘learning_rate’:0.01} will be automatically set If a list is given, it must include mandatory three items and an optional fourth.
The ‘update’ frequency in number of generated moves of finding the best scale factor. If None or 0 frequency is given, it means that the scale factor is fixed.
The ‘minimum’ allowed scale factor value.
The ‘maximum’ allowed scale factor value.
The scale factor ‘learning_rate’.
If a dict is given, all of ‘update’, ‘minimum’, ‘maximum’ and optional ‘learning_rate’ must be given
NB: If adjustScaleFactor first item (update frequency) is 0, the scale factor will remain untouched and the limits minimum and maximum won’t be checked.
For experimental constraints nanoscopic parameters must be overloaded
Design pattern implementation.
Overloading of Constraint reset method implementation.
reinitialize (boolean): If set to True, it will override the rest of the flags and will completely reinitialize the constraint.
flags (boolean): Reset the state, tried and accepted flags of the constraint.
data (boolean): Reset the constraints computed data.
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
_resetScaleFactor (bool): Internal fullrmc flag controlling whether the scale factor is reset as well. End users should not need to alter this.
Experimental data of the constraint.
experimentalData (numpy.ndarray): The experimental data array.
Experimental data points weight.
dataWeights (None, numpy.ndarray): The data weights array.
Constraint multiframe weight towards total in a mesoscopic system.
mesoscopicWeight (number): The mesoscopic weight.
Constraint multiframe mesoscopic prior array.
mesoscopicPrior (numpy.ndarray): The mesoscopic prior array.
Constraint multiframe nanoscopic subframe data.
nanoscopicData (object): The nanoscopic subframe data.
Constraint’s scaleFactor.
scaleFactor (number): The constraint’s scale factor.
Adjust scale factor dictionary.
adjustScaleFactor (dict): The scale factor adjustment settings dictionary.
Scale factor adjustment update frequency.
adjustScaleFactorUpdate (integer): The update frequency.
Scale factor adjustment minimum number allowed.
adjustScaleFactorMinimum (number): The minimum allowed scale factor value.
Scale factor adjustment maximum number allowed.
adjustScaleFactorMaximum (number): The maximum allowed scale factor value.
Scale factor adjustment learning rate.
adjustScaleFactorLearningRate (number): The learning rate.
Used daX limits.
limits (None, tuple): The (min, max) X limits.
Used data start index as calculated from limits.
limitsIndexStart (integer): The start index.
Used data end index as calculated from limits.
limitsIndexEnd (integer): The end index.
Set the scale factor. This method doesn’t allow specifying frames. It will target used frame only.
scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.
Set adjust scale factor. This method doesn’t allow specifying frames. It will target used frame only.
adjustScaleFactor (None, list, tuple, dict): Used to adjust fit or guess the best scale factor during stochastic engine runtime.
If None, default value {‘update’:10, ‘minimum’:0.8, ‘maximum’:1.2, ‘learning_rate’:0.01} will be automatically set If a list is given, it must include mandatory three items and an optional fourth.
The ‘update’ frequency in number of generated moves of finding the best scale factor. If None or 0 frequency is given, it means that the scale factor is fixed.
The ‘minimum’ allowed scale factor value.
The ‘maximum’ allowed scale factor value.
The scale factor ‘learning_rate’.
If a dict is given, all of ‘update’, ‘minimum’, ‘maximum’ and optional ‘learning_rate’ must be given
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
Set the constraint’s experimental data. This method will raise an error if called after adding constraint to stochastic engine.
experimentalData (numpy.ndarray, string, list, tuple): Experimental data as numpy.ndarray or string path to load data using numpy.loadtxt method. If list or tuple are given, they will be automatically converted to a numpy array by calling numpy.array(experimentalData). Finally experimental data type will be converted to fullrmc.Globals.FLOAT_TYPE
_log (bool): Internal fullrmc flag controlling whether this operation is logged. End users should not need to alter this.
Set experimental data points weight. Data weights will be automatically normalized.
dataWeights (None, string, list, numpy.ndarray): Weights array of the same number of points of experimentalData used in the constraint’s standard error computation. Therefore particular fitting emphasis can be put on different data points that might be considered as more or less important in order to get a reasonable and plausible model.
If None is given, all data points are considered of the same importance in the computation of the constraint’s standard error.
If string, weights will be automatically created. Accepted values are:
‘x’: this will generate monotoneously incrising weights with x value.
‘normalized’: this will generate weights to normalize loss computation with data intensity. Naturally, bigger data values get proportionally higher weight.
If numpy.ndarray is given, all weights must be positive and all zeros weighted data points won’t contribute to the total constraint’s standard error. At least a single weight point is required to be non-zeros and the weights array will be automatically scaled upon setting such as the sum of all the weights is equal to the number of data points.
If list of lists or list of list of tuples is given, items are definitions of weights intensity between bounds where sublist first item is lower bound, second item is upper bound and third item is weight intensity. Intensity can be negative therefore lowering the impact of a region towards total standard error. A possible fourth item can be given to specify the speed at which the region weight intensity is created. e.g. [(2.1, 5.3, 3), (7.3, 10, 2)]
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted. If subframe is given, rest of multiframe subframes will not be targeted.
Checks the constraint’s experimental data This method must be overloaded in all experimental constraint sub-classes.
experimentalData (numpy.ndarray): Experimental data numpy.ndarray.
The best scale factor value is computed by minimizing \(E=sM\).
\(E\) is the experimental data.
\(s\) is the scale factor.
\(M\) is the model constraint data.
This method doesn’t allow specifying frames. It will target used frame only.
experimentalData (numpy.ndarray): Experimental data.
modelData (numpy.ndarray): Constraint modal data.
dataWeights (None, numpy.ndarray): Data points weights to compute the scale factor. If None is given, all data points will be considered as having the same weight.
scaleFactor (number): The new scale factor fit value.
NB: This method won’t update the internal scale factor value of the constraint. It always computes the best scale factor given experimental and atomic model data.
Checks if scale factor should be updated according to the given scale factor frequency and engine’s accepted steps. If adjustment is due, a new scale factor will be computed using fit_scale_factor method, otherwise the constraint’s scale factor will be returned.
experimentalData (numpy.ndarray): the experimental data.
modelData (numpy.ndarray): the constraint modal data.
dataWeights (None, numpy.ndarray): the data points weights to compute the scale factor. If None is given, all data points will be considered as having the same weight.
#. scaleFactor (number): Constraint’s scale factor or the new scale factor fit value.
NB: This method WILL NOT UPDATE the internal scale factor value of the constraint.
compute experimental constraints loss given the set loss function
experimentalData (numpy.ndarray): Experimental data
modelData (numpy.ndarray): model data
agg (bool): whether to aggregate point losses
reset (boolean): whether to force resetting loss function data. Not all losses are resettable
_log (bool): Internal fullrmc flag controlling whether this computation is logged. End users should not need to alter this.
loss (number, numpy.ndarray): the final loss function returned as a number if ‘agg’ is True or a numpy.ndarray if agg is False
Get a dictionary look up table of constraint’s properties that are needed to plot or export
frame (string): frame to pull and build contraint data. It can be a traditional frame, a multiframe or a subframe
asMultiframe (bool): Whether to also aggregate and include multiframe-level weighted data in the returned look up table.
frameDataLUT (dictionary): properties value look up table. Keys are described herein. Values of keys that start with ‘frames-’ are a list for all frames. Values of keys that start with ‘weighted-’ are weighted values for all frames
frames-name: list of all frames name.
frames-mesoscopic_weight: list of all frames weight.
frames-number_of_removed_atoms: list of number of removed atoms from each frame.
frames-experimental_x: list of numpy array of experimental x data.
frames-experimental_y: list of numpy array of experimental y data.
frames-output: list of frames dictionary constraint output data
frames-model_x: list of numpy array of model x data.
frames-shape_array: list of system shape function (numpy array) of all frames.
frames-window_array: list of window function (numpy array) of all frames.
frames-scale_factor: list of all frames scale factor.
frames-standard_error: list of all frames standard error.
weighted-output: dictionary of all frames weighted constraint data using ‘frames-mesoscopic_weight’
weighted-number_of_removed_atoms: All frames averaged number of removed atoms using ‘frames-mesoscopic_weight’
weighted-scale_factor: All frames averaged scale factor using ‘frames-mesoscopic_weight’
weighted-standard_error: All frames weighted standard error using ‘frames-mesoscopic_weight’
Plot constraint data. This can be overloaded in children classes.
frame (None, string): The frame name to plot. If None, used frame will be plotted.
axes (None, matplotlib Axes): matplotlib Axes instance to plot in. If None is given a new plot figure will be created.
asMultiframe (boolean): whether to plot given frame as a multiframe. If not all subframes will be plotted as singular in a multi-axes figure
partialsIntra (boolean): Whether to add partials intra pair distribution function features to the plot.
partialsInter (boolean): Whether to partials inter pair distribution function features to the plot.
partialsTotal (boolean): Whether to partials total pair distribution function features to the plot.
shapeFunc (boolean): Whether to add shape function to the plot only when exists.
resoFunc (boolean): Whether to add resolution function to the plot only when exists.
thermalFunc (boolean): Whether to add thermal correction function to the plot only when exists.
figureAxesNCols (None, int): number of columns in figure to create axes in multi-axes figures. If None, number of columns will be automatically set.
subAdParams (None, dict): matplotlib.artist.Artist.subplots_adjust parameters subplots adjust parameters.
totParams (None, dict): constraint total plotting parameters
expParams (None, dict): constraint experimental data parameters
noWParams (None, dict): constraint total without window parameters
shaParams (None, dict): constraint shape function parameters
resoParams (None, dict): constraint experimental resolution parameters
sigmaParams (None, dict): constraint thermal correction sigma parameters
parParams (None, dict): constraint partials parameters
lossParams (None, dict): constraint loss shading parameters
xlabelParams (None, dict): matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): matplotlib.axes.Axes.set_ylabel parameters.
legendParams (None, dict):matplotlib.axes.Axes.legend parameters.
xticksParams (None, dict):matplotlib.axes.Axes.set_xticklabels parameters.
yticksParams (None, dict):matplotlib.axes.Axes.set_yticklabels parameters.
shareX (bool): whether to share the same xlabel to all axes
shareY (bool): whether to share the same ylabel to all axes
titleParams (bool,string, dict): matplotlib.axes.Axes.set_title parameters
gridParams (None, dict): matplotlib.axes.Axes.grid parameters
colors (None, tuple): Tuple of matplotlib colors cycled through for successive partials. If None, matplotlib defaults are used.
makers (tuple): Tuple of matplotlib markers cycled through for successive partials.
customParams (None, dict): Additional custom plotting parameters overriding computed defaults.
tightLayout (boolean): whether to call figure tight_layout method
twinxPadding (number): Padding fraction applied between successive twin x-axes when multiple ‘$twinx’ parameters are used.
xOffset (number): Constant offset added to the x axis data before plotting.
yOffset (number): Constant offset added to the y axis data before plotting.
xScale (None, string): matplotlib.axes.Axes.set_xscale scale name, e.g. ‘log’. If None, default linear scale is used.
yScale (None, string): matplotlib.axes.Axes.set_yscale scale name, e.g. ‘log’. If None, default linear scale is used.
minX (bool, number): Minimum x axis limit. If True, it is automatically computed.
maxX (bool, number): Maximum x axis limit. If True, it is automatically computed.
minY (bool, number): Minimum y axis limit. If True, it is automatically computed.
maxY (bool, number): Maximum y axis limit. If True, it is automatically computed.
residuals (boolean, dict): whether to plot residuals. If False, no residuals will be show. If True, default parameters will be used. If dict, it must be the residuals parameters. default residuals: {‘ratio’:0.2, ‘line2D’:{‘linestyle’:’-’, ‘linewidth’:1, ‘color’:’#1f77b4’}, ‘spine’:{‘visible’:True:}} (spine accepted properties are: ‘alpha’,’color’,’linestyle’,’linewidth’,’visible’)
show (boolean): Whether to render and show figure before returning.
_frameDataLUT: for internal use only
figure (matplotlib Figure): matplotlib used figure.
axes (matplotlib Axes): matplotlib used axes.
frameDataLUT (dict): the frame data LUT
plot multiframe subframes weight distribution histogram
frame (None, string): multiframe name. If None is given, used frame multiframe will be used
ax (None, matplotlib Axes): matplotlib Axes instance to plot in. If None is given a new plot figure will be created.
legendParams (None, dict): matplotlib.axes.Axes.legend parameters.
titleParams (None, string, dict): title format. If empty string is given no title will be added to figure axes
xlabelParams (None, dict): the x axis label parameters
ylabelParams (None, string): the y axis label parameters
tightLayout (boolean): whether to call figure tight_layout method
returning.
_frameDataLUT: for internal use only
figure (matplotlib Figure): matplotlib used figure.
axes (matplotlib Axes): matplotlib used axes.
frameDataLUT (dict): the frame data LUT
Export constraint data to text file or to an archive of files.
fileName (path): full file name and path.
frame (None, string): frame name to export data from. If multiframe is given, multiple files will be created with subframe name appended to the end.
asSingular (bool): If multiframe is nanoscopic, export subframes as singular frames. nanoscopic data will also be exported.
format (string): string format to export the data. format is as follows (%[flag]width[.precision]specifier)
delimiter (string): String or character separating columns.
comments (string): String that will be prepended to the header.
lines (string): The exported data as a single string, also written to fileName if fileName is not None.
Bases: Constraint
A singular constraint is a constraint that doesn’t allow multiple instances in the same engine.
Get whether only one instance of this constraint type is present in the stochastic engine. True for only itself found, False for other instance of the same __class__.__name__ or constraintId.
engine (stochastic fullrmc engine): Engine instance.
result (boolean): Whether constraint is singular in engine.
Checks whether only one instance of this constraint type is present in the stochastic engine. Raises Exception if multiple instances are present.
engine (Engine): The stochastic engine instance to check constraint instances against.
Bases: Constraint
A rigid constraint is a constraint that doesn’t count into the total standard error of the stochastic Engine. But it’s internal standard error must monotonously decrease or remain the same from one engine step to another. If standard error of an rigid constraint increases the step will be rejected even before engine’s new standardError get computed.
rejectProbability (Number): Rejecting probability of all steps where standard error increases. It must be between 0 and 1 where 1 means rejecting all steps where standardError increases and 0 means accepting all steps regardless whether standard error increases or not.
Rejection probability.
rejectProbability (number): The rejection probability value.
Set the rejection probability. This method doesn’t allow specifying frames. It will target used frame only.
rejectProbability (Number): rejecting probability of all steps where standard error increases. It must be between 0 and 1 where 1 means rejecting all steps where standardError increases and 0 means accepting all steps regardless whether standard error increases or not.
Given a standard error, return whether to keep or reject new standard error according to the constraint reject probability.
#. standardError (number): The standard error to compare with the Constraint standard error
result (boolean): True to reject step, False to accept
Given a standard error, return whether to keep or reject new standard error according to the constraint reject probability.
standardError (number): The standard error to compare with the Constraint standard error
result (boolean): True to accept step, False to reject
Bases: object
Mixin used to convert a regular constraint into a grains-aware
constraint. When mixed in with a Constraint subclass (e.g.
Grains_PairDistributionConstraint), it overrides compute_data,
compute_before_move and compute_after_move with grains-specific
nanoscopic implementations, and it prevents any repository dump so
that the grains engine internal bookkeeping isn’t polluted.
Design pattern implementation.
Subframes data.
subframesData (None, dict): The subframes data dictionary.
Constraints data.
grainsData (None, dict): The grains data dictionary.
set grains data
data (object): multiframe subframes data.
set subframes data
data (object): multiframe subframes data.
Design pattern implementation.
Design pattern implementation.
Design pattern implementation.
Collection of methods and classes definition useful for constraints computation
Get the Grains_Engine class from the Engine module
Grains_Engine (class): the coarse grain engine class
Bases: object
Shape function used to correct for particle shape. The shape function is subtracted from the total G(r) of g(r). It must be used when non-periodic boundary conditions are used to take into account the atomic density drop and to correct for the \(\rho_{0}\) approximation.
engine (Engine): The fitting engine.
weighting (string): The elements weighting.
qmin (number): The minimum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function.
qmax (number): The maximum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function.
dq (number): The reciprocal distance bin size in \(\AA^{-1}\) considered to compute the shape function.
rmin (number): The minimum distance in \(\AA\) considered upon building the histogram prior to computing the shape function.
rmax (number): The maximum distance in \(\AA\) considered upon building the histogram prior to computing the shape function.
dr (number): The bin size in \(\AA\) considered upon building the histogram prior to computing the shape function.
qBandPass (boolean, dict): This is a reciprocal space band-pass filter that can be used to fade reciprocal space high values to zero. Applying such filter will result in a smooth shape function. If True is given then qBandPass will be set to {‘low’:None, ‘high’:{‘type’:’sigmoid’, ‘position’:0.75*qmax, ‘coefficient’:10}, ‘normalize’:True}
normalized (boolean): whether to use the normalized form of the structure factor. This is needed when computing the shape function for a total radial distribution function.
N.B: tweak qmax as small as possible to reduce the wriggles …
Get shape function of G(r) used in a PairDistributionConstraint.
rValues (numpy.ndarray): The r values array.
compute (boolean): whether to recompute shape function reciprocal data.
shapeFunction (numpy.ndarray): The compute shape function.
Get shape function of g(r) used in a PairCorrelationConstraint.
rValues (numpy.ndarray): The r values array.
compute (boolean): whether to recompute shape function reciprocal data.
shapeFunction (numpy.ndarray): The compute shape function.
Get shape function of R(r) used in a RadialDistributionConstraint.
rValues (numpy.ndarray): The r values array.
compute (boolean): whether to recompute shape function reciprocal data.
shapeFunction (numpy.ndarray): The compute shape function.
Converts G(r) to R(r) by computing the following
Gr (numpy.ndarray): The G(r) numpy array of shape (number of points, 2)
elements (dict): dictionary where keys is elements type and values is the number of each element in the system. the sum of all values must be equal to the total number of elements in the system
weights (dict): dictionary of fixed weights.
rho0 (float): the number density of the system
Rr (numpy.ndarray): The R(r) numpy array of shape (number of points, 2)
# import
from fullrmc.Constraints import Collection
from fullrmc.Core.Collection import get_real_elements_weight
#weights = get_real_elements_weight(['Sr', 'Ti', 'O'], None, 'atomicNumber')
weights = {'Sr':7.02, 'Ti':-3.37, 'O':5.805}
Rr = Collection.convert_Gr_to_Rr(Gr=Gr,
elements=engine.numberOfAtomsPerElement,
weights=weights,
rho0 = engine.numberDensity)
Converts R(r) to G(r) by computing the following:
Rr (numpy.ndarray): The R(r) numpy array of shape (number of points, 2)
elements (dict): dictionary where keys is elements type and values is the number of each element in the system. the sum of all values must be equal to the total number of elements in the system
weights (dict): dictionary of fixed weights.
rho0 (float): the number density of the system
Gr (numpy.ndarray): The G(r) numpy array of shape (number of points, 2)
# import
from fullrmc.Constraints import Collection
weights = {'Sr':7.02, 'Ti':-3.37, 'O':5.805}
Gr = Collection.convert_Rr_to_Gr(Rr=Rr,
elements=engine.numberOfAtomsPerElement,
weights=weights,
rho0 = engine.numberDensity)
Converts G(r) to g(r) by computing the following:
Gr (numpy.ndarray): The G(r) numpy array of shape (number of points, 2)
minIndex (int, tuple): The minima indexes to compute the number density rho0. It can be a single peak or a list of peaks to compute the mean slope instead.
bySlope (None, int): whether to compute rho0 using the slope of the first n points. If given it overrides minIndex
rho0 (None, float): if given it overrides minIndex and bySlope
minimas (numpy.ndarray): The minimas array found using minIndex and used to compute the slope and therefore \(\rho_{0}\).
slope (float): The computed slope from the minimas.
rho0 (float): The number density of the material.
g(r) (numpy.ndarray): the computed g(r).
To visualize convertion
# import
from fullrmc.Constraints import Collection
# peak indexes can be different, adjust according to your data
minPeaksIndex = [1,3,4]
minimas, slope, rho0, gr = Collection.convert_Gr_to_gr(Gr, minIndex=minPeaksIndex)
print('slope: %s --> rho0: %s'%(slope,rho0))
import matplotlib.pyplot as plt
line = np.transpose( [[0, Gr[-1,0]], [0, slope*Gr[-1,0]]] )
plt.plot(Gr[:,0],Gr[:,1], label='G(r)')
plt.plot(minimas[:,0], minimas[:,1], 'o', label='minimas')
plt.plot(line[:,0], line[:,1], label='density')
plt.plot(gr[:,0],gr[:,1], label='g(r)')
plt.legend()
plt.show()
Get elements-pair thermal factors given a factors dictionary and a list of elements.
factors (None, dict): dictionary of element or elements pair key and factor values
defaultFactor (number): default factor value used when an elements pair’s factor is missing
elements (list): list of available elements
avgf (str, funct): average type in case pairs factor must be computed. Possible values are ‘arithmetic’, ‘geometric’ or a callable function
thermalFactor (None, dict): dictionary of elements pair thermal factors
Create atomic thermal-vibration correction convolution arrays.
thermalCorrections (None, dict): thermal correction parameters
histogramParameters (None, dict): histogram parameters
funcType (string): thermal correction function type
thermalArrays (None, dict): dictionary of thermal correction convolution arrays, keyed by elements pair. None if thermalCorrections or histogramParameters is None.
stats (None, dict): dictionary of the same keys holding each pair’s ‘sigma’, ‘width’, ‘nbins’ and ‘r’ statistics. None if thermalCorrections or histogramParameters is None.
Create experimental resolution correction array.
resolutionCorrections (None, dict): resolution correction parameters
histogramParameters (None, dict): histogram parameters
resolutionArray (None, numpy.ndarray): the computed resolution correction array. None if resolutionCorrections or histogramParameters is None.
Create qmax cutoff experimental correction array.
qmaxCorrections (None, dict): qmax corrections parameters
histogramParameters (None, dict): histogram parameters
funcType (string): qmax correction function type
qmaxArray (None, numpy.ndarray): the computed qmax cutoff correction array. None if qmaxCorrections or histogramParameters is None, or if qmax is None or <=0.
Converts F(q) to S(q) by computing the following:
Fq (numpy.ndarray): The F(q) numpy array of shape (number of points, 2)
elements (dict): dictionary where keys is elements type and values is the number of each element in the system. the sum of all values must be equal to the total number of elements in the system
weights (dict): dictionary of fixed weights.
rho0 (float): the number density of the system
Sq (numpy.ndarray): The S(q) numpy array of shape (number of points, 2)
# import
from fullrmc.Constraints import Collection
weights = {'Sr':7.02, 'Ti':-3.37, 'O':5.805}
Sq = Collection.convert_Fq_to_Sq(Fq=Fq,
elements=engine.numberOfAtomsPerElement,
weights=weights,
rho0 = engine.numberDensity)
Converts S(q) to F(q) by computing the following:
Sq (numpy.ndarray): The S(q) numpy array of shape (number of points, 2)
elements (dict): dictionary where keys is elements type and values is the number of each element in the system. the sum of all values must be equal to the total number of elements in the system
weights (dict): dictionary of fixed weights.
rho0 (float): the number density of the system
Fq (numpy.ndarray): The F(q) numpy array of shape (number of points, 2)
# import
from fullrmc.Constraints import Collection
weights = {'Sr':7.02, 'Ti':-3.37, 'O':5.805}
Fq = Collection.convert_Sq_to_Fq(Sq=Sq,
elements=engine.numberOfAtomsPerElement,
weights=weights,
rho0 = engine.numberDensity)
DistanceConstraints contains classes for all constraints related to distances between atoms.

Bases: RigidConstraint, SingularConstraint
Atomic distance constraint. This constraint govern atomic pair distances using a lower and upper boundary distances. This constraint is versatile enough to allow constraining pair distances of intra and inter molecular pairs using atoms index, name or element or user defined atom tags. Constraint atom pairs using atoms index is memory eager and shouldn’t be used to constrain all pairs but only when it’s needed.
Given ‘defaultLowerDistance’ and ‘defaultUpperDistance’ will be used to constrain all missing pairs in pairsDefinition.
When a pair is defined in given pairsDefinition, missing upper limit values won’t be populated with ‘defaultUpperDistance’ but will be left un-constrained.
If all of ‘pairsDefinition’, ‘defaultLowerDistance’ and ‘defaultUpperDistance’ are not given, an error will be raised upon setting the constraint engine.
defaultLowerDistance (None, number, tuple): The default lower distance allowed. If number is given it’s meant for intra and inter molecular distances. If tuple is given, it must contain 2 numbers for intra and inter default lower distances
defaultUpperDistance (None, number, tuple): The default upper distance allowed. If number is given it’s meant for intra and inter molecular distances. If tuple is given, it must contain 2 numbers for intra and inter default upper distances
tags (None,dict,list,tuple): If None is given all atom tags will be removed regardless of reset flag value. If a dict is given, keys are string tags and values the list of atom indexes. If a list is given, it must have as many atoms as the number of atoms in the system and the list items must be all strings for atom tags
pairsDefinition (None, dict, list, set, tuple): atomic pair distance definition. The definition can be set for ‘intra’-molecular ‘inter’-molecular or ‘both’ using the respective order of atoms definition by ‘index’, ‘tag’, ‘name’ and ‘element’. If None is given, all atomic distances will be automatically set to the default lower and upper distances. If a list is given, all definitions will be set to both intra-molecular and inter-molecular distances. If a dictionary is given, it can have ‘both’, ‘intra’ and ‘inter’ keys where ‘both’ stands for both intra and inter-molecular. When a definition is given for both it will be set automatically for intra-molecular inter-molecular atomic pair distances. If any of ‘intra’ or ‘inter’ values are None, default lower/upper limits will be omitted for all pairs. A definition is a list of 3, 4 or 5 items. A complete definition of 5 items will be given as (type, atom1, atom2, lower distance, upper distance) where type can be ‘index’, ‘tag’, ‘name’ or ‘element’ which specifies how to identify atom1 and atom2. If definition contains 4 items then the type will be infered from atom1 and atom2, if those are integers then it will be set to ‘index’ otherwise it will be set to ‘element’ If definition contains 3 items, then type will be deduced and the upper distance will be considered not defined. When a lower or a upper distance is set to None then distance constraint for given atom pairs is released.
flexible (boolean): Whether to allow atoms to break constraints definition under the condition of decreasing the constraint total standardError. If flexible is set to False, atoms will never be allowed to cross given lower and upper limits upon a move even if the move will decrease some other unsatisfying atoms distances, and therefore the total standardError of the constraint.
rejectProbability (Number): Probability, between 0 and 1, of rejecting a step that increases standardError. 1 rejects every such step; 0 accepts all steps regardless of standardError.
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Get current state and instantiation parameters
default lower distance value
default upper distance value
user defined atomic tags
list of atom tags
Flexible flag.
user defined pairs definition
dictionary of arrays of number of atomic pairs per definition.
indexes index numpy array of all system atoms
indexes index look up table to indexLimitsArray
number of unique indexes as defined in pairsDefinition
atom tag pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique indexes as defined in pairsDefinition
atom’s index pairs sorted list.
Numpy array look up for index pairs index.
atom’s tag pairs sorted list.
Numpy array look up for tag pairs index.
tags index numpy array of all system atoms
tags index look up table to tagLimitsArray
number of unique tags
atom tag pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique tags
names index numpy array of all system atoms
names index look up table to nameLimitsArray
number of unique atoms name
atom name pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique names
atom’s name pairs sorted list.
Numpy array look up for name pairs index.
elements index numpy array of all system atoms
elements index look up table to elementLimitsArray
number of unique atoms element
atom element pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique elements
atom’s element pairs sorted list.
Numpy array look up for element pairs index.
dictionary of constraints stats
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Set flexible flag.
flexible (boolean): Whether to allow atoms to break constraints definition under the condition of decreasing the constraint total standardError. If flexible is set to False, atoms will never be allowed to cross given lower and upper limits upon a move even if the move will decrease some other unsatisfying atoms distances, and therefore the total standardError of the constraint.
Set atom tags that can be used in setting atomic pair distances definition
tags (None,dict,list,tuple): If None is given all atom tags will be removed regardless of reset flag value. If a dict is given, keys are string tags and values the list of atom indexes. If a list is given, it must have as many atoms as the number of atoms in the system and the list items must be all strings for atom tags
reset (bool): If given tags is a dict, reset will remove all existing tags before setting the new ones
Sets the default lower distance.
defaultLowerDistance (None, number, tuple): The default lower distance allowed. If number is given it’s meant for intra and inter molecular distances. If tuple is given, it must contain 2 numbers for intra and inter default lower distances
Sets the default upper distance.
defaultUpperDistance (None, number, tuple): The default upper distance allowed. If number is given it’s meant for intra and inter molecular distances. If tuple is given, it must contain 2 numbers for intra and inter default upper distances
Given a standardError, return whether to keep or reject new standardError according to the constraint rejectProbability. In addition, if flexible flag is set to True, total number of atoms not satisfying constraints definition must be decreasing or at least remain the same.
standardError (number): Standard error to compare with Constraint’s standard error.
result (boolean): True to reject step, False to accept.
set pairs atomic distance pairs
pairsDefinition (None, dict, list, set, tuple): atomic pair distance definition. The definition can be set for ‘intra’-molecular ‘inter’-molecular or ‘both’ using the respective order of atoms definition by ‘index’, ‘tag’, ‘name’ and ‘element’. If None is given, all atomic distances will be automatically set to the default lower and upper distances.
If a list is given, all definitions will be set to both intra-molecular and inter-molecular distances.
If a dictionary is given, it can have ‘both’, ‘intra’ and ‘inter’ keys where ‘both’ stands for both intra and inter-molecular.
When a definition is given for both it will be automatically set for intra-molecular inter-molecular atomic pair distances.
If any of ‘intra’ or ‘inter’ values are None, default lower/upper limits will be omitted for all pairs.
A definition is a list of 3, 4 or 5 items. A complete definition of 5 items will be given as (type, atom1, atom2, lower distance, upper distance) where type can be ‘index’, ‘tag’, ‘name’ or ‘element’ which specifies how to identify atom1 and atom2.
If definition contains 3 items, then type will be deduced and the upper distance will be considered not defined. When a lower or a upper distance is set to None then distance constraint for given atom pairs is released.
If definition contains 4 items, if first item is not ‘name’, ‘element’ or ‘tag’ then the type will be infered from atom1 and atom2, if those are integers then it will be set to ‘index’ otherwise it will be set to ‘element’. If the first item is the definition type then the upper distance will be considered not defined.
pairsDefinition = {'both':[('ni','ni',3), ('element','c','c',2.1),
('element', 'ti','ti', 2.5, 15)] +
[(i,j,3,4) for i,j in zip(range(10),range(20,30))],
'intra':[('name',C11','H12,',2,None)] }
Get definition stats as a dictionary matching the data structure returned by the get_constraint_value method.
nested (boolean): Whether to get the dictionary nested in order per intra/inter molecular (mol), lower/upper boundary (bod), index/tag/name/element definition types (tp) and then atom pairs tuple as (atom0-atom1). If false, returned data will be a dictionary of (tp,mol,bod,pair) tuple keys
stats (dictionary): definition stats dictionary
Get constraint data in a dictionary format ready for histogram calculation and plotting.
data (None, dict): constraint dictionary data. If None, constraint data will be used
getAll (boolean): Some histogram pair data will always be 0 because of pairs definition priority. If getAll is False, histogram data will only be returned if ‘total_number_of_pairs’ is not 0
nested (boolean): Whether to get the dictionary histogram data as a nested as a single layer dictionary of list values.
data (dictionary): constraint histogram data.
# extract constraint histogram formatted output
data = self.get_histogram_data(nested=False)
# convert to a dataframe
import pandas as pd
dataFrame = pd.DataFrame(data)
Get constraint’s formatted dictionary data.
normalized (bool): whether to normalize distances by number of pairs.
nested (boolean): Whether to get the dictionary nested in order per intra/inter molecular (mol), lower/upper boundary (bod), index/tag/name/element definition types (tp), atom pairs tuple as (atom0-atom1) and finaly the distance/number (valk) key. If false, returned data will be a dictionary of (tp,mol,bod,pair,valk) tuple keys
data (dictionary): Formatted dictionary data. Keys are type pairs and values constraint data.
nested (boolean): Whether to get value as a nested disctionary
Compute the standard error (stdErr) of data not satisfying constraint’s conditions.
Where:
\(N\) is the total number of atoms in the system.
\(D_{ij}\) is the distance constraint set for atoms pair (i,j).
\(d_{ij}\) is the distance between atom i and atom j.
\(\delta\) is the Dirac delta function.
\(\int_{0}^{D_{ij}} \delta(x-d_{ij}) dx\) is equal to 1 if \(0 \leqslant d_{ij} \leqslant D_{ij}\) and 0 elsewhere.
data (dict): data used to compute standard error.
normalized (bool): whether to normalize distances by number of pairs.
resetLoss (boolean): This is to respect the design pattern
standardError (number): The calculated standardError.
Compute constraint’s data.
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
resetLoss (boolean): This is to respect the design pattern
asSingular (boolean): This is to respect the design pattern
data (dict): constraint data dictionary
total (None): This is to respect the design pattern
standardError (float): constraint standard error
Compute constraint before move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint’s data after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Compute and return constraint’s data and standard error as if given atom’s index was amputated.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Accept amputation of atom and sets constraints data and standard error accordingly.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.
Reject amputation of atom.
realIndex (numpy.ndarray): No used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to Constraint.plot with additional parameters
inboundParams (None, dict): matplotlib.axes.Axes.bar parameters for in-bound (satisfying) pairs.
outboundLowerParams (None, dict): matplotlib.axes.Axes.bar parameters for pairs violating the lower distance limit.
outboundUpperParams (None, dict): matplotlib.axes.Axes.bar parameters for pairs violating the upper distance limit.
txtParams (None, dict): matplotlib.axes.Axes.text parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
xticksParams (None, dict): modified matplotlib.axes.Axes.set_xticklabels parameters.
titleParams (None, dict): title format.
show (boolean): Whether to render and show figure before returning.
Bases: DistanceConstraint, Grains_Constraint
Design pattern implementation.
Design pattern implementation.
Design pattern implementation.
AtomicCoordinationConstraints contains classes for all constraints related to coordination number in spherical shells around atoms.

Bases: RigidConstraint, SingularConstraint
Controls the coordination number of atoms.
|
rejectProbability (Number): Probability, between 0 and 1, of rejecting a step that increases standardError. 1 rejects every such step; 0 accepts all steps regardless of standardError.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.AtomicCoordinationConstraints import AtomicCoordinationNumberConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
ACNC = AtomicCoordinationNumberConstraint()
ENGINE.add_constraints(ACNC)
# create definition
ACNC.set_coordination_number_definition( [ ('Al','Cl',1.5, 2.5, 2, 2),
('Al','S', 2.5, 3.0, 2, 2)] )
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Get current state and instantiation parameters
Alias to coordinationNumberDefinition
Copy of coordination number definition dictionary
List of coordination number core atoms index array.
List of coordination number shell atoms index array.
Array of number of core atoms
Array of lower shells distance.
Array of upper shells distance.
Array of minimum number of atoms in a shell.
Array of maximum number of atoms in a shell.
Shells weight which count in the computation of standard error.
Coordination number constraint data.
List of arrays where each element is pointing to a coordination number definition where the atom is a core.
List of arrays where each element is pointing to a coordination number definition where the atom is in a shell.
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Set the coordination number definition.
coordNumDef (None, list, tuple): Coordination number definition. It must be None, list or tuple where every element is a list or a tuple of exactly 6 items and an optional 7th item for weight.
core atoms: Can be any of the following:
string: indicating atomic element.
dictionary: Key as atomic attribute among (element, name) and value is the attribute value.
list, tuple, set, numpy.ndarray: core atoms index.
in shell atoms: Can be any of the following:
string: indicating atomic element.
dictionary: Key as atomic attribute among (element, name) and value is the attribute value.
list, tuple, set, numpy.ndarray: in shell atoms index
Lower distance limit of the coordination shell.
Upper distance limit of the coordination shell.
\(N_{min}\) : minimum number of neighbours in the shell.
\(N_{max}\) : maximum number of neighbours in the shell.
\(W_{i}\) : weight contribution to the standard error, this is optional, if not given it is set automatically to 1.0.
e.g. [ ('Ti','Ti', 2.5, 3.5, 5, 7.1, 1), ('Ni','Ti', 2.2, 3.1, 7.2, 9.7, 100), ...]
[ ({'element':'Ti'},'Ti', 2.5, 3.5, 5, 7.1, 0.1), ...]
[ ('name:au','Au', 2.5, 3.5, 4.1, 6.3), ...]
[ ({'name':'Ni'},'element:Ti', 2.2, 3.1, 7, 9), ...]
[ ('Ti',range(100,500), 2.2, 3.1, 7, 9), ...]
[ ([0,10,11,15,1000],{'name':'Ti'}, 2.2, 3.1, 7, 9, 5), ...]
Compute the standard error (StdErr) of data not satisfying constraint’s conditions.
Where:
\(S\) is the total number of defined coordination number shells.
\(W_{i}\) is the defined weight of coordination number shell i.
\(Dev_{i}\) is the standard deviation of the coordination number in shell definition i.
\(\overline{CN_{i}}\) is the mean coordination number value in shell definition i.
\(N_{min,i}\) is the defined minimum number of neighbours in shell definition i.
\(N_{max,i}\) is the defined maximum number of neighbours in shell definition i.
data (numpy.array): The constraint value data to compute standardError.
resetLoss (boolean): This is to respect the design pattern
standardError (number): The calculated standardError of the constraint.
Get constraint’s data.
data (numpy.array): The constraint value data
Compute constraint’s data.
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
resetLoss (boolean): This is to respect the design pattern
asSingular (boolean): This is to respect the design pattern
data (dict): constraint data dictionary
total (None): This is to respect the design pattern
standardError (float): constraint standard error
Compute constraint’s data before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint’s data after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move.
realIndexes (numpy.ndarray): not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move.
realIndexes (numpy.ndarray): not used here.
relativeIndexes (numpy.ndarray): Not used here.
Compute and return constraint’s data and standard error as if given atom’s index was amputated.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Accept amputation of atom and sets constraints data and standard error accordingly.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.
Reject amputation of atom.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here
Alias to Constraint.plot with additional parameters
dataParams (None, dict): modified constraint data plotting parameters
barParams (None, dict): matplotlib.axes.Axes.bar parameters
txtParams (None, dict): matplotlib.axes.Axes.text parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
xticksParams (None, dict): modified matplotlib.axes.Axes.set_xticklabels parameters.
titleParams (None, dict): title format.
show (boolean): Whether to render and show figure before returning.
BondConstraints contains classes for all constraints related to bond length between atoms.

Bases: RigidConstraint, SingularConstraint
Controls the bond’s length defined between two atoms.
Bond sketch defined between two atoms.¶ |
|
rejectProbability (Number): Probability, between 0 and 1, of rejecting a step that increases standardError. 1 rejects every such step; 0 accepts all steps regardless of standardError.
## Water (H2O) molecule sketch
##
## O
## / \
## / H2O \
## H1 H2
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.BondConstraints import BondConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
BC = BondConstraint()
ENGINE.add_constraints(BC)
# define intra-molecular bonds
BC.create_molecules_bonds( bondsDefinition={"H2O": [ ('name', 'O','H1', 0.88, 1.02),
('name', 'O','H2', 0.88, 1.02) ]} )
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Get current state and instantiation parameters
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
List of defined bonds
bonds definition copy if bonds are defined as such
constraint stats dictionary
supercell flag indicating whether bonds are set using supercell method
copy of user defined tags
Bonds dictionary map of every and each atom
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Sets bonds dictionary by parsing bondsList list.
bondsList (None, list): Bonds definition list. If None is given no bonds are defined. Otherwise it can be of any of the following two forms:
tuples format: every item must be a list or tuple of four items.
First atom index forming the bond.
Second atom index forming the bond.
Lower limit or the minimum bond length allowed.
Upper limit or the maximum bond length allowed.
four vectors format: List of exactly four lists or numpy.arrays of the same length.
List contains the first atoms index forming the bond.
List contains the second atoms index forming the bond.
List containing the lower limit or the minimum bond length allowed.
List containing the upper limit or the maximum bond length allowed.
tform (boolean): set whether given bondsList follows tuples format, If not then it must follow the four vectors one.
Deprecated. Calling this method raises an error; use ‘create_molecules_bonds’ instead.
Helper function that creates bonds in a molecular system using atom elements or unique atom names in molecules.
When parsing the pdb structure file, fullrmc considers a molecule as the consecutive collection of atoms sharing the same ‘Residue name’, ‘Sequence number’ and ‘Segment identifier’.
bondsDefinition (None, dict): The bonds definition. Every key must be a molecule’s name. Every key value must be a list of bonds definitions. Every bond definition is a list of four or five items:
item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’
item 1: bond first atom by type (must be given)
item 2: bond second atom by type (must be given)
item 3: bond lower length (must be given)
item 4: bond upper length (must be given)
e.g. (Carbon tetrachloride): bondsDefinition={"CCL4": [('name', 'C','CL1', 1.55,1.95),
('name', 'C','CL2', 1.55,1.95),
('name', 'C','CL3', 1.55,1.95),
('name', 'C','CL4', 1.55,1.95) ] }
Helper function that creates bonds in a crystalline system using unique atom names in the unitcell. When parsing the pdb structure file, fullrmc considers a molecule (in this case a unitcell) as the consecutive collection of atoms sharing the same ‘Residue name’, ‘Sequence number’ and ‘Segment identifier’.
Setting supercell bonds is equivalent to searching for bonds within every and each unitcell 26 neighbours. This guarantees that the constraint standard error remains zero throughout the whole simulation.
bondsDefinition (None, list): The list of bonds definition. Each definition is a tuple of four items
item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘element’
item 1: bond first atom by type (must be given)
item 2: bond second atom by type (must be given)
item 3: bond lower length (must be given)
item 4: bond upper length (must be given)
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.BondConstraints import BondConstraint
# create engine
ENGINE = Engine()
# build a supercell crystal structure and set it as the engine's structure
ops = ['X,Y,Z', '-X,Y,-Z', '-X,-Y,-Z', 'X,-Y,Z',
'1/2+X,1/2+Y,Z', '1/2-X,1/2+Y,-Z', '1/2-X,1/2-Y,-Z',
'1/2+X,1/2-Y,Z']
atoms = [('Co',0,0,0,1),('O',0,0.5,1),]
a = 5.18
b = 3.015
c = 3.017
alpha = 90. # (alpha, the angle between b and c)
beta = 125.55 # (beta, the angle between a and c)
gamma = 90. # (gamma, the angle between a and b)
supercell = (10,10,10)
ENGINE.build_crystal_set_pdb(symOps = symOps,
atoms = atoms,
unitcellBC = [a,b,c,alpha,beta,gamma],
supercell = supercell)
# create and set bond constraint
BC = BondConstraint()
ENGINE.add_constraints([BC])
BC.create_supercell_bonds(bondsDefinition=[('Co2','O1', 2,4)])
Helper function that create bonds by seeking atoms that are abiding with given definition. This can be used to dynamically set bonds for any atomic system where atomic bonds must be dynamically searched and fixed to avoid extensive non-physical geometric distortion during engine runtime. Setting bonds by search guarantees that the constraint standard error remains zero throughout the whole simulation. When bonds are set using this search method, bonds will be dynamically reset prior to engine run if constraint state doesn’t match engine’s constraint.
Three different ways are adopted to set a bond definition, using atoms ‘element’, ‘name’ or ‘tag’. For a set of 2 atoms, a definition priority is for ‘tag’, if not found ‘name’ will be searched and finally ‘element’
bondsDefinition (None, list,set,tuple): list of definitions. Every definition must be a tuple of 4 or 5 items. If 4 items are given than the first item is set to ‘element’. Definition tuple items are:
item 0: definition atoms type. can be ‘element’,’name’,’tag’. If missing, item 0 will be automatically set to ‘element’
item 1: bond first atom by type (must be given)
item 2: bond second atom by type (must be given)
item 3: bond lower length (must be given)
item 4: bond upper length (must be given)
tags (None,dict,list,tuple): tags are user defined labels for atoms that can be used along with atoms element and name in setting the bonds definition. If a dict is given, keys are string tags and values the list of atom indexes. If a list is given, it must have as many atoms as the number of atoms in the system and the list items must be all strings for atom tags
_search (bool): whether to seach for bonds. This is time consuming and computationally demanding. User might opt to set _search to True just to verify that bonds are found in the atomic system given the provided definition. When bonds are set using ‘search_and_set_bonds’ method, the latter will be called upon engine runtime to search for bonds if the engine state has changed since the search happened or if the engine state is different than the constraint’s one.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.BondConstraints import BondConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
BC = BondConstraint()
ENGINE.add_constraints(BC)
# define intra-molecular bonds
BC.search_and_set_bonds( [('name','ni1','ni1',5,7),
('element','ni','ni',3,4),
('ti','ti',3,4),
('ni','ti',3,4)])
Compute the standard error (StdErr) of data not satisfying constraint conditions.
Where:
\(C\) is the total number of defined bonds constraints.
\(\beta_{i}^{min}\) is the bond constraint lower limit set for constraint i.
\(\beta_{i}^{max}\) is the bond constraint upper limit set for constraint i.
\(\beta_{i}\) is the bond length computed for constraint i.
\(\delta\) is the Dirac delta function.
\(\int_{0}^{\beta_{i}^{min}} \delta(\beta-\beta_{i}) d \beta\) is equal to 1 if \(0 \leqslant \beta_{i} \leqslant \beta_{i}^{min}\) and 0 elsewhere.
\(\int_{\beta_{i}^{max}}^{\infty} \delta(\beta-\beta_{i}) d \beta\) is equal to 1 if \(\beta_{i}^{max} \leqslant \beta_{i} \leqslant \infty\) and 0 elsewhere.
data (object): Data to compute standardError.
resetLoss (boolean): This is to respect the design pattern
standardError (number): The calculated standardError of the given data.
Get constraint’s data.
data (numpy.array): The constraint value data
Compute constraint’s data.
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
resetLoss (boolean): This is to respect the design pattern
asSingular (boolean): This is to respect the design pattern
data (dict): constraint data dictionary
total (None): This is to respect the design pattern
standardError (float): constraint standard error
Compute constraint’s data before move is executed.
realIndexes (numpy.ndarray): Group atoms index the move will be applied to.
relativeIndexes (numpy.ndarray): Not used here.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Compute and return constraint’s data and standard error as if given atom’s index was amputated.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Accept amputation of atom and sets constraints data and standard error accordingly.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Not used here.
Reject amputation of atom.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to Constraint.plot with additional parameters
spacing (float): spacing between definitions histgrams
numberOfTicks (integer): number of ticks per definition histogram
nbins (integer): number of bins per definition histogram
barsRelativeWidth (float): histogram bar relative width >0 and <1
splitBy (None, string): Split definition histograms by atom element, name or merely distance. accepts None, ‘element’, ‘name’
stackHorizontal (boolean): whether to stack definition plots horizontally or vertically
colorCodeXticksLabels (boolean): whether to color code x ticks per definition color
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
titleParams (None, dict): axes title parameters
AngleConstraints contains classes for all constraints related angles between atoms.

Bases: RigidConstraint, SingularConstraint
Controls angle defined between 3 defined atoms, a first atom called central and the remaining two called left and right.
Angle sketch defined between three atoms.¶ |
|
rejectProbability (Number): Rejecting probability of all steps where standardError increases. It must be between 0 and 1 where 1 means rejecting all steps where standardError increases and 0 means accepting all steps regardless whether standardError increases or not.
## Methane (CH4) molecule sketch
##
## H4
## |
## |
## _- C -_
## H1- / -_
## / H3
## H2
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.AngleConstraints import BondsAngleConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
BAC = BondsAngleConstraint()
ENGINE.add_constraints(BAC)
# define intra-molecular angles
BAC.create_molecules_angles( anglesDefinition={"CH4": [ ('name', 'C','H1','H2', 100, 120),
('name', 'C','H2','H3', 100, 120),
('name', 'C','H3','H4', 100, 120),
('name', 'C','H4','H1', 100, 120) ]} )
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Get current state and instantiation parameters
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Defined angles list.
angles definition copy if angles are defined as such
constraint stats dictionary
angles dictionary of every and each atom.
user defined tags
supercell flag indicating whether angles are set using supercell method
Listen to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Sets the angles dictionary by parsing the anglesList. All angles are in degrees.
anglesList (None, list): The angles list definition that can be given in two different formats.
tuples format: every item must be a list of five items.
Central atom index.
Index of the left atom forming the angle (interchangeable with the right atom).
Index of the right atom forming the angle (interchangeable with the left atom).
Minimum lower limit or the minimum angle allowed in degrees which later will be converted to rad.
Maximum upper limit or the maximum angle allowed in degrees which later will be converted to rad.
five vectors format: List of exactly five lists or numpy.arrays or vectors of the same length.
List containing central atom indexes.
List containing the index of the left atom forming the angle (interchangeable with the right atom).
List containing the index of the right atom forming the angle (interchangeable with the left atom).
List containing the minimum lower limit or the minimum angle allowed in degrees which later will be converted to rad.
List containing the maximum upper limit or the maximum angle allowed in degrees which later will be converted to rad.
tform (boolean): set whether given anglesList follows tuples format, If False, then it must follow the five vectors one.
Deprecated. Calling this method raises an error; use ‘create_molecules_angles’ instead.
Helper function that creates angles in a molecular system using atom elements or unique atom names in molecules.
When parsing the pdb structure file, fullrmc considers a molecule as the consecutive collection of atoms sharing the same ‘Residue name’, ‘Sequence number’ and ‘Segment identifier’.
anglesDefinition (None, dict): Angles definition dictionary. Every key must be a molecule’s name. Every key value must be a list of angles definitions. Every angle definition is a list of five or six items:
item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’
item 1: angle central atom by type (must be given)
item 2: angle left atom by type (must be given)
item 3: angle right atom by type (must be given)
item 4: angle lower bound in degrees (must be given)
item 5: angle upper bound in degrees (must be given)
e.g. (Carbon tetrachloride): anglesDefinition={"CCL4": [('name', 'C','CL1','CL2', 105,115),
('name', 'C','CL2','CL3', 105,115),
('name', 'C','CL3','CL4', 105,115),
('name', 'C','CL4','CL1', 105,115) ] }
Helper function that creates angles in a supercell system. Calling this method requires the engine to have the supercell properties set. Setting supercell angles is equivalent to searching for angles within every and each unitcell and its 26 neighbours. This guarantees that the constraint standard error remains zero throughout the whole simulation.
anglesDefinition (None, list): The list of angles definition. Each definition is a tuple of 9 items
item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘element’
item 1: angle central atom by type (must be given)
item 2: angle left atom by type (must be given)
item 3: angle right atom by type (must be given)
item 4: angle central to left lower distance (must be given)
item 5: angle central to left upper distance (must be given)
item 6: angle central to right lower distance. If missing, central to left lower distance will be used
item 7: angle central to right upper distance. If missing central to left upper distance will be used
item 8: angle lower bound in degrees (must be given)
item 9: angle upper bound in degrees (must be given)
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.AngleConstraints import BondsAngleConstraint
# create engine
ENGINE = Engine()
# build a supercell crystal structure and set it as the engine's structure
symOps = ['X,Y,Z', '-X,Y,-Z', '-X,-Y,-Z', 'X,-Y,Z',
'1/2+X,1/2+Y,Z', '1/2-X,1/2+Y,-Z', '1/2-X,1/2-Y,-Z',
'1/2+X,1/2-Y,Z']
atoms = [('Co',0,0,0,1),('O',0,0.5,1),]
a = 5.18
b = 3.015
c = 3.017
alpha = 90. # (alpha, the angle between b and c)
beta = 125.55 # (beta, the angle between a and c)
gamma = 90. # (gamma, the angle between a and b)
supercell = (10,10,10)
ENGINE.build_crystal_set_pdb(symOps = symOps,
atoms = atoms,
unitcellBC = [a,b,c,alpha,beta,gamma],
supercell = supercell)
# create and set angle constraint
BC = BondsAngleConstraint()
ENGINE.add_constraints([BC])
BC.create_supercell_angles(anglesDefinition=[('O','Co','Co',2,4, 30, 120)])
Create angles by seeking atoms that are abiding with given definition. This can be used to dynamically set angles for non-molecular systems such as glass and crystalline materials where atomic angles are needed to fix initial structure from extensive non-physical geometric distortion. Setting angles by search guarantees that the constraint standard error remains zero throughout the whole simulation. When angles are set using this search method, angles will be dynamically reset prior to engine run if constraint state doesn’t match engine’s constraint.
Three different ways are adopted to set an angle definition, using atoms ‘element’, ‘name’ or ‘tag’. For a set of 3 atoms, a definition priority is for ‘tag’, if not found ‘name’ will be searched and finally ‘element’
anglesDefinition (None, list,set,tuple): list of definitions. Every definition must be a tuple of 7, 8, 9 or 10 items.
If 7 items are given then item 0, 6 and 7 are assumed missing. item 0 will be automatically set to ‘element’ and item 6 and 7 will be automatically set to item 4 and 5.
If 8 items are given, then item 6 and 7 are assumed missing and they will be automatically set to item 4 and 5.
If 9 items are given, then item 0 is assumed missing and it will be set to ‘element’
item 0: definition atoms type. can be ‘element’,’name’,’tag’. If missing, item 0 will be automatically set to ‘element’
item 1: angle central atom by type (must be given)
item 2: angle left atom by type (must be given)
item 3: angle right atom by type (must be given)
item 4: angle central to left lower distance (must be given)
item 5: angle central to left upper distance (must be given)
item 6: angle central to right lower distance. If missing, central to left lower distance will be used
item 7: angle central to right upper distance. If missing central to left upper distance will be used
item 8: angle lower bound in degrees (must be given)
item 9: angle upper bound in degrees (must be given)
tags (None,dict,list,tuple): tags are user defined labels for atoms that can be used along with atoms element and name in setting the angles definition. If a dict is given, keys are string tags and values the list of atom indexes. If a list is given, it must have as many atoms as the number of atoms in the system and the list items must be all strings for atom tags
_search (bool): whether to seach for angles. This is time consuming and computationally demanding. User might opt to set _search to True just to verify that angles are found in the atomic system given the provided definition. When angles are set using ‘search_and_set_angles’ method, the latter will be called upon engine runtime to search for angles if the engine state has changed since the search happened or if the engine state is different than the constraint’s one.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.AngleConstraints import BondsAngleConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
BA = BondsAngleConstraint()
ENGINE.add_constraints(BA)
# define intra-molecular angles
BA.search_and_set_angles(anglesDefinition= [('ni','ni','ni', 2.5,3.5, 70,120),
('ni','ti','ni', 2.0,3.0, 70,120),
('name','C1','H11','H12', 2.0,3.0, 2.5,4.0, 30,80),
('tag','t1','t1','t0', 1.0,2.0, 1.5,3.0, 40,120),],
tags = {'t0':[0,1,2,3,4], 't1':list(range(5,20))},
_search = True)
Compute the standard error (StdErr) of data not satisfying constraint conditions.
Where:
\(C\) is the total number of defined angles constraints.
\(\theta_{i}^{min}\) is the angle constraint lower limit set for constraint i.
\(\theta_{i}^{max}\) is the angle constraint upper limit set for constraint i.
\(\theta_{i}\) is the angle computed for constraint i.
\(\delta\) is the Dirac delta function.
\(\int_{0}^{\theta_{i}^{min}} \delta(\theta-\theta_{i}) d \theta\) is equal to 1 if \(0 \leqslant \theta_{i} \leqslant \theta_{i}^{min}\) and 0 elsewhere.
\(\int_{\theta_{i}^{max}}^{\pi} \delta(\theta-\theta_{i}) d \theta\) is equal to 1 if \(\theta_{i}^{max} \leqslant \theta_{i} \leqslant \pi\) and 0 elsewhere.
data (numpy.array): Constraint’s data to compute standardError.
resetLoss (boolean): This is to respect the design pattern
standardError (number): The calculated standardError of the given data.
Get constraint’s data value.
data (dictionary): constraint data, where keys are the element wise intra and inter molecular angle definitions and values are the computed data.
Compute constraint’s data.
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
resetLoss (boolean): This is to respect the design pattern
asSingular (boolean): This is to respect the design pattern
data (dict): constraint data dictionary
total (None): This is to respect the design pattern
standardError (float): constraint standard error
Compute constraint before move is executed.
realIndexes (numpy.ndarray): Group atoms index the move will be applied to.
relativeIndexes (numpy.ndarray): Not used here.
Compute constraint after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Accept amputation of atom and set constraint’s data and standard error accordingly.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Not used here.
Reject amputation of atom.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to Constraint.plot with additional parameters
spacing (float): spacing between definitions histgrams
numberOfTicks (integer): number of ticks per definition histogram
nbins (integer): number of bins per definition histogram
barsRelativeWidth (float): histogram bar relative width >0 and <1
element, name or merely distance. accepts None, ‘element’, ‘name’
horizontally or vertically
per definition color
parameters.
parameters.
titleParams (None, dict): axes title parameters
ImproperAngleConstraints contains classes for all constraint’s related to improper angles between atoms.

Bases: RigidConstraint, SingularConstraint
Dihedral angle is defined between two intersecting planes formed with defined atoms. Dihedral angle constraint can control up to three angle shells at the same times.
Dihedral angle sketch defined between two planes formed with four atoms.¶ |
rejectProbability (Number): Probability, between 0 and 1, of rejecting a step that increases standardError. 1 rejects every such step; 0 accepts all steps regardless of standardError.
## Butane (BUT) molecule sketch
##
## H13 H22 H32 H43
## | | | |
## H11---C1---C2---C3---C4---H41
## | | | |
## H12 H21 H31 H42
##
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.DihedralAngleConstraints import DihedralAngleConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
DAC = DihedralAngleConstraint()
ENGINE.add_constraints(DAC)
# define intra-molecular dihedral angles
DAC.create_molecules_angles( anglesDefinition={"BUT": [ ('name', 'C1','C2','C3','C4', 40,80, 100,140, 290,330), ] })
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
constraint stats dictionary
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Get current state and instantiation parameters
Improper angles list.
angles definition copy if dihedral angles are defined as such
Angles dictionary for every and each atom.
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Sets the angles dictionary by parsing the anglesList list. All angles are in degrees. A dihedral angle can control up to three angle shells at the same time, each defined by different lower and upper angle bounds simulating three different dihedral potential energy minimums. Dihedral angles are defined from 0 to 360 degrees. A shell’s lower and upper bounds define a dihedral angle clockwise. To account for the wraparound at 0 and 360 degrees, the lower bound is allowed to be higher than the upper bound.
e.g. (50, 100) is a dihedral shell defined in the angle range between 50 and 100 degrees. But (100, 50) dihedral shell is defined between 100 to 360 degrees and wraps the range from 0 to 100. (50, 100) and (100, 50) are complementary and cover the whole range from 0 to 360 deg.
anglesList (None,list): The angles list definition.
tuples format: every item must be a list of ten items.
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.
Minimum lower limit of the first shell or minimum angle allowed in degrees which later will be converted to rad.
Maximum upper limit of the first shell or maximum angle allowed in degrees which later will be converted to rad.
Minimum lower limit of the second shell or minimum angle allowed in degrees which later will be converted to rad.
Maximum upper limit of the second shell or maximum angle allowed in degrees which later will be converted to rad.
Minimum lower limit of the third shell or minimum angle allowed in degrees which later will be converted to rad.
Maximum upper limit of the third shell or maximum angle allowed in degrees.
ten vectors format: every item must be a list of ten items.
List containing first atoms index of the first plane.
List containing second atoms index of the first plane and first atoms index of the second plane.
List containing third atoms indexes of the first plane and second atoms index of the second plane.
List containing fourth atoms index of the second plane.
List containing minimum lower limit of the first shell or minimum angle allowed in degrees which later will be converted to rad.
List containing maximum upper limit of the first shell or maximum angle allowed in degrees which later will be converted to rad.
List containing minimum lower limit of the second shell or minimum angle allowed in degrees which later will be converted to rad.
List containing maximum upper limit of the second shell or maximum angle allowed in degrees which later will be converted to rad.
List containing minimum lower limit of the third shell or minimum angle allowed in degrees which later will be converted to rad.
List containing maximum upper limit of the third shell or maximum angle allowed in degrees which later will be converted to rad.
tform (boolean): set whether given anglesList follows tuples format, If not then it must follow the ten vectors one.
N.B. Defining three shells boundaries is mandatory. In case fewer than three shells is needed, it suffices to repeat one of the shells boundaries.
e.g. (‘C1’,’C2’,’C3’,’C4’, 40,80, 100,140, 40,80), in the herein definition the last shell is a repetition of the first which means only two shells are defined.
Deprecated. Calling this method raises an error; use ‘create_molecules_angles’ instead.
Helper function that creates dihedral angles in a molecular system using atom elements or unique atom names in molecules.
When parsing the pdb structure file, fullrmc considers a molecule as the consecutive collection of atoms sharing the same ‘Residue name’, ‘Sequence number’ and ‘Segment identifier’.
anglesDefinition (None, dict): The angles definition. Every key must be a molecule name (residue name in pdb file). Every key value must be a list of angles definitions. Every angle definition is a list of ten items where:
item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’
item 1: dihedral first atom by type of the first plane (must be given)
item 2: dihedral second atom by type of the first plane which is also the first atom of the second plane (must be given)
item 3: dihedral third atom by type of the first plane which is also the second atom of the second plane (must be given)
item 4: dihedral third atom by type of the second plane(must be given)
item 5: Minimum lower limit of the first shell or the minimum angle allowed in degrees (must be given)
item 6: Maximum upper limit of the first or the maximum angle allowed in degrees (must be given)
item 7: Minimum lower limit of the second shell or the minimum angle allowed in degrees (must be given)
item 8: Maximum upper limit of the second or the maximum angle allowed in degrees (must be given)
item 9: Minimum lower limit of the third shell or the minimum angle allowed in degrees (must be given)
item 10: Maximum upper limit of the third or the maximum angle allowed in degrees (must be given)
e.g. (Butane): anglesDefinition={"BUT": [ ('name', 'C1','C2','C3','C4', 40,80, 100,140, 290,330), ] }
Compute the standard error (StdErr) of data not satisfying constraint conditions.
Where:
\(C\) is the total number of defined improper angles constraints.
\(\theta_{i}^{min}\) is the improper angle constraint lower limit set for constraint i.
\(\theta_{i}^{max}\) is the improper angle constraint upper limit set for constraint i.
\(\theta_{i}\) is the improper angle computed for constraint i.
\(\delta\) is the Dirac delta function.
\(\int_{0}^{\theta_{i}^{min}} \delta(\theta-\theta_{i}) d \theta\) is equal to 1 if \(0 \leqslant \theta_{i} \leqslant \theta_{i}^{min}\) and 0 elsewhere.
\(\int_{\theta_{i}^{max}}^{\pi} \delta(\theta-\theta_{i}) d \theta\) is equal to 1 if \(\theta_{i}^{max} \leqslant \theta_{i} \leqslant \pi\) and 0 elsewhere.
data (numpy.array): The constraint value data to compute standardError.
resetLoss (boolean): This is to respect the design pattern
standardError (number): The calculated standardError of the constraint.
Get constraint’s data.
data (numpy.array): The constraint value data
Compute constraint’s data.
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
resetLoss (boolean): This is to respect the design pattern
asSingular (boolean): This is to respect the design pattern
data (dict): constraint data dictionary
total (None): This is to respect the design pattern
standardError (float): constraint standard error
Compute constraint’s data before move is executed.
realIndexes (numpy.ndarray): Group atoms index the move will be applied to.
relativeIndexes (numpy.ndarray): Not used here.
Compute constraint’s data after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Accept amputation of atom and set constraint’s data and standard error accordingly.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Not used here.
Reject amputation of atom.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to Constraint.plot with additional parameters
spacing (float): spacing between definitions histgrams
numberOfTicks (integer): number of ticks per definition histogram
nbins (integer): number of bins per definition histogram
barsRelativeWidth (float): histogram bar relative width >0 and <1
splitBy (None, string): Split definition histograms by atom element, name or merely distance. accepts None, ‘element’, ‘name’
stackHorizontal (boolean): whether to stack definition plots horizontally or vertically
colorCodeXticksLabels (boolean): whether to color code x ticks per definition color
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
titleParams (None, dict): axes title parameters
ImproperAngleConstraints contains classes for all constraints related to improper angles between atoms.

Bases: RigidConstraint, SingularConstraint
Controls the improper angle formed with 4 defined atoms. It’s mainly used to keep the improper atom in the plane defined with three other atoms. The improper vector is defined as the vector from the first atom of the plane to the improper atom. Therefore the improper angle is defined between the improper vector and the plane.
Improper angle sketch defined between four atoms.¶ |
rejectProbability (Number): Probability, between 0 and 1, of rejecting a step that increases standardError. 1 rejects every such step; 0 accepts all steps regardless of standardError.
## Tetrahydrofuran (THF) molecule sketch
##
## O
## H41 / \ H11
## \ / \ /
## H42-- C4 THF C1 --H12
## \ MOLECULE /
## \ /
## H31-- C3-------C2 --H21
## / \
## H32 H22
##
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.ImproperAngleConstraints import ImproperAngleConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
IAC = ImproperAngleConstraint()
ENGINE.add_constraints(IAC)
# define intra-molecular improper angles
IAC.create_molecules_angles( anglesDefinition={"THF": [ ('name', 'C2','O','C1','C4', -15, 15),
('name', 'C3','O','C1','C4', -15, 15) ] })
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Get current state and instantiation parameters
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Get improper angles list.
angles definition copy if improper angles are defined as such
Get angles dictionary for every and each atom.
constraint stats dictionary
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Sets the angles dictionary by parsing the anglesList list.
anglesList (None, list): Angles list definition.
tuples format: every item must be a list of six items.
Improper atom index that must be in the plane.
Index of atom ‘O’ considered the origin of the plane.
Index of atom ‘x’ used to calculated ‘Ox’ vector.
Index of atom ‘y’ used to calculated ‘Oy’ vector.
Minimum lower limit or minimum angle allowed in degrees which later will be converted to rad.
Maximum upper limit or maximum angle allowed in degrees which later will be converted to rad.
six vectors format: every item must be a list of six items.
List containing improper atoms index that must be in the plane.
List containing index of atoms ‘O’ considered the origin of the plane.
List containing index of atoms ‘x’ used to calculated ‘Ox’ vector.
List containing index of atom ‘y’ used to calculated ‘Oy’ vector.
List containing minimum lower limit or minimum angle allowed in degrees which later will be converted to rad.
List containing maximum upper limit or maximum angle allowed in degrees which later will be converted to rad.
tform (boolean): Whether given anglesList follows tuples format, If not then it must follow the six vectors one.
Deprecated. Calling this method raises an error; use ‘create_molecules_angles’ instead.
Helper function that creates improper angles in a molecular system using atom elements or unique atom names in molecules.
When parsing the pdb structure file, fullrmc considers a molecule as the consecutive collection of atoms sharing the same ‘Residue name’, ‘Sequence number’ and ‘Segment identifier’.
anglesDefinition (None, dict): Angles definition. Every key must be a molecule name. Every key value must be a list of angles definitions. Every angle definition is a list of five items where:
item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’
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)
e.g. (Benzene): anglesDefinition={"BENZ": [('name', 'C3','C1','C2','C6', -10,10),
('name', 'C4','C1','C2','C6', -10,10),
('name', 'C5','C1','C2','C6', -10,10) ] }
Compute the standard error (StdErr) of data not satisfying constraint’s conditions.
Where:
\(C\) is the total number of defined improper angles constraints.
\(\theta_{i}^{min}\) is the improper angle constraint lower limit set for constraint i.
\(\theta_{i}^{max}\) is the improper angle constraint upper limit set for constraint i.
\(\theta_{i}\) is the improper angle computed for constraint i.
\(\delta\) is the Dirac delta function.
\(\int_{0}^{\theta_{i}^{min}} \delta(\theta-\theta_{i}) d \theta\) is equal to 1 if \(0 \leqslant \theta_{i} \leqslant \theta_{i}^{min}\) and 0 elsewhere.
\(\int_{\theta_{i}^{max}}^{\pi} \delta(\theta-\theta_{i}) d \theta\) is equal to 1 if \(\theta_{i}^{max} \leqslant \theta_{i} \leqslant \pi\) and 0 elsewhere.
data (numpy.array): data to compute standardError.
resetLoss (boolean): This is to respect the design pattern
standardError (number): computed standardError of given data.
Get constraint’s data value.
data (dictionary): constraint data.
Compute constraint’s data.
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
resetLoss (boolean): This is to respect the design pattern
asSingular (boolean): This is to respect the design pattern
data (dict): constraint data dictionary
total (None): This is to respect the design pattern
standardError (float): constraint standard error
Compute constraint’s data before move is executed.
realIndexes (numpy.ndarray): Group atoms index the move will be applied to.
relativeIndexes (numpy.ndarray): Not used here.
Compute constraint’s data after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Accept amputation of atom and sets constraint’s data and standard error accordingly.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Not used here.
Reject amputation of atom.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to Constraint.plot with additional parameters
spacing (float): spacing between definitions histgrams
numberOfTicks (integer): number of ticks per definition histogram
nbins (integer): number of bins per definition histogram
barsRelativeWidth (float): histogram bar relative width >0 and <1
splitBy (None, string): Split definition histograms by atom element, name or merely distance. accepts None, ‘element’, ‘name’
stackHorizontal (boolean): whether to stack definition plots horizontally or vertically
colorCodeXticksLabels (boolean): whether to color code x ticks per definition color
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
titleParams (None, dict): axes title parameters
PairDistributionConstraints contains classes for all constraints related to experimental pair distribution functions.

Bases: ExperimentalConstraint, AtomsPairWeighting, HistogramCorrections
Controls the total pair distribution function (pdf) of atomic configuration noted as G(r) that is also known as the Billinge & Egami or Proffen & Billinge G(r). The pair distribution function is directly calculated from the experimental diffraction pattern. It is obtained from the Sine Fourier transform of the total-scattering function as the following:
Theoretically G(r) oscillates about zero. Also \(G(r) \rightarrow 0\) when \(r \rightarrow \infty\) and \(G(r) \rightarrow 0\) when \(r \rightarrow 0\) with a slope of \(-4\pi\rho_{0}\) where \(\rho_{0}\) is the number density of the material.
Model wise, G(r) is computed after calculating the so called Pair Correlation Function noted as g(r). The relation between G(r) and g(r) is given by
\(\rho_{r}\) is the number density fluctuation at distance \(r\). The computation of g(r) is straightforward from an atomistic model and it is given by \(g(r)=\rho_{r} / \rho_{0}\).
The pair distribution function \(G(r)\) describes the pair wise density structure of the material and is known as the Billinge & Egami (Phys. Rev. B, 47, 14386-14406 (1993). (2001) 34 172-177) or the Proffen & Billinge function (PDFFIT Users Guide. Private communication (1998)).
On the other hand, the total radial distribution function noted \(R(r)\) is another form of distribution functions that is also widely used to describe the structure of a materials and it’s known as the Keen distribution function (J. Appl. Cryst. 34 172-177 (2001))
Finally, g(r) is calculated after binning all pair atomic distances into a weighted histograms of values \(n(r)\) from which local number densities are computed as the following:
The partial radial distribution function or \(g_{i,j}(r)dr\) gives the number of atoms j in an annulus of thickness dr at distance r from another atom i. Therefore, the coordination number, or the number of neighbors within the distances interval \([a,b]\) is given by \(\int_{a}^{b} 4 \pi r^{2} c_{j} \rho_{0} g_{i,j}(r)dr\)
Where:
\(Q\) is the momentum transfer.
\(r\) is the distance between two atoms.
\(N\) is the total number of atoms in the system.
\(V\) is the volume of the system.
\(i,j\) atoms element pair i and j.
\(N_{i,j}\) is the total number of atoms pair i and j in the system.
\(c_{i}=\frac{n_{i}}{V}\) is molar ratio atom type i.
\(b_{i}\) is the coherent scattering length of element i (e.g. Xray, neutron, etc.).
\(\bar{b_{i}} = \frac{b_{i}} {\sum \limits_{j}^{N} b_{j}}\) is the coherent scattering length of element i, averaged over all elements as well as the different isotopes and nuclear spin states of i in case of neutron scattering.
\(\rho_{0}\) is the average number density of all atoms in the system.
\(\rho_{<i,j>}\) is the average number density of i,j atom pairs the system.
\(\rho_{i,j}(r)\) is the pair density function of atom i,j pairs.
\(R(r)\) is the radial distribution function (rdf).
\(n_{i,j}(r)\) is the number of atoms i neighbouring j at a distance r.
\(v(r)\) is the annulus volume at distance r and of thickness dr.
|
experimentalData (numpy.ndarray, string): Experimental data as numpy.ndarray or string path to load data using numpy.loadtxt.
dataWeights (None, numpy.ndarray): Weights array of the same length as experimentalData, used in the constraint’s standard error computation. This allows fitting emphasis to be placed on data points considered more or less important, to obtain a reasonable and plausible model.
If None, all data points are considered equally important in computing the constraint’s standard error.
If a numpy.ndarray is given, all weights must be positive; zero-weighted data points do not contribute to the total standard error. At least one weight must be non-zero, and the weights array is automatically scaled so that the sum of all weights equals the number of data points.
weighting (string): The elements weighting scheme. It must be any atomic attribute (atomicNumber, neutronCohb, neutronIncohb, neutronCohXs, neutronIncohXs, atomicWeight, covalentRadius) defined in pdbparser database. In case of xrays or neutrons experimental weights, one can simply set weighting to ‘xrays’ or ‘neutrons’ and the value will be automatically adjusted to respectively ‘atomicNumber’ and ‘neutronCohb’. If attribute values are missing in the pdbparser database, atomic weights must be given in atomsWeight dictionary argument.
atomsWeight (None, dict): Atoms weight dictionary where keys are atoms element and values are custom weights. If None is given or partially given, missing elements weighting will be fully set given weighting scheme.
pairsWeight (None, dict): Atom pairs weight. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2. Customizing pairs weight is needed for differential or resonant experimental setups. If el1 weighting or atomWeigth value is x and el2 value is y then (el1,el2) pair value weight is x*y.
custPartScatteringPower (None, dict): Atom pairs scattering power. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2.
scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.
adjustScaleFactor (None, list, tuple, dict): Used to adjust or auto-fit the best scale factor during stochastic engine runtime.
If None, the default {‘update’:10, ‘minimum’:0.8, ‘maximum’:1.2, ‘learning_rate’:0.01} is used.
If a list is given, it must include three mandatory items and an optional fourth:
The ‘update’ frequency, in number of generated moves, for finding the best scale factor. If None or 0, the scale factor is fixed.
The ‘minimum’ allowed scale factor value.
The ‘maximum’ allowed scale factor value.
The scale factor ‘learning_rate’.
If a dict is given, it must include ‘update’, ‘minimum’, ‘maximum’ and, optionally, ‘learning_rate’.
shapeFuncParams (None, numpy.ndarray, dict): The shape function is subtracted from the total G(r). It must be used when non-periodic boundary conditions are used to take into account the atomic density drop and to correct for the \(\rho_{0}\) approximation. The shape function can be set to None which means unsused, or set as a constant shape given by a numpy.ndarray or computed from all atoms and updated every ‘updateFreq’ accepted moves. If dict is given the following keywords can be given, otherwise default values will be automatically set.
rmin (number) default (0.00) : The minimum distance in \(\AA\) considered upon building the histogram prior to computing the shape function. If None, rmin will be automatically set to \(0.2\ *\ maximum\ box\ distance\) at engine runtime. If <1 is given, it’s then considered the max box distance ratio and therefore automatically set during engine runtime to \(rmin\ *\ maximum\ box\ distance\)
rmax (None, number) default (None) : The maximum distance in \(\AA\) considered upon building the histogram prior to computing the shape function. If not defined, rmax will be automatically set to \(maximum\ box\ distance + 1\AA\) at engine runtime.
dr (number) default (0.5) : The bin size in \(\AA\) considered upon building the histogram prior to computing the shape function. If not defined, it will be automatically set to 0.5.
qmin (number) default (0.001) : The minimum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function. If not defined, it will be automatically set to 0.001.
qmax (None, number) default (None) : The maximum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function. If not defined, it will be automatically set to \(\frac{2\pi}{rmin}\)
dq (number) default (0.005) : The reciprocal distance bin size in \(\AA^{-1}\) considered to compute the shape function. If not defined, it will be automatically set to 0.005.
updateFreq (integer) default (1000) : The frequency of recomputing the shape function in number of accepted moves.
modulate large wiggles due to finite number of data points upon real to reciprocal space transformation. Wiggles modulation is achieved by doing number of data points adjustment in real space and reciprocal space averaging. If float, it must be >=0 and if Integer is given, it must be >=0
flexible (boolean, float) default (0.1) : Whether to allow updated shape function deteriorating the constraint standard error. If False, any increase in standard error will reject the newly updated shape function. If True, always accept new shape function. If a number is given it will be the maximum accepted standard error ratio increase e.g. flexbile set to 1.0 means that a newly computed shape function is accepted as long as the standard error do not increase by 100%
smoothing (None, numpy.ndarray, list, dict) default ({“z”:2, ‘ps’:0.15}) : The shape function smoothing function. If None, no smoothing will be applied. If a list or a numpy.ndarray is given then this will be be the smoothing filter. If dict is given, then two parameters can be set. z for the filter z score and ps for the filter size in percent of size of computed shape array
thermalCorrections (None, number, dict): Atomic thermal vibration parameters used to correct for the broadening of partial histogram peaks. If None, no correction is made. If a number is given, it is used as the thermal vibration coefficient for all element pairs. If a dictionary is given, it can include any of the ‘set_thermal_corrections’ method parameters.
qmaxCorrections (None, number, dict): Experimental real space atomic distribution is obtained by a Fourier transform of the reduced structure factor F(q). However, the experimental q range is limited by a certain maximum measurable value \(Q_{max}\). Theoretically, this is similar to multiplying an infinite q range F(q) with a Heaviside step function cutting off at \(Q_{max}\). Fourier transforming this multiplied step function from the reciprocal to real space will result in a convolution with sine cardinal function defined as \(S(r)=sinc(Q_{max}r)=sin(Q_{max}r)/rQ_{max}r)\). If None is given, no \(Q_{max}\) correction will be made. If a number is given, it will be considered the experimental \(Q_{max}\) in \(\AA^{-1}\). If a dictionary is given, it can then include any of ‘set_qmax_corrections’ method parameters.
resolutionCorrections (None, number, dict): Experimental resolution correction parameters defined as a simple multiplication of the total atomic distribution with \(e^{-0.5\sigma_{q}^2r^2}\). If None is given, no experimental resolution corrections will be made. If a number is given, it will be considered the damping value \(\sigma_{q}\). If a dictionary is given, it can then include any of ‘set_resolution_corrections’ method parameters.
windowFunction (None, dict, numpy.ndarray): The window function to convolute with the computed pair distribution function before comparing it to the experimental data. Experimental G(r) typically shows artificial wrinkles, largely because it is obtained via a sine Fourier transform of the experimental structure factor S(q); the window function approximates these numerical artefacts. If a dict is given, it is used as kwargs for fullrmc.Core.Collection.get_normal_filter, with default values {‘z’:3, ‘ps’:0.05} (3 standard deviations, 5% size width).
limits (None, tuple, list): The distance limits to compute the histograms. If None is given, the limits will be automatically set the min and max distance of the experimental data. Otherwise, a tuple of exactly two items where the first is the minimum distance or None and the second is the maximum distance or None.
NB: If adjustScaleFactor first item (frequency) is 0, the scale factor will remain untouched and the limits minimum and maximum won’t be checked.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairDistributionConstraints import PairDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
PDC = PairDistributionConstraint(experimentalData="pdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PDC)
For experimental constraints nanoscopic parameters must be overloaded
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Get current state and instantiation parameters
Experimental data distances bin.
Experimental data minimum distances.
Experimental data maximum distances.
Histogram size.
Experimental distances array.
Shells center array.
Shells volume array.
Experimental pair distribution function data.
Window function.
Window function.
Shape function data array.
Shape function update frequency.
shape function parameters
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Set the shape function. The shape function can be set to None which means unsused, or set as a constant shape given by a numpy.ndarray or computed from all atoms and updated every ‘updateFreq’ accepted moves. The shape function is subtracted from the total G(r). It must be used when non-periodic boundary conditions are used to take into account the atomic density drop and to correct for the \(\rho_{0}\) approximation.
shapeFuncParams (None, numpy.ndarray, dict): The shape function is subtracted from the total G(r). It must be used when non-periodic boundary conditions are used to take into account the atomic density drop and to correct for the \(\rho_{0}\) approximation. The shape function can be set to None which means unsused, or set as a constant shape given by a numpy.ndarray or computed from all atoms and updated every ‘updateFreq’ accepted moves. If dict is given the following keywords can be given, otherwise default values will be automatically set.
rmin (number) default (0.00) : The minimum distance in \(\AA\) considered upon building the histogram prior to computing the shape function. If None, rmin will be automatically set to \(0.2\ *\ maximum\ box\ distance\) at engine runtime. If <1 is given, it’s then considered the max box distance ratio and therefore automatically set during engine runtime to \(rmin\ *\ maximum\ box\ distance\)
rmax (None, number) default (None) : The maximum distance in \(\AA\) considered upon building the histogram prior to computing the shape function. If not defined, rmax will be automatically set to \(maximum\ box\ distance + 1\AA\) at engine runtime.
dr (number) default (0.5) : The bin size in \(\AA\) considered upon building the histogram prior to computing the shape function. If not defined, it will be automatically set to 0.5.
qmin (None, number) default (0.001) : The minimum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function. If not defined, it will be automatically set to 0.001.
qmax (None, number) default (None) : The maximum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function. If not defined, it will be automatically set to \(\frac{2\pi}{rmin}\)
dq (number) default (0.005) : The reciprocal distance bin size in \(\AA^{-1}\) considered to compute the shape function. If not defined, it will be automatically set to 0.005.
updateFreq (integer) default (1000) : The frequency of recomputing the shape function in number of accepted moves.
qBandPass (boolean, dict) default (True): This is a reciprocal space band-pass filter that can be used to fade reciprocal space high values to zero. Applying such filter will result in a smooth shape function. If True is given then qBandPass will be set to {‘low’:None, ‘high’:{‘type’:’sigmoid’, ‘position’:0.75*qmax, ‘coefficient’:10}, ‘normalize’:True}
modulation (boolean, integer, float) default (False) : This is used to modulate large wiggles due to finite number of data points upon real to reciprocal space transformation. Wiggles modulation is achieved by doing number of data points adjustment in real space and reciprocal space averaging. If True, modulation of half a period will be done given by \(\pi/(shellCenters[-1]-shellCenters[0])\)
If float, it must be >=0 multiplying the computed half a period
If Integer is given, it must be >=0 specifying the number of data points to modulate
flexible (boolean, float) default (0.1) : Whether to allow updated shape function deteriorating the constraint standard error. If False, any increase in standard error will reject the newly updated shape function. If True, always accept new shape function. If a number is given it will be the maximum accepted standard error ratio increase e.g. flexbile set to 1.0 means that a newly computed shape function is accepted as long as the standard error do not increase by 100%
smoothing (None, numpy.ndarray, list, dict) default (None) : The shape function smoothing function. If None, no smoothing will be applied. If a list or a numpy.ndarray is given then this will be be the smoothing filter. If dict is given, then two parameters can be set. z for the filter z score and ps for the filter size in percent of size of computed shape array. e.g. {“z”:2, ‘ps’:0.15}
Set convolution window function.
windowFunction (None, dict, numpy.ndarray): The window function to convolute with the computed pair distribution function before comparing it to the experimental data. Experimental G(r) typically shows artificial wrinkles, largely because it is obtained via a sine Fourier transform of the experimental structure factor S(q); the window function approximates these numerical artefacts. If a dict is given, it is used as kwargs for fullrmc.Core.Collection.get_normal_filter, with default values {‘z’:3, ‘ps’:0.05} (3 standard deviations, 5% size width).
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.
Set constraint’s experimental data.
experimentalData (numpy.ndarray, string): The experimental data as numpy.ndarray or string path to load data using numpy.loadtxt function.
Set the histogram computation limits.
limits (None, tuple, list): Distance limits to bound experimental data and compute histograms. If None is given, the limits will be automatically set the min and max distance of the experimental data. Otherwise, a tuple of exactly two items where the first is the minimum distance or None and the second is the maximum distance or None.
Check whether experimental data is correct.
experimentalData (object): Experimental data to check.
result (boolean): Whether it is correct or not.
message (str): Checking message that explains whats’s wrong with the given data.
Compute the standard error (StdErr) using the engine defined loss function
data (numpy.ndarray): The constraint data
resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!
standardError (number): The calculated constraint’s standardError.
Compute and set constraint’s standardError.
Get constraint total and standard error
data (None, dict): data to compute total. If None, constraint data will be used.
rho0 (None, number): the system number density. If None, engine number density is used
total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned
stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned
Compute all partial Pair Distribution Functions (PDFs).
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.
Compute all partial Pair Distribution Functions (PDFs).
PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.
Compute constraint’s data.
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
data (dict): constraint data dictionary
total (numpy.ndarray): constraint total pair distribution function
standardError (float): constraint standard error
Compute constraint before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Compute and return constraint’s data and standard error as if given atom is amputated.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.
Accept amputated atom and sets constraints data and standard error accordingly.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Reject amputated atom and set constraint’s data and standard error accordingly.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: PairDistributionConstraint, Grains_Constraint
PairDistributionConstraint implementation for coarse grains system
Clone constraint given multiframeStructure parameters.
Overloaded to force _shapeUpdateFreq to 1.
Design pattern implementation.
Compute constraint before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
PairCorrelationConstraints contains classes for all constraints related to experimental pair correlation functions.

Bases: PairDistributionConstraint
Controls the total pair correlation function (pcf) of the system noted as g(r). pcf indicates the probability of finding atomic pairs separated by the real space distance r. Theoretically g(r) oscillates about 1. Also \(g(r) \rightarrow 1\) when \(r \rightarrow \infty\) and it takes the exact value of zero for \(r\) shorter than the distance of the closest possible approach of pairs of atoms.
Pair correlation function g(r) and pair distribution function G(r) are directly related as in the following: \(g(r)=1+(\frac{G(r)}{4 \pi \rho_{0} r})\).
g(r) is calculated after binning all pair atomic distances into a weighted histograms of values \(n(r)\) from which local number densities are computed as in the following:
The partial radial distribution function or \(g_{i,j}(r)dr\) gives the number of atoms j in an annulus of thickness dr at distance r from another atom i. Therefore, the coordination number, or the number of neighbors within the distances interval \([a,b]\) is given by \(\int_{a}^{b} 4 \pi r^{2} c_{j} \rho_{0} g_{i,j}(r)dr\)
Where:
\(Q\) is the momentum transfer.
\(r\) is the distance between two atoms.
\(N\) is the total number of atoms in the system.
\(V\) is the volume of the system.
\(i,j\) atoms element pair i and j.
\(N_{i,j}\) is the total number of atoms pair i and j in the system.
\(c_{i}=\frac{n_{i}}{V}\) is molar ratio atom type i.
\(b_{i}\) is the coherent scattering length of element i (e.g. Xray, neutron, etc.).
\(\bar{b_{i}} = \frac{b_{i}} {\sum \limits_{j}^{N} b_{j}}\) is the coherent scattering length of element i, averaged over all elements as well as the different isotopes and nuclear spin states of i in case of neutron scattering.
\(\rho_{0}\) is the average number density of all atoms in the system.
\(\rho_{<i,j>}\) is the average number density of i,j atom pairs the system.
\(\rho_{i,j}(r)\) is the pair density function of atom i,j pairs.
\(R(r)\) is the radial distribution function (rdf).
\(n_{i,j}(r)\) is the number of atoms i neighbouring j at a distance r.
\(v(r)\) is the annulus volume at distance r and of thickness dr.
Refer to PairDistributionConstraint
|
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.PairCorrelationConstraints import PairCorrelationConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
PCC = PairCorrelationConstraint(experimentalData="pcf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PCC)
Compute and set constraint’s standardError.
Get constraint total and standard error
data (None, dict): data to compute total. If None, constraint data will be used.
rho0 (None, number): the system number density. If None, engine number density is used
total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned
stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned
Overload to bring back g(r) to G(r) prior to fitting scale factor. g(r) -> 1 at high r and this will create a wrong scale factor. Overloading can be avoided but is kept for performance reasons.
Get constraint’s data dictionary value.
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.
Compute constraint’s data.
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
data (dict): constraint data dictionary
total (numpy.ndarray): constraint total pair correlation function
standardError (float): constraint standard error
Compute constraint’s data before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint’s data after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Compute and return constraint’s data and standard error as if given atom is amputated.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: PairCorrelationConstraint, Grains_Constraint
PairCorrelationConstraint implementation for coarse grains system
Clone constraint given multiframeStructure parameters.
Overloaded to force _shapeUpdateFreq to 1.
Design pattern implementation.
Compute constraint before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
PairCorrelationConstraints contains classes for all constraints related to experimental pair correlation functions.

Bases: PairDistributionConstraint
Controls the total radial distribution function (rdf) of the system noted as R(r). Just like the pair distribution function G(r) this form of distribution function is widely used and is also known as the Keen distribution function (J. Appl. Cryst. 34 172-177 (2001))
All of the pair distribution function ‘G(r)’, pair correlation function ‘g(r)’ and total radial distribution function ‘R(r)’ are related one to another as in the following formula:
Where:
\(Q\) is the momentum transfer.
\(r\) is the distance between two atoms.
\(N\) is the total number of atoms in the system.
\(V\) is the volume of the system.
\(i,j\) atoms element pair i and j.
\(N_{i,j}\) is the total number of atoms pair i and j in the system.
\(c_{i}=\frac{n_{i}}{V}\) is molar ratio atom type i.
\(b_{i}\) is the coherent scattering length of element i (e.g. Xray, neutron, etc.).
\(\bar{b_{i}} = \frac{b_{i}} {\sum \limits_{j}^{N} b_{j}}\) is the coherent scattering length of element i, averaged over all elements as well as the different isotopes and nuclear spin states of i in case of neutron scattering.
\(\rho_{0}\) is the average number density of all atoms in the system.
\(\rho_{<i,j>}\) is the average number density of i,j atom pairs the system.
\(\rho_{i,j}(r)\) is the pair density function of atom i,j pairs.
\(R(r)\) is the radial distribution function (rdf).
\(n_{i,j}(r)\) is the number of atoms i neighbouring j at a distance r.
\(v(r)\) is the annulus volume at distance r and of thickness dr.
NB fullrmc adopts opposite nomenclature to Keen’s, \(G(r)\) in fullrmc is the \(G^{PDF}(r)\) in Keen’s annotation. While \(R(r)\) in fullrmc is keen’s \(G(r)\)
Refer to PairDistributionConstraint
Normalized structure factor of Strotium Titanim Oxide.¶ |
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.RadialDistributionConstraints import RadialDistributionConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
PCC = RadialDistributionConstraint(experimentalData="rdf.dat", weighting="atomicNumber")
ENGINE.add_constraints(PCC)
Compute and set constraint’s standardError.
Get constraint total and standard error
data (None, dict): data to compute total. If None, constraint data will be used.
rho0 (None, number): the system number density. If None, engine number density is used
total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned
stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned
Get constraint’s data dictionary value.
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.
Compute constraint’s data.
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
data (dict): constraint data dictionary
total (numpy.ndarray): constraint total radial correlation function
standardError (float): constraint standard error
Compute constraint’s data before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint’s data after move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Compute and return constraint’s data and standard error as if given atom is amputated.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: RadialDistributionConstraint, Grains_Constraint
RadialDistributionConstraint implementation for coarse grains system
Clone constraint given multiframeStructure parameters.
Overloaded to force _shapeUpdateFreq to 1.
Design pattern implementation.
Compute constraint before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
StructureFactorConstraints contains classes for all constraints related experimental static structure factor functions.

Bases: ExperimentalConstraint, AtomsPairWeighting, HistogramCorrections
Controls the Structure Factor noted as S(Q) and also called total-scattering structure function or Static Structure Factor. S(Q) is a dimensionless quantity and normalized such as the average value \(<S(Q)>=1\).
S(Q) is simply the normalized and corrected powder diffraction pattern once experimental artefacts have been removed.
The computation of S(Q) is done through an inverse Sine Fourier transform of the computed pair distribution function G(r).
From an atomistic model and histogram point of view, G(r) is computed as the following:
g(r) is calculated after binning all pair atomic distances into a weighted histograms as the following:
Where:
\(Q\) is the momentum transfer.
\(r\) is the distance between two atoms.
\(\rho_{i,j}(r)\) is the pair density function of atoms i and j.
\(\rho_{0}\) is the average number density of the system.
\(w_{i,j}\) is the relative weighting of atom types i and j.
\(R(r)\) is the radial distribution function (rdf).
\(N\) is the total number of atoms.
\(V\) is the volume of the system.
\(n_{i,j}(r)\) is the number of atoms i neighbouring j at a distance r.
\(v(r)\) is the annulus volume at distance r and of thickness dr.
\(N_{i,j}\) is the total number of atoms i and j in the system.
Reduced structure factor of memory shape Nickel-Titanium alloy.¶ |
experimentalData (numpy.ndarray, string): Experimental data as numpy.ndarray or string path to load data using numpy.loadtxt method.
dataWeights (None, numpy.ndarray): Weights array of the same length as experimentalData, used in the constraint’s standard error computation. This allows fitting emphasis to be placed on data points considered more or less important, to obtain a reasonable and plausible model.
If None, all data points are considered equally important in computing the constraint’s standard error.
If a numpy.ndarray is given, all weights must be positive; zero-weighted data points do not contribute to the total standard error. At least one weight must be non-zero, and the weights array is automatically scaled so that the sum of all weights equals the number of data points.
weighting (string): The elements weighting scheme. It must be any atomic attribute (atomicNumber, neutronCohb, neutronIncohb, neutronCohXs, neutronIncohXs, atomicWeight, covalentRadius) defined in pdbparser database. In case of xrays or neutrons experimental weights, one can simply set weighting to ‘xrays’ or ‘neutrons’ and the value will be automatically adjusted to respectively ‘atomicNumber’ and ‘neutronCohb’. If attribute values are missing in the pdbparser database, atomic weights must be given in atomsWeight dictionary argument.
atomsWeight (None, dict): Atoms weight dictionary where keys are atoms element and values are custom weights. If None is given or partially given, missing elements weighting will be fully set given weighting scheme.
custPartScatteringPower (None, dict): Atom pairs scattering power. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2.
pairsWeight (None, dict): Atom pairs weight. Keys are tuples of two elements. Redundancy is not allowed, (el1,el2) is a pair key, (el2,el1) is not allowed to be given unless el1==el2. Customizing pairs weight is needed for differential or resonant experimental setups. If el1 weighting or atomWeigth value is x and el2 value is y then (el1,el2) pair value weight is x*y.
rmin (None, number): The minimum distance value to compute G(r) histogram. If None is given, rmin is computed as \(2 \pi / Q_{max}\).
rmax (None, number): The maximum distance value to compute G(r) histogram. If None is given, rmax is computed as \(2 \pi / dQ\).
dr (None, number): The distance bin value to compute G(r) histogram. If None is given, bin is computed as \(2 \pi / (Q_{max}-Q_{min})\).
scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.
adjustScaleFactor (list, tuple, dict): Used to adjust or auto-fit the best scale factor during stochastic engine runtime.
If a list is given, it must include three mandatory items and an optional fourth:
The ‘update’ frequency, in number of generated moves, for finding the best scale factor. If 0, the scale factor is fixed.
The ‘minimum’ allowed scale factor value.
The ‘maximum’ allowed scale factor value.
The scale factor ‘learning_rate’.
If a dict is given, it must include ‘update’, ‘minimum’, ‘maximum’ and, optionally, ‘learning_rate’.
thermalCorrections (None, number, dict): Atomic thermal vibration parameters used to correct for the broadening of partial histogram peaks. If None, no correction is made. If a number is given, it is used as the thermal vibration coefficient for all element pairs. If a dictionary is given, it can include any of the ‘set_thermal_corrections’ method parameters.
qmaxCorrections (None, number, dict): Not used in q space constraints
resolutionCorrections (None, number, dict): Experimental resolution correction parameters defined as a simple multiplication of the total atomic distribution with \(e^{-0.5\sigma_{q}^2r^2}\). If None is given, no experimental resolution corrections will be made. If a number is given, it will be considered the damping value \(\sigma_{q}\). If a dictionary is given, it can then include any of ‘set_resolution_corrections’ method parameters.
windowFunction (None, dict, numpy.ndarray): The window function to convolute with the computed pair distribution function before comparing it to the experimental data. Experimental G(r) typically shows artificial wrinkles, largely because it is obtained via a sine Fourier transform of the experimental structure factor S(q); the window function approximates these numerical artefacts. If a dict is given, it is used as kwargs for fullrmc.Core.Collection.get_normal_filter, with default values {‘z’:3, ‘ps’:0.05} (3 standard deviations, 5% size width).
limits (None, tuple, list): The distance limits to compute the histograms. If None is given, the limits will be automatically set the min and max distance of the experimental data. Otherwise, a tuple of exactly two items where the first is the minimum distance or None and the second is the maximum distance or None.
NB: If adjustScaleFactor first item (frequency) is 0, the scale factor will remain untouched and the limits minimum and maximum won’t be checked.
# import fullrmc modules
from fullrmc.Engine import Engine
from fullrmc.Constraints.StructureFactorConstraints import StructureFactorConstraint
# create engine
ENGINE = Engine(path='my_engine.stc')
# set pdb file
ENGINE.set_pdb('system.pdb')
# create and add constraint
SFC = StructureFactorConstraint(experimentalData="sq.dat", weighting="atomicNumber")
ENGINE.add_constraints(SFC)
For experimental constraints nanoscopic parameters must be overloaded
Create a constraint instance given instantiation parameters
params (dict): instantiation parameters
obj (Constraint): the created instance
Update instance using parameters
params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property
Get current state and instantiation parameters
Histogram minimum distance.
Histogram maximum distance.
The distance bin value to compute G(r) histogram as instantiated and given by user
The computed distance bin value to compute G(r). If given dr is not None, distance bin will be equal to dr
Computed histogram minimum distance.
Computed histogram maximum distance.
Experimental data reciprocal distances minimum.
Experimental data reciprocal distances maximum.
Experimental data reciprocal distances bin size.
Experimental data used q values.
Histogram size
Shells center array
Shells volume array
Experimental Structure Factor or S(q)
Convolution window function.
Convolution window function.
G(r) to S(q) transformation matrix.
Listens to any message sent from the Broadcaster.
message (object): Any python object to send to constraint’s listen method.
argument (object): Any type of argument to pass to the listeners.
Set rmin value.
rmin (None, number): The minimum distance value to compute G(r) histogram. If None is given, rmin is computed as \(2 \pi / Q_{max}\).
Set rmax value.
rmax (None, number): The maximum distance value to compute G(r) histogram. If None is given, rmax is computed as \(2 \pi / dQ\).
Set dr value.
dr (None, number): The distance bin value to compute G(r) histogram. If None is given, bin is computed as \(max(0.01, 2 \pi / (Q_{max}-Q_{min}))\).
Set convolution window function.
windowFunction (None, dict, numpy.ndarray): The window function to convolute with the computed pair distribution function before comparing it to the experimental data. Experimental G(r) typically shows artificial wrinkles, largely because it is obtained via a sine Fourier transform of the experimental structure factor S(q); the window function approximates these numerical artefacts. If a dict is given, it is used as kwargs for fullrmc.Core.Collection.get_normal_filter, with default values {‘z’:3, ‘ps’:0.05} (3 standard deviations, 5% size width).
frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.
Set constraint’s experimental data.
experimentalData (numpy.ndarray, string): The experimental data as numpy.ndarray or string path to load data using numpy.loadtxt function.
Set the reciprocal distance limits (qmin, qmax).
limits (None, tuple, list): Distance limits to bound experimental data and compute histograms. If None is given, the limits will be automatically set to min and max reciprocal distance recorded in experimental data. If given, a tuple of minimum reciprocal distance (qmin) or None and maximum reciprocal distance (qmax) or None should be given.
Compute and set constraint’s standardError.
Check whether experimental data is correct.
experimentalData (object): The experimental data to check.
result (boolean): Whether it is correct or not.
message (str): Checking message that explains whats’s wrong with the given data
Compute the standard error (StdErr) using the engine defined loss function
data (numpy.ndarray): The constraint data
resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!
standardError (number): The calculated constraint’s standardError.
Get constraint total and standard error
data (None, dict): data to compute total. If None, constraint data will be used.
rho0 (None, number): the system number density. If None, engine number density is used
total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned
stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned
Compute all partial Structure Factor (SQs).
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
SQs (dictionary): The SQs dictionnary, where keys are the element wise intra and inter molecular SQs and values are the computed SQs.
Compute all partial Structure Factor (SQs).
SQs (dictionary): The SQs dictionnary, where keys are the element wise intra and inter molecular SQs and values are the computed SQs.
Overload to reduce S(q) prior to fitting scale factor. S(q) -> 1 at high q and this will create a wrong scale factor. Overloading can be avoided but is kept for performance reasons.
Compute constraint’s data.
asSingular (boolean): In the case where engine used frame is a subframe, constraint value will be computed according to the multiframe structure. If True is given, multiframe structure will be ignored and the value will be computed as if the subframe is a traditional single frame. This is just similar to when multiframe is statistical.
resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!
update (boolean): whether to update constraint data and standard error with new computation. If data is computed and updated by another thread or process while the stochastic engine is running, this might lead to a state alteration of the constraint which will lead to a no additional accepted moves in the run
data (dict): constraint data dictionary
total (numpy.ndarray): constraint total structure factor function
standardError (float): constraint standard error
Compute constraint before move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Accept move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Reject move
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Not used here.
Compute and return constraint’s data and standard error as if given atom is amputated.
realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.
relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.
Accept amputated atom and sets constraints data and standard error accordingly.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Reject amputated atom and set constraint’s data and standard error accordingly.
realIndex (numpy.ndarray): Not used here.
relativeIndex (numpy.ndarray): Not used here.
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: StructureFactorConstraint
The Reduced or Kernel Structure Factor that we will note K(Q)=S(Q)-1 is exactly the same quantity as the Structure Factor but with the slight difference that it is normalized to 0 rather than 1 and therefore \(<S(Q)>=0\).
The computation of \(K(Q)=S(Q)-1\) is done through a Sine inverse Fourier transform of the computed pair distribution function noted as G(r).
The only reason why the Reduced Structure Factor is implemented, is because many experimental data are treated in this form. And it is just convenient not to manipulate the experimental data every time.
dummy overload that does exactly the same thing
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: StructureFactorConstraint
The normalized structure factor will be noted F(Q) and it computes the total-scattering structure factor also known as keen structure factor (J. Appl. Cryst. 34 172-177 (2001)).
NB fullrmc adopts opposite nomenclature to Keen’s, \(F(Q)\) in fullrmc is the \(S(Q)\) in Keen’s annotation. While \(S(Q)\) in fullrmc is the sine Fourier transform of the pair distribution function \(G(r)\)
Normalized structure factor of Strotium Titanim Oxide.¶ |
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: StructureFactorConstraint, Grains_Constraint
Clone constraint given multiframeStructure parameters.
Design pattern implementation.
Compute constraint before move is executed.
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
Compute constraint after move is executed
realIndexes (numpy.ndarray): Not used here.
relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.
movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.
Bases: Grains_StructureFactorConstraint
dummy overload that does exactly the same thing
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.
Bases: Grains_StructureFactorConstraint
Alias to ExperimentalConstraint.plot with additional parameters
xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.
ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.