diffpy.pdfgui.control package

Submodules

diffpy.pdfgui.control.pdfcomponent module

class diffpy.pdfgui.control.pdfcomponent.PDFComponent(name)[source]

Bases: object

Common base class.

close(force=False)[source]

Close myself.

force – if forcibly (no wait)

diffpy.pdfgui.control.constraint module

Class Constraint for storage of a single constraint equation constraints will be stored in { variable : constraint } dictionary.

class diffpy.pdfgui.control.constraint.Constraint(formula, value=None)[source]

Bases: object

Constraint –> storage and check of a single constraint equation.

Data members:
formula – right-side of constraint equation (string). When

assigned it is checked for math correctness and updates the parguess dictionary

parguess – read-only dictionary of parameter indices and their

estimated initial values. Values are None if they cannot be estimated.

Private members:

__lhs – last value of constrained variable passed to guess()

evalFormula(parvalues)[source]

Evaluate constraint formula.

parvalues – dictionary of int parameter indices and float values.

returns formula result

guess(value)[source]

Guess the initial values of parameters contained in parguess.

value – current value of the constrained variable

The keys of self.parguess are indices of parameters used in formula, and the values are suggested parameter values (None if they cannot be estimated).

returns a copy of self.parguess

lambdaFormula()[source]

Build lambda function from constraint formula. Lambda function expects dictionary argument.

returns lambda function

diffpy.pdfgui.control.controlerrors module

exception diffpy.pdfgui.control.controlerrors.ControlConfigError(info)[source]

Bases: ControlError

PDFGuiControl exception class – object config is invalid.

exception diffpy.pdfgui.control.controlerrors.ControlError(info)[source]

Bases: Exception

Basic PDFGuiControl exception class.

exception diffpy.pdfgui.control.controlerrors.ControlFileError(info)[source]

Bases: ControlError

PDFGuiControl exception class – object config is invalid.

exception diffpy.pdfgui.control.controlerrors.ControlIndexError(info)[source]

Bases: ControlError

PDFGuiControl exception class – index out of bound.

exception diffpy.pdfgui.control.controlerrors.ControlKeyError(info)[source]

Bases: ControlError

PDFGuiControl exception class – requested object can’t be found.

exception diffpy.pdfgui.control.controlerrors.ControlRuntimeError(info)[source]

Bases: ControlError

PDFGuiControl exception class – various irrecoverable runtime error.

exception diffpy.pdfgui.control.controlerrors.ControlStatusError(info)[source]

Bases: ControlError

PDFGuiControl exception class – Fitting status doesn’t match.

exception diffpy.pdfgui.control.controlerrors.ControlSyntaxError(info)[source]

Bases: ControlError

PDFGuiControl exception class – invalid syntax of constraint formula.

exception diffpy.pdfgui.control.controlerrors.ControlTypeError(info)[source]

Bases: ControlError

PDFGuiControl exception class – Type mismatch.

exception diffpy.pdfgui.control.controlerrors.ControlValueError(info)[source]

Bases: ControlError

PDFGuiControl exception class – Invalid value.

exception diffpy.pdfgui.control.controlerrors.TempControlSelectError(info)[source]

Bases: ControlError

Temporary define this error to identify the select-control error in python3.

diffpy.pdfgui.control.pdflist module

class diffpy.pdfgui.control.pdflist.PDFList(*args)[source]

Bases: list

List class of PDFComponent, which can be accessed through index or a name string.

items()[source]

Get name-object pairs.

return: a list of tuple ( name, object)

keys()[source]

Get the names of the held objects.

return: list of names

rename(idnmrf, newname)[source]

Rename an item.

idnmrf – index,name or reference to the object newname – new name

values()[source]

Get all held objects.

return: list of objects

diffpy.pdfgui.control.pdfguimacros module

Methods for macros used in pdfgui.

diffpy.pdfgui.control.pdfguimacros.makeDopingSeries(control, fit, base, dopant, paths, doping)[source]

Make a temperature series.

control – pdguicontrol instance fit – The template fit base – Name of the base element dopant – Name of the dopant element paths – list of path names of new datasets doping – list of doping values corresponding to the datasets

returns a list of the new fit organization objects

diffpy.pdfgui.control.pdfguimacros.makeRSeries(control, fit, maxfirst=None, maxlast=None, maxstep=None, minfirst=None, minlast=None, minstep=None)[source]

Make an series of fits with an increasing r-range.

The new fits are appended to the end of any current fits in the control.

control – The control object that will contain the fits fit – The prototype fit maxfirst – The first value of the maximum of the fit range maxlast – The last value of the maximum of the fit range maxstep – The step size of the maximum of the fit range minfirst – The first value of the minimum of the fit range minlast – The last value of the minimum of the fit range minstep – The step size of the minimum of the fit range

returns a list of the new fit organization objects

diffpy.pdfgui.control.pdfguimacros.makeTemperatureSeries(control, fit, paths, temperatures)[source]

Make a temperature series.

control – pdguicontrol instance fit – The template fit paths – list of path names of new datasets temperatures – list of temperatures corresponding to the datasets

returns a list of the new fit organization objects

diffpy.pdfgui.control.calculation module

Class Calculation for performing PDF simulation from model structure.

class diffpy.pdfgui.control.calculation.Calculation(name)[source]

Bases: PDFComponent

Perform a theoretical computation of PDF from model structure.

