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

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.

Inheritance diagram of fullrmc.Core.Constraint
fullrmc.Core.Constraint.randfloat()

random() -> x in the interval [0, 1).

class fullrmc.Core.Constraint.Constraint

Bases: ListenerBase

A constraint is used to direct the evolution of the atomic configuration towards the desired and most meaningful one.

classmethod create(params, engine, *args, **kwargs)

Design pattern implementation. Subclasses must overload this classmethod to build and return a new constraint instance from stored parameters.

Parameters:
  1. params (dict): The constraint’s stored parameters used to rebuild the instance.

  2. engine (Engine): The engine instance the constraint will be bound to.

  3. args (tuple): Additional positional arguments.

  4. kwargs (dict): Additional keyword arguments.

property parameters

Design pattern implementation.

classmethod get_parameters_for_nanoscopic(*args, **kwargs)

For general constraints no nanoscopic parameters are needed.

Returns:
  1. parameters (None): Always None for the base Constraint class.

update(params)

Design pattern implementation. Subclasses must overload this method to update the constraint’s internal state from params.

Parameters:
  1. params (dict): The new parameters to update the constraint with.

get_update_parameters(constraint)

Get update parameters that can be used to update this constraint to the given one

Parameters:
  1. constraint (dict, Constraint): Given constraint parameters of constraint instance of the same type as this constraint

Returns:
  1. parameters (dict): Update parameters

property constraintId

Constraint unique ID create at instantiation time.

Returns:
  1. constraintId (string): The constraint’s unique id (its listenerId).

property constraintName

Constraints unique name in engine given when added to engine.

Returns:
  1. constraintName (string): The constraint’s name.

property engine

Stochastic fullrmc’s engine instance.

Returns:
  1. engine (None, Engine): The bound engine instance, or None if not yet added to an engine.

property usedFrame

Get used frame in engine. If None then engine is not defined yet.

Returns:
  1. usedFrame (None, string): The engine’s currently used frame.

property computationCost

Computation cost number.

Returns:
  1. computationCost (number): The constraint’s computation cost.

property state

Constraint’s state.

Returns:
  1. state (object): The constraint’s current internal state marker.

property tried

Constraint’s number of tried moves.

Returns:
  1. tried (integer): The number of tried moves.

property accepted

Constraint’s number of accepted moves.

Returns:
  1. accepted (integer): The number of accepted moves.

property used

Constraint’s used flag. Defines whether constraint is used in the stochastic engine at runtime or set inactive.

Returns:
  1. used (boolean): Whether the constraint is active.

property variance

Constraint’s variance used in the stochastic engine at runtime to calculate the total constraint’s standard error.

Returns:
  1. variance (number): The constraint’s variance.

property listenerData

Listener data.

Returns:
  1. listenerData (object): The constraint’s listener data.

property optimizationParameters

Optimization parameters.

Returns:
  1. optimizationParameters (object): The constraint’s optimization parameters.

property constraintWeight

Constraint’s weight (1./variance) used in the stochastic engine at runtime to calculate the total constraint’s standard error.

Returns:
  1. constraintWeight (number): The constraint’s weight.

property standardError

Constraint’s standard error value.

Returns:
  1. standardError (number): The constraint’s standard error.

property originalData

Constraint’s original data calculated upon initialization.

Returns:
  1. originalData (object): The constraint’s original data.

property data

Constraint’s current calculated data.

Returns:
  1. data (object): The constraint’s current data.

property activeAtomsDataBeforeMove

Constraint’s current calculated data before last move.

Returns:
  1. activeAtomsDataBeforeMove (object): The data before the last move.

property activeAtomsDataAfterMove

Constraint’s current calculated data after last move.

Returns:
  1. activeAtomsDataAfterMove (object): The data after the last move.

property afterMoveStandardError

Constraint’s current calculated StandardError after last move.

Returns:
  1. afterMoveStandardError (number): The standard error after the last move.

property amputationData

Constraint’s current calculated data after amputation.

Returns:
  1. amputationData (object): The data after amputation.

property amputationStandardError

Constraint’s current calculated StandardError after amputation.

Returns:
  1. amputationStandardError (number): The standard error after amputation.

property mesoscopicWeight

Design pattern implementation. In this case it’s always 1.

Returns:
  1. mesoscopicWeight (FLOAT_TYPE): Always 1.

property mesoscopicPrior

Design pattern implementation. In this case it’s always 0.

Returns:
  1. mesoscopicPrior (FLOAT_TYPE): Always 0.

property nanoscopicData

Design pattern implementation. In this case it’s always None.

Returns:
  1. nanoscopicData (None): Always None.

is_in_engine(engine)

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

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

Returns:
  1. result (boolean): Whether constraint exists in engine.

set_variance(value, frame=None)

Set constraint’s variance that is used in the computation of the total stochastic engine standard error.

Parameters:
  1. value (number): Any positive non zero number.

  2. frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.

set_computation_cost(value, frame=None)

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.

Parameters:
  1. value (number): computation cost.

  2. frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.

set_used(*args, **kwargs)

Set used flag.

Parameters:
  1. value (boolean): True to use this constraint in stochastic engine runtime.

  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, all other multiframe subframes will be targeted if constraints is ExperimentalConstraint.

set_state(value)

Set constraint’s state. When constraint’s state and stochastic engine’s state don’t match, constraint’s data must be re-calculated.

Parameters:
  1. value (object): Constraint state value.

set_tried(value)

Set constraint’s number of tried moves.

Parameters:
  1. value (integer): Constraint tried moves value.

increment_tried()

Increment number of tried moves.

set_accepted(value)

Set constraint’s number of accepted moves.

Parameters:
  1. value (integer): Constraint’s number of accepted moves.

increment_accepted()

Increment constraint’s number of accepted moves.

set_standard_error(value)

Set constraint’s standardError value.

Parameters:
  1. value (number): standard error value.

set_data(value)

Set constraint’s data value.

Parameters:
  1. value (number): constraint’s data.

set_active_atoms_data_before_move(value)

Set constraint’s before move happens active atoms data value.

Parameters:
  1. value (number): Data value.

set_active_atoms_data_after_move(value)

Set constraint’s after move happens active atoms data value.

Parameters:
  1. value (number): data value.

set_after_move_standard_error(value)

Set constraint’s standard error value after move happens.

Parameters:
  1. value (number): standard error value.

set_amputation_data(value)

Set constraint’s after amputation data.

Parameters:
  1. value (number): data value.

set_amputation_standard_error(value)

Set constraint’s standardError after amputation.

Parameters:
  1. value (number): standard error value.

reset_constraint(reinitialize=True, flags=False, data=False, frame=None)

Reset constraint.

Parameters:
  1. reinitialize (boolean): If set to True, it will override the rest of the flags and will completely reinitialize the constraint.

  2. flags (boolean): Reset the state, tried and accepted flags of the constraint.

  3. data (boolean): Reset the constraints computed data.

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

update_standard_error()

Compute and set constraint’s standard error by calling compute_standard_error method and passing constraint’s data.

get_frame_data(frame, *args, **kwargs)

Get a dictionary look up table of constraint’s properties

Parameters:
  1. frame (string): frame to pull and build contraint data. It can be a traditional frame, a multiframe or a subframe

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

get_constraint_value()

Design pattern implementation.

get_constraint_original_value()

Design pattern implementation.

compute_standard_error()

Design pattern implementation.

compute_data(*args, **kwargs)

Design pattern implementation.

compute_before_move(realIndexes, relativeIndexes)

Design pattern implementation. Subclasses must overload this method to compute constraint data before atoms are moved.

Parameters:
  1. realIndexes (numpy.ndarray): Group real atoms indexes.

  2. relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Design pattern implementation. Subclasses must overload this method to compute constraint data after atoms are moved.

Parameters:
  1. realIndexes (numpy.ndarray): Group real atoms indexes.

  2. relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.

  3. movedBoxCoordinates (numpy.ndarray): The new moved atoms coordinates in box coordinates system.

accept_move(realIndexes, relativeIndexes)

Design pattern implementation. Subclasses must overload this method to accept a previously computed move.

Parameters:
  1. realIndexes (numpy.ndarray): Group real atoms indexes.

  2. relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.

reject_move(realIndexes, relativeIndexes)

Design pattern implementation. Subclasses must overload this method to reject a previously computed move.

Parameters:
  1. realIndexes (numpy.ndarray): Group real atoms indexes.

  2. relativeIndexes (numpy.ndarray): Group relative atoms indexes to the surrounding boundary conditions box.

compute_as_if_amputated(realIndex, relativeIndex)

Design pattern implementation. Subclasses must overload this method to compute constraint data as if a single atom was amputated (removed) from the system.

Parameters:
  1. realIndex (numpy.ndarray): The atom real index.

  2. relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.

compute_as_if_inserted(realIndex, relativeIndex)

Design pattern implementation. Subclasses must overload this method to compute constraint data as if a single atom was inserted into the system.

Parameters:
  1. realIndex (numpy.ndarray): The atom real index.

  2. relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.

accept_amputation(realIndex, relativeIndex)

Design pattern implementation. Subclasses must overload this method to accept a previously computed amputation.

Parameters:
  1. realIndex (numpy.ndarray): The atom real index.

  2. relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.

reject_amputation(realIndex, relativeIndex)

Design pattern implementation. Subclasses must overload this method to reject a previously computed amputation.

Parameters:
  1. realIndex (numpy.ndarray): The atom real index.

  2. relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.

accept_insertion(realIndex, relativeIndex)

Design pattern implementation. Subclasses must overload this method to accept a previously computed insertion.

Parameters:
  1. realIndex (numpy.ndarray): The atom real index.

  2. relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.

reject_insertion(realIndex, relativeIndex)

Design pattern implementation. Subclasses must overload this method to reject a previously computed insertion.

Parameters:
  1. realIndex (numpy.ndarray): The atom real index.

  2. relativeIndex (numpy.ndarray): The atom relative index to the surrounding boundary conditions box.

export(fileName, frame=None, format='%s', delimiter='\t', comments='#', *args, **kwargs)

Export constraint data to text file or to an archive of files.

Parameters:
  1. fileName (path): full file name and path.

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

  3. format (string): string format to export the data. format is as follows (%[flag]width[.precision]specifier)

  4. delimiter (string): String or character separating columns.

  5. comments (string): String that will be prepended to the header.

Returns:
  1. lines (string): The exported data as a single string, also written to fileName if fileName is not None.

plot(frame=None, axes=None, figureAxesNCols=None, subAdParams={'bottom': None, 'hspace': 0.4, 'left': None, 'right': None, 'top': None, 'wspace': None}, dataParams={'label': 'Y', 'linewidth': 2}, xlabelParams=True, ylabelParams=True, xticksParams={'fontsize': 8, 'rotation': 90}, yticksParams={'fontsize': 8, 'rotation': 0}, legendParams={'fontsize': 8, 'frameon': False, 'loc': 'upper right', 'ncol': 1}, shareX=True, shareY=True, titleParams=True, gridParams=None, tightLayout=False, show=True, _frameDataLUT=None, **paramsKwargs)

Plot constraint data. This can be overloaded in children classes.

Parameters:
  1. frame (None, string): The frame name to plot. If None, used frame will be plotted.

  2. axes (None, matplotlib Axes): matplotlib Axes instance to plot in. If None is given a new plot figure will be created.

  3. figureAxesNCols (None, int): number of columns in figure to create axes in multi-axes figures. If None, number of columns will be automatically set.

  4. subAdParams (None, dict): matplotlib.artist.Artist.subplots_adjust parameters subplots adjust parameters.

  5. dataParams (None, dict): constraint data plotting parameters

  6. xlabelParams (None, dict): matplotlib.axes.Axes.set_xlabel parameters.

  7. ylabelParams (None, dict): matplotlib.axes.Axes.set_ylabel parameters.

  8. legendParams (None, dict):matplotlib.axes.Axes.legend parameters.

  9. xticksParams (None, dict):matplotlib.axes.Axes.set_xticklabels parameters.

  10. yticksParams (None, dict):matplotlib.axes.Axes.set_yticklabels parameters.

  11. shareX (boolean): Whether all axes in a multi-axes figure should share the same x axis.

  12. shareY (boolean): Whether all axes in a multi-axes figure should share the same y axis.

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

  14. gridParams (None, dict): matplotlib.axes.Axes.grid parameters

  15. tightLayout (boolean): whether to call figure tight_layout method

  16. show (boolean): Whether to render and show figure before returning.

  17. _frameDataLUT: for internal use only

Returns:
  1. figure (matplotlib Figure): matplotlib used figure.

  2. axes (matplotlib Axes): matplotlib used axes.

  3. frameDataLUT (dict): the frame data LUT

class fullrmc.Core.Constraint.HistogramCorrections(thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None)

Bases: object

Base implementation to be used along with experimental constraints that need any type of histogram corrections.

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

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

  3. 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)
property thermalCorrections

Atomic thermal vibration broadening correction parameters.

Returns:
  1. thermalCorrections (dict): The thermal corrections parameters.

property thermalArrays

Atomic thermal vibration broadening correction arrays.

Returns:
  1. thermalArrays (None, dict): The thermal correction arrays.

property qmaxCorrections

Experimental \(Q_{max}\) cutoff correction parameters.

Returns:
  1. qmaxCorrections (dict): The qmax corrections parameters.

property qmaxArray

Experimental \(Q_{max}\) cutoff correction array.

Returns:
  1. qmaxArray (None, numpy.ndarray): The qmax correction array.

property resolutionCorrections

Experimental resolution correction parameters.

Returns:
  1. resolutionCorrections (None, dict): The resolution corrections parameters.

property resolutionArray

Experimental resolution correction array.

Returns:
  1. resolutionArray (None, numpy.ndarray): The resolution correction array.

property histogramParameters

Get histogram parameters.

Returns:
  1. histogramParameters (None, dict): The histogram parameters.

static get_optimization_parameters_template(engine=None, frame=None, defaults=None)

Get default parameters for optimization.

Parameters:
  1. engine (None, Engine): The stochastic engine used to resolve the frame category and repository. If None, no frame-specific resolution is performed.

  2. frame (None, str): stochastic engine frame. If None, engine used frame will be set

  3. defaults (None, dict): Optional dictionary of default values overriding the built-in template defaults.

Returns:
  1. params (dict): The optimization parameters template dictionary.

get_optimization_step_parameters_template(parameters=None)

create optimization step parameters template

Parameters:
  1. parameters (None, dict): starting parameters dictionary. If None, optimizationParameters will be used

Returns:
  1. 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)
get_optimization_cycle_parameters_template(parameters=None)

create optimization cycle parameters template

Parameters:
  1. parameters (None, dict): starting parameters dictionary. If None, optimizationParameters will be used

Returns:
  1. 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_optimization_step(parameters=None, name='custom_optimization', locker=None, _save=True)

Run a single optimization step given parameters

Parameters:
  1. parameters (None, dict): dictionary of optimization parameters. If None, constraint optimizationParameters will be used

  2. name (str): optimization step name. This is used for logging purposes

  3. locker (None, object): Optional repository locker to use while dumping optimization data. If None, the engine’s repository locker will be used when available.

  4. _save (bool): Internal fullrmc flag controlling whether the optimization results are dumped to the repository. End users should not need to alter this.

Returns:
  1. optimizer (StochasticEngineOptimizer): the used StochasticEngineOptimizer instance

  2. summary (list): optimization summary dictionary as a single list item

run_optimization_cycle(cycle=None, ncycles=None, locker=None, _save=True)

Run optimization cycle of steps given parameters

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

  2. ncycles (None, integer): Number of cycles to run. If None, constraint optimizationParameters ‘ncycles’ value will be used, defaulting to 1.

  3. locker (None, object): Optional repository locker to use while dumping optimization data. If None, the engine’s repository locker will be used when available.

  4. _save (bool): Internal fullrmc flag controlling whether the optimization results are dumped to the repository. End users should not need to alter this.

Returns:
  1. optimizer (StochasticEngineOptimizer): the used StochasticEngineOptimizer instance

  2. summary (list): list of cycles results

set_optimization_parameters(parameters, frame=None)

set corrections optimization parameters

Parameters:
  1. parameters (None, dict): the optimization parameters dictionary.

  2. 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_thermal_corrections(factors=True, defaultFactor=0.01, delta1=0, delta2=0, qbroad=0, broadening=1, frame=None)

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}>\)

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

  2. defaultFactor (None, number): elements default isotropic mean square deviation factor value. If None is given, previously set value will be used

  3. delta1 (number): default delta1 parameter for all atom pairs as defined in the anisotropic formula

  4. delta2 (number): default delta2 parameter for all atom pairs as defined in the anisotropic formula

  5. qbroad (number): default qbroad parameter for all atom pairs as defined in the anisotropic formula

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

  7. 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_resolution_corrections(value=True, frame=None)

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}\)

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

  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.

# 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_qmax_corrections(qmax=True, rWidth=True, frame=None)

Set t:math:Q_{max} corrections parameters

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

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

  3. 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)
class fullrmc.Core.Constraint.AtomsPairWeighting(weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None)

Bases: object

Base implementation to be used in constraints that need atoms pair weighting

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

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

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

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

property elementsPairs

Elements pairs.

Returns:
  1. elementsPairs (list): List of element pair tuples.

property weighting

Elements weighting definition.

Returns:
  1. weighting (string): The elements weighting scheme name.

property atomsWeight

Customized atoms weight.

Returns:
  1. atomsWeight (None, dict): The customized atoms weight dict.

property pairsWeight

Customized atom pairs weight.

Returns:
  1. pairsWeight (None, dict): The customized atom pairs weight dict.

property partialsScatteringPower

Partials distribution scattering power.

Returns:
  1. partialsScatteringPower (dict): The partials scattering power dictionary.

property customPartialsScatteringPower

Custom partials distribution scattering power.

Returns:
  1. customPartialsScatteringPower (None, dict): The custom partials scattering power dictionary.

property custPartScatteringPower

Alias to customPartialsScatteringPower.

Returns:
  1. custPartScatteringPower (None, dict): The custom partials scattering power dictionary.

property weightingScheme

Elements weights and partials scattering power for given weighting without applying user defined atomsWeight and pairsWeight.

Returns:
  1. elementsWeight (None, dict): The computed elements weight dictionary, or None if engine is not set.

  2. pairScattPower (None, dict): The computed pairs scattering power dictionary, or None if engine is not set.

property elementsPairsScatteringPower

Elements and pairs weights scattering power after applying user defined atomsWeight and pairsWeight.

Returns:
  1. elementsSP (None, dict): The elements scattering power dictionary, or None if engine or elementsPairs are not set.

  2. pairsSP (None, dict): The pairs scattering power dictionary, or None if engine or elementsPairs are not set.

set_weighting(*args, **kwargs)

Set elements weighting. It must be a valid entry of pdbparser atom’s database.

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

set_atoms_weight(*args, **kwargs)

Custom set atoms weight. This is the way to customize setting atoms weights different than the given weighting scheme.

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

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

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

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

class fullrmc.Core.Constraint.ExperimentalConstraint(experimentalData, dataWeights=None, scaleFactor=1.0, adjustScaleFactor=None, _log=True)

Bases: Constraint

Experimental constraint is any constraint related to experimental data.

Parameters:
  1. engine (None, fullrmc.Engine): Constraint’s stochastic engine.

  2. experimentalData (numpy.ndarray, string): Experimental data given as numpy.ndarray or string path to load data using numpy.loadtxt method.

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

  4. scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.

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

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

    2. The ‘minimum’ allowed scale factor value.

    3. The ‘maximum’ allowed scale factor value.

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

classmethod get_parameters_for_nanoscopic(*args, **kwargs)

For experimental constraints nanoscopic parameters must be overloaded

get_total(*args, **kwargs)

Design pattern implementation.

reset_constraint(reinitialize=True, flags=False, data=False, frame=None, _resetScaleFactor=True)

Overloading of Constraint reset method implementation.

Parameters:
  1. reinitialize (boolean): If set to True, it will override the rest of the flags and will completely reinitialize the constraint.

  2. flags (boolean): Reset the state, tried and accepted flags of the constraint.

  3. data (boolean): Reset the constraints computed data.

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

  5. _resetScaleFactor (bool): Internal fullrmc flag controlling whether the scale factor is reset as well. End users should not need to alter this.

property experimentalData

Experimental data of the constraint.

Returns:
  1. experimentalData (numpy.ndarray): The experimental data array.

property dataWeights

Experimental data points weight.

Returns:
  1. dataWeights (None, numpy.ndarray): The data weights array.

property mesoscopicWeight

Constraint multiframe weight towards total in a mesoscopic system.

Returns:
  1. mesoscopicWeight (number): The mesoscopic weight.

property mesoscopicPrior

Constraint multiframe mesoscopic prior array.

Returns:
  1. mesoscopicPrior (numpy.ndarray): The mesoscopic prior array.

property nanoscopicData

Constraint multiframe nanoscopic subframe data.

Returns:
  1. nanoscopicData (object): The nanoscopic subframe data.

property scaleFactor

Constraint’s scaleFactor.

Returns:
  1. scaleFactor (number): The constraint’s scale factor.

property adjustScaleFactor

Adjust scale factor dictionary.

Returns:
  1. adjustScaleFactor (dict): The scale factor adjustment settings dictionary.

property adjustScaleFactorUpdate

Scale factor adjustment update frequency.

Returns:
  1. adjustScaleFactorUpdate (integer): The update frequency.

property adjustScaleFactorMinimum

Scale factor adjustment minimum number allowed.

Returns:
  1. adjustScaleFactorMinimum (number): The minimum allowed scale factor value.

property adjustScaleFactorMaximum

Scale factor adjustment maximum number allowed.

Returns:
  1. adjustScaleFactorMaximum (number): The maximum allowed scale factor value.

property adjustScaleFactorLearningRate

Scale factor adjustment learning rate.

Returns:
  1. adjustScaleFactorLearningRate (number): The learning rate.

property limits

Used daX limits.

Returns:
  1. limits (None, tuple): The (min, max) X limits.

property limitsIndexStart

Used data start index as calculated from limits.

Returns:
  1. limitsIndexStart (integer): The start index.

property limitsIndexEnd

Used data end index as calculated from limits.

Returns:
  1. limitsIndexEnd (integer): The end index.

set_scale_factor(scaleFactor)

Set the scale factor. This method doesn’t allow specifying frames. It will target used frame only.

Parameters:
  1. scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.

set_adjust_scale_factor(adjustScaleFactor, frame=None)

Set adjust scale factor. This method doesn’t allow specifying frames. It will target used frame only.

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

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

    2. The ‘minimum’ allowed scale factor value.

    3. The ‘maximum’ allowed scale factor value.

    4. The scale factor ‘learning_rate’.

    If a dict is given, all of ‘update’, ‘minimum’, ‘maximum’ and optional ‘learning_rate’ must be given

  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.

set_experimental_data(experimentalData, _log=True)

Set the constraint’s experimental data. This method will raise an error if called after adding constraint to stochastic engine.

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

  2. _log (bool): Internal fullrmc flag controlling whether this operation is logged. End users should not need to alter this.

set_data_weights(*args, **kwargs)

Set experimental data points weight. Data weights will be automatically normalized.

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

    1. ‘x’: this will generate monotoneously incrising weights with x value.

    2. ‘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)]

  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.

check_experimental_data(experimentalData)

Checks the constraint’s experimental data This method must be overloaded in all experimental constraint sub-classes.