Data members:

rmin – read-only lower boundary of rcalc, change with setRGrid() rstep – read-only r-grid step, use setRGrid() to change it rmax – read-only upper boundary of rcalc, change with setRGrid() rlen – read-only number of r points, set by setRGrid().

To be used in PdfFit.alloc()

rcalc – list of r values, this is set after calculation is finished Gcalc – list of calculated G values stype – scattering type, ‘X’ or ‘N’ qmax – maximum value of Q in inverse Angstroms. Termination ripples

are ignored for qmax=0.

qdamp – specifies width of Gaussian damping factor in pdf_obs due

to imperfect Q resolution

qbroad – quadratic peak broadening factor related to dataset spdiameter – particle diameter for shape damping function.

Note: this attribute has been moved to FitStructure and is maintained only for backward compatible reading of PDFgui project files.

dscale – total scale factor

calculate()[source]

Do the real calculation.

copy(other=None)[source]

Copy self to other. if other is None, create new instance.

other – reference to other object

returns reference to copied object

getData(dataname, step=None)[source]

Get Calculation data member.

name – data item name step – ignored, just for compatibility with Organizer.getData()

returns data object, be it a single number, a list, or a list of list

getMetaData(name)[source]

Get meta data value.

name – meta data name returns meta data value

getMetaDataNames()[source]

Return all applicable meta data names.

getXNames()[source]

Get names of data item which can be plotted as x.

returns a name str list

getYNames()[source]

Get names of data item which can be plotted as y.

returns a name str list

load(z, subpath)[source]

Load data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

returns a tree of internal hierarchy

save(z, subpath)[source]

Save data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

setRGrid(rmin=None, rstep=None, rmax=None)[source]

Change specified r-grid parameters (rmin, rstep, rmax). Adjust rmax for integer number of steps.

rmin – new low rcalc boundary rstep – new r-grid step rmax – new maximum rcalc, slightly adjusted to accommodate rstep

No return value. Raise ControlValueError for invalid range specification.

start()[source]

Entry function for calculation.

write(filename)[source]

Write this calculated PDF to a file.

filename – name of file to write to

No return value.

writeStr()[source]

String representation of calculated PDF.

Returns data string

diffpy.pdfgui.control.pdfstructure module

class diffpy.pdfgui.control.pdfstructure.PDFStructure(name, *args, **kwargs)[source]

Bases: PDFComponent, PDFFitStructure

PDFStructure contains structure information, which can be used for 3D rendering as well as structure refinement.

copy(other=None)[source]

Copy self to other. if other is None, create an instance.

other – ref to other object

returns reference to copied object

getvar(var)[source]

Obtain value corresponding to PdfFit phase variable var This can be used when guessing Parameter values from constraints dictionary.

var – string representation of PdfFit variable. Possible values:

pscale, spdiameter, stepcut, delta1, delta2, sratio, rcut, lat(n), where n = 1..6, x(i), y(i), z(i), occ(i), u11(i), u22(i), u33(i), u12(i), u13(i), u23(i), where i=1..Natoms

returns value of var

read(filename, format='auto')[source]

Load structure from a file, raise ControlFileError for invalid or unknown structure format.

filename – file to be loaded format – structure format such as ‘pdffit’, ‘pdb’, ‘xyz’. When

‘auto’ all available formats are tried in a row.

Return instance of StructureParser used to load the data. See Structure.read() for more info.

setvar(var, value)[source]

Assign to data member using PdfFit-style variable This can be used when applying constraint equations with particular parameter values.

var – string representation of PdfFit variable. Possible values:

pscale, spdiameter, stepcut, delta1, delta2, sratio, rcut, lat(n), where n=1..6, x(i), y(i), z(i), occ(i), u11(i), u22(i), u33(i), u12(i), u13(i), u23(i), where i=1..Natoms

value – new value of the variable

diffpy.pdfgui.control.fitdataset module

Class FitDataSet for experimental PDF data and related fitting parameters.

class diffpy.pdfgui.control.fitdataset.FitDataSet(name)[source]

Bases: PDFDataSet

FitDataSet stores experimental and calculated PDF data and related fitting parameters. Inherited from PDFDataSet.

Data members (in addition to those in PDFDataSet):

fitrmin – lower boundary for data fitting, property fitrmax – upper boundary for data fitting, property fitrstep – r-step used for fitted data, property constraints – dictionary of { var_string : Constraint_instance } initial – dictionary of initial values of refinable variables refined – dictionary of refined values of refinable variables

Calculated members:

rcalc – list of r points where Gcalc is calculated, cached property Gcalc – list of calculated G values, cached property dGcalc – list of standard deviations of Gcalc, cached property Gtrunc – Gobs resampled to rcalc grid, cached property dGtrunc – dGobs resampled to rcalc grid, cached property Gdiff – difference curve, Gdiff = Gtrunc - Gcalc, property crw – cumulative rw of the fit

The data in rcalc, Gcalc, dGcalc, Gtrunc, dGtrunc are recalculated and cached when r-sampling changes. Any change to fitrmin, fitrmax and fitrstep sets the _rcalc_changed flag.

Refinable variables: qdamp, qbroad, dscale Note: self.refvar is the same as self.initial[refvar].

Class data:

persistentItems – list of attributes saved in project file

property Gcalc

List of calculate G values.

property Gdiff