Parameters:
  1. experimentalData (numpy.ndarray): Experimental data numpy.ndarray.

fit_scale_factor(experimentalData, modelData, dataWeights)

The best scale factor value is computed by minimizing \(E=sM\).

Where:
  1. \(E\) is the experimental data.

  2. \(s\) is the scale factor.

  3. \(M\) is the model constraint data.

This method doesn’t allow specifying frames. It will target used frame only.

Parameters:
  1. experimentalData (numpy.ndarray): Experimental data.

  2. modelData (numpy.ndarray): Constraint modal data.

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

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

get_adjusted_scale_factor(experimentalData, modelData, dataWeights)

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.

Parameters:
  1. experimentalData (numpy.ndarray): the experimental data.

  2. modelData (numpy.ndarray): the constraint modal data.

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

Returns:

#. 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_loss(experimentalData, modelData, agg=True, reset=False, _log=True)

compute experimental constraints loss given the set loss function

Parameters:
  1. experimentalData (numpy.ndarray): Experimental data

  2. modelData (numpy.ndarray): model data

  3. agg (bool): whether to aggregate point losses

  4. reset (boolean): whether to force resetting loss function data. Not all losses are resettable

  5. _log (bool): Internal fullrmc flag controlling whether this computation is logged. End users should not need to alter this.

Returns:
  1. 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_frame_data(frame, asMultiframe=False, *args, **kwargs)

Get a dictionary look up table of constraint’s properties that are needed to plot or export

Parameters:
  1. frame (string): frame to pull and build contraint data. It can be a traditional frame, a multiframe or a subframe

  2. asMultiframe (bool): Whether to also aggregate and include multiframe-level weighted data in the returned look up table.

Returns:
  1. 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(frame=None, axes=None, asMultiframe=True, partialsIntra=True, partialsInter=True, partialsTotal=False, shapeFunc=True, resoFunc=True, thermalFunc=True, figureAxesNCols=None, subAdParams={'bottom': None, 'hspace': 0.4, 'left': None, 'right': None, 'top': None, 'wspace': 0.4}, totParams={'color': 'black', 'label': 'total', 'linewidth': 2.0, 'zorder': 1}, expParams={'color': 'red', 'label': 'experimental', 'marker': 'o', 'markersize': 5, 'markevery': 1, 'zorder': 0}, noWParams={'color': 'black', 'label': 'total - no window', 'linewidth': 1.0, 'zorder': 1}, shaParams={'color': 'black', 'label': '$\\rho_{s}$', 'linestyle': 'dashed', 'linewidth': 1.0, 'zorder': 2}, resoParams={'$color_twinx': True, '$twinx': True, '$twinx_ylabel': 'Experimental Resolution Correction', 'color': '#8FBC8F', 'label': '$e^{-{\\sigma_{q}^2r^2}}$', 'linestyle': 'dotted', 'linewidth': 1.0, 'marker': '+', 'markevery': 100, 'zorder': 2}, sigmaParams={'$twinx': True, '$twinx_ylabel': 'Thermal Correction $\\sigma_{i,j}$ $(\\AA^{-1})$', 'linestyle': 'dotted', 'linewidth': 1.0, 'marker': '2', 'markevery': 100, 'zorder': 2}, lossParams={'alpha': 0.2, 'color': 'red', 'label': 'loss [{lossName}]', 'zorder': -1}, parParams={'linewidth': 1.0, 'markersize': 5, 'markevery': 5, 'zorder': 3}, xlabelParams={'size': 10, 'xlabel': 'X'}, ylabelParams={'size': 10, 'ylabel': 'Y'}, xticksParams={'fontsize': 8, 'rotation': 0}, yticksParams={'fontsize': 8, 'rotation': 0}, shareX=True, shareY=True, legendParams={'fontsize': 8, 'frameon': False, 'loc': 'upper right', 'ncol': 2}, titleParams=True, gridParams=None, colors=None, makers=('', '.', '+', '^', '|'), customParams=None, tightLayout=False, residuals=True, twinxPadding=0.075, xOffset=0, yOffset=0, xScale=None, yScale=None, minX=True, maxX=True, minY=True, maxY=True, show=True, _frameDataLUT=None, **paramsKwargs)

Plot constraint data. This can be overloaded in children classes.

Parameters:
  1. frame (None, string): The frame name to plot. If None, used frame will be plotted.

  2. axes (None, matplotlib Axes): matplotlib Axes instance to plot in. If None is given a new plot figure will be created.

  3. asMultiframe (boolean): whether to plot given frame as a multiframe. If not all subframes will be plotted as singular in a multi-axes figure

  4. partialsIntra (boolean): Whether to add partials intra pair distribution function features to the plot.

  5. partialsInter (boolean): Whether to partials inter pair distribution function features to the plot.

  6. partialsTotal (boolean): Whether to partials total pair distribution function features to the plot.

  7. shapeFunc (boolean): Whether to add shape function to the plot only when exists.

  8. resoFunc (boolean): Whether to add resolution function to the plot only when exists.

  9. thermalFunc (boolean): Whether to add thermal correction function to the plot only when exists.

  10. figureAxesNCols (None, int): number of columns in figure to create axes in multi-axes figures. If None, number of columns will be automatically set.

  11. subAdParams (None, dict): matplotlib.artist.Artist.subplots_adjust parameters subplots adjust parameters.

  12. totParams (None, dict): constraint total plotting parameters

  13. expParams (None, dict): constraint experimental data parameters

  14. noWParams (None, dict): constraint total without window parameters

  15. shaParams (None, dict): constraint shape function parameters

  16. resoParams (None, dict): constraint experimental resolution parameters

  17. sigmaParams (None, dict): constraint thermal correction sigma parameters

  18. parParams (None, dict): constraint partials parameters

  19. lossParams (None, dict): constraint loss shading parameters

  20. xlabelParams (None, dict): matplotlib.axes.Axes.set_xlabel parameters.

  21. ylabelParams (None, dict): matplotlib.axes.Axes.set_ylabel parameters.

  22. legendParams (None, dict):matplotlib.axes.Axes.legend parameters.

  23. xticksParams (None, dict):matplotlib.axes.Axes.set_xticklabels parameters.

  24. yticksParams (None, dict):matplotlib.axes.Axes.set_yticklabels parameters.

  25. shareX (bool): whether to share the same xlabel to all axes

  26. shareY (bool): whether to share the same ylabel to all axes

  27. titleParams (bool,string, dict): matplotlib.axes.Axes.set_title parameters

  28. gridParams (None, dict): matplotlib.axes.Axes.grid parameters

  29. colors (None, tuple): Tuple of matplotlib colors cycled through for successive partials. If None, matplotlib defaults are used.

  30. makers (tuple): Tuple of matplotlib markers cycled through for successive partials.

  31. customParams (None, dict): Additional custom plotting parameters overriding computed defaults.

  32. tightLayout (boolean): whether to call figure tight_layout method

  33. twinxPadding (number): Padding fraction applied between successive twin x-axes when multiple ‘$twinx’ parameters are used.

  34. xOffset (number): Constant offset added to the x axis data before plotting.

  35. yOffset (number): Constant offset added to the y axis data before plotting.

  36. xScale (None, string): matplotlib.axes.Axes.set_xscale scale name, e.g. ‘log’. If None, default linear scale is used.

  37. yScale (None, string): matplotlib.axes.Axes.set_yscale scale name, e.g. ‘log’. If None, default linear scale is used.

  38. minX (bool, number): Minimum x axis limit. If True, it is automatically computed.

  39. maxX (bool, number): Maximum x axis limit. If True, it is automatically computed.

  40. minY (bool, number): Minimum y axis limit. If True, it is automatically computed.

  41. maxY (bool, number): Maximum y axis limit. If True, it is automatically computed.

  42. 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’)

  43. show (boolean): Whether to render and show figure before returning.

  44. _frameDataLUT: for internal use only

Returns:
  1. figure (matplotlib Figure): matplotlib used figure.

  2. axes (matplotlib Axes): matplotlib used axes.

  3. frameDataLUT (dict): the frame data LUT

plot_mesoscopic_distribution(frame, ax=None, legendParams={'fontsize': 8, 'frameon': False, 'loc': 'upper right', 'ncol': 1}, titleParams='@{frame} [mesoscopic ratio]', xlabelParams=True, ylabelParams=True, tightLayout=True, show=True, _frameDataLUT=None)

plot multiframe subframes weight distribution histogram

Parameters:
  1. frame (None, string): multiframe name. If None is given, used frame multiframe will be used

  2. ax (None, matplotlib Axes): matplotlib Axes instance to plot in. If None is given a new plot figure will be created.

  3. legendParams (None, dict): matplotlib.axes.Axes.legend parameters.

  4. titleParams (None, string, dict): title format. If empty string is given no title will be added to figure axes

  5. xlabelParams (None, dict): the x axis label parameters

  6. ylabelParams (None, string): the y axis label parameters

  7. tightLayout (boolean): whether to call figure tight_layout method

  8. show (boolean): Whether to render and show figure before

    returning.

  9. _frameDataLUT: for internal use only

Returns:
  1. figure (matplotlib Figure): matplotlib used figure.

  2. axes (matplotlib Axes): matplotlib used axes.

  3. frameDataLUT (dict): the frame data LUT

export(fileName, frame=None, asSingular=True, format='%12.5f', delimiter='\t', comments='#', *args, **kwargs)

Export constraint data to text file or to an archive of files.

Parameters:
  1. fileName (path): full file name and path.

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

  3. asSingular (bool): If multiframe is nanoscopic, export subframes as singular frames. nanoscopic data will also be exported.

  4. format (string): string format to export the data. format is as follows (%[flag]width[.precision]specifier)

  5. delimiter (string): String or character separating columns.

  6. comments (string): String that will be prepended to the header.

Returns:
  1. lines (string): The exported data as a single string, also written to fileName if fileName is not None.

class fullrmc.Core.Constraint.SingularConstraint

Bases: Constraint

A singular constraint is a constraint that doesn’t allow multiple instances in the same engine.

is_singular(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.

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

Returns:
  1. result (boolean): Whether constraint is singular in engine.

assert_singular(engine)

Checks whether only one instance of this constraint type is present in the stochastic engine. Raises Exception if multiple instances are present.

Parameters:
  1. engine (Engine): The stochastic engine instance to check constraint instances against.

class fullrmc.Core.Constraint.RigidConstraint(rejectProbability)

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.

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

property rejectProbability

Rejection probability.

Returns:
  1. rejectProbability (number): The rejection probability value.

set_reject_probability(rejectProbability)

Set the rejection probability. This method doesn’t allow specifying frames. It will target used frame only.

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

should_step_get_rejected(standardError)

Given a standard error, return whether to keep or reject new standard error according to the constraint reject probability.

Parameters:

#. standardError (number): The standard error to compare with the Constraint standard error

Returns:
  1. result (boolean): True to reject step, False to accept

should_step_get_accepted(standardError)

Given a standard error, return whether to keep or reject new standard error according to the constraint reject probability.

Parameters:
  1. standardError (number): The standard error to compare with the Constraint standard error

Returns:
  1. result (boolean): True to accept step, False to reject

class fullrmc.Core.Constraint.Grains_Constraint

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.

classmethod clone(*args, **kwargs)

Design pattern implementation.

property subframesData

Subframes data.

Returns:
  1. subframesData (None, dict): The subframes data dictionary.

property grainsData

Constraints data.

Returns:
  1. grainsData (None, dict): The grains data dictionary.

set_subframes_data(data)

set grains data

Parameters:
  1. data (object): multiframe subframes data.

set_grains_data(data)

set subframes data

Parameters:
  1. data (object): multiframe subframes data.

nanoscopic_compute_data(*args, **kwargs)

Design pattern implementation.

nanoscopic_compute_before_move(*args, **kwargs)

Design pattern implementation.

nanoscopic_compute_after_move(*args, **kwargs)

Design pattern implementation.

fullrmc.Constraints package

Collection

Collection of methods and classes definition useful for constraints computation

fullrmc.Constraints.Collection.get_Grains_Engine()

Get the Grains_Engine class from the Engine module

Returns:
  1. Grains_Engine (class): the coarse grain engine class

class fullrmc.Constraints.Collection.ShapeFunction(engine, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, qmin=0.001, qmax=1, dq=0.005, rmin=0.0, rmax=100, dr=1, qBandPass=False, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, normalized=False)

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.

Parameters:
  1. engine (Engine): The fitting engine.

  2. weighting (string): The elements weighting.

  3. qmin (number): The minimum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function.

  4. qmax (number): The maximum reciprocal distance q in \(\AA^{-1}\) considered to compute the shape function.

  5. dq (number): The reciprocal distance bin size in \(\AA^{-1}\) considered to compute the shape function.

  6. rmin (number): The minimum distance in \(\AA\) considered upon building the histogram prior to computing the shape function.

  7. rmax (number): The maximum distance in \(\AA\) considered upon building the histogram prior to computing the shape function.

  8. dr (number): The bin size in \(\AA\) considered upon building the histogram prior to computing the shape function.

  9. 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}

  10. 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_Gr_shape_function(rValues, modulation=False, compute=True)

Get shape function of G(r) used in a PairDistributionConstraint.

Parameters:
  1. rValues (numpy.ndarray): The r values array.

  2. compute (boolean): whether to recompute shape function reciprocal data.

Returns:
  1. shapeFunction (numpy.ndarray): The compute shape function.

get_gr_shape_function(rValues, modulation=False, compute=True)

Get shape function of g(r) used in a PairCorrelationConstraint.

Parameters:
  1. rValues (numpy.ndarray): The r values array.

  2. compute (boolean): whether to recompute shape function reciprocal data.

Returns:
  1. shapeFunction (numpy.ndarray): The compute shape function.

get_Rr_shape_function(rValues, modulation=False, compute=True)

Get shape function of R(r) used in a RadialDistributionConstraint.

Parameters:
  1. rValues (numpy.ndarray): The r values array.

  2. compute (boolean): whether to recompute shape function reciprocal data.

Returns:
  1. shapeFunction (numpy.ndarray): The compute shape function.

fullrmc.Constraints.Collection.convert_Gr_to_Rr(Gr, elements, weights, rho0)

Converts G(r) to R(r) by computing the following

\[4 \pi r \rho_{0} R(r) = G(r) \sum \limits_{i}^{N} c_{i}\bar{b_{i}}\]
Parameters:
  1. Gr (numpy.ndarray): The G(r) numpy array of shape (number of points, 2)

  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

  3. weights (dict): dictionary of fixed weights.

  4. rho0 (float): the number density of the system

Returns:
  1. 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)
fullrmc.Constraints.Collection.convert_Rr_to_Gr(Rr, elements, weights, rho0)

Converts R(r) to G(r) by computing the following:

\[4 \pi r \rho_{0} R(r) = G(r) \sum \limits_{i}^{N} c_{i}\bar{b_{i}}\]
Parameters:
  1. Rr (numpy.ndarray): The R(r) numpy array of shape (number of points, 2)

  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

  3. weights (dict): dictionary of fixed weights.

  4. rho0 (float): the number density of the system

Returns:
  1. 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)
fullrmc.Constraints.Collection.convert_Gr_to_gr(Gr, minIndex, bySlope=None, rho0=None)

Converts G(r) to g(r) by computing the following:

\[g(r)=1+(\frac{G(r)}{4 \pi \rho_{0} r})\]
Parameters:
  1. Gr (numpy.ndarray): The G(r) numpy array of shape (number of points, 2)

  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.

  3. bySlope (None, int): whether to compute rho0 using the slope of the first n points. If given it overrides minIndex

  4. rho0 (None, float): if given it overrides minIndex and bySlope

Returns:
  1. minimas (numpy.ndarray): The minimas array found using minIndex and used to compute the slope and therefore \(\rho_{0}\).

  2. slope (float): The computed slope from the minimas.

  3. rho0 (float): The number density of the material.

  4. 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()
fullrmc.Constraints.Collection.get_element_pairs_thermal_factors(factors, defaultFactor, elements, avgf='arithmetic')

Get elements-pair thermal factors given a factors dictionary and a list of elements.

Parameters:
  1. factors (None, dict): dictionary of element or elements pair key and factor values

  2. defaultFactor (number): default factor value used when an elements pair’s factor is missing

  3. elements (list): list of available elements

  4. avgf (str, funct): average type in case pairs factor must be computed. Possible values are ‘arithmetic’, ‘geometric’ or a callable function

Returns:
  1. thermalFactor (None, dict): dictionary of elements pair thermal factors

fullrmc.Constraints.Collection.get_thermal_corrections_arrays(thermalCorrections, histogramParameters, funcType='normalized_guassian')

Create atomic thermal-vibration correction convolution arrays.

Parameters:
  1. thermalCorrections (None, dict): thermal correction parameters

  2. histogramParameters (None, dict): histogram parameters

  3. funcType (string): thermal correction function type

Returns:
  1. thermalArrays (None, dict): dictionary of thermal correction convolution arrays, keyed by elements pair. None if thermalCorrections or histogramParameters is None.

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

fullrmc.Constraints.Collection.get_resolution_corrections_array(resolutionCorrections, histogramParameters)

Create experimental resolution correction array.

Parameters:
  1. resolutionCorrections (None, dict): resolution correction parameters

  2. histogramParameters (None, dict): histogram parameters

Returns:
  1. resolutionArray (None, numpy.ndarray): the computed resolution correction array. None if resolutionCorrections or histogramParameters is None.

fullrmc.Constraints.Collection.get_qmax_corrections_array(qmaxCorrections, histogramParameters, funcType='sinc')

Create qmax cutoff experimental correction array.

Parameters:
  1. qmaxCorrections (None, dict): qmax corrections parameters

  2. histogramParameters (None, dict): histogram parameters

  3. funcType (string): qmax correction function type

Returns:
  1. qmaxArray (None, numpy.ndarray): the computed qmax cutoff correction array. None if qmaxCorrections or histogramParameters is None, or if qmax is None or <=0.

fullrmc.Constraints.Collection.convert_Fq_to_Sq(Fq, elements, weights, rho0)

Converts F(q) to S(q) by computing the following:

\[S(q) = 1 + \frac{F(q)}{\left( \sum \limits_{i}^{N} c_{i}\bar{b_{i}} \right)^{2}}\]
Parameters:
  1. Fq (numpy.ndarray): The F(q) numpy array of shape (number of points, 2)

  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

  3. weights (dict): dictionary of fixed weights.

  4. rho0 (float): the number density of the system

Returns:
  1. 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)
fullrmc.Constraints.Collection.convert_Sq_to_Fq(Sq, elements, weights, rho0)

Converts S(q) to F(q) by computing the following:

\[F(q) = \left(S(q) - 1\right) \left( \sum \limits_{i}^{N} c_{i}\bar{b_{i}} \right)^{2}\]
Parameters:
  1. Sq (numpy.ndarray): The S(q) numpy array of shape (number of points, 2)

  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

  3. weights (dict): dictionary of fixed weights.

  4. rho0 (float): the number density of the system

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

DistanceConstraints contains classes for all constraints related to distances between atoms.

Inheritance diagram of fullrmc.Constraints.DistanceConstraints
class fullrmc.Constraints.DistanceConstraints.DistanceConstraint(defaultLowerDistance=1.5, defaultUpperDistance=None, tags=None, pairsDefinition=None, flexible=True, rejectProbability=1, **kwargs)

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.

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

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

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

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

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

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

classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property parameters

Get current state and instantiation parameters

property defaultLowerDistance

default lower distance value

property defaultUpperDistance

default upper distance value

property tags

user defined atomic tags

property atomsTag

list of atom tags

property flexible

Flexible flag.

property pairsDefinition

user defined pairs definition

property stats

dictionary of arrays of number of atomic pairs per definition.

property indexesIndex

indexes index numpy array of all system atoms

property indexesLUT

indexes index look up table to indexLimitsArray

property numberOfIndexes

number of unique indexes as defined in pairsDefinition

property indexLimitsArray

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

property indexPairs

atom’s index pairs sorted list.

property indexPairsIndex

Numpy array look up for index pairs index.

property tagPairs

atom’s tag pairs sorted list.

property tagPairsIndex

Numpy array look up for tag pairs index.

property tagsIndex

tags index numpy array of all system atoms

property numberOfAtomsPerTag
property tagsLUT

tags index look up table to tagLimitsArray

property numberOfTags

number of unique tags

property tagLimitsArray

atom tag pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique tags

property namesIndex

names index numpy array of all system atoms

property numberOfAtomsPerName
property namesLUT

names index look up table to nameLimitsArray

property numberOfNames

number of unique atoms name

property nameLimitsArray

atom name pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique names

property namePairs

atom’s name pairs sorted list.

property namePairsIndex

Numpy array look up for name pairs index.

property elementsIndex

elements index numpy array of all system atoms

property elementsLUT

elements index look up table to elementLimitsArray

property numberOfElements

number of unique atoms element

property elementLimitsArray

atom element pairs intra/inter molecular, lower/upper limit numpy array (n,n,2,2) where n is the number of unique elements

property elementPairs

atom’s element pairs sorted list.

property elementPairsIndex

Numpy array look up for element pairs index.

property constraintStats

dictionary of constraints stats

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_flexible(flexible)

Set flexible flag.

Parameters:
  1. 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_tags(tags, reset=False)

Set atom tags that can be used in setting atomic pair distances definition

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

  2. reset (bool): If given tags is a dict, reset will remove all existing tags before setting the new ones

set_default_lower_distance(defaultLowerDistance)

Sets the default lower distance.

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

set_default_upper_distance(defaultUpperDistance)

Sets the default upper distance.

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

should_step_get_rejected(standardError)

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.

Parameters:
  1. standardError (number): Standard error to compare with Constraint’s standard error.

Returns:
  1. result (boolean): True to reject step, False to accept.

set_pairs_definition(pairsDefinition)

set pairs atomic distance pairs

Parameters:
  1. 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_stats(nested=False)

Get definition stats as a dictionary matching the data structure returned by the get_constraint_value method.

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

Returns:
  1. stats (dictionary): definition stats dictionary

get_histogram_data(data=None, getAll=False, nested=True)

Get constraint data in a dictionary format ready for histogram calculation and plotting.

Parameters:
  1. data (None, dict): constraint dictionary data. If None, constraint data will be used

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

  3. nested (boolean): Whether to get the dictionary histogram data as a nested as a single layer dictionary of list values.

Returns:
  1. 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_value(normalized=False, nested=False)

Get constraint’s formatted dictionary data.

Parameters:
  1. normalized (bool): whether to normalize distances by number of pairs.

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

Returns:
  1. data (dictionary): Formatted dictionary data. Keys are type pairs and values constraint data.

  2. nested (boolean): Whether to get value as a nested disctionary

compute_standard_error(data, normalized=False, resetLoss=False)

Compute the standard error (stdErr) of data not satisfying constraint’s conditions.

\[stdErr = \sum \limits_{i}^{N} \sum \limits_{i+1}^{N} \left| d_{ij}-D_{ij}) \right| \int_{0}^{D_{ij}} \delta(x-d_{ij}) dx\]

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.

Parameters:
  1. data (dict): data used to compute standard error.

  2. normalized (bool): whether to normalize distances by number of pairs.

  3. resetLoss (boolean): This is to respect the design pattern

Returns:
  1. standardError (number): The calculated standardError.

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): This is to respect the design pattern

  3. asSingular (boolean): This is to respect the design pattern

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

  2. total (None): This is to respect the design pattern

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint’s data after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom’s index was amputated.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

accept_amputation(realIndex, relativeIndex)