Difference between observed and calculated PDF on rcalc grid.

property Gtrunc

Gobs resampled to rcalc grid.

applyParameters(parameters)[source]

Evaluate constraint formulas and adjust self.initial.

parameters – dictionary of parameter indices with Parameter instances.

Dictionary may also have float-type values.

changeParameterIndex(oldidx, newidx)[source]

Change a parameter index to a new value.

This will replace all instances of one parameter name with another in this fit.

clear()[source]

Reset all data members to initial empty values.

clearRefined()[source]

Clear all refinement results.

copy(other=None)[source]

Copy self to other. if other is None, create new instance.

other – ref to other object

returns reference to copied object

property crw

cumulative rw on rcalc grid

property dGcalc

List of standard deviations of Gcalc.

property dGtrunc

dGobs resampled to rcalc grid.

findParameters()[source]

Obtain dictionary of parameters used by self.constraints. The keys of returned dictionary are integer parameter indices, and their values Parameter instances, with guessed initial values.

returns dictionary of indices and Parameter instances

property fitrmax

Upper boundary for simulated PDF curve.

property fitrmin

Lower boundary for simulated PDF curve.

property fitrstep

R-step used for simulated PDF curve.

getData(name, step=-1)[source]

Get self’s data member.

name – data item name step – step info, it can be:

  1. a number ( -1 means latest step ): for single step

  2. a list of numbers: for multiple steps

  3. None: for all steps

returns data object, be it a single number, a list, or a list of list

getFitSamplingType()[source]

Description of r-sampling used in the fit. This method compares self.fitrstep with r-sampling in the observed data and with Nyquist r step.

Return a string, possible values are “data”, “Nyquist” or “custom”.

getNyquistSampling()[source]

Return r-step corresponding to Nyquist sampling at the qmax value.

When qmax is zero, return r-step in the observed data.

getObsSampling()[source]

Return the average r-step used in robs or zero when not defined.

getXNames()[source]

Get names of data item which can be plotted as x.

returns list of strings

getYNames()[source]

Get names of data item which can be plotted as y.

returns list of strings

load(z, subpath)[source]

Load data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

obtainRefined(server, idataset)[source]

Upload refined datataset from PdfFit server instance.

server – instance of PdfFit server idataset – index of this dataset in server

persistentItems = ['rcalc', 'Gcalc', 'dGcalc', 'fitrmin', 'fitrmax', 'fitrstep', 'initial', 'refined']
property rcalc

R-grid for refined data, read-only. Use fitrmin, fitrmax, fitrstep to change it

read(filename)[source]

Same as readObs().

readObs(filename)[source]

Load experimental PDF data from PDFGetX2 or PDFGetN gr file.

filename – file to read from

returns self

readObsStr(datastring)[source]

Read experimental PDF data from a string.

datastring – string of raw data

returns self

readStr(datastring)[source]

Same as readObsStr().

save(z, subpath)[source]

Save data to a zipped project file.

z – zipped project file subpath – path to its own storage within project file

setFitSamplingType(tp, value=None)[source]

GUI interface to set fitrstep, i.e., r-grid for fitting.

tp – description of fit sampling type. Possible values are

“data” … same as used in experimental PDF “Nyquist” … sampling at Nyquist spacing “custom” … user specified value

value – new value of fitrstep, only used when tp is “custom”.

No return value.

Raises ValueError for unknown tp string.

write(filename)[source]

Same as writeCalc(). Use writeObs() to save experimental PDF data.

filename – name of file to write to

No return value.

writeCalc(filename)[source]

Write calculated PDF data to a file.

filename – name of file to write to

No return value.

writeCalcStr()[source]

String representation of calculated PDF data.

Return data string.

writeObs(filename)[source]

Write observed PDF data to a file.

filename – name of file to write to

No return value.

writeObsStr()[source]

String representation of observed PDF data.

Return data string.

writeResampledObs(filename)[source]

Write resampled PDF data in Gtrunc to a file.

filename – name of the file to write to

No return value.

writeResampledObsStr()[source]

String representation of resampled PDF data in Gtrunc.

Return data string.

writeStr()[source]

Same as writeCalcStr. Use writeObsStr() for experimental PDF.

Return data string.

diffpy.pdfgui.control.fitdataset.grid_interpolation(x0, y0, x1, left=None, right=None, tp=None)[source]

Interpolate values from one grid onto another using either linear or Whittaker–Shannon interpolation.

Parameters:
  • x0 (array_like) – Original x-grid, must be equally spaced.

  • y0 (array_like) – Original values defined on x0.

  • x1 (array_like) – New x-grid upon which to interpolate.

  • tp ({'data', 'Nyquist', 'custom'}, optional) – Corresponding fit sampling type. Use Whittaker–Shannon interpolation for Nyquist resampling and linear interpolation otherwise. If not provided, linear interpolation is used.

  • left (float, optional) – Value for interpolated y1 for x1 below the x0 range. Default: if tp=’Nyquist’ then y1[0] is used. Otherwise 0.0 is used.

  • right (float, optional) – Value for interpolated y1 for x1 above the x0 range. Default: if tp=’Nyquist’ then y1[-1] is used. Otherwise 0.0 is used.

Returns:

Array of interpolated values on the new grid x1.

Return type:

numpy.ndarray

Notes