Accept amputation of atom and sets constraints data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.

reject_amputation(realIndex, relativeIndex)

Reject amputation of atom.

Parameters:
  1. realIndex (numpy.ndarray): No used here.

  2. relativeIndex (numpy.ndarray): Not used here.

plot(inboundParams={'color': '#0066ff', 'label': 'in-bound', 'width': 0.6}, outboundLowerParams={'color': '#d62728', 'label': 'lower error', 'width': 0.6}, outboundUpperParams={'color': '#dea623', 'label': 'upper error', 'width': 0.6}, txtParams={'color': 'black', 'fontsize': 8, 'horizontalalignment': 'center', 'rotation': 90, 'verticalalignment': 'center'}, xlabelParams={'size': 10, 'xlabel': 'Definitions'}, ylabelParams={'size': 10, 'ylabel': 'Number of pairs'}, xticksParams={'fontsize': 8, 'rotation': 45}, **kwargs)

Alias to Constraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. inboundParams (None, dict): matplotlib.axes.Axes.bar parameters for in-bound (satisfying) pairs.

  2. outboundLowerParams (None, dict): matplotlib.axes.Axes.bar parameters for pairs violating the lower distance limit.

  3. outboundUpperParams (None, dict): matplotlib.axes.Axes.bar parameters for pairs violating the upper distance limit.

  4. txtParams (None, dict): matplotlib.axes.Axes.text parameters

  5. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  6. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

  7. xticksParams (None, dict): modified matplotlib.axes.Axes.set_xticklabels parameters.

  8. titleParams (None, dict): title format.

  9. show (boolean): Whether to render and show figure before returning.

class fullrmc.Constraints.DistanceConstraints.Grains_DistanceConstraint(*args, **kwargs)

Bases: DistanceConstraint, Grains_Constraint

nanoscopic_compute_data(*args, **kwargs)

Design pattern implementation.

nanoscopic_compute_before_move(*args, **kwargs)

Design pattern implementation.

nanoscopic_compute_after_move(*args, **kwargs)

Design pattern implementation.

CoordinationConstraints

AtomicCoordinationConstraints contains classes for all constraints related to coordination number in spherical shells around atoms.

Inheritance diagram of fullrmc.Constraints.AtomicCoordinationConstraints
class fullrmc.Constraints.AtomicCoordinationConstraints.AtomicCoordinationNumberConstraint(rejectProbability=1)

Bases: RigidConstraint, SingularConstraint

Controls the coordination number of atoms.

_images/atomic_coordination_number_constraint_plot_method.png
Parameters:
  1. 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)] )
classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property parameters

Get current state and instantiation parameters

property coordNumDef

Alias to coordinationNumberDefinition

property coordinationNumberDefinition

Copy of coordination number definition dictionary

property coresIndexes

List of coordination number core atoms index array.

property shellsIndexes

List of coordination number shell atoms index array.

property numberOfCores

Array of number of core atoms

property lowerShells

Array of lower shells distance.

property upperShells

Array of upper shells distance.

property minAtoms

Array of minimum number of atoms in a shell.

property maxAtoms

Array of maximum number of atoms in a shell.

property weights

Shells weight which count in the computation of standard error.

property data

Coordination number constraint data.

property asCoreDefIdxs

List of arrays where each element is pointing to a coordination number definition where the atom is a core.

property inShellDefIdxs

List of arrays where each element is pointing to a coordination number definition where the atom is in a shell.

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_coordination_number_definition(coordNumDef)

Set the coordination number definition.

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

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

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

    3. Lower distance limit of the coordination shell.

    4. Upper distance limit of the coordination shell.

    5. \(N_{min}\) : minimum number of neighbours in the shell.

    6. \(N_{max}\) : maximum number of neighbours in the shell.

    7. \(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_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) of data not satisfying constraint’s conditions.

\[StdErr = \sum \limits_{i}^{S} Dev_{i}\]
\[\begin{split}Dev_{i}=\begin{cases} W_{i}*( N_{min,i}-\overline{CN_{i}} ), & \text{if $\overline{CN_{i}}<N_{min,i}$}.\\ W_{i}*( \overline{CN_{i}}-N_{max,i} ), & \text{if $\overline{CN_{i}}>N_{max,i}$}.\\ 0 , & \text{if $N_{min,i}<=\overline{CN_{i}}<=N_{max,i}$} \end{cases}\end{split}\]

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.

Parameters:
  1. data (numpy.array): The constraint value data to compute standardError.

  2. resetLoss (boolean): This is to respect the design pattern

Returns:
  1. standardError (number): The calculated standardError of the constraint.

get_constraint_value()

Get constraint’s data.

Returns:
  1. data (numpy.array): The constraint value data

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): This is to respect the design pattern

  3. asSingular (boolean): This is to respect the design pattern

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

  2. total (None): This is to respect the design pattern

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint’s data before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint’s data after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move.

Parameters:
  1. realIndexes (numpy.ndarray): not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move.

Parameters:
  1. realIndexes (numpy.ndarray): not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom’s index was amputated.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

accept_amputation(realIndex, relativeIndex)

Accept amputation of atom and sets constraints data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.

reject_amputation(realIndex, relativeIndex)

Reject amputation of atom.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here

plot(dataParams={'color': '#ffcc00', 'label': 'mean coord num', 'linewidth': 0, 'marker': 'o', 'markersize': 20, 'markevery': 1}, barParams={'color': '#99ccff', 'label': 'boundaries', 'width': 0.6}, txtParams={'color': 'black', 'fontsize': 8, 'horizontalalignment': 'center', 'rotation': 90, 'verticalalignment': 'center'}, xlabelParams={'size': 10, 'xlabel': 'Core-Shell atoms'}, ylabelParams={'size': 10, 'ylabel': 'Coordination number'}, xticksParams={'fontsize': 8, 'rotation': 45}, titleParams={'fontsize': 8, 'label': '@{frame} (${numberOfRemovedAtoms:.1f}$ $rem.$ $at.$) $Std.Err.={standardError:.3f}$'}, **kwargs)

Alias to Constraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. dataParams (None, dict): modified constraint data plotting parameters

  2. barParams (None, dict): matplotlib.axes.Axes.bar parameters

  3. txtParams (None, dict): matplotlib.axes.Axes.text parameters

  4. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  5. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

  6. xticksParams (None, dict): modified matplotlib.axes.Axes.set_xticklabels parameters.

  7. titleParams (None, dict): title format.

  8. show (boolean): Whether to render and show figure before returning.

BondConstraints

BondConstraints contains classes for all constraints related to bond length between atoms.

Inheritance diagram of fullrmc.Constraints.BondConstraints
class fullrmc.Constraints.BondConstraints.BondConstraint(rejectProbability=1)

Bases: RigidConstraint, SingularConstraint

Controls the bond’s length defined between two atoms.

_images/bondSketch.png

Bond sketch defined between two atoms.

_images/bond_constraint_plot_method.png
Parameters:
  1. 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) ]} )
classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

property parameters

Get current state and instantiation parameters

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property bondsList

List of defined bonds

property bondsDefinition

bonds definition copy if bonds are defined as such

property constraintStats

constraint stats dictionary

property supercell

supercell flag indicating whether bonds are set using supercell method

property tags

copy of user defined tags

property bonds

Bonds dictionary map of every and each atom

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_bonds(bondsList, tform=True)

Sets bonds dictionary by parsing bondsList list.

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

    1. First atom index forming the bond.

    2. Second atom index forming the bond.

    3. Lower limit or the minimum bond length allowed.

    4. Upper limit or the maximum bond length allowed.

    four vectors format: List of exactly four lists or numpy.arrays of the same length.

    1. List contains the first atoms index forming the bond.

    2. List contains the second atoms index forming the bond.

    3. List containing the lower limit or the minimum bond length allowed.

    4. List containing the upper limit or the maximum bond length allowed.

  2. tform (boolean): set whether given bondsList follows tuples format, If not then it must follow the four vectors one.

create_bonds_by_definition(*args, **kwargs)

Deprecated. Calling this method raises an error; use ‘create_molecules_bonds’ instead.

create_molecules_bonds(bondsDefinition)

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

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

    1. item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’

    2. item 1: bond first atom by type (must be given)

    3. item 2: bond second atom by type (must be given)

    4. item 3: bond lower length (must be given)

    5. 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) ] }
create_supercell_bonds(bondsDefinition)

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.

Parameters:
  1. bondsDefinition (None, list): The list of bonds definition. Each definition is a tuple of four items

    1. item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘element’

    2. item 1: bond first atom by type (must be given)

    3. item 2: bond second atom by type (must be given)

    4. item 3: bond lower length (must be given)

    5. 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)])
search_and_set_bonds(bondsDefinition, tags=None, _search=False)

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’

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

    1. item 0: definition atoms type. can be ‘element’,’name’,’tag’. If missing, item 0 will be automatically set to ‘element’

    2. item 1: bond first atom by type (must be given)

    3. item 2: bond second atom by type (must be given)

    4. item 3: bond lower length (must be given)

    5. item 4: bond upper length (must be given)

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

  3. _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_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) of data not satisfying constraint conditions.

\[StdErr = \sum \limits_{i}^{C} ( \beta_{i} - \beta_{i}^{min} ) ^{2} \int_{0}^{\beta_{i}^{min}} \delta(\beta-\beta_{i}) d \beta + ( \beta_{i} - \beta_{i}^{max} ) ^{2} \int_{\beta_{i}^{max}}^{\infty} \delta(\beta-\beta_{i}) d \beta\]

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.

Parameters:
  1. data (object): Data to compute standardError.

  2. resetLoss (boolean): This is to respect the design pattern

Returns:
  1. standardError (number): The calculated standardError of the given data.

get_constraint_value()

Get constraint’s data.

Returns:
  1. data (numpy.array): The constraint value data

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): This is to respect the design pattern

  3. asSingular (boolean): This is to respect the design pattern

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

  2. total (None): This is to respect the design pattern

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint’s data before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Group atoms index the move will be applied to.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom’s index was amputated.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

accept_amputation(realIndex, relativeIndex)

Accept amputation of atom and sets constraints data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Not used here.

reject_amputation(realIndex, relativeIndex)

Reject amputation of atom.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

plot(spacing=0.1, numberOfTicks=3, nbins=20, barsRelativeWidth=0.95, splitBy='element', stackHorizontal=True, colorCodeXticksLabels=True, xlabelParams={'size': 10, 'xlabel': '$r(\\AA)$'}, ylabelParams={'size': 10, 'ylabel': 'Count'}, limitsParams={'color': None, 'linestyle': '--', 'linewidth': 1.0}, **kwargs)

Alias to Constraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. spacing (float): spacing between definitions histgrams

  2. numberOfTicks (integer): number of ticks per definition histogram

  3. nbins (integer): number of bins per definition histogram

  4. barsRelativeWidth (float): histogram bar relative width >0 and <1

  5. splitBy (None, string): Split definition histograms by atom element, name or merely distance. accepts None, ‘element’, ‘name’

  6. stackHorizontal (boolean): whether to stack definition plots horizontally or vertically

  7. colorCodeXticksLabels (boolean): whether to color code x ticks per definition color

  8. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  9. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

  10. titleParams (None, dict): axes title parameters

AngleConstraints

AngleConstraints contains classes for all constraints related angles between atoms.

Inheritance diagram of fullrmc.Constraints.AngleConstraints
class fullrmc.Constraints.AngleConstraints.BondsAngleConstraint(rejectProbability=1)

Bases: RigidConstraint, SingularConstraint

Controls angle defined between 3 defined atoms, a first atom called central and the remaining two called left and right.

_images/angleSketch.png

Angle sketch defined between three atoms.

_images/bonds_angle_constraint_plot_method.png
Parameters:
  1. 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) ]} )
classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

property parameters

Get current state and instantiation parameters

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property anglesList

Defined angles list.

property anglesDefinition

angles definition copy if angles are defined as such

property constraintStats

constraint stats dictionary

property angles

angles dictionary of every and each atom.

property tags

user defined tags

property supercell

supercell flag indicating whether angles are set using supercell method

listen(message, argument=None)

Listen to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_angles(anglesList, tform=True)

Sets the angles dictionary by parsing the anglesList. All angles are in degrees.

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

    1. Central atom index.

    2. Index of the left atom forming the angle (interchangeable with the right atom).

    3. Index of the right atom forming the angle (interchangeable with the left atom).

    4. Minimum lower limit or the minimum angle allowed in degrees which later will be converted to rad.

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

    1. List containing central atom indexes.

    2. List containing the index of the left atom forming the angle (interchangeable with the right atom).

    3. List containing the index of the right atom forming the angle (interchangeable with the left atom).

    4. List containing the minimum lower limit or the minimum angle allowed in degrees which later will be converted to rad.

    5. List containing the maximum upper limit or the maximum angle allowed in degrees which later will be converted to rad.

  1. tform (boolean): set whether given anglesList follows tuples format, If False, then it must follow the five vectors one.

create_angles_by_definition(*args, **kwargs)

Deprecated. Calling this method raises an error; use ‘create_molecules_angles’ instead.

create_molecules_angles(anglesDefinition)

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

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

    1. item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’

    2. item 1: angle central atom by type (must be given)

    3. item 2: angle left atom by type (must be given)

    4. item 3: angle right atom by type (must be given)

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

    6. 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) ] }
create_supercell_angles(anglesDefinition)

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.

Parameters:
  1. anglesDefinition (None, list): The list of angles definition. Each definition is a tuple of 9 items

    1. item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘element’

    2. item 1: angle central atom by type (must be given)

    3. item 2: angle left atom by type (must be given)

    4. item 3: angle right atom by type (must be given)

    5. item 4: angle central to left lower distance (must be given)

    6. item 5: angle central to left upper distance (must be given)

    7. item 6: angle central to right lower distance. If missing, central to left lower distance will be used

    8. item 7: angle central to right upper distance. If missing central to left upper distance will be used

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

    10. 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)])
search_and_set_angles(anglesDefinition, tags=None, _search=False)

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’

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

    1. item 0: definition atoms type. can be ‘element’,’name’,’tag’. If missing, item 0 will be automatically set to ‘element’

    2. item 1: angle central atom by type (must be given)

    3. item 2: angle left atom by type (must be given)

    4. item 3: angle right atom by type (must be given)

    5. item 4: angle central to left lower distance (must be given)

    6. item 5: angle central to left upper distance (must be given)

    7. item 6: angle central to right lower distance. If missing, central to left lower distance will be used

    8. item 7: angle central to right upper distance. If missing central to left upper distance will be used

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

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

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

  3. _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_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) of data not satisfying constraint conditions.

\[StdErr = \sum \limits_{i}^{C} ( \theta_{i} - \theta_{i}^{min} ) ^{2} \int_{0}^{\theta_{i}^{min}} \delta(\theta-\theta_{i}) d \theta + ( \theta_{i} - \theta_{i}^{max} ) ^{2} \int_{\theta_{i}^{max}}^{\pi} \delta(\theta-\theta_{i}) d \theta\]

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.

Parameters:
  1. data (numpy.array): Constraint’s data to compute standardError.

  2. resetLoss (boolean): This is to respect the design pattern

Returns:
  1. standardError (number): The calculated standardError of the given data.

get_constraint_value()

Get constraint’s data value.

Returns:
  1. data (dictionary): constraint data, where keys are the element wise intra and inter molecular angle definitions and values are the computed data.

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): This is to respect the design pattern

  3. asSingular (boolean): This is to respect the design pattern

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

  2. total (None): This is to respect the design pattern

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Group atoms index the move will be applied to.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

accept_amputation(realIndex, relativeIndex)

Accept amputation of atom and set constraint’s data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Not used here.

reject_amputation(realIndex, relativeIndex)

Reject amputation of atom.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

plot(spacing=2, numberOfTicks=2, nbins=20, barsRelativeWidth=0.95, splitBy='element', stackHorizontal=True, colorCodeXticksLabels=True, xlabelParams={'size': 10, 'xlabel': '$deg.$'}, ylabelParams={'size': 10, 'ylabel': 'number'}, limitsParams={'color': None, 'linestyle': '--', 'linewidth': 1.0}, **kwargs)

Alias to Constraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. spacing (float): spacing between definitions histgrams

  2. numberOfTicks (integer): number of ticks per definition histogram

  3. nbins (integer): number of bins per definition histogram

  4. barsRelativeWidth (float): histogram bar relative width >0 and <1

  5. splitBy (None, string): Split definition histograms by atom

    element, name or merely distance. accepts None, ‘element’, ‘name’

  6. stackHorizontal (boolean): whether to stack definition plots

    horizontally or vertically

  7. colorCodeXticksLabels (boolean): whether to color code x ticks

    per definition color

  8. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel

    parameters.

  9. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel

    parameters.

  10. titleParams (None, dict): axes title parameters

DihedralAngleConstraints

ImproperAngleConstraints contains classes for all constraint’s related to improper angles between atoms.

Inheritance diagram of fullrmc.Constraints.ImproperAngleConstraints
class fullrmc.Constraints.DihedralAngleConstraints.DihedralAngleConstraint(rejectProbability=1)

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.

_images/dihedralSketch.png

Dihedral angle sketch defined between two planes formed with four atoms.

Parameters:
  1. 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), ] })
classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

property constraintStats

constraint stats dictionary

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property parameters

Get current state and instantiation parameters

property anglesList

Improper angles list.

property anglesDefinition

angles definition copy if dihedral angles are defined as such

property angles

Angles dictionary for every and each atom.

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_angles(anglesList, tform=True)

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.

Parameters:
  1. anglesList (None,list): The angles list definition.

    tuples format: every item must be a list of ten items.

    1. First atom index of the first plane.

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

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

    4. Fourth atom index of the second plane.

    5. Minimum lower limit of the first shell or minimum angle allowed in degrees which later will be converted to rad.

    6. Maximum upper limit of the first shell or maximum angle allowed in degrees which later will be converted to rad.

    7. Minimum lower limit of the second shell or minimum angle allowed in degrees which later will be converted to rad.

    8. Maximum upper limit of the second shell or maximum angle allowed in degrees which later will be converted to rad.

    9. Minimum lower limit of the third shell or minimum angle allowed in degrees which later will be converted to rad.

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

    1. List containing first atoms index of the first plane.

    2. List containing second atoms index of the first plane and first atoms index of the second plane.

    3. List containing third atoms indexes of the first plane and second atoms index of the second plane.

    4. List containing fourth atoms index of the second plane.

    5. List containing minimum lower limit of the first shell or minimum angle allowed in degrees which later will be converted to rad.

    6. List containing maximum upper limit of the first shell or maximum angle allowed in degrees which later will be converted to rad.

    7. List containing minimum lower limit of the second shell or minimum angle allowed in degrees which later will be converted to rad.

    8. List containing maximum upper limit of the second shell or maximum angle allowed in degrees which later will be converted to rad.

    9. List containing minimum lower limit of the third shell or minimum angle allowed in degrees which later will be converted to rad.

    10. List containing maximum upper limit of the third shell or maximum angle allowed in degrees which later will be converted to rad.

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

create_angles_by_definition(*args, **kwargs)

Deprecated. Calling this method raises an error; use ‘create_molecules_angles’ instead.

create_molecules_angles(anglesDefinition)

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

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

    1. item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’

    2. item 1: dihedral first atom by type of the first plane (must be given)

    3. item 2: dihedral second atom by type of the first plane which is also the first atom of the second plane (must be given)

    4. item 3: dihedral third atom by type of the first plane which is also the second atom of the second plane (must be given)

    5. item 4: dihedral third atom by type of the second plane(must be given)

    6. item 5: Minimum lower limit of the first shell or the minimum angle allowed in degrees (must be given)

    7. item 6: Maximum upper limit of the first or the maximum angle allowed in degrees (must be given)

    8. item 7: Minimum lower limit of the second shell or the minimum angle allowed in degrees (must be given)

    9. item 8: Maximum upper limit of the second or the maximum angle allowed in degrees (must be given)

    10. item 9: Minimum lower limit of the third shell or the minimum angle allowed in degrees (must be given)

    11. 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_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) of data not satisfying constraint conditions.

\[StdErr = \sum \limits_{i}^{C} ( \theta_{i} - \theta_{i}^{min} ) ^{2} \int_{0}^{\theta_{i}^{min}} \delta(\theta-\theta_{i}) d \theta + ( \theta_{i} - \theta_{i}^{max} ) ^{2} \int_{\theta_{i}^{max}}^{\pi} \delta(\theta-\theta_{i}) d \theta\]

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.

Parameters:
  1. data (numpy.array): The constraint value data to compute standardError.

  2. resetLoss (boolean): This is to respect the design pattern

Returns:
  1. standardError (number): The calculated standardError of the constraint.

get_constraint_value()

Get constraint’s data.

Returns:
  1. data (numpy.array): The constraint value data

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): This is to respect the design pattern

  3. asSingular (boolean): This is to respect the design pattern

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

  2. total (None): This is to respect the design pattern

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint’s data before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Group atoms index the move will be applied to.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint’s data after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

accept_amputation(realIndex, relativeIndex)

Accept amputation of atom and set constraint’s data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Not used here.

reject_amputation(realIndex, relativeIndex)

Reject amputation of atom.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

plot(spacing=2, numberOfTicks=3, nbins=20, barsRelativeWidth=0.95, splitBy='element', stackHorizontal=False, colorCodeXticksLabels=True, xlabelParams={'size': 10, 'xlabel': '$deg.$'}, ylabelParams={'size': 10, 'ylabel': 'Count'}, limitsParams={'color': None, 'linestyle': None, 'linewidth': 1.0}, **kwargs)

Alias to Constraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. spacing (float): spacing between definitions histgrams

  2. numberOfTicks (integer): number of ticks per definition histogram

  3. nbins (integer): number of bins per definition histogram

  4. barsRelativeWidth (float): histogram bar relative width >0 and <1

  5. splitBy (None, string): Split definition histograms by atom element, name or merely distance. accepts None, ‘element’, ‘name’

  6. stackHorizontal (boolean): whether to stack definition plots horizontally or vertically

  7. colorCodeXticksLabels (boolean): whether to color code x ticks per definition color

  8. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  9. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

  10. titleParams (None, dict): axes title parameters

ImproperAngleConstraints

ImproperAngleConstraints contains classes for all constraints related to improper angles between atoms.

Inheritance diagram of fullrmc.Constraints.ImproperAngleConstraints
class fullrmc.Constraints.ImproperAngleConstraints.ImproperAngleConstraint(rejectProbability=1)

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.

_images/improperSketch.png

Improper angle sketch defined between four atoms.

Parameters:
  1. 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) ] })
classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

property parameters

Get current state and instantiation parameters

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property anglesList

Get improper angles list.

property anglesDefinition

angles definition copy if improper angles are defined as such

property angles

Get angles dictionary for every and each atom.

property constraintStats

constraint stats dictionary

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_angles(anglesList, tform=True)

Sets the angles dictionary by parsing the anglesList list.

Parameters:
  1. anglesList (None, list): Angles list definition.

    tuples format: every item must be a list of six items.

    1. Improper atom index that must be in the plane.

    2. Index of atom ‘O’ considered the origin of the plane.

    3. Index of atom ‘x’ used to calculated ‘Ox’ vector.

    4. Index of atom ‘y’ used to calculated ‘Oy’ vector.

    5. Minimum lower limit or minimum angle allowed in degrees which later will be converted to rad.

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

    1. List containing improper atoms index that must be in the plane.

    2. List containing index of atoms ‘O’ considered the origin of the plane.

    3. List containing index of atoms ‘x’ used to calculated ‘Ox’ vector.

    4. List containing index of atom ‘y’ used to calculated ‘Oy’ vector.

    5. List containing minimum lower limit or minimum angle allowed in degrees which later will be converted to rad.

    6. List containing maximum upper limit or maximum angle allowed in degrees which later will be converted to rad.

  1. tform (boolean): Whether given anglesList follows tuples format, If not then it must follow the six vectors one.