When tp=’Nyquist’, the function calls wsinterp() to perform Whittaker–Shannon interpolation. Otherwise it uses the internal _linear_interpolation() routine.

diffpy.pdfgui.control.structureviewer module

Structure plotting in an external viewer process.

class diffpy.pdfgui.control.structureviewer.StructureViewer(executable=None, argstr=None, fileformat=None)[source]

Bases: object

Class for plotting structure in general structure viewer. It takes care of creating temporary structure file in a desired format and launching structure viewer as a background process. The temporary files are removed when StructureViewer instance goes out of scope.

Data attributes:

executable – full path to the structure viewer executable or an executable

that can be found in system PATH. By default ‘’ (not set).

argstr – argument string for the viewer program, it can use shell

quoting. Instances of ‘%s’ in the string are replaced with temporary structure file. By default ‘%s’

fileformat – structure format that can be loaded by the viewer.

Must be one of output formats supported by diffpy.structure package. By default ‘pdb’.

_tmpdir – Temporary directory for structure files opened by the viewer.

tmpdir is None before the first call to plot. The directory and everything inside is removed when StructureViewer goes out of the scope.

_plotcount – Number of plots created by this viewer.

getConfig()[source]

Return current configuration of StructureViewer instance.

Returns new dictionary with the following keys: (‘executable’, ‘argstr’, ‘fileformat’)

static getFileFormats()[source]

Return list of valid values for the fileformat attribute.

plot(stru)[source]

Launch new structure viewer and open a temporary copy of stru.

stru – instance of Structure class from diffpy.structure

No return value. Raise ControlConfigError if structure viewer could not be launched.

setConfig(cfg)[source]

Configure StructureViewer instance using values in a dictionary.

cfg – configuration dictionary, with the same keys as returned

by getConfig(). Any other keys are ignored.

No return value.

diffpy.pdfgui.control.structureviewer.getStructureViewer()[source]

Factory returning singleton instance of the StructureViewer class.

diffpy.pdfgui.control.plotter module

class diffpy.pdfgui.control.plotter.Plotter(name=None)[source]

Bases: PDFComponent

Plots a single graph.

It can have multiple curves.

class Curve(name, plotwnd, xStr, yStr, steps, ids, offset, style)[source]

Bases: object

Curve stores the information for a curve in the plot.

There are three ways of forming x and y data lists. (1) r and g(r) from a single refinement are vectors by themselves (2) A scalar data item (any item other than r and g(r)) can form a vector if multiple timeSteps (refinement steps) are specified. (3) A scalar data item (any item other than r and g(r)) can form a vector if multiple refinement (multiple ids) are specified

name – The curve name plotwnd – The window where the curve is drawn xStr – Data name (string) for x axis yStr – Data name (string) for y axis steps – refinement step list ids – The list of object ids that the curve is related to offset – curve displacement in y direction style –The drawing style of the curve xData, yData – data to be plotted x, y – original data for exporting (curve could be shifted) bMultiData – if the curve data comes from multiple data objects bMultiStep – if the curve data comes from multiple refinement step ref – reference of curve in the plot window initialized – if curve has been inserted dataChanged – if curve data has changed

draw()[source]

Draw the curve in the graph.

It will make sure the data is OK, and plot to the screen.

notify(changedIds=None, plotwnd=None)[source]

Notify Curve object certain data is updated.

changedIds – objects to which changed data is associated with

validate()[source]

Validate(self) –> check if the curve is valid.

Validity is broken: (1) when xStr or yStr doesn’t refer to a legal vector (2) when sizes of xStr and yStr don’t match

buildLineStyle(index=-1)[source]

Generate a line style.

index – plotting style index

buildLineSymbolStyle(index=-1)[source]

Generate a linesymbol style.

index – plotting style index

buildSymbolStyle(index=-1)[source]

Generate a symbol style.

index – plotting style index

close(force=True)[source]

Close up the plot.

force – if True, close forcibly

export(filename)[source]

Export current data to external file.

filename – the name of the file to save data

notify(data)[source]

Change of the data is notified.

data – data object that has changed

onWindowClose()[source]

Get called when self.window is closed by user.

plot(xName, yNames, ids, shift, dry)[source]

Make a 2D plot.

xName – x data item name yNames – list of y data item names ids – Objects where y data items are taken from shift – y spacing for different ids dry – dry run

show(bShow=None)[source]

Show the plot on screen.

bShow – True to show, False to Hide. None to toggle return value: current status of window

diffpy.pdfgui.control.plotter.deblank(s)[source]

Remove all whitespace from the given string.

diffpy.pdfgui.control.fitstructure module

Class FitStructure for storage of one phase and related fitting parameters.

class diffpy.pdfgui.control.fitstructure.FitStructure(name, *args, **kwargs)[source]

Bases: PDFStructure

FitStructure holds initial and refined structure and related fit parameters. Inherited from PDFStructure.

Class data members:

symposeps – tolerance for recognizing site as symmetry position

Data members (in addition to those in PDFStructure):

owner – instance of parent Fitting (set in Organizer.add()) initial – initial structure, same as self refined – refined structure when available or None constraints – dictionary of { refvar_string : Constraint_instance } selected_pairs – string of selected pairs, by default “all-all”.

Use setSelectedPairs() and getSelectedPairs() methods to access its value.

custom_spacegroup – instance of SpaceGroup which has no equivalent