create_angles_by_definition(*args, **kwargs)

Deprecated. Calling this method raises an error; use ‘create_molecules_angles’ instead.

create_molecules_angles(anglesDefinition)

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

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

    1. item 0: definition atoms type. can be ‘element’,’name’. If missing, item 0 will be automatically set to ‘name’

    2. item 1: angle improper atom by type (must be given)

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

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

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

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

    7. 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_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) of data not satisfying constraint’s conditions.

\[StdErr = \sum \limits_{i}^{C} ( \theta_{i} - \theta_{i}^{min} ) ^{2} \int_{0}^{\theta_{i}^{min}} \delta(\theta-\theta_{i}) d \theta + ( \theta_{i} - \theta_{i}^{max} ) ^{2} \int_{\theta_{i}^{max}}^{\pi} \delta(\theta-\theta_{i}) d \theta\]

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.

Parameters:
  1. data (numpy.array): data to compute standardError.

  2. resetLoss (boolean): This is to respect the design pattern

Returns:
  1. standardError (number): computed standardError of given data.

get_constraint_value()

Get constraint’s data value.

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

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): This is to respect the design pattern

  3. asSingular (boolean): This is to respect the design pattern

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

  2. total (None): This is to respect the design pattern

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint’s data before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Group atoms index the move will be applied to.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint’s data after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

accept_amputation(realIndex, relativeIndex)

Accept amputation of atom and sets constraint’s data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Not used here.

reject_amputation(realIndex, relativeIndex)

Reject amputation of atom.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

plot(spacing=2, numberOfTicks=2, nbins=20, barsRelativeWidth=0.95, splitBy='element', stackHorizontal=True, colorCodeXticksLabels=True, xlabelParams={'size': 10, 'xlabel': '$deg.$'}, ylabelParams={'size': 10, 'ylabel': 'Count'}, limitsParams={'color': None, 'linestyle': '--', 'linewidth': 1.0}, **kwargs)

Alias to Constraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. spacing (float): spacing between definitions histgrams

  2. numberOfTicks (integer): number of ticks per definition histogram

  3. nbins (integer): number of bins per definition histogram

  4. barsRelativeWidth (float): histogram bar relative width >0 and <1

  5. splitBy (None, string): Split definition histograms by atom element, name or merely distance. accepts None, ‘element’, ‘name’

  6. stackHorizontal (boolean): whether to stack definition plots horizontally or vertically

  7. colorCodeXticksLabels (boolean): whether to color code x ticks per definition color

  8. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  9. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

  10. titleParams (None, dict): axes title parameters

PairDistributionConstraints

PairDistributionConstraints contains classes for all constraints related to experimental pair distribution functions.

Inheritance diagram of fullrmc.Constraints.PairDistributionConstraints
class fullrmc.Constraints.PairDistributionConstraints.PairDistributionConstraint(experimentalData, dataWeights=None, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None, scaleFactor=1.0, adjustScaleFactor=None, shapeFuncParams=None, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, windowFunction=None, limits=None)

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:

\[ \begin{align}\begin{aligned}G(r) = \frac{2}{\pi} \int_{0}^{\infty} Q [S(Q)-1]sin(Qr)dQ \\ S(Q) = 1+ \frac{4 \pi}{Q} \int_{0}^{\infty} r (\rho_{r} - \rho_{0}) sin(Qr) dr \\ = 1+ \frac{1}{Q} \int_{0}^{\infty} G(r) sin(Qr) dr\end{aligned}\end{align} \]

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

\[G(r) = 4 \pi r (\rho_{r} - \rho_{0}) = 4 \pi \rho_{0} r (g(r)-1) = \frac{R(r)}{r} - 4 \pi \rho_{0}\]

\(\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:

\[g(r) = \sum \limits_{i,j}^{N} w_{i,j} g_{i,j}(r) = \sum \limits_{i,j}^{N} w_{i,j} \frac{\rho_{i,j}(r)}{\rho_{<i,j>}} = \sum \limits_{i,j}^{N} w_{i,j} \frac{n_{i,j}(r) / v(r)}{N_{i,j} / V}\]
\[w_{i,j}= \frac{ c_{i}c_{j}b_{i}b_{j} } {\sum \limits_{i,j} c_{i}c_{j}b_{i}b_{j}}\]

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.

_images/pair_distribution_constraint_plot_method.png
Parameters:
  1. experimentalData (numpy.ndarray, string): Experimental data as numpy.ndarray or string path to load data using numpy.loadtxt.

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

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

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

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

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

  7. scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.

  8. 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:

    1. The ‘update’ frequency, in number of generated moves, for finding the best scale factor. If None or 0, the scale factor is fixed.

    2. The ‘minimum’ allowed scale factor value.

    3. The ‘maximum’ allowed scale factor value.

    4. The scale factor ‘learning_rate’.

    If a dict is given, it must include ‘update’, ‘minimum’, ‘maximum’ and, optionally, ‘learning_rate’.

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

    • modulation (boolean, integer, float) : 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 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

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

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

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

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

  14. 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)
classmethod get_parameters_for_nanoscopic(engine, frame, cname, metadata=None)

For experimental constraints nanoscopic parameters must be overloaded

classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property parameters

Get current state and instantiation parameters

property distanceBin

Experimental data distances bin.

property minimumDistance

Experimental data minimum distances.

property maximumDistance

Experimental data maximum distances.

property histogramSize

Histogram size.

property experimentalDistances

Experimental distances array.

property shellCenters

Shells center array.

property shellVolumes

Shells volume array.

property experimentalPDF

Experimental pair distribution function data.

property windowFunction

Window function.

property windowArray

Window function.

property shapeArray

Shape function data array.

property shapeUpdateFreq

Shape function update frequency.

property shapeFuncParams

shape function parameters

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_shape_function_parameters(*args, **kwargs)

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.

Parameters:
  1. 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_window_function(*args, **kwargs)

Set convolution window function.

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

  2. frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.

set_experimental_data(experimentalData, _log=True)

Set constraint’s experimental data.

Parameters:
  1. experimentalData (numpy.ndarray, string): The experimental data as numpy.ndarray or string path to load data using numpy.loadtxt function.

set_limits(*args, **kwargs)

Set the histogram computation limits.

Parameters:
  1. 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_experimental_data(experimentalData)

Check whether experimental data is correct.

Parameters:
  1. experimentalData (object): Experimental data to check.

Returns:
  1. result (boolean): Whether it is correct or not.

  2. message (str): Checking message that explains whats’s wrong with the given data.

compute_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) using the engine defined loss function

Parameters:
  1. data (numpy.ndarray): The constraint data

  2. resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!

Returns:
  1. standardError (number): The calculated constraint’s standardError.

update_standard_error()

Compute and set constraint’s standardError.

get_total(data=None, rho0=None, asSingular=False)

Get constraint total and standard error

Parameters:
  1. data (None, dict): data to compute total. If None, constraint data will be used.

  2. rho0 (None, number): the system number density. If None, engine number density is used

Returns:
  1. total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned

  2. stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned

get_constraint_value(asSingular=False)

Compute all partial Pair Distribution Functions (PDFs).

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

Returns:
  1. PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.

get_constraint_original_value()

Compute all partial Pair Distribution Functions (PDFs).

Returns:
  1. PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!

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

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

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

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom is amputated.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.

accept_amputation(realIndex, relativeIndex)

Accept amputated atom and sets constraints data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

reject_amputation(realIndex, relativeIndex)

Reject amputated atom and set constraint’s data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

get_multiframe_weights(frame)
plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.PairDistributionConstraints.Grains_PairDistributionConstraint(*args, **kwargs)

Bases: PairDistributionConstraint, Grains_Constraint

PairDistributionConstraint implementation for coarse grains system

classmethod clone(parameters, engine=None)

Clone constraint given multiframeStructure parameters.

set_shape_function_parameters(*args, **kwargs)

Overloaded to force _shapeUpdateFreq to 1.

nanoscopic_compute_data(update=True, resetLoss=False, recomputeInter=True, *args, **kwargs)

Design pattern implementation.

nanoscopic_compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

nanoscopic_compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

PairCorrelationConstraints

PairCorrelationConstraints contains classes for all constraints related to experimental pair correlation functions.

Inheritance diagram of fullrmc.Constraints.PairCorrelationConstraints
class fullrmc.Constraints.PairCorrelationConstraints.PairCorrelationConstraint(experimentalData, dataWeights=None, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None, scaleFactor=1.0, adjustScaleFactor=None, shapeFuncParams=None, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, windowFunction=None, limits=None)

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:

\[g(r) = \sum \limits_{i,j}^{N} w_{i,j} g_{i,j}(r) = \sum \limits_{i,j}^{N} w_{i,j} \frac{\rho_{i,j}(r)}{\rho_{<i,j>}} = \sum \limits_{i,j}^{N} w_{i,j} \frac{n_{i,j}(r) / v(r)}{N_{i,j} / V}\]
\[w_{i,j}= \frac{ c_{i}c_{j}b_{i}b_{j} } {\sum \limits_{i,j} c_{i}c_{j}b_{i}b_{j}}\]

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.

Parameters:

Refer to PairDistributionConstraint

_images/pair_correlation_constraint_plot_method.png
# 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)
update_standard_error()

Compute and set constraint’s standardError.

get_total(data=None, rho0=None, asSingular=False)

Get constraint total and standard error

Parameters:
  1. data (None, dict): data to compute total. If None, constraint data will be used.

  2. rho0 (None, number): the system number density. If None, engine number density is used

Returns:
  1. total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned

  2. stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned

get_adjusted_scale_factor(experimentalData, modelData, dataWeights, rho0)

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_value(asSingular=False)

Get constraint’s data dictionary value.

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

Returns:
  1. PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!

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

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

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

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint’s data before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint’s data after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom is amputated.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.PairCorrelationConstraints.Grains_PairCorrelationConstraint(*args, **kwargs)

Bases: PairCorrelationConstraint, Grains_Constraint

PairCorrelationConstraint implementation for coarse grains system

classmethod clone(parameters, engine=None)

Clone constraint given multiframeStructure parameters.

set_shape_function_parameters(*args, **kwargs)

Overloaded to force _shapeUpdateFreq to 1.

nanoscopic_compute_data(resetLoss=False, update=True, recomputeInter=True, *args, **kwargs)

Design pattern implementation.

nanoscopic_compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

nanoscopic_compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

RadialDistributionConstraints

PairCorrelationConstraints contains classes for all constraints related to experimental pair correlation functions.

Inheritance diagram of fullrmc.Constraints.PairCorrelationConstraints
class fullrmc.Constraints.RadialDistributionConstraints.RadialDistributionConstraint(experimentalData, dataWeights=None, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None, scaleFactor=1.0, adjustScaleFactor=None, shapeFuncParams=None, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, windowFunction=None, limits=None)

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:

\[G(r) = 4 \pi r (\rho_{r} - \rho_{0}) = 4 \pi \rho_{0} r (g(r)-1) = \frac{R(r)}{r} - 4 \pi \rho_{0}\]
\[g(r) = \sum \limits_{i,j}^{N} w_{i,j} g_{i,j}(r) = \sum \limits_{i,j}^{N} w_{i,j} \frac{\rho_{i,j}(r)}{\rho_{<i,j>}} = \sum \limits_{i,j}^{N} w_{i,j} \frac{n_{i,j}(r) / v(r)}{N_{i,j} / V}\]
\[w_{i,j}= \frac{ c_{i}c_{j}b_{i}b_{j} } {\sum \limits_{i,j} c_{i}c_{j}b_{i}b_{j}}\]

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)\)

Parameters:

Refer to PairDistributionConstraint

_images/radial_distribution_constraint_plot_method.png

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)
update_standard_error()

Compute and set constraint’s standardError.

get_total(data=None, rho0=None, asSingular=False)

Get constraint total and standard error

Parameters:
  1. data (None, dict): data to compute total. If None, constraint data will be used.

  2. rho0 (None, number): the system number density. If None, engine number density is used

Returns:
  1. total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned

  2. stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned

get_constraint_value(asSingular=False)

Get constraint’s data dictionary value.

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

Returns:
  1. PDFs (dictionary): The PDFs dictionnary, where keys are the element wise intra and inter molecular PDFs and values are the computed PDFs.

compute_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!

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

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

  2. total (numpy.ndarray): constraint total radial correlation function

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint’s data before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint’s data after move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom is amputated.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.RadialDistributionConstraints.Grains_RadialDistributionConstraint(*args, **kwargs)

Bases: RadialDistributionConstraint, Grains_Constraint

RadialDistributionConstraint implementation for coarse grains system

classmethod clone(parameters, engine=None)

Clone constraint given multiframeStructure parameters.

set_shape_function_parameters(*args, **kwargs)

Overloaded to force _shapeUpdateFreq to 1.

nanoscopic_compute_data(resetLoss=False, update=True, recomputeInter=True, *args, **kwargs)

Design pattern implementation.

nanoscopic_compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

nanoscopic_compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

StructureFactorConstraints

StructureFactorConstraints contains classes for all constraints related experimental static structure factor functions.

Inheritance diagram of fullrmc.Constraints.StructureFactorConstraints
class fullrmc.Constraints.StructureFactorConstraints.StructureFactorConstraint(experimentalData, dataWeights=None, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None, rmin=None, rmax=None, dr=None, scaleFactor=1.0, adjustScaleFactor=None, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, windowFunction=None, limits=None, _log=True)

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

\[S(Q) = 1+ \frac{1}{Q} \int_{0}^{\infty} G(r) sin(Qr) dr\]

From an atomistic model and histogram point of view, G(r) is computed as the following:

\[G(r) = 4 \pi r (\rho_{r} - \rho_{0}) = 4 \pi \rho_{0} r (g(r)-1) = \frac{R(r)}{r} - 4 \pi \rho_{0}\]

g(r) is calculated after binning all pair atomic distances into a weighted histograms as the following:

\[g(r) = \sum \limits_{i,j}^{N} w_{i,j} \frac{\rho_{i,j}(r)}{\rho_{0}} = \sum \limits_{i,j}^{N} w_{i,j} \frac{n_{i,j}(r) / v(r)}{N_{i,j} / V}\]

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.

_images/reduced_structure_factor_constraint_plot_method.png

Reduced structure factor of memory shape Nickel-Titanium alloy.

Parameters:
  1. experimentalData (numpy.ndarray, string): Experimental data as numpy.ndarray or string path to load data using numpy.loadtxt method.

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

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

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

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

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

  7. rmin (None, number): The minimum distance value to compute G(r) histogram. If None is given, rmin is computed as \(2 \pi / Q_{max}\).

  8. rmax (None, number): The maximum distance value to compute G(r) histogram. If None is given, rmax is computed as \(2 \pi / dQ\).

  9. 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})\).

  10. scaleFactor (number): A normalization scale factor used to normalize the computed data to the experimental ones.

  11. 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:

    1. The ‘update’ frequency, in number of generated moves, for finding the best scale factor. If 0, the scale factor is fixed.

    2. The ‘minimum’ allowed scale factor value.

    3. The ‘maximum’ allowed scale factor value.

    4. The scale factor ‘learning_rate’.

    If a dict is given, it must include ‘update’, ‘minimum’, ‘maximum’ and, optionally, ‘learning_rate’.

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

  13. qmaxCorrections (None, number, dict): Not used in q space constraints

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

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

  16. 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)
classmethod get_parameters_for_nanoscopic(engine, frame, cname, metadata=None)

For experimental constraints nanoscopic parameters must be overloaded

classmethod create(params, engine, *args, **kwargs)

Create a constraint instance given instantiation parameters

Parameters:
  1. params (dict): instantiation parameters

Returns:
  1. obj (Constraint): the created instance

update(params)

Update instance using parameters

Parameters:
  1. params (dict): instantiation parameters. Can be pure (key,value) dictionary or as returned from parameters instance property

property parameters

Get current state and instantiation parameters

property rmin

Histogram minimum distance.

property rmax

Histogram maximum distance.

property dr

The distance bin value to compute G(r) histogram as instantiated and given by user

property distanceBin

The computed distance bin value to compute G(r). If given dr is not None, distance bin will be equal to dr

property minimumDistance

Computed histogram minimum distance.

property maximumDistance

Computed histogram maximum distance.

property qmin

Experimental data reciprocal distances minimum.

property qmax

Experimental data reciprocal distances maximum.

property dq

Experimental data reciprocal distances bin size.

property experimentalQValues

Experimental data used q values.

property histogramSize

Histogram size

property shellCenters

Shells center array

property shellVolumes

Shells volume array

property experimentalSF

Experimental Structure Factor or S(q)

property windowFunction

Convolution window function.

property windowArray

Convolution window function.

property Gr2SqMatrix

G(r) to S(q) transformation matrix.

listen(message, argument=None)

Listens to any message sent from the Broadcaster.

Parameters:
  1. message (object): Any python object to send to constraint’s listen method.

  2. argument (object): Any type of argument to pass to the listeners.

set_rmin(*args, **kwargs)

Set rmin value.

Parameters:
  1. 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(*args, **kwargs)

Set rmax value.

Parameters:
  1. 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(*args, **kwargs)

Set dr value.

Parameters:
  1. 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_window_function(*args, **kwargs)

Set convolution window function.

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

  2. frame (None, string): Target frame name. If None, engine used frame is used. If multiframe is given, all subframes will be targeted.

set_experimental_data(experimentalData, _log=True)

Set constraint’s experimental data.

Parameters:
  1. experimentalData (numpy.ndarray, string): The experimental data as numpy.ndarray or string path to load data using numpy.loadtxt function.

set_limits(*args, **kwargs)

Set the reciprocal distance limits (qmin, qmax).

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

update_standard_error()

Compute and set constraint’s standardError.

check_experimental_data(experimentalData)

Check whether experimental data is correct.

Parameters:
  1. experimentalData (object): The experimental data to check.

Returns:
  1. result (boolean): Whether it is correct or not.

  2. message (str): Checking message that explains whats’s wrong with the given data

compute_standard_error(data, resetLoss=False)

Compute the standard error (StdErr) using the engine defined loss function

Parameters:
  1. data (numpy.ndarray): The constraint data

  2. resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!

Returns:
  1. standardError (number): The calculated constraint’s standardError.

get_total(data=None, rho0=None, asSingular=False)

Get constraint total and standard error

Parameters:
  1. data (None, dict): data to compute total. If None, constraint data will be used.

  2. rho0 (None, number): the system number density. If None, engine number density is used

Returns:
  1. total (None, numpy.ndarray): constraint total array. If given data and constraint data are both None, None is returned

  2. stdError(None, number): constraint standard error. If given data and constraint data are both None, None is returned

get_constraint_value(asSingular=False)

Compute all partial Structure Factor (SQs).

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

Returns:
  1. SQs (dictionary): The SQs dictionnary, where keys are the element wise intra and inter molecular SQs and values are the computed SQs.

get_constraint_original_value()

Compute all partial Structure Factor (SQs).

Returns:
  1. SQs (dictionary): The SQs dictionnary, where keys are the element wise intra and inter molecular SQs and values are the computed SQs.

get_adjusted_scale_factor(experimentalData, modelData, dataWeights)

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_data(*args, **kwargs)

Compute constraint’s data.

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

  2. resetLoss (boolean): whether to force resetting loss function data. Not all losses are resettable!

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

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

  2. total (numpy.ndarray): constraint total structure factor function

  3. standardError (float): constraint standard error

compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

accept_move(realIndexes, relativeIndexes)

Accept move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

reject_move(realIndexes, relativeIndexes)

Reject move

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Not used here.

compute_as_if_amputated(realIndex, relativeIndex)

Compute and return constraint’s data and standard error as if given atom is amputated.

Parameters:
  1. realIndex (numpy.ndarray): Atom’s index as a numpy array of a single element.

  2. relativeIndex (numpy.ndarray): Atom’s relative index as a numpy array of a single element.

accept_amputation(realIndex, relativeIndex)

Accept amputated atom and sets constraints data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

reject_amputation(realIndex, relativeIndex)

Reject amputated atom and set constraint’s data and standard error accordingly.

Parameters:
  1. realIndex (numpy.ndarray): Not used here.

  2. relativeIndex (numpy.ndarray): Not used here.

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.StructureFactorConstraints.ReducedStructureFactorConstraint(experimentalData, dataWeights=None, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None, rmin=None, rmax=None, dr=None, scaleFactor=1.0, adjustScaleFactor=None, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, windowFunction=None, limits=None, _log=True)

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

\[S(Q) = \frac{1}{Q} \int_{0}^{\infty} G(r) sin(Qr) dr\]

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.

get_adjusted_scale_factor(experimentalData, modelData, dataWeights)

dummy overload that does exactly the same thing

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.StructureFactorConstraints.NormalizedStructureFactorConstraint(experimentalData, dataWeights=None, weighting='atomicNumber', atomsWeight=None, pairsWeight=None, custPartScatteringPower=None, rmin=None, rmax=None, dr=None, scaleFactor=1.0, adjustScaleFactor=None, thermalCorrections=None, qmaxCorrections=None, resolutionCorrections=None, windowFunction=None, limits=None, _log=True)

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

\[F\left(Q\right)=\frac{{4\pi\rho}_0}{q}\int_{0}^{\infty}rG\left(r\right)sin\left(qr\right)dr\]

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)\)

_images/normalized_structure_factor_constraint_plot_method.png

Normalized structure factor of Strotium Titanim Oxide.

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.StructureFactorConstraints.Grains_StructureFactorConstraint(*args, **kwargs)

Bases: StructureFactorConstraint, Grains_Constraint

classmethod clone(parameters, engine=None)

Clone constraint given multiframeStructure parameters.

nanoscopic_compute_data(update=True, recomputeInter=True, *args, **kwargs)

Design pattern implementation.

nanoscopic_compute_before_move(realIndexes, relativeIndexes)

Compute constraint before move is executed.

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

nanoscopic_compute_after_move(realIndexes, relativeIndexes, movedBoxCoordinates)

Compute constraint after move is executed

Parameters:
  1. realIndexes (numpy.ndarray): Not used here.

  2. relativeIndexes (numpy.ndarray): Group atoms relative index the move will be applied to.

  3. movedBoxCoordinates (numpy.ndarray): The moved atoms new coordinates.

class fullrmc.Constraints.StructureFactorConstraints.Grains_ReducedStructureFactorConstraint(*args, **kwargs)

Bases: Grains_StructureFactorConstraint

get_adjusted_scale_factor(experimentalData, modelData, dataWeights)

dummy overload that does exactly the same thing

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.

class fullrmc.Constraints.StructureFactorConstraints.Grains_NormalizedStructureFactorConstraint(*args, **kwargs)

Bases: Grains_StructureFactorConstraint

plot(xlabelParams=True, ylabelParams=True, **kwargs)

Alias to ExperimentalConstraint.plot with additional parameters

Additional/Adjusted Parameters:
  1. xlabelParams (None, dict): modified matplotlib.axes.Axes.set_xlabel parameters.

  2. ylabelParams (None, dict): modified matplotlib.axes.Axes.set_ylabel parameters.