in diffpy.structure.spacegroups module. This can happen after reading from a CIF file. When equivalent space group exists, custom_spacegroup is None.

Refinable variables: pscale, spdiameter, delta1, delta2, sratio, lat(n),

where n=1..6, x(i), y(i), z(i), occ(i), u11(i), u22(i), u33(i), u12(i), u13(i), u23(i), where i=1..Natoms

Non-refinable variable: rcut, stepcut

applyPairSelection(server, phaseidx)[source]

Apply pair selection for calculations of partial PDF.

server – instance of PdfFit engine phaseidx – phase index in PdfFit engine starting from 1

applyParameters(parameters)[source]

Evaluate constraint formulas and adjust initial PDFStructure.

parameters – dictionary of parameter indices with Parameter

instance values. Values may also be float type.

applySymmetryConstraints(spacegroup, indices, posflag, Uijflag, sgoffset=[0, 0, 0])[source]

Generate symmetry constraints for positions and thermal factors. Both positions and thermal factors may get corrected to reflect space group symmetry. Old positional and thermal constraints get erased. New parameter indices start at fist decade after the last used parameter.

spacegroup – instance of SpaceGroup from diffpy.structure indices – list of integer indices of atoms to be expanded posflag – required bool flag for constraining positions Uijflag – required bool flag for Uij constrainment sgoffset – optional offset of space group origin [0,0,0]

changeParameterIndex(oldidx, newidx)[source]

Change a parameter index to a new value.

This will replace all instances of one parameter name with another in this fit.

clearRefined()[source]

Clear all refinement results.

copy(other=None)[source]

Copy self to other. if other is None, create new instance.

other – reference to other object

returns reference to copied object

deleteAtoms(indices)[source]

Removed atoms at given indices and adjust self.constraints.

indices – list of integer indices of atoms to be deleted

expandAsymmetricUnit(spacegroup, indices, sgoffset=[0, 0, 0])[source]

Perform symmetry expansion for atoms at given indices. Temperature factors may be corrected to reflect the symmetry. All constraints for expanded atoms are erased with the exception of the occupancy(“occ”. Constraints of unaffected atoms are adjusted for new positions self.initial.

spacegroup – instance of SpaceGroup from diffpy.structure indices – list of integer indices of atoms to be expanded sgoffset – optional offset of space group origin [0,0,0]

expandSuperCell(mno)[source]

Perform supercell expansion for this structure and adjust constraints for positions and lattice parameters. New lattice parameters are multiplied and fractional coordinates divided by corresponding multiplier. New atoms are grouped with their source in the original cell.

mno – tuple or list of three positive integer cell multipliers along the a, b, c axis

findParameters()[source]

Obtain dictionary of parameters used by self.constraints. The keys of returned dictionary are integer parameter indices, and the values are Parameter instances, with guessed initial values.

returns dictionary of indices and Parameter instances

getData(name, step=-1)[source]

Get self’s data member.

name – data item name step – step info, it can be:

  1. a number ( -1 means latest step ): for single step

  2. a list of numbers: for multiple steps

  3. None: for all steps

returns data object, be it a single number, a list, or a list of list

getPairSelectionFlags(s=None)[source]

Translate string s to a list of allowed values for first and second pair index. Raise ControlValueError for invalid syntax of s. See setSelectedPairs() docstring for a definition of pair selection syntax.

s – string describing selected pairs (default: self.selected_pairs)

Return a dictionary with following keys:

firstflags – list of selection flags for first indices secondflags – list of selection flags for second indices fixed_pair_string – argument corrected to standard syntax

getSelectedIndices(s)[source]

Indices of the atoms that match the specified selection string.

s – selection string consisting of one or more atom selection

words formatted as [!]{element|indexOrRange|all} Example: “1:4, 7, Cl”.

Return a list of integers. Raise ControlValueError for invalid selection string format.

getSelectedPairs()[source]
getSpaceGroup(sgname)[source]

Find space group in getSpaceGroupList() by short_name or number. sgname can be non-standard in case of CIF file defined space group.

Return instance of SpaceGroup. Raise ValueError if sgname cannot be found or when it is not present in getSpaceGroupList().

getSpaceGroupList()[source]

Return a list of SpaceGroup instances sorted by International Tables number.

When custom_spacegroup is defined, the list starts with custom_spacegroup.

getXNames()[source]

Get names of data item which can be plotted as x.

returns a name str list

getYNames()[source]

Get names of data item which can be plotted as y.

returns a name str list

insertAtoms(index, atomlist)[source]

Insert list of atoms before index and adjust self.constraints.

index – position in the initial structure, atoms are appended

when larger than len(self.initial).

atomlist – list of atom instances.

isSpaceGroupPossible(spacegroup)[source]

Check if space group is consistent with lattice parameters.

spacegroup – instance of SpaceGroup

Return bool.

load(z, subpath)[source]

Load structure from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

obtainRefined(server, iphase)[source]

Upload refined phase from PdfFit server instance.

server – instance of PdfFit server iphase – index of this phase in server

read(filename, format='auto')[source]

Load structure from a file, raise ControlFileError for invalid or unknown structure format. Overloads PDFStructure.read() to handle custom_spacegroup attribute.

filename – file to be loaded format – structure format such as ‘pdffit’, ‘pdb’, ‘xyz’. When

‘auto’ all available formats are tried in a row.

Return instance of StructureParser used to load the data. See Structure.read() for more info.

readStr(s, format='auto')[source]

Same as PDFStructure.readStr, but handle the custom_spacegroup data.

Return instance of StructureParser used to load the data. See Structure.readStr() for more info.

save(z, subpath)[source]

Save structure to a zipped project file.

z – zipped project file subpath – path to its own storage within project file

setSelectedPairs(s)[source]

Set the value of selected_pairs to s, raise ControlValueError when s has invalid syntax. The selected_pairs is a comma separated list of words formatted as.

[!]{element|indexOrRange|all}-[!]{element|indexOrRange|all}

where ‘!’ excludes the given atoms from first or second pair.

Examples

all-all all possible pairs Na-Na only Na-Na pairs all-all, !Na- all pairs except Na-Na (first index skips Na) all-all, -!Na same as previous (second index skips Na) Na-1:4 pairs of Na and first 4 atoms all-all, !Cl-!Cl exclude any pairs containing Cl all-all, !Cl-, -!Cl same as previous 1-all only pairs including the first atom

Use getPairSelectionFlags() method to get a list of included values for first and second pair index.

sorted_standard_space_groups = []
symposeps = 0.001

diffpy.pdfgui.control.fitting module

class diffpy.pdfgui.control.fitting.Fitting(name)[source]

Bases: Organizer

Fitting is the class to control a PdfFit process running locally. Fitting will start a new thread to interact with the PdfFit server.

rw: fitness parameter tolerancy: accuracy requirement step: current refinement step res: fitting result string parameters: parameter dictionary

CONFIGURED = 4
CONNECTED = 2
DONE = 8
INITIALIZED = 1
PAUSED = 2048
QUEUED = 512
RUNNING = 1024
VOID = 256
class Worker(fitting)[source]

Bases: Thread

Worker is the daemon thread of fitting.

run()[source]

Overload function from Thread.

appendStep(source)[source]

After a refinement step is done, append all data from self to the historical storage, i.e., self.snapshots.

source – where to get the fitted data, in deed it’s a PdfFit2 instance

applyParameters()[source]

Evaluate all constrained variables using current parameters.

buildNameDict()[source]

Build up a data name dictionary, which will map data name to a unique index.

The private dataNameDict has such structure: { ‘d_data1’:{‘Gobs’:12, ‘Gcalc’:11, ….},

‘d_data2’:{‘Gobs’:10, ‘Gcalc’:9, ….}, … ‘p_ph1’:{‘lat(1)’:1,’lat(2)’:2, …..}, ‘p_ph1’:{‘lat(1)’:3,’lat(2)’:4, …..}, … ‘f_fit’:{‘rw’:100, 1:101, 2:102}

}

The value of each sub-dict is the corresponding index of this data item in the snapshot. The prefix d_ p_ f_ make dataset,struc,fitname unique within the shared name space of dictionary

changeParameterIndex(oldidx, newidx)[source]

Change a parameter index to a new value.

This will replace all instances of one parameter name with another in the containing fit.

close(force=False)[source]

Close up the fitting in order to exit.

force – if force to exit

configure()[source]

Configure fitting.

copy(other=None)[source]

Copy self to other. if other is None, create an instance.

other – ref to other object return value: reference to copied object

getData(name, step=-1)[source]

Get self’s data member.

name – data item name step – step info, it can be:

  1. a number ( -1 means latest step ): for single step

  2. a list of numbers: for multiple steps

  3. None: for all steps

returns data object, be it a single number, a list, or a list of list

getMetaData(name)[source]

Get meta data value.

name – meta data name returns meta data value

getMetaDataNames()[source]

Return all applicable meta data names.

getServer()[source]

Get a PDFfit2 instance either locally or remotely.

getXNames()[source]

Get names of data item which can be plotted as x.

returns a name str list

getYNames()[source]

Get names of data item which can be plotted as y.

returns a name str list

isThreadRunning()[source]

Check if fitting thread is running.

return: True if running, False otherwise

join()[source]

Wait for current fitting to finish.

load(z, subpath)[source]

Load data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

returns a tree of internal hierarchy

outputBondAngle(struc, i, j, k)[source]

Output bond angle defined by atoms i, j, k. The angle is calculated using the shortest lengths ji and jk with respect to periodic boundary conditions.

struc – instance of PDFStructure i, j, k – atom indices starting at 1

No return value. The result should be automatically added to the Output Window, because all server output is sent there.

Raise ControlValueError for invalid indices i, j, k.

outputBondLengthAtoms(struc, i, j)[source]

Output shortest bond between atoms i, j. Periodic boundary conditions are applied to find the shortest bond.

struc – instance of PDFStructure i, j – atom indices starting at 1

No return value. The result should be automatically added to the Output Window, because all server output is sent there.

Raise ControlValueError for invalid indices i, j.

outputBondLengthTypes(struc, a1, a2, lb, ub)[source]

Output all a1-a2 bond lengths within specified range.

struc – instance of PDFStructure a1 – symbol of the first element in pair or “ALL” a2 – symbol of the second element in pair or “ALL” lb – lower bond length boundary ub – upper bond length boundary

No return value. The result should be automatically added to the Output Window, because all server output is sent there.

Raise ControlValueError for invalid element symbols.

pause(bPause=None)[source]

Pause ( self, bPause = None ) –> pause a fitting process.

bPause – True to pause, False to restart. If None, it will figure out

by itself.

queue(enter=True)[source]

Queue or dequeue self.

enter – True to queue, False to dequeue

refine_step()[source]

Run a single step of the fit.

return value: True if refinement is finished, otherwise False

resetStatus()[source]

Reset status back to initialized.

run()[source]

Function to be run in daemon thread.

save(z, subpath)[source]

Save data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

start()[source]

Start fitting.

stop()[source]

Stop the fitting.

stripped()[source]

Make a copy stripped of all unpickleable data members. The copy should be suitable for pickling and has the following data members removed:

controlCenter, lock, pauseEvent, thread

returns reference to stripped copy

updateParameters()[source]

Update parameters dictionary from active constraints.

returns self.parameters

diffpy.pdfgui.control.fitting.getEngineExceptions()[source]

Return a tuple of possible exceptions from diffpy.pdffit2.pdffit2.

diffpy.pdfgui.control.fitting.handleEngineException(error, gui=None)[source]

Common handler of PDFfit2 engine exceptions.

error – instance of PDFfit2 exception gui – reference to GUI when active

diffpy.pdfgui.control.pdfguicontrol module

class diffpy.pdfgui.control.pdfguicontrol.CtrlUnpickler[source]

Bases: object

Occasionally the project file may be generated on a platform where PYTHONPATH is not correctly set up.

CtrlUnpickler will transform the module path in the project file to be relative to diffpy so that it can be safely loaded. Only constraints and parameters need this class to un- pickle.

static loads(s)[source]
class diffpy.pdfgui.control.pdfguicontrol.PDFGuiControl(gui=None)[source]

Bases: object

PDFGuiControl holds all the data GUI needs to access or change It has a container of Calculation and Fitting instances.

Each Calculation and Fitting has a unique name.

class QueueManager(control)[source]

Bases: Thread

run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

add(ID, position=None)[source]

Add fitting/calculation to internal list.

Id – reference to the object to be inserted position – where the object is to be inserted, default is last

checkQueue()[source]

Find next fitting in the queue and start it.

close(force=True)[source]

Close a project.

force – if exit forciably

copy(src)[source]

Copy src object.

src – reference to the source object return: reference to the copy

enqueue(fits, enter=True)[source]

Enqueue or dequeue fittings.

fits – list of fittings to be queued/dequeued enter – True to queue, False to dequeue

exit()[source]

Exit when program finished.

getEngineOutput()[source]

Get the output from the engine.

index(ID)[source]

Return position index of an object in its owner list.

ID – ID of object return: index

load(projfile)[source]

Load project from projfile.

projfile – a zip file of everything

loadDataset(targetID, filename, name=None, position=None)[source]

Load Dataset from a file to a Fitting.

targetID – reference to Fitting name – name of the new Dataset, default is file basename position – where the dataset is to be inserted, default is last

return: Dataset reference

loadStructure(targetID, filename, name=None, position=None)[source]

Add blank structure to a Fitting.

targetID – reference to Fitting name – name of the new Structure, default is file basename

return: Structure reference

newCalculation(targetID, name, position=None)[source]

Insert a new instance of Calculation to a Fitting.

targetID – reference to Fitting name – unique name for this Calculation position – where Calculation is inserted, default is last place

return: Calculation reference

newFitting(name, position=None)[source]

Insert a new instance of Fitting.

name – unique name for this Fitting position – where Fitting is inserted, default is last place

return: Fitting reference

newStructure(targetID, name, position=None)[source]

Add blank structure to a Fitting.

targetID – reference to Fitting name – name of the new Structure position – where the structure is to be inserted, default is last

return: Structure reference

paste(dup, target=None, new_name=None, position=None)[source]

Paste copied object to target under new_name, the default new_name will be name of src.

dup – reference to the copied object target – target object where the copy should be inserted new_name – new name to be given to the copy position – where in the target object should the copy be inserted

return: reference to the pasted object

plot(xItem, yItems, Ids, shift=1.0, dry=False)[source]

Make a 2D plot.

xItem – x data item name yItems – list of y data item names Ids – Objects where y data items are taken from shift – y displacement for each curve dry – not a real plot, only check if plot is valid

redirectStdout()[source]

Redirect standard out.

This redirect engine output to StringIO if not done yet.

remove(ID)[source]

Remove Fitting, Calculation, Dataset or Structure identified by ID.

ID: reference to the object to be removed return: removed object

rename(ID, new_name)[source]

Rename Fitting, Calculation, Dataset or Structure identified by ID.

ID: reference to the object to be renamed new_name: new name to be given to the object

reset()[source]

Clean up for a new project.

save(projfile=None)[source]

Save project to projfile, default projfile is self.projfile.

This method first writes to a temporary file and only when successful, it overwrites projfile with the temporary file content. These steps prevent corruption of existing projects should something go wrong in the middle of save. As an added benefit, all permissions and ownership flags in an existing projfile are preserved.

start(IDlist)[source]

Execute Calculations and Fittings in IDlist.

startQueue()[source]

Start queue manager.

stop()[source]

Stop all Fittings.

diffpy.pdfgui.control.pdfguicontrol.pdfguicontrol(*args, **kwargs)[source]

This function will return the single instance of class PDFGuiControl.

diffpy.pdfgui.control.parameter module

Class Parameter for handling one refined parameter To be stored in Fitting.parameters { idx : parameter } dictionary.

class diffpy.pdfgui.control.parameter.Parameter(idx, initial=0.0)[source]

Bases: object

Parameter is class for value and properties of refined parameter. Because the initial value of Parameter may come from another Fitting, it is accessed by setInitial(), initialStr() and initialValue() methods.

Data members:

idx – integer identifier of this parameter in PdfFit name – optional description refined – refined value of the parameter, float or None. fixed – flag for fixing the parameter in refinement [False]

Private members:

__initial – stores the initial value, float, or “=fitname:idx” string __fitrepr – None or string representation of Fitting instance

initialStr()[source]

Convert initial value to string.

returns string in “=fitname:idx” or “%f” format

initialValue()[source]

Convert initial value to float. For linked parameters it may raise:

ControlKeyError if source Fitting does not exist KeyError when parameter does not exist ControlRunTimeError for self-dependent parameters

returns the initial value

setInitial(initial)[source]

Set initial value to float or refined value from another Fitting.

initial – initial value, it can be something convertible to float,

Fitting reference or string in “=fitname” or “=fitname:idx” format.

diffpy.pdfgui.control.pdfdataset module

Class PDFDataSet for experimental PDF data.

exception diffpy.pdfgui.control.pdfdataset.PDFDataFormatError[source]

Bases: Exception

Exception class marking failure to process PDF data string.

class diffpy.pdfgui.control.pdfdataset.PDFDataSet(name)[source]

Bases: PDFComponent

PDFDataSet is a class for experimental PDF data.

Data members:

robs – list of observed r points Gobs – list of observed G values drobs – list of standard deviations of robs dGobs – list of standard deviations of Gobs stype – scattering type, ‘X’ or ‘N’ qmax – maximum value of Q in inverse Angstroms. Termination

ripples are neglected for qmax=0.

qdamp – specifies width of Gaussian damping factor in pdf_obs due

to imperfect Q resolution

qbroad – quadratic peak broadening factor related to dataset spdiameter – particle diameter for shape damping function

Note: This attribute was moved to PDFStructure. It is kept for backward compatibility when reading PDFgui project files.

dscale – scale factor of this dataset rmin – same as robs[0] rmax – same as robs[-1] filename – set to absolute path after reading from file metadata – dictionary for other experimental conditions, such as

temperature or doping

Global member:

persistentItems – list of attributes saved in project file refinableVars – set (dict) of refinable variable names.

clear()[source]

Reset all data members to initial empty values.

copy(other=None)[source]

Copy self to other. if other is None, create new instance.

other – ref to other object returns reference to copied object

getvar(var)[source]

Obtain value corresponding to PdfFit dataset variable. Used by findParameters().

var – string representation of dataset PdfFit variable.

Possible values: qdamp, qbroad, dscale

returns value of var

persistentItems = ['robs', 'Gobs', 'drobs', 'dGobs', 'stype', 'qmax', 'qdamp', 'qbroad', 'dscale', 'rmin', 'rmax', 'metadata']
read(filename)[source]

Load data from PDFGetX2 or PDFGetN gr file.

filename – file to read from

returns self

readStr(datastring)[source]

Read experimental PDF data from a string.

datastring – string of raw data

returns self

refinableVars = {'dscale': None, 'qbroad': None, 'qdamp': None}
setvar(var, value)[source]

Assign data member using PdfFit-style variable. Used by applyParameters().

var – string representation of dataset PdfFit variable.

Possible values: qdamp, qbroad, dscale

value – new value of the variable

write(filename)[source]

Write experimental PDF data to a file.

filename – name of file to write to

No return value.

writeStr()[source]

String representation of experimental PDF data.

Return data string.

diffpy.pdfgui.control.organizer module

class diffpy.pdfgui.control.organizer.Organizer(name)[source]

Bases: PDFComponent

Base class for Fitting. It holds separate lists of datasets, strucs and calculations.

datasets: dataset list strucs: structure list calcs: calculation list

add(id, position=None)[source]

Add structure/dataset/calculation.

id – reference to structure/dataset/calculation position – position to insert, by default the last one

copy(other=None)[source]

Copy self to other. if other is None, create an instance.

other – ref to other object returns reference to copied object

getCalculation(pos)[source]

Get calculation by position.

pos – the position of calculation in the list

getDataSet(pos)[source]

Get dataset by position.

pos – the position of dataset in the list

getStructure(pos)[source]

Get structure by position.

pos – the position of structure in the list

hasCalculations()[source]

Check to see if there are calculations.

hasDataSets()[source]

Check to see if there are datasets.

hasStructures()[source]

Check to see if there are structures.

index(id)[source]

Find the position of item in the list.

id – id of object return : object position

load(z, subpath)[source]

Load data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

returns a tree of internal hierarchy

organization()[source]

Get internal organization.

returns a tree of internal hierarchy

remove(id)[source]

Remove structure/dataset/calculation.

id – reference to structure/dataset/calculation

rename(id, newname)[source]

Rename structure/dataset/calculation.

id – reference to structure/dataset/calculation newname – new name to be given

save(z, subpath)[source]

Save data from a zipped project file.

z – zipped project file subpath – path to its own storage within project file

diffpy.pdfgui.control.organizer.spd_assigned(ds)[source]
diffpy.pdfgui.control.organizer.spd_constrained(ds)[source]