Welcome to McSAS’s documentation!

McSAS Quick Usage guide

Introduction

This guide is intended as an aid to getting the first fits using McSAS.

For comprehensive details of what goes on under the hood, please refer as a baseline to the available publications. Additionally, the code is open source, and provides the best “documentation” of what actually takes place.

When publishing results using this code, the user is requested to cite either or both of the following works:

Bressler, I, Pauw, B. R, and Thuenemann, A., submitted to J. Appl. Cryst.,
arXiv:1412.1900
Pauw, B. R., Pedersen, J. S., Tardif, S., Takata, M. and Iversen, B. B.,
  1. Appl. Cryst. 46 (2013), 365—371.

Scope of the code capabilities

The McSAS code at the moment can:

  1. Fit supplied data to a variety of models, with absolute unit support.
  2. Graphically show the distributions of selected parameters and associated parameter ranges.
  3. Graphical output includes distribution population modes with uncertainties.
  4. Output the fit, data, settings, and distributions for further processing.
  5. Can be used with or without user interface, using command-line arguments.

-1. Starting McSAS

McSAS can be used on both Linux / Unix systems (including MacOS X) as well as personal computers running Windows.

On Unix- and Unix-like computers, McSAS can be started from any terminal by typing:
$ /path/to/mcsas/main.py

On Windows, the compiled executable can be double-clicked to start.

0. Loading test data

A demonstration dataset has been simulated using SASFit, and output in a three-column file: “testdata/quickstartdemo1.csv”.

The dataset can be loaded by right-clicking in the empty list in the “Data Files”-tab. When loaded, the list shows some information of the data: its length, content, q-limits, and scatterer radius limits calculated using the Q limits (theoretically, the spacing between Q-points also dictates the size limits, but the tendency of users to use much too narrowly-spaced Q-points would result in unworkable estimates).

Lastly, the “log”-window shows how many datapoints had an uncertainty estimate below 1% of the intensity. These datapoint uncertainty values have been adjusted to 1%, as that is a practically demonstrated limit of SAS data accuracy.

1. Configuring the algorithm

The algorithm uses several internal parameters. Some of these can be adjusted in the “Algorithm”-tab of the user interface. They are:

  1. The convergence criterion. If the uncertainty estimates provided with the data are not accurate, or if the fitting model chosen is unsuitable or incompletely descriptive, the algorithm may not arrive at a final solution (a convergence criterion of 1 or below).
  2. Number of repetitions from which uncertainties are determined. Set to 10 for the quick start.
  3. Number of contributions. This can be adjusted to minimise the optimization time. The average optimisation time can be found in the “Timing” line on the graphical output.
  4. Background (checkbox). When set, it will add a flat background contribution to the fit

If necessary, the other internal algorithm parameters can be changed through careful editing of the “mcsasparameters.json” parameter dictionary. This should not be needed for common use.

2. Configuring the Model

For the quick start, the model selected should be the “Sphere” model. After selecting this model, verify that the sphere radius is “Active”, then move back to the “Data files”-tab, and double-click the “quickstartdemo1”-line to copy the sphere size estimates to the model.

3. Configuring the Post-fit Analysis

Select the already filled lines in the “Post-fit Analysis”-tab, and select “remove” from the right-click menu. Then add a new entry to the list by selecting “add range” from the right-click menu. In the emerging window, change the histogram X-axis scaling from “lin” to “log” and click “add”.

The settings are now complete.

4. Running the fit

Click the “start”-button. Optimisation takes 36 seconds on a 3.4 GHz intel i7 iMac (2012 model).

5. The result

The result window should pop up automatically and resemble the plot shown in quickstartdemo1.pdf

_images/quickstartdemo1.png

The left-hand plot shows the data in black with error bars, the MC fit in red, and a green line indicating the fitted background level (not shown as it approaches zero). The background value is furthermore indicated in the legend.

The right-hand plot shows the resulting volume-weighted size histogram, with uncertainties on the bars, and the red dashed line indicating the minimum level required for each bin to contribute a measurable amount to the scattering pattern (i.e. more than the uncertainty).

As is clear from the vertical axis on that plot, the partial volume fractions are unrealistic if the scattering contrast has not been set. One may also want to rebin the plot in fewer bins to reduce the relative uncertainties on the bins.

5. Getting peak parameters

Above the size distribution, the population statistics can be found suhc as the mean, the variance, skew and kurtosis (each with their own uncertainty estimates). These are valid for the entire range, and are calculated from the individual contributions (not from the histogram). If we want to find the values for the individual populations, we need to set the correct ranges in the Post-fit Analysis list:

  1. 3.14 - 20, (binning e.g. 20 bins, linearly spaced, volume-weighted)
  2. 20 - 75, (binning for example as above)
  3. 75 - 150, (ibid.)

And then pressing “start” again. (This restarts the fitting procedure. A “Re-analyze”-option is in the works but was not finished at the time of writing)

This should give the following figure (as shown in quickstartdemo1a.pdf):

_images/quickstartdemo1a.png

The mean of each population is slightly shifted upward as compared to the simulation parameters (given in paragraph 8). Note, however, that the simulation parameters define the numeric mean, whereas the ones shown in the histogram are the volumetric mean. Therefore, the latter are shifted up.

6. Further results

In the directory that the “quickstartdemo1.csv”-file was located, you will find several more files after a successful fit. These are the automatically saved results. They all contain a timestamp on when the fit was performed. Files with an asterisk are only present if the fit was successful. They are:

  1. quickstartdemo1_[timestamp].pdf*: the autosaved plot
  2. quickstartdemo1_[timestamp]_log.txt: the fitting log window.
  3. quickstartdemo1_[timestamp]_contributions.pickle*: A pickled list of raw contributions.
  4. quickstartdemo1_[timestamp]_hist[parameter].csv*: The histogram information of every range.
  5. quickstartdemo1_[timestamp]_stats[parameter].csv*: The statistics information of every range
  6. quickstartdemo1_[timestamp]_settings.cfg: The settings used in the fit.

7. What’s next?

If you have the ability and interest in improving the code, please consider joining the development effort, which will work on including more shapes and adding slit-smearing options.

If you have more questions that are not answered in either 1) the paper, 2) the code, and 3) this document, feel free to send me an e-mail which you can find on the papers or http://mcsas.net/.

Good luck!

8. SASFit test data settings:

SASfit version 0.94.5, precompiled Mac OS X version. quickstartdemo1.csv:

  1. Spheres, gaussian dist, N = 0.00105, S = 10, X0 = 100, eta = 1.
  2. Spheres, gaussian dist, N = 0.0135, S = 10, X0 = 40, eta = 1.
  3. Spheres, gaussian dist, N = 0.4, S = 3, X0 = 8, eta = 1.

The Math Behind

SAXS

In models.sphere the form factor is defined as:

\[\begin{split}\def\v#1{{\bf #1}} ff_{sph}(q, r) &= { 3 ~ sin(qr) - qr ~ cos(qr) \over (qr)^3 } \\ v_{sph}(r) &= {\tiny {4 \over 3}} ~ \pi ~ r^3 \\ v_{sph,abs}(r, \Delta\rho) &= \Delta\rho^2 ~ v_{sph}(r)\end{split}\]
Where q is
the scattering vector loaded from the data file and possibly preprocessed, respectively filtered by defining min/max q or masking invalid values equal or below zero.
r denotes
the radius of the sphere set in the user interface (UI) or varied during optimization.
\(\Delta\rho\) denotes
the scattering length density difference constant of the model against the solution which is defined in the UI.
Sphere.formfactor(dataset)[source]

Calculates the form factor of a sphere defined by:

\(F(q, r) = { 3 ~ sin(qr) - qr \cdot cos(qr) \over (qr)^3 }\)

Sphere.volume()[source]

Calculates the volume of a sphere defined by:

\(v(r) = {4\pi \over 3} r^3\)

Sphere.absVolume()[source]

Calculates the volume of a sphere taking the scattering length density difference \(\Delta\rho\) into account:

\(v_{abs}(r, \Delta\rho) = v_{sph}(r) \cdot \Delta\rho^2\)

SASModel.weight()[source]

Calculates an intensity weighting used during fitting. It is based on the scatterers volume. It can be modified by a user-defined compensation exponent c. The default value is \(c={2 \over 3}\)

\(w(r) = v(r)^{2c}\)

SASModel.calcIntensity(data, compensationExponent=None)[source]

Returns the intensity I, the volume \(v_{abs}\) and the intensity weights w for a single parameter contribution over all q:

\(I(q,r) = F^2(q,r) \cdot w(r)\)

Source Code Documentation

Contents:

mcsas.mcsas package

Submodules

mcsas.mcsas.backgroundscalingfit module
class BackgroundScalingFit(findBackground, *args)[source]

Bases: object

Chi-squared convergence calculation happens here. Optimizes the scaling and background factor to match intCalc closest to intObs. Returns an array with scaling factors. Input initial guess sc has to be a two-element array with the scaling and background.

Input arguments:

Parameters:
  • intObs – An array of measured, respectively observed intensities
  • intCalc – An array of intensities which should be scaled to match intObs
  • intError – An array of uncertainties to match intObs
  • sc – A 2-element array of initial guesses for scaling factor and background
  • ver(optional) Can be set to 1 for old version, more robust but slow, default 2 for new version, 10x faster than version 1, requires decent starting values
  • outputIntensity(optional) Return the scaled intensity as third output argument, default: False
  • background(optional) Enables a flat background contribution, default: True
Returns:

(sc, conval): A tuple of an array containing the intensity scaling factor and background and the reduced chi-squared value.

static aGoFsAlpha(dataMeas, dataErr, dataCalc)[source]

The alternative Goodness-of-Fit value without alpha, i.e. multiplied by alpha, according to [Henn 2016] ( http://dx.doi.org/10.1107/S2053273316013206 ).

calc(data, modelData, sc, ver=2)[source]

Warning

method ‘mcsas.backgroundscalingfit.BackgroundScalingFit.calc’ undocumented

static chi(sc, dataMeas, dataErr, dataCalc)[source]

Chi calculation, difference of measured and calculated signal.

static chiNoBg(sc, dataMeas, dataErr, dataCalc)[source]

Chi calculation, difference of measured and calculated signal, scaling only, no backgrund.

static chiSqr(dataMeas, dataErr, dataCalc)[source]

Reduced Chi-squared calculation, size of parameter-space not taken into account; for data with known intError.

dataScaled(data, sc)[source]

Returns the input data scaled by the provided factor and background level applied if requested.

fitLM(dataMeas, dataErr, dataCalc, sc)[source]

Warning

method ‘mcsas.backgroundscalingfit.BackgroundScalingFit.fitLM’ undocumented

fitSimplex(dataMeas, dataErr, dataCalc, sc)[source]

Warning

method ‘mcsas.backgroundscalingfit.BackgroundScalingFit.fitSimplex’ undocumented

mcsas.mcsas.mcsas module
class McSAS[source]

Bases: bases.algorithm.algorithmbase.AlgorithmBase

Main class containing all functions required to do Monte Carlo fitting.

Required:

  • data: The dataset to fit.
    Has to be an instance of :py:class:SASData
  • model: The scattering model object to assume.
    It has to be an instance of ScatteringModel.

For more settings, see mcsas/mcsasparameters.json

Returns:

A McSAS object with the following Results stored in the result member attribute. These can be extracted using McSAS.result[<parameterIndexNumber>][‘<Keyword>’] where the parameterIndexNumber indicates which shape parameter information is requested. E.g. an ellipsoid has 3: width, height and orientation. (Some information is only stored in parameterIndexNumber = 0 (default)).

Keyword may be one of the following:

fitMeasValMean: 1D array (common result)
The fitted measVal, given as the mean of all numReps Results.
fitX0: 1D array (common result)
Corresponding q values (may be different than the input q if X0Bounds was used).
fitMeasValStd: array (common result)
Standard deviation of the fitted I(q), calculated as the standard deviation of all numReps results.
contribs: size array (numContribs x numReps) (common result)
Collection of numContribs contributions fitted to best represent the provided I(q) data. Contains the Results of each of numReps iterations. This can be used for rebinning without having to re-optimize.
scalingFactors: size array (2 x numReps) (common result)
Scaling and background values for each repetition. Used to display background level in data and fit plot.
histogramXLowerEdge: array
histogram bin left edge position (x-axis in histogram).
histogramXMean: array
Center positions for the size histogram bins (x-axis in histogram, used for errorbars).
histogramXWidth: array
histogram bin width (x-axis in histogram, defines bar plot bar widths).
volumeHistogramYMean: array
Volume-weighted particle size distribution values for all numReps Results (y-axis bar height).
numberHistogramYMean: array
Number-weighted analogue of the above volumeHistogramYMean.
volumeHistogramRepetitionsY: size array (self.histogramBins x numReps)
Volume-weighted particle size distribution bin values for each fit repetition (the mean of which is volumeHistogramYMean, and the sample standard deviation is volumeHistogramYStd).
numberHistogramRepetitionsY: size array (self.histogramBins x numReps)
Number-weighted particle size distribution bin values for each MC fit repetition.
volumeHistogramYStd: array
Standard deviations of the corresponding volume-weighted size distribution bins, calculated from numReps repetitions of the model fitting function.
numberHistogramYStd: array
Standard deviation for the number-weigthed distribution.
volumeFraction: size array (numContribs x numReps)
Volume fractions for each of numContribs contributions in each of numReps iterations.
numberFraction: size array (numContribs x numReps)
Number fraction for each contribution.
totalVolumeFraction: size array (numReps)
Total scatterer volume fraction for each of the numReps iterations.
totalNumberFraction: size array (numReps)
Total number fraction.
minimumRequiredVolume: size array (numContribs x numReps)
Minimum required volume fraction for each contribution to become statistically significant.
minimumRequiredNumber: size array (numContribs x numReps)
Number-weighted analogue to minimumRequiredVolume.
volumeHistogramMinimumRequired: size array (histogramXMean)
Array with the minimum required volume fraction per bin to become statistically significant. Used to display minimum required level in histogram.
numberHistogramMinimumRequired: size array (histogramXMean)
Number-weighted analogue to volumeHistogramMinimumRequired.
scalingFactors: size array (2 x numReps)
Scaling and background values for each repetition. Used to display background level in data and fit plot.
totalVolumeFraction: size array (numReps)
Total scatterer volume fraction for each of the numReps iterations.
minimumRequiredVolume: size array (numContribs x numReps)
Minimum required volube fraction for each contribution to become statistically significant.
volumeHistogramMinimumRequired: size array (histogramXMean)
Array with the minimum required volume fraction per bin to become statistically significant. Used to display minimum required level in histogram.

Creates instances from defined parameters and replaces the class attributes accordingly.

analyse()[source]

This function runs the Monte Carlo optimisation a multitude (numReps) of times. If convergence is not achieved, it will try again for a maximum of maxRetries attempts.

calc(**kwargs)[source]

Warning

method ‘mcsas.mcsas.McSAS.calc’ undocumented

data = None
classmethod factory()[source]

Warning

method ‘mcsas.mcsas.McSAS.factory’ undocumented

gen2DMeasVal()[source]

This function is optionally run after the histogram procedure for anisotropic images, and will calculate the MC fit measVal in image form

histogram(contribs=None)[source]

Takes the contribs result from the McSAS.analyse() function and calculates the corresponding volume- and number fractions for each contribution as well as the minimum observability limits. It will subsequently bin the Result across the range for histogramming purposes.

While the volume-weighted distribution will be in absolute units (providing volume fractions of material within a given size range), the number distributions have been normalized to 1.

Output a list of dictionaries with one dictionary per shape parameter:

histogramXLowerEdge: array
histogram bin left edge position (x-axis in histogram)
histogramXMean: array
Center positions for the size histogram bins (x-axis in histogram, used for errorbars)
histogramXWidth: array
histogram bin width (x-axis in histogram, defines bar plot bar widths)
volumeHistogramYMean: array
Volume-weighted particle size distribution values for all numReps Results (y-axis bar height)
numberHistogramYMean: array
Number-weighted analogue of the above volumeHistogramYMean
volumeHistogramRepetitionsY: size (histogramBins x numReps)
array Volume-weighted particle size distribution bin values for each MC fit repetition (whose mean is volumeHistogramYMean, and whose sample standard deviation is volumeHistogramYStd)
numberHistogramRepetitionsY: size (histogramBins x numReps)
array Number-weighted particle size distribution bin values for each MC fit repetition
volumeHistogramYStd: array
Standard deviations of the corresponding volume-weighted size distribution bins, calculated from numReps repetitions of the model fitting function
numberHistogramYStd: array
Standard deviation for the number-weigthed distribution
volumeFraction: size (numContribs x numReps) array
Volume fractions for each of numContribs contributions in each of numReps iterations
numberFraction: size (numContribs x numReps) array
Number fraction for each contribution
totalVolumeFraction: size (numReps) array
Total scatterer volume fraction for each of the numReps iterations
totalNumberFraction: size (numReps) array
Total number fraction
minimumRequiredVolume: size (numContribs x numReps) array
minimum required volume fraction for each contribution to become statistically significant.
minimumRequiredNumber: size (numContribs x numReps) array
number-weighted analogue to minimumRequiredVolume
volumeHistogramMinimumRequired: size (histogramXMean) array
array with the minimum required volume fraction per bin to become statistically significant. Used to display minimum required level in histogram.
numberHistogramMinimumRequired: size (histogramXMean) array
number-weighted analogue to volumeHistogramMinimumRequired
scalingFactors: size (2 x numReps) array
Scaling and background values for each repetition. Used to display background level in data and fit plot.
mcFit(numContribs, minConvergence, outputMeasVal=False, outputDetails=False, nRun=None)[source]

Object-oriented, shape-flexible core of the Monte Carlo procedure. Takes optional arguments:

outputMeasVal:
Returns the fitted measVal besides the Result
outputDetails:
details of the fitting procedure, number of iterations and so on
nRun: “serial number” of run. Used to store results in parameters
in the right place
model = None
plot(axisMargin=0.3, outputFilename=None, autoClose=False)[source]

Expects outputFilename to be of type gui.calc.OutputFilename.

result = None
array(value)

Warning

function ‘mcsas.mcsas.array’ undocumented

mcsas.mcsas.mcsasdefaultcfg module

default for settings and info used for a McSAS run used by McSASCfg

class ExtendedEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

JSON encoder extended to deal with Unicode, arrays and cls descriptions

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(obj)[source]

Warning

method ‘mcsas.mcsasdefaultcfg.ExtendedEncoder.default’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘mcsas.mcsasdefaultcfg.Parameter’ undocumented

class cInfo(**kwargs)[source]

Bases: object

This class contains all the information required to read, verify and write configuration parameters files.

initialise the defaults and populate the database with values where appropriate default parameter file can be provided using kwarg: paramDefFile = ‘path/to/file’ mcsasparameters.json should be in the same directory as this function

getPar(key)[source]

Warning

method ‘mcsas.mcsasdefaultcfg.cInfo.getPar’ undocumented

getParVal(par)[source]

shortcut method for getting the value of a parameter

loadParams(fname=None)[source]

writes the default definitions and bounds for the configuration parameters to self.parameters Can also be used to update existing parameters from supplied filename

parameterNames = []
parameters = None
parseConfig()[source]

Runs through the entire settings, raising warnings where necessary

setParVal(par, value)[source]

shortcut method for setting the value of a parameter only

writeConfig(fname)[source]

writes the configuration to a settings file. Required input parameter is the filename to write to.

mcsas.mcsas.mcsasparameters module
class McSASParameters(paramDefFile=None)[source]

Bases: utils.propertynames.PropertyNames

Defines the static parameters used for the fitting procedure:
  • model: an instance of McSAS.model defining the fitting model
  • contribParamBounds: Bounds of the active (fitting) parameter
  • qBounds: limits in q between which the fit is applied
  • psiBounds: limits in azimuthal angle (2D patterns only) to which
    the fit is applied
  • qMagnitude: indicates the multiplier to scale q to m^-1
  • iMagnitude: indicates the multiplier to scale I to (m sr)^-1
  • histogramBins: number of bins to use for size distribution
    determination. Does not affect fit
  • histogramXScale: can be “log” or “linear”, sets the horizontal
    axis scaling. Does not affect fit
  • histogramWeighting: can be “volume”(recommended) or “number”.
    Determines whether to plot the volume-weighted size distribution (which is closest to what is measured in a scattering measurement) or a number-weighted size distribution.
  • deltaRhoSquared the value (in m^{-4}) of the squared electron
    density contrast. Typically on the order of 10^{25} to 10^{30} for X-ray scattering measurements. To get a correct volume fraction, the intensity must be in reciprocal meters, as must q and the object size parameters must be adjusted accordingly.
  • startFromMinimum: may be depreciated: starts with an initial guess
    consisting of minimum size values rather than random. For testing purposes only.
  • maxRetries: if a single optimisation fails, it will be retried
    this integer of times.
  • maskNegativeInt: may be depreciated due to overlap with similar
    functionality in the McSAS.data molule. Setting this will ignore datapoints with intensity values < 0
  • maskZeroInt: similar to above, but for intensity values = 0

Most of them should be moved to McSAS as dynamic parameters of type Parameter which allows them to be configurable in the GUI. Some, esp. histogramBins and histogramXScale should be moved to a custom FitParameter class along with the active flag. (WIP)

Extension in progress: the class can take keyword-value pairs to overwrite (some of) the parameter values. Additionally, a default configuration file (json-style) can be provided using kwarg: paramDefFile = 'path/to/file' A (limited) set of custom parameters can be supplied in another configuration file that overwrite the defaults: paramFile = 'path/to/file'

The order is:

  • default file, whose values are superseded by
  • custom file, whose values are superseded by
  • keyword-value pairs, which only set parameter values, or
  • keyword-dict pairs, which sets parameter attributes as defined in the supplied dictionary

initialise the defaults and populate the database with values where appropriate default parameter file can be provided using kwarg: paramDefFile = ‘path/to/file’ relative to application root dir

contribParamBounds = ()
loadParameters(filename)[source]

Warning

method ‘mcsas.mcsasparameters.McSASParameters.loadParameters’ undocumented

model = None
paramDefFile = 'mcsas/mcsasparameters.json'
parameters = []
pickUnit(unitClass=None, displayUnit=None)[source]

returns a unit object instance of the right class and displayUnit

Parameter(*args, **kwargs)

Warning

function ‘mcsas.mcsasparameters.Parameter’ undocumented

mcsas.mcsas.plotting module

Defines the format of the final report on success of an MC fit.

class CoordinateFormat(xname, xunit, yname, yunit)[source]

Bases: object

A Function object which sets up the particular formatting with axis name and associated unit at initialization time and formats plot coordinates given as (x,y) pair.

class PlotResults(allRes, dataset, axisMargin=0.3, outputFilename=None, modelData=None, autoClose=False, logToFile=False, queue=None)[source]

Bases: object

This function plots the output of the Monte-Carlo procedure in two windows, with the left window the measured signal versus the fitted measVal (on double-log scale), and the righthand window the size distribution.

figInit(nHists, figureTitle, nR=1)[source]

initialize figure and initialise axes using GridSpec. Each rangeinfo (nR) contains two rows and nHists + 1 columns. the top row axes are for placing text objects: settings and stats. The bottom row axes are for plotting the fits and the histograms TODO: add settings to window title? (next to figure_xy)

formatAlgoInfo()[source]

Preformats the algorithm information ready for printing the colons are surrounded by string-marks, to force laTeX rendering

formatRangeInfo(parHist, RI, weighti=0)[source]

Preformats the rangeInfo results ready for printing

plot1D(dataset, fitX0, fitMeasVal, qAxis)[source]

plots 1D data and fit

classmethod plotGrid(ax)[source]

Warning

method ‘mcsas.plotting.PlotResults.plotGrid’ undocumented

plotHist(plotPar, parHist, hAxis, rangei)[source]

histogram plot

plotInfo(InfoAxis)[source]

plots the range statistics in the small info axes above plots

plotPartial(fitX0, fitMeasVal, fitSTD, qAxis, label='MC partial measVal')[source]

plots 1D data and fit

plotStats(parHist, rangei, fig, InfoAxis)[source]

plots the range statistics in the small info axes above plots

setAxis(ah)[source]

Warning

method ‘mcsas.plotting.PlotResults.setAxis’ undocumented

class PlotSeriesStats[source]

Bases: object

Simple 1D plotting of series statistics.

plot(stats)[source]

Warning

method ‘mcsas.plotting.PlotSeriesStats.plot’ undocumented

show()[source]

Warning

method ‘mcsas.plotting.PlotSeriesStats.show’ undocumented

getTextSize(fig, fontProps)[source]

Returns the width and height of a character for the given font setup. This can be different on each platform.

Module contents

McSAS Core

mcsas.models package

Submodules

mcsas.models.cylindersisotropic module
class CylindersIsotropic[source]

Bases: bases.model.sasmodel.SASModel

Form factor of cylinders previous version (length-fixed) checked against SASfit

absVolume()[source]

Warning

method ‘models.cylindersisotropic.CylindersIsotropic.absVolume’ undocumented

formfactor(dataset)[source]

Warning

method ‘models.cylindersisotropic.CylindersIsotropic.formfactor’ undocumented

parameters = (None, None, None, None, None, None, None)
shortName = 'Isotropic Cylinders'
volume()[source]

Warning

method ‘models.cylindersisotropic.CylindersIsotropic.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.cylindersisotropic.Parameter’ undocumented

mcsas.models.cylindersisotropicaspect module
class CylindersIsotropic[source]

Bases: bases.model.sasmodel.SASModel

Form factor of cylinders which are radially isotropic (so not spherically isotropic!) !!!completed but not verified!!!

formfactor(dataset)[source]

Warning

method ‘models.cylindersisotropicaspect.CylindersIsotropic.formfactor’ undocumented

parameters = (None, None, None, None)
shortName = 'Cylinders defined by aspect ratio'
volume()[source]

Warning

method ‘models.cylindersisotropicaspect.CylindersIsotropic.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.cylindersisotropicaspect.Parameter’ undocumented

mcsas.models.cylindersradiallyisotropic module
class CylindersRadiallyIsotropic[source]

Bases: bases.model.sasmodel.SASModel

Form factor of cylinders which are radially isotropic (so not spherically isotropic!) !!!completed but not verified!!!

absVolume()[source]

Warning

method ‘models.cylindersradiallyisotropic.CylindersRadiallyIsotropic.absVolume’ undocumented

formfactor(dataset)[source]

Warning

method ‘models.cylindersradiallyisotropic.CylindersRadiallyIsotropic.formfactor’ undocumented

parameters = (None, None, None, None, None)
shortName = 'Radially (in-plane) isotropic cylinders'
volume()[source]

Warning

method ‘models.cylindersradiallyisotropic.CylindersRadiallyIsotropic.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.cylindersradiallyisotropic.Parameter’ undocumented

mcsas.models.cylindersradiallyisotropictilted module

This model is a special case of the radially isotropic cylinders, where the cylinders are also slightly tilted out of the plane parallel to the detector. This out of plane tilt is described using a Gaussian. The integration over this tilt angle is done over several segments of the Gaussian PDF, with each segment occupying an equal cumulative probability. The centroid value used for the integration is the mass-weighted centre.

class CylindersRadiallyIsotropicTilted[source]

Bases: bases.model.sasmodel.SASModel

Form factor of cylinders UNFINISHED which are radially isotropic (so not spherically isotropic!)

formfactor(dataset)[source]

Warning

method ‘models.cylindersradiallyisotropictilted.CylindersRadiallyIsotropicTilted.formfactor’ undocumented

parameters = (None, None, None, None, None, None)
shortName = 'Cylinders defined by aspect ratio'
volume()[source]

Warning

method ‘models.cylindersradiallyisotropictilted.CylindersRadiallyIsotropicTilted.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.cylindersradiallyisotropictilted.Parameter’ undocumented

mcsas.models.ellipsoidalcoreshell module
class EllipsoidalCoreShell[source]

Bases: bases.model.sasmodel.SASModel

Form factor for an ellipsoidal core shell structure as defined in the SASfit manual (par. 3.2.3) Tested 2014-01-21 against SASfit function with good agreement.

absVolume()[source]

Warning

method ‘models.ellipsoidalcoreshell.EllipsoidalCoreShell.absVolume’ undocumented

formfactor(dataset)[source]

Warning

method ‘models.ellipsoidalcoreshell.EllipsoidalCoreShell.formfactor’ undocumented

parameters = (None, None, None, None, None, None, None)
shortName = 'Core-Shell Ellipsoid'
volume()[source]

Warning

method ‘models.ellipsoidalcoreshell.EllipsoidalCoreShell.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.ellipsoidalcoreshell.Parameter’ undocumented

mcsas.models.ellipsoidsisotropic module
class EllipsoidsIsotropic[source]

Bases: bases.model.sasmodel.SASModel

Form factor for a spheroidal structure with semi-axes a = b, c. c can be set to be an aspect ratio with respect to a tested with Ellipsoid II from SASfit 20140626

absVolume()[source]

Warning

method ‘models.ellipsoidsisotropic.EllipsoidsIsotropic.absVolume’ undocumented

formfactor(dataset)[source]

Warning

method ‘models.ellipsoidsisotropic.EllipsoidsIsotropic.formfactor’ undocumented

parameters = (None, None, None, None, None, None)
shortName = 'Isotropic Ellipsoids'
volume()[source]

Warning

method ‘models.ellipsoidsisotropic.EllipsoidsIsotropic.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.ellipsoidsisotropic.Parameter’ undocumented

mcsas.models.gaussianchain module
class GaussianChain[source]

Bases: bases.model.sasmodel.SASModel

Form factor of flexible polymer chains which are not selfavoiding and obey Gaussian statistics after [Debye47]

See also: http://sasfit.sf.net/manual/Gaussian_Chain#Gauss_2

[Debye47]P. Debye, Mollecular-weight determination by light scattering, Journal of Physical and Colloid Chemistry, 51:18–32, 1947.

I_0 = (bp - (k * Rg^2) * eta_s)^2 with k = 1 nm. k * Rg^2 = volume approximation

fixTestParams = functools.partial(<function GaussianChain.fixTestParams>, <class 'models.gaussianchain.GaussianChain'>)
formfactor(dataset)[source]

Warning

method ‘models.gaussianchain.GaussianChain.formfactor’ undocumented

parameters = (None, None, None, None)
shortName = 'Gaussian Chain'
volume()[source]

Warning

method ‘models.gaussianchain.GaussianChain.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.gaussianchain.Parameter’ undocumented

test()[source]

Warning

function ‘models.gaussianchain.test’ undocumented

mcsas.models.kholodenko module
class Kholodenko[source]

Bases: bases.model.sasmodel.SASModel

Form factor of a worm-like structure after [Kholodenko93]

[Kholodenko93]A. L. Kholodenko. Analytical calculation of the scattering function for polymers of arbitrary flexibility using the dirac propagator. Macromolecules, 26:4179–4183, 1993.
formfactor(dataset)[source]

Warning

method ‘models.kholodenko.Kholodenko.formfactor’ undocumented

parameters = (None, None, None)
shortName = 'Kholodenko Worm'
volume()[source]

Warning

method ‘models.kholodenko.Kholodenko.volume’ undocumented

calcPcs(u)[source]

Warning

function ‘models.kholodenko.calcPcs’ undocumented

core(z, qValue, kuhnLength, x)[source]

Warning

function ‘models.kholodenko.core’ undocumented

coreIntegral(qValue, kuhnLength, x)[source]

Warning

function ‘models.kholodenko.coreIntegral’ undocumented

test()[source]

Warning

function ‘models.kholodenko.test’ undocumented

mcsas.models.lmadensesphere module
class LMADenseSphere[source]

Bases: bases.model.sasmodel.SASModel

Form factor of a sphere convoluted with a structure factor, equations 15-17 from Pedersen, J. Appl. Cryst. 27 (1994), 595–608. Correct eqn given in Kinning and Thomas, Macromolecules 17 (1984) 1712. Internally set parameters are volume fraction of the hard spheres, and the multiplication factor /mf/ for an additional stand-off distance between the hard spheres: Rh=mf*R where Rh is the hard-sphere radius (“interaction radius”) used in the structure factor, R is the radius of the sphere, and mf is the multiplication factor.

absVolume()[source]

Warning

method ‘models.lmadensesphere.LMADenseSphere.absVolume’ undocumented

canSmear = True
formfactor(dataset)[source]

Warning

method ‘models.lmadensesphere.LMADenseSphere.formfactor’ undocumented

parameters = (None, None, None, None)
shortName = 'LMADenseSphere'
volume()[source]

Warning

method ‘models.lmadensesphere.LMADenseSphere.volume’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘models.lmadensesphere.Parameter’ undocumented

mcsas.models.sphere module
Parameter(*args, **kwargs)

Warning

function ‘models.sphere.Parameter’ undocumented

class Sphere[source]

Bases: bases.model.sasmodel.SASModel

Form factor of a sphere

absVolume()[source]

Calculates the volume of a sphere taking the scattering length density difference \(\Delta\rho\) into account:

\(v_{abs}(r, \Delta\rho) = v_{sph}(r) \cdot \Delta\rho^2\)

canSmear = True
formfactor(dataset)[source]

Calculates the form factor of a sphere defined by:

\(F(q, r) = { 3 ~ sin(qr) - qr \cdot cos(qr) \over (qr)^3 }\)

parameters = (None, None)
shortName = 'Sphere'
surface()[source]

Calculates the surface of a sphere defined by:

\(s(r) = 4 \pi r^2\)

volume()[source]

Calculates the volume of a sphere defined by:

\(v(r) = {4\pi \over 3} r^3\)

test()[source]

Warning

function ‘models.sphere.test’ undocumented

mcsas.models.sphericalcoreshell module
Parameter(*args, **kwargs)

Warning

function ‘models.sphericalcoreshell.Parameter’ undocumented

class SphericalCoreShell[source]

Bases: bases.model.sasmodel.SASModel

Form factor for a spherical core shell structure as defined in the SASfit manual (par. 3.1.4, Spherical Shell III). One modification is the ability to specify SLD for core, shell and solvent, identical to the notation used in the Core-shell ellipsoid. Compared wiht a SASfit-generated model (both with and without distribution)

absVolume()[source]

Warning

method ‘models.sphericalcoreshell.SphericalCoreShell.absVolume’ undocumented

formfactor(dataset)[source]

Warning

method ‘models.sphericalcoreshell.SphericalCoreShell.formfactor’ undocumented

parameters = (None, None, None, None, None)
shortName = 'Core-Shell Sphere'
volume()[source]

Warning

method ‘models.sphericalcoreshell.SphericalCoreShell.volume’ undocumented

Module contents

mcsas.gui package

Subpackages

mcsas.gui.bases package
Subpackages
mcsas.gui.bases.mainwindow package
Submodules
mcsas.gui.bases.mainwindow.mainwindow module
class MainWindow(appversion, parent=None)[source]

Bases: QMainWindow, gui.bases.mainwindow.ui_mainwindow.Ui_MainWindow, gui.bases.mixins.appsettings.AppSettings

Main window base class.

Provides functionality for storing and loading application settings, managing widgets.

closeEvent(event)[source]

Warning

method ‘gui.bases.mainwindow.mainwindow.MainWindow.closeEvent’ undocumented

getCommandlineArguments()[source]

Get command line arguments, if any.

onStartupSignal
restoreSettings()[source]

Load defaults for settings if missing and available.

show()[source]

Warning

method ‘gui.bases.mainwindow.mainwindow.MainWindow.show’ undocumented

storeSettings()[source]

Warning

method ‘gui.bases.mainwindow.mainwindow.MainWindow.storeSettings’ undocumented

mcsas.gui.bases.mainwindow.mainwindow_rc module
qCleanupResources()[source]

Warning

function ‘gui.bases.mainwindow.mainwindow_rc.qCleanupResources’ undocumented

qInitResources()[source]

Warning

function ‘gui.bases.mainwindow.mainwindow_rc.qInitResources’ undocumented

mcsas.gui.bases.mainwindow.ui_mainwindow module
class Ui_MainWindow[source]

Bases: object

retranslateUi(MainWindow)[source]

Warning

method ‘gui.bases.mainwindow.ui_mainwindow.Ui_MainWindow.retranslateUi’ undocumented

setupUi(MainWindow)[source]

Warning

method ‘gui.bases.mainwindow.ui_mainwindow.Ui_MainWindow.setupUi’ undocumented

Module contents
mcsas.gui.bases.mixins package
Submodules
mcsas.gui.bases.mixins.appsettings module
class AppSettings[source]

Bases: object

appSettings
setRootGroup()[source]

Resets any QSettings group(s) currently set.

mcsas.gui.bases.mixins.contextmenuwidget module
class ContextMenuWidget[source]

Bases: object

Menu states are mutual exclusive states of available context menu actions.

Menu states map to boolean methods of this object. The names of a state equal names of methods of this object otherwise the menu state is useless. updateMenu() tests the states, i.e. boolean methods for a true return value. The first one specifies the menu to be build. If none matches, the ‘default’ state will be used.

Menu states are defined by updateMenuState(). The provided list of entry names has to be a partial set of those returned by menuEntries(). Entries may be defined by addMenuEntry().

TODO: Instead of multiple inheritance, convert it to a standalone object. Problems: need to store bound methods as callbacks, to get state on update() The widget this menu applies to needs to be stored only once at init.

action(name)[source]

Warning

method ‘gui.bases.mixins.contextmenuwidget.ContextMenuWidget.action’ undocumented

addMenuEntry(name=None, text=None, toolTip=None, shortCut=None, checkable=False, checked=False, callbacks=None, menuStates=None)[source]

Argument ‘callbacks’ is supposed to be a list of methods which will be connected to the QAction.triggered signal.

addMenuEntryAction(name, action, menuStates=None)[source]

Common menu states: default and all. ‘all’ includes the default state. Everything else expects a method of the same name which evaluates to True or False. It is used to show or hide the respective context menu action. Actions bound to the same state appear grouped in the menu. The underlying ordered dict preserves the order of states.

addMenuSeparator(menuStates=None)[source]

Warning

method ‘gui.bases.mixins.contextmenuwidget.ContextMenuWidget.addMenuSeparator’ undocumented

addToMenuState(stateName, *entryNames)[source]

Warning

method ‘gui.bases.mixins.contextmenuwidget.ContextMenuWidget.addToMenuState’ undocumented

allMenuStates = '*'
menuEntries(stateName)[source]

Warning

method ‘gui.bases.mixins.contextmenuwidget.ContextMenuWidget.menuEntries’ undocumented

removeMenuEntries(stateName)[source]

Warning

method ‘gui.bases.mixins.contextmenuwidget.ContextMenuWidget.removeMenuEntries’ undocumented

updateMenu(widget=None)[source]

Warning

method ‘gui.bases.mixins.contextmenuwidget.ContextMenuWidget.updateMenu’ undocumented

escapeAmp(text)[source]

Warning

function ‘gui.bases.mixins.contextmenuwidget.escapeAmp’ undocumented

mcsas.gui.bases.mixins.dropwidget module
class DropWidget[source]

Bases: object

Drag&Drop support for widgets which inherit from this.

dragEnterEvent(ev)[source]

Warning

method ‘gui.bases.mixins.dropwidget.DropWidget.dragEnterEvent’ undocumented

dropEvent(ev)[source]

Warning

method ‘gui.bases.mixins.dropwidget.DropWidget.dropEvent’ undocumented

mcsas.gui.bases.mixins.titlehandler module
class TitleHandler(title)[source]

Bases: bases.dataset.titlemixin.TitleMixin

registerUpdateFunc(func)[source]

Warning

method ‘gui.bases.mixins.titlehandler.TitleHandler.registerUpdateFunc’ undocumented

classmethod setup(parent, title)[source]

Gets a title and the widget this title belongs to.

update(obj)[source]

Warning

method ‘gui.bases.mixins.titlehandler.TitleHandler.update’ undocumented

Module contents
Submodules
mcsas.gui.bases.datalist module
class DataItem(data)[source]

Bases: QTreeWidgetItem

Generates a QTreeWidgetItem from arbitrary python objects. Storing those objects separately.

data(*args)[source]

Warning

method ‘gui.bases.datalist.DataItem.data’ undocumented

dataId()[source]

Warning

method ‘gui.bases.datalist.DataItem.dataId’ undocumented

getItemProperty(value)[source]

For a value, returns this items getter/setter methods according to value type.

static hash32(data)[source]

Avoids OverFlowError at setData() with PySide on MacOS.

isRemovable
isTopLevelItem()[source]

Warning

method ‘gui.bases.datalist.DataItem.isTopLevelItem’ undocumented

listIndex()[source]

Index of this items top most parent in the treewidget.

remove()[source]

Removes the item from its treewidget or parent item.

setAlignment(alignment)[source]

Warning

method ‘gui.bases.datalist.DataItem.setAlignment’ undocumented

setChanged(column)[source]

Warning

method ‘gui.bases.datalist.DataItem.setChanged’ undocumented

setClicked(column)[source]

Warning

method ‘gui.bases.datalist.DataItem.setClicked’ undocumented

update()[source]

Updates this item according to eventually changed data object

wasClickedAndChanged()[source]

Tests if this item was previously clicked and changed in the UI.

class DataList(parent=None, title=None, withBtn=True, nestedItems=True)[source]

Bases: QWidget, gui.bases.mixins.dropwidget.DropWidget, gui.bases.mixins.contextmenuwidget.ContextMenuWidget

Manages all loaded spectra.

>>> from utilsgui import DialogInteraction, DisplayException
>>> from spectralist import SpectraList
>>> sl = DialogInteraction.instance(SpectraList)

Test available actions >>> [str(action.text()) for action in sl.listWidget.actions()] [‘load spectra’, ‘remove’, ‘’, ‘save matrices’, ‘select all’] >>> sl.listWidget.count() 0

Test methods on empty list >>> sl.updateSpectra() >>> sl.removeSelectedSpectra() >>> [sl.getMatrix(i) for i in -1,0,1] [None, None, None] >>> DialogInteraction.query(DisplayException, sl.saveMatrix, ... slot = ‘accept’) >>> sl.selectionChangedSlot()

add(data)[source]

Warning

method ‘gui.bases.datalist.DataList.add’ undocumented

clear()[source]

Warning

method ‘gui.bases.datalist.DataList.clear’ undocumented

currentSelection()[source]

Warning

method ‘gui.bases.datalist.DataList.currentSelection’ undocumented

data(indexOrItem=None, selectedOnly=False)[source]

Returns the list of data for a given list index or list widget item. If none is specified return the data of all items or the data of selected items only, if desired.

expandAll()[source]

Warning

method ‘gui.bases.datalist.DataList.expandAll’ undocumented

fitColumnsToContents(*args)[source]

Warning

method ‘gui.bases.datalist.DataList.fitColumnsToContents’ undocumented

hasSelection()[source]

Warning

method ‘gui.bases.datalist.DataList.hasSelection’ undocumented

isEmpty()[source]

Warning

method ‘gui.bases.datalist.DataList.isEmpty’ undocumented

isNotEmpty()[source]

Warning

method ‘gui.bases.datalist.DataList.isNotEmpty’ undocumented

isRemovableSelected()[source]

True, if there is at least one item selected which may be removed

itemDoubleClicked(item, column)[source]

Warning

method ‘gui.bases.datalist.DataList.itemDoubleClicked’ undocumented

itemUpdate(item, column)[source]

Reimplement to update item if changed by user in GUI

itemsHaveChildren()[source]

Warning

method ‘gui.bases.datalist.DataList.itemsHaveChildren’ undocumented

leaveEvent(event)[source]

Warning

method ‘gui.bases.datalist.DataList.leaveEvent’ undocumented

loadData(sourceList=None, processSourceFunc=None, showProgress=True, alignment=None, **kwargs)[source]

Loads a list of data source items.

processSourceFunc is expected to be a function which gets individual elements of sourceList as argument. It returns an arbitrary data item which is then added to this data list widget.

Reimplement it in child classes and it will be called on load button and add action signal.

This method handles exceptions and progress indication.

Test loading a single spectra >>> import utils >>> from tests import TestData >>> from utilsgui import DialogInteraction, UiSettings, fileDialogType >>> from chemsettings import ChemSettings >>> from datafiltersgui import DataFiltersGui >>> from spectralist import SpectraList >>> cs = DialogInteraction.instance(ChemSettings) >>> dfg = DialogInteraction.instance(DataFiltersGui) >>> sl = DialogInteraction.instance(SpectraList, settings = cs) >>> utils.LastPath.path = TestData.spectra(0) >>> DialogInteraction.query(fileDialogType(), sl.loadData, ... slot = ‘accept’) >>> sl.updateSpectra() >>> utils.LastPath.path = utils.getTempFileName() >>> matrixfiles = DialogInteraction.query(fileDialogType(), sl.saveMatrix, ... slot = ‘accept’) >>> len(matrixfiles) 1 >>> matrixfiles

Verify written matrix data with existent matrix export >>> TestData.verifyMatrix(TestData.spectra(0), ... matrixfiles[0]) True

removeItems(indexList)[source]

Deletes items specified in the given list of indices.

removeSelected()[source]

Warning

method ‘gui.bases.datalist.DataList.removeSelected’ undocumented

reraiseLast()[source]

Reraise the last error if any and display an error message dialog.

selectAll()[source]

Selects all items in the list if not all are selected. Clears the selection if all items in the list already are selected.

selectionChanged()[source]

Warning

method ‘gui.bases.datalist.DataList.selectionChanged’ undocumented

setCurrentIndex(index)[source]

Warning

method ‘gui.bases.datalist.DataList.setCurrentIndex’ undocumented

setHeader(labels=None)[source]

Warning

method ‘gui.bases.datalist.DataList.setHeader’ undocumented

setupUi()[source]

Reimplement this in child classes for custom UI configuration.

sigEditingFinished
sigEmpty
sigReceivedUrls
sigRemovedData
sigSelectedData
sigUpdatedData
topLevelItems()[source]

Warning

method ‘gui.bases.datalist.DataList.topLevelItems’ undocumented

updateData(selectedOnly=False, showProgress=True, updateFunc=None, prepareFunc=None, stopFunc=None, **kwargs)[source]

Calls the provided function on all data items.

The object returned by prepareFunc() is forwarded as optional argument to updateFunc(dataItem, optionalArguments = None).

updateItems()[source]

Warning

method ‘gui.bases.datalist.DataList.updateItems’ undocumented

mcsas.gui.bases.dockwidget module
class DockWidget(parent, childWidgetType, *args, **kwargs)[source]

Bases: QDockWidget

Widget for docking in a QMainWindow environment.

child
closeEvent(event)[source]

Warning

method ‘gui.bases.dockwidget.DockWidget.closeEvent’ undocumented

onVisibilityChange(visible)[source]

Warning

method ‘gui.bases.dockwidget.DockWidget.onVisibilityChange’ undocumented

mcsas.gui.bases.logwidget module
class LogWidget(parent=None, appversion=None)[source]

Bases: QTextBrowser, gui.bases.mixins.contextmenuwidget.ContextMenuWidget

Simple TextEdit which can save its contents to file.

Fill it with text. >>> from gui.utils.dialoginteraction import DialogInteraction >>> from gui.widgets.logwidget import LogWidget >>> testdata = ‘blablubbanblubb’ >>> te = DialogInteraction.instance(LogWidget) >>> te.append(testdata) >>> te.contents() == testdata True

Call save to file dialog and save. >>> fn = str(DialogInteraction.query(fileDialogType(), te.saveToFile, ... slot = ‘accept’))

Verify written data and remove test file. >>> import os >>> data = None >>> if fn is not None: ... data = open(fn).read() ... os.remove(fn) >>> data == testdata True

PlainTextEdit Tests: Simple TextEdit which can save its contents to file.

Fill it with text. >>> from utilsgui import DialogInteraction, fileDialogType >>> from plaintextedit import PlainTextEdit >>> testdata = ‘blablubbanblubb’ >>> te = DialogInteraction.instance(PlainTextEdit) >>> te.appendPlainText(testdata) >>> te.toPlainText() == testdata True

Call save to file dialog and save. >>> fn = str(DialogInteraction.query(fileDialogType(), te.saveToFile, ... slot = ‘accept’))

Verify written data and remove test file. >>> import os >>> data = None >>> if fn is not None: ... data = open(fn).read() ... os.remove(fn) >>> data == testdata True

addWatchDir(path)[source]

Adds a directory to check for plotlog messages from multiprocessing.

append(text)[source]

Appends a new line of text.

appversion
clear()[source]

Warning

method ‘gui.bases.logwidget.LogWidget.clear’ undocumented

contents()[source]

Warning

method ‘gui.bases.logwidget.LogWidget.contents’ undocumented

isCopyAvailable()[source]

Warning

method ‘gui.bases.logwidget.LogWidget.isCopyAvailable’ undocumented

isEmpty()[source]

Warning

method ‘gui.bases.logwidget.LogWidget.isEmpty’ undocumented

onCloseSlot()[source]

Workaround to exit a program during calculation. Logging a message processes Qt events (see append()). It makes sure this slot is called if connected to a application close signal. For example, emitted by the main window on closeEvent().

saveToFile(filename=None)[source]

Warning

method ‘gui.bases.logwidget.LogWidget.saveToFile’ undocumented

scrollToBottom()[source]

Warning

method ‘gui.bases.logwidget.LogWidget.scrollToBottom’ undocumented

scrollToTop()[source]

Warning

method ‘gui.bases.logwidget.LogWidget.scrollToTop’ undocumented

setCopyAvailable(yes)[source]

Warning

method ‘gui.bases.logwidget.LogWidget.setCopyAvailable’ undocumented

title = None
url2href(text)[source]

http://daringfireball.net/2010/07/improved_regex_for_matching_urls

mcsas.gui.bases.settingswidget module
class SettingsWidget(parent=None)[source]

Bases: QWidget

Provides access to user provided application settings.

Call get(‘<objectname>’) to get an input widget value.

connectInputWidgets(widget)

Warning

method ‘gui.bases.settingswidget.SettingsWidget.connectInputWidgets’ undocumented

get(key, defaultValue=None)[source]

Retrieves the values for a given key name.

static getEditingFinishedSignal(widget)[source]

Warning

method ‘gui.bases.settingswidget.SettingsWidget.getEditingFinishedSignal’ undocumented

getInputWidget(datatype)[source]

Warning

method ‘gui.bases.settingswidget.SettingsWidget.getInputWidget’ undocumented

getValue(widget, defaultValue=None)[source]

Retrieves the values for a given widget.

getWidget(key)[source]

Warning

method ‘gui.bases.settingswidget.SettingsWidget.getWidget’ undocumented

set(key, value)[source]

Warning

method ‘gui.bases.settingswidget.SettingsWidget.set’ undocumented

setValue(widget, value)[source]

Warning

method ‘gui.bases.settingswidget.SettingsWidget.setValue’ undocumented

sigValueChanged
sigValuesChanged
mcsas.gui.bases.settingswidget_test module
class TestSettings(parent=None)[source]

Bases: gui.bases.settingswidget.SettingsWidget

setupUi(dummy)[source]

Warning

method ‘gui.bases.settingswidget_test.TestSettings.setupUi’ undocumented

testFloatingPointInputBox()[source]

Warning

function ‘gui.bases.settingswidget_test.testFloatingPointInputBox’ undocumented

testIntegerInputBox()[source]

Warning

function ‘gui.bases.settingswidget_test.testIntegerInputBox’ undocumented

testTextualInputBox()[source]

Warning

function ‘gui.bases.settingswidget_test.testTextualInputBox’ undocumented

w
Module contents
mcsas.gui.utils package
Subpackages
mcsas.gui.utils.appversion package
Submodules
mcsas.gui.utils.appversion.appversion module
class AppVersion(programName=None, versionNumber=None, organizationName=None, organizationDomain=None, defaultSettings=None)[source]

Bases: object

Stores version meta data.

defaultSettings()[source]

Warning

method ‘gui.utils.appversion.appversion.AppVersion.defaultSettings’ undocumented

classmethod isValid(other)[source]

Warning

method ‘gui.utils.appversion.appversion.AppVersion.isValid’ undocumented

name()[source]

Warning

method ‘gui.utils.appversion.appversion.AppVersion.name’ undocumented

number()[source]

Warning

method ‘gui.utils.appversion.appversion.AppVersion.number’ undocumented

organizationDomain()[source]

Warning

method ‘gui.utils.appversion.appversion.AppVersion.organizationDomain’ undocumented

organizationName()[source]

Warning

method ‘gui.utils.appversion.appversion.AppVersion.organizationName’ undocumented

static updateFile(module, newversion)[source]

Updates the version string within a given module. Replaces the version string in the source code textually. Assumes there is an AppVersion constructor call in the module.

mcsas.gui.utils.appversion.qappversion module
class QAppVersion(*args, **kwargs)[source]

Bases: gui.utils.appversion.appversion.AppVersion

Set QCoreApplication properties based on version meta data.

settingsKey()[source]

Version dependent settings key.

Module contents
Submodules
mcsas.gui.utils.dialoginteraction module
class DialogInteraction(config)[source]

Bases: QThread

Simulates user interaction on blocking widgets.

Calls a specified slot on all widgets of a given type after a given delay. Please see tests in other classes for examples.

config: A dict containing argument/value pairs. For valid arguments, please see _propertyNames.

classmethod application()[source]

Warning

method ‘gui.utils.dialoginteraction.DialogInteraction.application’ undocumented

classmethod instance(instanceType, *args, **kwargs)[source]

Warning

method ‘gui.utils.dialoginteraction.DialogInteraction.instance’ undocumented

classmethod query(queryType, blockingFunc, *args, **kwargs)[source]

Warning

method ‘gui.utils.dialoginteraction.DialogInteraction.query’ undocumented

classmethod queryInstance(instanceType, *args, **kwargs)[source]

Warning

method ‘gui.utils.dialoginteraction.DialogInteraction.queryInstance’ undocumented

run()[source]

Warning

method ‘gui.utils.dialoginteraction.DialogInteraction.run’ undocumented

mcsas.gui.utils.displayexception module
class DisplayException(exception, level='critical', fmt=None)[source]

Bases: QMessageBox

Displays a message box with the text of a provided exception. level: one of ‘question’, ‘info’, ‘warning’, ‘critical’

>>> from utilsgui import DisplayException, DialogInteraction
>>> from utils import AppError
>>> de = DialogInteraction.queryInstance(DisplayException,
...                                      AppError("test"),
...                                      button = 'default')
>>> type(de).__name__
'DisplayException'
>>> de.result() == 0
True
classmethod classAndMethodName()[source]

Retrieves some meta info to decribe the error further.

mcsas.gui.utils.filedialog module

File dialogs and convenience functions.

fileDialog(parent, labeltext, path, directory=False, readOnly=True)[source]

Opens a dialog to select one or more files for reading.

Alternative to native file dialogs.

fileDialogType()[source]

Warning

function ‘gui.utils.filedialog.fileDialogType’ undocumented

getOpenFiles(parent, labeltext, path, filefilter=None, multiple=True)[source]

Warning

function ‘gui.utils.filedialog.getOpenFiles’ undocumented

getSaveDirectory(parent, labeltext, path)[source]

Warning

function ‘gui.utils.filedialog.getSaveDirectory’ undocumented

getSaveFile(parent, labeltext, path, filefilter)[source]

Warning

function ‘gui.utils.filedialog.getSaveFile’ undocumented

makeFilter(filterList)[source]

Warning

function ‘gui.utils.filedialog.makeFilter’ undocumented

mcsas.gui.utils.progressdialog module
class ProgressDialog(parent=None, title=None, count=0)[source]

Bases: QProgressDialog

A progress dialog to visualize calculation status of the program.

Tests the ProgressDialog with 10 steps, cancels in between. >>> import time >>> from utilsgui import ProgressDialog, DialogInteraction >>> pd = DialogInteraction.queryInstance(ProgressDialog, ... slot = ‘cancel’, ... count = 11) >>> for i in range(0, pd.maximum()): ... dummy = pd.update() ... time.sleep(0.2) >>> pd.wasCanceled() True

Tests again, without cancel this time. >>> pd.reset() >>> for i in range(0, pd.maximum()): ... dummy = pd.update() ... time.sleep(0.2) >>> pd.wasCanceled() False

update()[source]

Updates progress status and returns True if canceled, False otherwise.

mcsas.gui.utils.signal module
tryDisconnect(sig, slot)[source]

Tries to disconnect signal sig from slot slot.

mcsas.gui.utils.translate module
tr(s)[source]

Warning

function ‘gui.utils.translate.tr’ undocumented

Module contents
processEventLoop()[source]

Warning

function ‘gui.utils.processEventLoop’ undocumented

Submodules

mcsas.gui.algorithmwidget module
class AlgorithmWidget(parent, algorithm, appSettings)[source]

Bases: gui.bases.settingswidget.SettingsWidget, gui.bases.mixins.appsettings.AppSettings

algorithm

Retrieves AlgorithmBase object containing all parameters for this settings.

blockSigValueChanged()[source]

Warning

method ‘gui.algorithmwidget.AlgorithmWidget.blockSigValueChanged’ undocumented

static clearLayout(layout, newParent=None)[source]

Removes all widgets from the given layout and reparents them if newParent is a sub class of QWidget

inputWidgets

Returns all existing input names (for store/restore).

keys
makeSetting(param, activeBtns=False)[source]

Creates an input widget for the provided Parameter and configures it appropriately.

makeWidgets(*args)[source]

Warning

method ‘gui.algorithmwidget.AlgorithmWidget.makeWidgets’ undocumented

onBackendUpdate()[source]

Warning

method ‘gui.algorithmwidget.AlgorithmWidget.onBackendUpdate’ undocumented

static removeWidgets(widget)[source]

Removes all widgets from the layout of the given widget.

resizeEvent(resizeEvent)[source]

Resizes widget based on available width.

resizeWidgets(targetWidth)[source]

Warning

method ‘gui.algorithmwidget.AlgorithmWidget.resizeWidgets’ undocumented

restoreSession(section=None)[source]

Warning

method ‘gui.algorithmwidget.AlgorithmWidget.restoreSession’ undocumented

sigBackendUpdated
storeSession(section=None)[source]

Stores current UI configuration to persistent application settings.

uiWidgets

May return a list of input widgets compatible but not associated to a parameter, e.g. for UI configuration. To be overridden in subclasses.

unblockSigValueChanged()[source]

Warning

method ‘gui.algorithmwidget.AlgorithmWidget.unblockSigValueChanged’ undocumented

updateAll()[source]

Called in MainWindow on calculation start.

updateParam(param, emitBackendUpdated=True)[source]

Write UI settings back to the algorithm. Processes all input widgets which belong to a certain parameter.

updateUi()[source]

Update input widgets according to possibly changed backend data.

updateWidget(widget, emitBackendUpdated=True)[source]

Write UI settings back to the algorithm. Gets the parameter associated with a certain widget and processes all related widgets as well.

class SettingsGridWidget(parent, algorithm, appSettings=None, showParams=None)[source]

Bases: gui.algorithmwidget.AlgorithmWidget

Base class for displaying simple input boxes of various settings arranged on a grid dynamically based on the width of the window.

Additional arguments: showParams is a list of parameter names to show in this widget. If not specified it shows all available parameters by default.

resizeWidgets(targetWidth)[source]

Creates a new layout with appropriate row/column count.

isNotNone(lst)[source]

Warning

function ‘gui.algorithmwidget.isNotNone’ undocumented

rearrangeWidgets(layout, widgets, targetWidth)[source]

Warning

function ‘gui.algorithmwidget.rearrangeWidgets’ undocumented

mcsas.gui.calc module
class Calculator[source]

Bases: utils.hdf.HDFMixin

algo
hdfLoad(filehandle)[source]

load a calculator configuration

hdfWrite(hdf)[source]

write a calculator configuration.

indent = ' '
isStopped()[source]

Warning

method ‘gui.calc.Calculator.isStopped’ undocumented

model
modelActiveParams()[source]

Warning

method ‘gui.calc.Calculator.modelActiveParams’ undocumented

modelParams()[source]

Warning

method ‘gui.calc.Calculator.modelParams’ undocumented

nolog = False
postProcess()[source]

Warning

method ‘gui.calc.Calculator.postProcess’ undocumented

prepare()[source]

Resets series data. Supposed to be called before each run of multiple __call__() invokations.

stop()[source]

Warning

method ‘gui.calc.Calculator.stop’ undocumented

class OutputFilename(dataset, createDir=True)[source]

Bases: object

Generates output filenames with a common time stamp and logs appropriate messages.

basename
filename(kind=None, extension='.txt')[source]

Creates a file name from data base name, its directory and the current timestamp. It’s created once so that all output files have the same base name and timestamp.

filenameVerbose(kind, descr, extension='.txt')[source]

Returns the file name as in filename() and logs a descriptive message containing the full file name which is usually click-able.

outDir
timestamp
cfgwrite(self, fp)[source]

Write an .ini-format representation of the configuration state.

mcsas.gui.datawidget module
class DataWidget(parent, appSettings)[source]

Bases: QWidget, gui.bases.mixins.appsettings.AppSettings

buildUi(dataobj)[source]

Warning

method ‘gui.datawidget.DataWidget.buildUi’ undocumented

clearUi()[source]

Warning

method ‘gui.datawidget.DataWidget.clearUi’ undocumented

makeConfigUi(config)[source]

Warning

method ‘gui.datawidget.DataWidget.makeConfigUi’ undocumented

onBackendUpdate()[source]

Warning

method ‘gui.datawidget.DataWidget.onBackendUpdate’ undocumented

onDataSelected(dataobj)

Warning

method ‘gui.datawidget.DataWidget.onDataSelected’ undocumented

onEmptyDataList()[source]

Forgets which data settings were already restored.

restoreSession()[source]

Warning

method ‘gui.datawidget.DataWidget.restoreSession’ undocumented

sigConfig
storeSession()[source]

Warning

method ‘gui.datawidget.DataWidget.storeSession’ undocumented

mcsas.gui.filelist module
class FileList(parent=None, title=None, withBtn=True, nestedItems=True)[source]

Bases: gui.bases.datalist.DataList

configFromLast()[source]

Get the data config of the last item in the list.

itemDoubleClicked(item, column)[source]

Warning

method ‘gui.filelist.FileList.itemDoubleClicked’ undocumented

loadData(fileList=None)[source]

Warning

method ‘gui.filelist.FileList.loadData’ undocumented

setDataConfig(dataConfig)[source]

Propagates the given DataConfig to all DataObj in the list. Makes sure that all data sets have the same configuration finally. Disable this in order to have individual per-data-set configuration.

setupUi()[source]

Warning

method ‘gui.filelist.FileList.setupUi’ undocumented

sigSphericalSizeRange
mcsas.gui.liststyle module
makeAlternatingRowColorsTransparent(widget)[source]

Warning

function ‘gui.liststyle.makeAlternatingRowColorsTransparent’ undocumented

setBackgroundStyleSheet(widget, imgpath)[source]

Warning

function ‘gui.liststyle.setBackgroundStyleSheet’ undocumented

mcsas.gui.mainwindow module
class MainWindow(parent=None, args=None)[source]

Bases: gui.bases.mainwindow.mainwindow.MainWindow

calc()[source]

Warning

method ‘gui.mainwindow.MainWindow.calc’ undocumented

calculator

Returns a calculator object.

closeEvent(closeEvent)[source]

Warning

method ‘gui.mainwindow.MainWindow.closeEvent’ undocumented

fileDialog()[source]

Warning

method ‘gui.mainwindow.MainWindow.fileDialog’ undocumented

initUi()[source]

Warning

method ‘gui.mainwindow.MainWindow.initUi’ undocumented

keyPressEvent(keyEvent)[source]

Warning

method ‘gui.mainwindow.MainWindow.keyPressEvent’ undocumented

onCloseSignal
onStartStopClick(checked)[source]

Warning

method ‘gui.mainwindow.MainWindow.onStartStopClick’ undocumented

restoreSettings()[source]

Warning

method ‘gui.mainwindow.MainWindow.restoreSettings’ undocumented

setupUi(*args)[source]

Warning

method ‘gui.mainwindow.MainWindow.setupUi’ undocumented

storeSettings()[source]

Warning

method ‘gui.mainwindow.MainWindow.storeSettings’ undocumented

class ToolBox(*args, **kwargs)[source]

Bases: QToolBox

QToolBox containing the widgets for user settings. Used to propagate resize events to child widgets to enable responsive behaviour. On MacOS, fixes failed detection of size changes in child widget due to scroll area.

resizeEvent(event)[source]

Warning

method ‘gui.mainwindow.ToolBox.resizeEvent’ undocumented

eventLoop(args)[source]

Starts the UI event loop and get command line parser arguments.

mcsas.gui.modelwidget module
class ModelWidget(parent, calculator, *args)[source]

Bases: gui.algorithmwidget.AlgorithmWidget

algorithm
model
onDataSelected(dataobj)[source]

Gets the data which is currently selected in the UI and rebuilds the model selection box based on compatible models.

restoreSession(model=None)[source]

Load last known user settings from persistent app settings.

selectModel(model)[source]

model: string containing the name of the model to select. Calls _selectModelSlot() via signal.

setSphericalSizeRange(minVal, maxVal)[source]

Warning

method ‘gui.modelwidget.ModelWidget.setSphericalSizeRange’ undocumented

setStatsWidget(statsWidget)[source]

Sets the statistics widget to use for updating ranges.

storeSession(section=None)[source]

Warning

method ‘gui.modelwidget.ModelWidget.storeSession’ undocumented

mcsas.gui.optimizationwidget module
class OptimizationWidget(*args)[source]

Bases: gui.algorithmwidget.AlgorithmWidget

onDataSelected(dataobj)[source]

Sets defaults for certain types of DataConfig selected, respectively fixes some values.

resizeWidgets(targetWidth)[source]

Creates a new layout with appropriate row/column count.

restoreSession(*args, **kwargs)[source]

Warning

method ‘gui.optimizationwidget.OptimizationWidget.restoreSession’ undocumented

storeSession(*args, **kwargs)[source]

Warning

method ‘gui.optimizationwidget.OptimizationWidget.storeSession’ undocumented

uiWidgets
mcsas.gui.qt module
mcsas.gui.rangelist module
class RangeDialog(parent=None, model=None)[source]

Bases: QDialog

Creates a modal dialog window to ask the user for a range to be added.

output()[source]

Warning

method ‘gui.rangelist.RangeDialog.output’ undocumented

class RangeList(calculator=None, appSettings=None, **kwargs)[source]

Bases: gui.bases.datalist.DataList, gui.bases.mixins.appsettings.AppSettings

append(histList)[source]

Warning

method ‘gui.rangelist.RangeList.append’ undocumented

editEntry()[source]

Warning

method ‘gui.rangelist.RangeList.editEntry’ undocumented

itemUpdate(item, column)[source]

Warning

method ‘gui.rangelist.RangeList.itemUpdate’ undocumented

loadData(ranges=None)[source]

Overridden base class method for adding entries to the list.

mouseDoubleClickEvent(event)[source]

Shows RangeDialog on double click.

onRemoval(removedHistograms)[source]

Warning

method ‘gui.rangelist.RangeList.onRemoval’ undocumented

recalc()[source]

Warning

method ‘gui.rangelist.RangeList.recalc’ undocumented

restoreSession()[source]

Load last known user settings from persistent app settings.

setupUi()[source]

Warning

method ‘gui.rangelist.RangeList.setupUi’ undocumented

storeSession()[source]

Warning

method ‘gui.rangelist.RangeList.storeSession’ undocumented

updateHistograms()[source]

Called after UI update by sigBackendUpdated from an AlgorithmWidget.

getItemIndex(comboBox, text)[source]

Warning

function ‘gui.rangelist.getItemIndex’ undocumented

mcsas.gui.scientrybox module
class SciEntryBox(parent=None)[source]

Bases: QLineEdit

fmt
indicateCorrectness(isValid)[source]

Warning

method ‘gui.scientrybox.SciEntryBox.indicateCorrectness’ undocumented

static numberFormat(decimals=None)[source]

Warning

method ‘gui.scientrybox.SciEntryBox.numberFormat’ undocumented

setMaximum(value)[source]

Work around issues regarding round-off errors by the ‘g’ format type when comparing numbers from user input with calculation results.

setMinimum(value)[source]

Work around issues regarding round-off errors by the ‘g’ format type when comparing numbers from user input with calculation results.

setPrefix(value)[source]

Warning

method ‘gui.scientrybox.SciEntryBox.setPrefix’ undocumented

setRange(lo, hi)[source]

Warning

method ‘gui.scientrybox.SciEntryBox.setRange’ undocumented

setValue(value)[source]

Warning

method ‘gui.scientrybox.SciEntryBox.setValue’ undocumented

toolTipFmt = 'A value between {lo} and {hi} (including).'
classmethod updateToolTip(widget, decimals=None)[source]

Warning

method ‘gui.scientrybox.SciEntryBox.updateToolTip’ undocumented

value()[source]

Warning

method ‘gui.scientrybox.SciEntryBox.value’ undocumented

class SciEntryValidator(parent=None)[source]

Bases: QDoubleValidator

Assumes the associated QLineEdit is provided as parent object in the constructor.

fixup(input)[source]

Restricts the value to the valid range defined by setTop() and setBottom(). Limits the precision as well.

validate(input, pos)[source]

Warning

method ‘gui.scientrybox.SciEntryValidator.validate’ undocumented

mcsas.gui.settingsgroup module
class AdvancedSettings(*args, **kwargs)[source]

Bases: gui.settingsgroup.SettingsGroup, QGroupBox

showAdvanced(show=False)[source]

Warning

method ‘gui.settingsgroup.AdvancedSettings.showAdvanced’ undocumented

updateWidgets(widget=None)[source]

Warning

method ‘gui.settingsgroup.AdvancedSettings.updateWidgets’ undocumented

class DefaultSettings(*args, **kwargs)[source]

Bases: gui.settingsgroup.SettingsGroup, QWidget

class SettingsGroup(*args, **kwargs)[source]

Bases: object

rearrangeWidgets(targetWidth)[source]

Warning

method ‘gui.settingsgroup.SettingsGroup.rearrangeWidgets’ undocumented

mcsas.gui.version module

Module contents

mcsas.log package

Submodules

mcsas.log.log module

Interface and convenience methods for general logging.

addHandler(handler)[source]

Set up a new handler and add it for logging.

formatter()[source]

Date and time format for logging, ISO 8601:2004

removeHandler(handler)[source]

Warning

function ‘log.log.removeHandler’ undocumented

replaceHandler(handler)[source]

Warning

function ‘log.log.replaceHandler’ undocumented

replaceStdOutErr(sout=None, serr=None)[source]

Replaces stdout/err with calls to logging.info/error.

timestamp()[source]

Current local time in seconds.

timestampFormat()[source]

Format for current local time, suitable for file names. >>> timestampFormat() ‘%Y-%m-%d_%H-%M-%S’

timestampFormatted(ts=None)[source]

Current local time. >>> timestamp() == time.strftime(“%Y-%m-%d_%H-%M-%S”) True

mcsas.log.sink module

Interface and convenience methods for general logging.

class Sink[source]

Bases: object

buf = None
flush()[source]

Warning

method ‘log.sink.Sink.flush’ undocumented

process(msg, func)[source]

Warning

method ‘log.sink.Sink.process’ undocumented

class StdErrSink[source]

Bases: log.sink.Sink

write(msg)[source]

Warning

method ‘log.sink.StdErrSink.write’ undocumented

class StdOutSink[source]

Bases: log.sink.Sink

write(msg)[source]

Warning

method ‘log.sink.StdOutSink.write’ undocumented

mcsas.log.widgethandler module
class WidgetHandler(widget)[source]

Bases: logging.Handler

A logging.Handler which appends messages to some widget.append().

>>> import logging
>>> from PyQt4.QtGui import QPlainTextEdit
>>> from utilsgui import DialogInteraction
>>> from logdock import LogHandler
>>> pte = DialogInteraction.instance(QPlainTextEdit)
>>> handler = LogHandler(pte)
>>> msg = "testest"
>>> handler.emit(logging.LogRecord("", 0, "", 0, msg, (), None))
>>> str(pte.toPlainText()) == msg
True
emit(record)[source]

Warning

method ‘log.widgethandler.WidgetHandler.emit’ undocumented

widget

Module contents

getWidgetHandlers()[source]

Returns all active WidgetHandlers for logging.

mcsas.utils package

Submodules

mcsas.utils.binning module
  • binningArray(): Can be used to do n-by-n pixel binning of 2D detector images. The returned uncertainty is the larger of either the binned uncertainty or the sample standard deviation in the bin.
  • binning1d(): bins the data and propagates errors, or calculates errors if not initially provided
  • binningWeighted1d(): Weighted binning, where the intensities of a pixel are divided between the two neighbouring bins depending on the distances to the centres. If error provided is empty, the standard deviation of the intensities in the bins are computed.
array(value)

Warning

function ‘utils.binning.array’ undocumented

binning1d(q, intensity, error=None, numBins=200, stats='std')[source]

An unweighted binning routine. The intensities are sorted across bins of equal size. If provided error is empty, the standard deviation of the intensities in the bins are computed.

binningArray(q, psi, intensity, error, s=2)[source]

This function applies a simple s-by-s binning routine on images. It calculates new error based on old error superseded by standard deviation in a bin.

binningWeighted1d(q, intensity, error=None, numBins=200, stats='se')[source]

Implementation of the binning routine written in Matlab. The intensities are divided across the q-range in bins of equal size. The intensities of a pixel are divided between the two neighbouring bins depending on the distances to the centres. If error provided is empty, the standard deviation of the intensities in the bins are computed.

Usage:

qbin, ibin, ebin = binning_weighted_1d(q, intensity, error = [],
                                       numBins = 200, stats = 'se')

Optional input arguments:

numBins: integer indicating the number of bins to divide the intensity
over. Alternatively, this can be an array of equidistant bin centres. If you go this route, depending on the range, not all intensity may be counted.
stats: Can be set to ‘auto’. This takes the maximum error between
supplied Poisson statistics error-based errors or the standard error.

Written by Brian R. Pauw, 2011, released under BSD open source license.

mcsas.utils.classproperty module
class classproperty[source]

Bases: property

Subclass property to make classmethod properties possible.

Use it like this:

@classproperty
@classmethod
def var(cls):
    <code>

Getters only, see http://stackoverflow.com/questions/128573/using-property-on-classmethods

mcsas.utils.devtools module

Definitions used during development only. This module is supposed to not being required in a release package.

DBG(*args, **kwargs)[source]

Warning

function ‘utils.devtools.DBG’ undocumented

DBGF(*args)[source]

Warning

function ‘utils.devtools.DBGF’ undocumented

mcsas.utils.error module

Some Error classes.

exception AppError(msg='')[source]

Bases: Exception

classmethod getMessage(msg='')[source]

Warning

method ‘utils.error.AppError.getMessage’ undocumented

msg = ''

General error with descriptive message to be forwarded and shown to the user in a message box.

exception EmptySelection(msg='')[source]

Bases: utils.error.AppError

exception FileError(msg, fn)[source]

Bases: utils.error.AppError

exception InitError(msg='')[source]

Bases: utils.error.AppError

exception LoadError(msg='')[source]

Bases: utils.error.AppError

exception VerboseError[source]

Bases: utils.error.AppError

Verbose Exception containing class and method where it was raised. A cache makes sure VerboseErrors with the same name can be matched.

classmethod new(name, msg='')[source]

Creates an exception dynamically. Remembers previous ones for testing

classmethod prefix(msg)[source]

Retrieves some meta info to decribe the error further.

mcsas.utils.findmodels module

For use in gui/modelwidget.py, to help find valid calculation models

class FindModels(*searchPaths)[source]

Bases: object

Finds all methods of type ScatteringModel in the subdirectories starting from searchPath. searchPath defaults to the root mcsas pwd + “models”. returns a list of full paths, and a list of associated model names

classmethod candidateFiles(*searchPaths)[source]

Warning

method ‘utils.findmodels.FindModels.candidateFiles’ undocumented

classmethod getSearchPaths()[source]

Warning

method ‘utils.findmodels.FindModels.getSearchPaths’ undocumented

classmethod libraryPath()[source]

Warning

method ‘utils.findmodels.FindModels.libraryPath’ undocumented

classmethod rootName()[source]

Warning

method ‘utils.findmodels.FindModels.rootName’ undocumented

classproperty(func)

Warning

function ‘utils.findmodels.classproperty’ undocumented

findFiles(searchPath, extension)[source]

generator for files ending in .py code from: http://stackoverflow.com/questions/2186525

reorder(indata, priorityKeys)[source]

Warning

function ‘utils.findmodels.reorder’ undocumented

mcsas.utils.hdf module

Helper functions for HDF5 functionality

HDFCleanup(infile)[source]

Unused space is reclaimed by making a copy of the contents in the current hdf 5 file object, and moves the copy in place of the original. if the input argument supplied is a file name instead of an HDF5 object, the method returns nothing. Else, the method returns the new HDF5 object

class HDFMixin[source]

Bases: object

classmethod hdfLoad()[source]

Restores an instance of this type from a given HDF file location or group.

hdfStore(filename, rootLocation=None)[source]

Writes itself to an HDF file at the given position or group.

hdfWrite(hdf)[source]

To be overridden by sub classes to store themselves in an HDF structure. hdf: a HDFWriter instance.

class HDFWriter(hdfHandle, rootLocation=None)[source]

Bases: object

Represents an open HDF file location in memory and keeps track of the current address/name for reading or writing. Once this object looses scope, its data is actually written to file.

location
log(msg)[source]

Warning

method ‘utils.hdf.HDFWriter.log’ undocumented

classmethod open(filename, rootLocation=None)[source]

Warning

method ‘utils.hdf.HDFWriter.open’ undocumented

writeAttribute(key, value)[source]

Warning

method ‘utils.hdf.HDFWriter.writeAttribute’ undocumented

writeAttributes(**kwargs)[source]

Warning

method ‘utils.hdf.HDFWriter.writeAttributes’ undocumented

writeDataset(name, data)[source]

Warning

method ‘utils.hdf.HDFWriter.writeDataset’ undocumented

writeMember(obj, memberName)[source]

Warning

method ‘utils.hdf.HDFWriter.writeMember’ undocumented

writeMembers(obj, *members)[source]

Warning

method ‘utils.hdf.HDFWriter.writeMembers’ undocumented

getCallerInfo(referenceType=None, stackOffset=0)[source]

referenceType: Stop the search for a frame when this type for a local ‘self’ is found. stackOffset: grab that frame counted from the last instead of search

mcsas.utils.lastpath module

General utilities without GUI dependencies.

class LastPath[source]

Bases: object

Stores a file system path for use in file open dialogs.

How to test this platform independent? >>> from utils import LastPath, getHomeDir >>> LastPath.path == getHomeDir() True >>> LastPath.path = ‘.’ >>> LastPath.path == ‘.’ True

classmethod get()[source]

Warning

method ‘utils.lastpath.LastPath.get’ undocumented

classmethod set(lastpath)[source]

Accepts a directory path or a file path. Determines the directory itself in the latter case.

getHomeDir()[source]

Warning

function ‘utils.lastpath.getHomeDir’ undocumented

mcsas.utils.loadstore module
  • pickleLoad(): Reads in pickled data from a file (by filename)
  • pickleStore(): write a block or dictionary to a file (by filename)
pickleLoad(filename)[source]

Loads data from a pickle file

pickleStore(filename, somedata)[source]

Writes python object to a file.

mcsas.utils.mixedmethod module

This module implements a mixedmethod() decorator for class definitions. Basic idea found here: http://www.daniweb.com/software-development/python/code/406393/mixedmethod-mixes-class-and-instance-method-into-one

Usually, a class method works for an instance only. If decorated with @classmethod it works for the class/type and for the instance but ignores all instance data and works with the class data only. Methods in a class decorated with @mixedmethod work with class/type and instances in the same way BUT if the underlying object is a class/type it works on the class/type data. If the underlying object is an instance it works on the instance data. Thus, for instances modifications apply to that individual instance only. For classes modifications apply on the class level which applies changes to all instances created from that.

class mixedmethod(func)[source]

Bases: object

This decorator mutates a function defined in a class into a ‘mixed’ class and instance method. Usage:

class Spam:
    @mixedmethod
    def egg(selforcls, *args, **kwargs):
        # selforcls is the instance when called on an instance
        # selforcls is the class when called on the class
        pass
mcsas.utils.parameter module
FitParameter(*args, **kwargs)[source]

Warning

function ‘utils.parameter.FitParameter’ undocumented

class FitParameterBase[source]

Bases: bases.algorithm.parameter.ParameterBase

Deriving parameters for curve fitting from bases.algorithm.parameter to introduce more specific fit related attributes.

activeRange = functools.partial(<function FitParameterBase.activeRange>, <class 'utils.parameter.FitParameterBase'>)
activeVal = functools.partial(<function FitParameterBase.activeVal>, <class 'utils.parameter.FitParameterBase'>)
activeValues = functools.partial(<function _makeGetter.<locals>.getter>, <class 'utils.parameter.FitParameterBase'>)
displayActiveRange = functools.partial(<function FitParameterBase.displayActiveRange>, <class 'utils.parameter.FitParameterBase'>)
hdfStoreAsMember()[source]

Warning

method ‘utils.parameter.FitParameterBase.hdfStoreAsMember’ undocumented

histograms = functools.partial(<function _makeGetter.<locals>.getter>, <class 'utils.parameter.FitParameterBase'>)
isActive = functools.partial(<function _makeGetter.<locals>.getter>, <class 'utils.parameter.FitParameterBase'>)
setActive = functools.partial(<function FitParameterBase.setIsActive>, <class 'utils.parameter.FitParameterBase'>)
setActiveRange = functools.partial(<function FitParameterBase.setActiveRange>, <class 'utils.parameter.FitParameterBase'>)
setActiveVal = functools.partial(<function FitParameterBase.setActiveVal>, <class 'utils.parameter.FitParameterBase'>)
setActiveValues = functools.partial(<function _makeSetter.<locals>.setter>, <class 'utils.parameter.FitParameterBase'>)
setDisplayActiveRange = functools.partial(<function FitParameterBase.setDisplayActiveRange>, <class 'utils.parameter.FitParameterBase'>)
setHistograms = functools.partial(<function _makeSetter.<locals>.setter>, <class 'utils.parameter.FitParameterBase'>)
setIsActive = functools.partial(<function FitParameterBase.setIsActive>, <class 'utils.parameter.FitParameterBase'>)
setValueRange = functools.partial(<function FitParameterBase.setValueRange>, <class 'utils.parameter.FitParameterBase'>)
class FitParameterBoolean[source]

Bases: utils.parameter.FitParameterBase, bases.algorithm.parameter.ParameterBoolean

class FitParameterFloat[source]

Bases: utils.parameter.FitParameterNumerical, bases.algorithm.parameter.ParameterFloat

class FitParameterLog[source]

Bases: utils.parameter.FitParameterBase, bases.algorithm.parameter.ParameterLog

class FitParameterNumerical[source]

Bases: utils.parameter.FitParameterBase, bases.algorithm.parameter.ParameterNumerical

generate(lower=None, upper=None, count=1)[source]

Warning

method ‘utils.parameter.FitParameterNumerical.generate’ undocumented

class FitParameterString[source]

Bases: utils.parameter.FitParameterBase, bases.algorithm.parameter.ParameterString

class Histogram(param, lower, upper, binCount=50, xscale=None, yweight=None, autoFollow=True)[source]

Bases: bases.dataset.dataset.DataSet, bases.dataset.dataset.DisplayMixin

Stores histogram related settings of a parameter. The results too, eventually(?). yes, please. Stores&calculates rangeInfo() results for all available weighting options.

Creates an histogram with default bin count, will be updated later.

autoFollow
binCount
bins
calc(contribs, paramIndex, fractions)[source]

Warning

method ‘utils.parameter.Histogram.calc’ undocumented

cdf
classmethod displayData()[source]

Properties used for UI display.

classmethod displayDataDescr()[source]

Descriptive text of fields for UI display.

hdfWrite(hdf)[source]

Warning

method ‘utils.parameter.Histogram.hdfWrite’ undocumented

classmethod integralProps()[source]

All properties needed to properly serialize and restore this histogram. Same order expected by the constructor.

lower
lowerDisplay

Lower limit in display units including the unit text.

moments
observability
param
paramName
updateRange()[source]

Restricts histogram range according to changed parameter range if needed. Checks histogram range against parameter limits.

upper
upperDisplay

Upper limit in display units including the unit text.

xLowerEdge
xMean
xWidth
xrange
xscale
static xscaling(index=None)[source]

Warning

method ‘utils.parameter.Histogram.xscaling’ undocumented

yweight
static yweighting(index=None)[source]

Warning

method ‘utils.parameter.Histogram.yweighting’ undocumented

class Histograms[source]

Bases: list

Manages a set of user configured histograms for evaluation after monte-carlo run.

append(value)[source]

Warning

method ‘utils.parameter.Histograms.append’ undocumented

calc(*args)[source]

Warning

method ‘utils.parameter.Histograms.calc’ undocumented

clear()[source]

Warning

method ‘utils.parameter.Histograms.clear’ undocumented

hdfWrite(hdf)[source]

Warning

method ‘utils.parameter.Histograms.hdfWrite’ undocumented

updateRanges()[source]

Updates ranges of all histograms.

class Moments(contribs, paramIndex, valueRange, fraction, algo=None)[source]

Bases: object

static fieldNames()[source]

Returns the field names in the same order as str()

fields

Tuple of member data incl. uncertainty for export.

intensity
kurtosis
mean
skew
total
varName = '_kurtosis'
variance
Parameter(*args, **kwargs)

Warning

function ‘utils.parameter.Parameter’ undocumented

class VectorResult(vecResult)[source]

Bases: object

Stores multiple populations of a single result data vector. Calculates statistics at initialization.

full
mean
std
classproperty(func)

Warning

function ‘utils.parameter.classproperty’ undocumented

isActiveFitParam(param)[source]

Checks any type of parameter for activeness. Shorter than that below or a try/except clause.

isFitParam(param)[source]

Warning

function ‘utils.parameter.isFitParam’ undocumented

mcsas.utils.pickleinstancemethods module
mcsas.utils.propertynames module
class PropertyNames[source]

Bases: object

classmethod propNames()[source]

Warning

method ‘utils.propertynames.PropertyNames.propNames’ undocumented

classmethod properties()[source]

Returns all attributes configured in this class.

mcsas.utils.tests module

Utils for testing something.

assertName(newName, errorType, noWhitespace=False)[source]

Warning

function ‘utils.tests.assertName’ undocumented

isCallable(obj)[source]

Warning

function ‘utils.tests.isCallable’ undocumented

isFrozen()[source]

Warning

function ‘utils.tests.isFrozen’ undocumented

isInteger(obj)[source]

Warning

function ‘utils.tests.isInteger’ undocumented

isLinux()[source]

Warning

function ‘utils.tests.isLinux’ undocumented

isList(obj)[source]

Warning

function ‘utils.tests.isList’ undocumented

isMac()[source]

Warning

function ‘utils.tests.isMac’ undocumented

isMap(obj)[source]

Warning

function ‘utils.tests.isMap’ undocumented

isNonEmptyString(obj)[source]

Warning

function ‘utils.tests.isNonEmptyString’ undocumented

isNumber(obj)[source]

Warning

function ‘utils.tests.isNumber’ undocumented

isSet(obj)[source]

Warning

function ‘utils.tests.isSet’ undocumented

isString(obj)[source]

Warning

function ‘utils.tests.isString’ undocumented

isWindows()[source]

Warning

function ‘utils.tests.isWindows’ undocumented

testfor(condition, exception, errorMessage='')[source]

Warning

function ‘utils.tests.testfor’ undocumented

mcsas.utils.units module

Defines methods for using and manipulating units of variables. Some default magnitude-name dictionaries are provided, but the user can supply their own dictionary if required. Default unit to translate to must be set. Required keyword arguments:

  • magnitudedict: a dictionary of magnitude - name pairs. Names must be
    unicode strings.
  • simagnitudename: the si magnitude name.

Example usage:

>>> rUnit = Length("nm")
>>> rUnit.siMagnitudeName
u'm'
>>> rUnit.displayMagnitudeName
u'nm'
>>> rUnit.magnitudeConversion
1e-09

or:

>>> rUnit.toSi(32)
3.2e-08

Selecting a default:

>>> qUnit = ScatteringVector(u"cm⁻¹")
>>> qUnit.magnitudeConversion
100.0
class Angle(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class Area(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class DynamicViscosity(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class Fraction(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class Length(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class NoUnit(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class SLD(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class ScatteringIntensity(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class ScatteringVector(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class Temperature(magnitudeName=None)[source]

Bases: utils.units.Unit

test case for special conversions. Done by redefining toSI and toDisplay. Implemented units are given in _magnitudeMap.

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

magnitudeConversion
toDisplay(value)[source]

Warning

method ‘utils.units.Temperature.toDisplay’ undocumented

toSi(value)[source]

Warning

method ‘utils.units.Temperature.toSi’ undocumented

class Time(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

class Unit(magnitudeName=None)[source]

Bases: object

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

availableMagnitudeNames
displayMagnitude
displayMagnitudeName
hdfWrite(hdf)[source]

Warning

method ‘utils.units.Unit.hdfWrite’ undocumented

static invName(unitString)[source]

Adds an ⁻¹ sign or removes it if already present

classmethod magnitude(name)[source]

Returns a (numerical) magnitude matching a magnitude name

magnitudeConversion

Scaling factor to move from display magnitude to si units. Required display argument:

displaymagnitudename : The name of the magnitude to convert from

Optional display argument:

simagnitudename : The name of the magnitude to convert to.
Defaults to self.siMagnitudeName
Returns:
float : A scaling factor for display unit to scale to si unit.
magnitudeMapping = {}
classmethod name()[source]

Warning

method ‘utils.units.Unit.name’ undocumented

siMagnitude = ''
siMagnitudeName = ''
toDisplay(value)[source]

Warning

method ‘utils.units.Unit.toDisplay’ undocumented

toSi(value)[source]

Warning

method ‘utils.units.Unit.toSi’ undocumented

class Volume(magnitudeName=None)[source]

Bases: utils.units.Unit

Set up a unit of measurement. The provided magnitude name is used by default in the UI. Using SI units if unspecified.

Module contents

classname(obj)[source]

Warning

function ‘utils.classname’ undocumented

classproperty(func)

Warning

function ‘utils.classproperty’ undocumented

clip(value, minv, maxv)[source]

Expects a range tuple or list consisting of lower and upper limits.

fixFilename(filename)[source]

Works around Windows file path length limitation of 260 chars.

hashNumpyArray(arr)[source]

Warning

function ‘utils.hashNumpyArray’ undocumented

mcopen(fn, mode, encoding='utf8')[source]

Warning

function ‘utils.mcopen’ undocumented

mcsas.datafile package

Submodules

mcsas.datafile.arrayfile module
class ArrayFile(filename, **kwargs)[source]

Bases: datafile.asciifile.AsciiFile

A data file containing a single array of data, mostly.

classmethod fileFilter()[source]

Warning

method ‘datafile.arrayfile.ArrayFile.fileFilter’ undocumented

getDataObj()[source]

Warning

method ‘datafile.arrayfile.ArrayFile.getDataObj’ undocumented

parseLines(asciiLines, **kwargs)[source]

Parses lines of an ASCII file in order to extract a single array of numbers. Reimplement this in subclasses for different behaviour.

rawArray
classproperty(func)

Warning

function ‘datafile.arrayfile.classproperty’ undocumented

np_array(value)

Warning

function ‘datafile.arrayfile.np_array’ undocumented

mcsas.datafile.asciifile module
class AsciiFile(filename, **kwargs)[source]

Bases: datafile.datafile.DataFile

A generic ascii data file.

classmethod appendFile(filename, data, **kwargs)[source]

like writeFile but appends data to an existing file

classmethod appendHeaderLine(filename, header)[source]

writes a single-line header to a file consisting of a string or tuple of strings to be joined

classmethod formatData(data, **kwargs)[source]

Warning

method ‘datafile.asciifile.AsciiFile.formatData’ undocumented

classmethod formatRow(row, **kwargs)[source]

Warning

method ‘datafile.asciifile.AsciiFile.formatRow’ undocumented

classmethod formatValue(value)[source]

Warning

method ‘datafile.asciifile.AsciiFile.formatValue’ undocumented

newline = '\n'
parseLines(asciiLines, **kwargs)[source]

Parses lines of an ASCII file in order to extract a single array of numbers. Reimplement this in subclasses for different behaviour.

readArray(asciiLines, dataType=<class 'float'>, startLine=0, endLine=None, **kwargs)[source]

Reads a numpy.array from a specified segment (startLine, endLine) of a line buffer given by asciiLines. Stops at lines incompatible to previous lines read due to different number of fields or incompatible data type. Returns the last line successfully parsed and the populated numpy.array.

readFile(**kwargs)[source]

Warning

method ‘datafile.asciifile.AsciiFile.readFile’ undocumented

readTuple(fields, dataType=<class 'float'>, **kwargs)[source]

Converts each field to the requested datatype. Raises an error if it is incompatible, the line is skipped in that case.

separator = ' '
valueFormat = '{0: 14.6E}'
classmethod writeFile(filename, data, **kwargs)[source]

Warning

method ‘datafile.asciifile.AsciiFile.writeFile’ undocumented

classmethod writeHeaderLine(filename, header)[source]

writes a single-line header to a file consisting of a string or tuple of strings to be joined

np_array(value)

Warning

function ‘datafile.asciifile.np_array’ undocumented

mcsas.datafile.datafile module
class DataFile(filename, **kwargs)[source]

Bases: object

Base class for handling data files. Can be initialized with a file (name) to read or with a data array.

Test error behaviour >>> from utils import DataFile, getTempFileName, getTempFile, FileNotFound >>> fn = getTempFileName() >>> try: DataFile.checkFilename(fn) ... except FileNotFound, e: str(e).find(fn) > 0 True

Prepare test data file >>> fd = getTempFile() >>> l = [‘123 234n’, ‘1,23 43.4rn’, ‘2.3; 34,4n’, ... ‘21.2 42 2n’, ‘23,2 3.4 n’] >>> fd.writelines(l) >>> fd.close()

Test data parsing >>> df = DataFile() >>> df.loadFile(fd.name) [(‘123’, ‘234’), (‘1.23’, ‘43.4’), (‘2.3’, ‘34.4’), (‘21.2’, ‘42’, ‘2’), (‘23.2’, ‘3.4’)]

Remove test data finally >>> import os >>> if os.path.isfile(fd.name): ... os.remove(fd.name)

classmethod extensions()[source]

Warning

method ‘datafile.datafile.DataFile.extensions’ undocumented

fileFilter

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
def f(cls, arg1, arg2, ...): ... f = classmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

filename

Absolute path name of this file.

getDataObj()[source]

Creates and returns the appropriate DataObj instance for this file type.

name

The plain name of the file with path and extension stripped.

readFile(**kwargs)[source]

Gets a proper file name and returns file data. May modify the instance. To be reimplemented.

static sanitizeReadFilename(filename)[source]

Checks provided filename for plausibility and updates LastPath.

classmethod sanitizeWriteFilename(filename)[source]

Checks and sets the file name to write to.

setFilename(filename)[source]

Checks provided filename for plausibility and updates LastPath

write(filename, **kwargs)[source]

Warning

method ‘datafile.datafile.DataFile.write’ undocumented

classmethod writeData(filename, data, **kwargs)[source]

Convenience method to write data directly to file.

classmethod writeFile(filename, data, **kwargs)[source]

Gets a proper file name and numpy array and writes it to file. Reimplement this.

classproperty(func)

Warning

function ‘datafile.datafile.classproperty’ undocumented

mcsas.datafile.nxcansasfile module
class NXSHeader(dataCount, description=None)[source]

Bases: object

line(index)[source]

Returns the specified line of the header as string.

classmethod maxLines()[source]

Warning

method ‘datafile.nxcansasfile.NXSHeader.maxLines’ undocumented

class NXcanSASFile(filename, **kwargs)[source]

Bases: datafile.datafile.DataFile

A NXcanSAS file, which is a NeXus-conform HDF5 file for storing corrected SAS data.

dataRoot
classmethod fileFilter()[source]

Warning

method ‘datafile.nxcansasfile.NXcanSASFile.fileFilter’ undocumented

classmethod getDataObj()[source]

Warning

method ‘datafile.nxcansasfile.NXcanSASFile.getDataObj’ undocumented

rawArray
readFile(**kwargs)[source]

Warning

method ‘datafile.nxcansasfile.NXcanSASFile.readFile’ undocumented

readItem(element)[source]

Warning

method ‘datafile.nxcansasfile.NXcanSASFile.readItem’ undocumented

classproperty(func)

Warning

function ‘datafile.nxcansasfile.classproperty’ undocumented

mcsas.datafile.pdhfile module
class PDHFile(filename, **kwargs)[source]

Bases: datafile.arrayfile.ArrayFile

classmethod fileFilter()[source]

Warning

method ‘datafile.pdhfile.PDHFile.fileFilter’ undocumented

classmethod formatData(data, description=None)[source]

Warning

method ‘datafile.pdhfile.PDHFile.formatData’ undocumented

parseLines(asciiLines, **kwargs)[source]

Warning

method ‘datafile.pdhfile.PDHFile.parseLines’ undocumented

class PDHHeader(dataCount, description=None)[source]

Bases: object

line(index)[source]

Returns the specified line of the header as string.

classmethod maxLines()[source]

Warning

method ‘datafile.pdhfile.PDHHeader.maxLines’ undocumented

classproperty(func)

Warning

function ‘datafile.pdhfile.classproperty’ undocumented

Module contents

class DataFile(filename, **kwargs)[source]

Bases: object

Base class for handling data files. Can be initialized with a file (name) to read or with a data array.

Test error behaviour >>> from utils import DataFile, getTempFileName, getTempFile, FileNotFound >>> fn = getTempFileName() >>> try: DataFile.checkFilename(fn) ... except FileNotFound, e: str(e).find(fn) > 0 True

Prepare test data file >>> fd = getTempFile() >>> l = [‘123 234n’, ‘1,23 43.4rn’, ‘2.3; 34,4n’, ... ‘21.2 42 2n’, ‘23,2 3.4 n’] >>> fd.writelines(l) >>> fd.close()

Test data parsing >>> df = DataFile() >>> df.loadFile(fd.name) [(‘123’, ‘234’), (‘1.23’, ‘43.4’), (‘2.3’, ‘34.4’), (‘21.2’, ‘42’, ‘2’), (‘23.2’, ‘3.4’)]

Remove test data finally >>> import os >>> if os.path.isfile(fd.name): ... os.remove(fd.name)

classmethod extensions()[source]

Warning

method ‘datafile.DataFile.extensions’ undocumented

fileFilter

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
def f(cls, arg1, arg2, ...): ... f = classmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

filename

Absolute path name of this file.

getDataObj()[source]

Creates and returns the appropriate DataObj instance for this file type.

name

The plain name of the file with path and extension stripped.

readFile(**kwargs)[source]

Gets a proper file name and returns file data. May modify the instance. To be reimplemented.

static sanitizeReadFilename(filename)[source]

Checks provided filename for plausibility and updates LastPath.

classmethod sanitizeWriteFilename(filename)[source]

Checks and sets the file name to write to.

setFilename(filename)[source]

Checks provided filename for plausibility and updates LastPath

write(filename, **kwargs)[source]

Warning

method ‘datafile.DataFile.write’ undocumented

classmethod writeData(filename, data, **kwargs)[source]

Convenience method to write data directly to file.

classmethod writeFile(filename, data, **kwargs)[source]

Gets a proper file name and numpy array and writes it to file. Reimplement this.

class AsciiFile(filename, **kwargs)[source]

Bases: datafile.datafile.DataFile

A generic ascii data file.

classmethod appendFile(filename, data, **kwargs)[source]

like writeFile but appends data to an existing file

classmethod appendHeaderLine(filename, header)[source]

writes a single-line header to a file consisting of a string or tuple of strings to be joined

classmethod formatData(data, **kwargs)[source]

Warning

method ‘datafile.AsciiFile.formatData’ undocumented

classmethod formatRow(row, **kwargs)[source]

Warning

method ‘datafile.AsciiFile.formatRow’ undocumented

classmethod formatValue(value)[source]

Warning

method ‘datafile.AsciiFile.formatValue’ undocumented

newline = '\n'
parseLines(asciiLines, **kwargs)[source]

Parses lines of an ASCII file in order to extract a single array of numbers. Reimplement this in subclasses for different behaviour.

readArray(asciiLines, dataType=<class 'float'>, startLine=0, endLine=None, **kwargs)[source]

Reads a numpy.array from a specified segment (startLine, endLine) of a line buffer given by asciiLines. Stops at lines incompatible to previous lines read due to different number of fields or incompatible data type. Returns the last line successfully parsed and the populated numpy.array.

readFile(**kwargs)[source]

Warning

method ‘datafile.AsciiFile.readFile’ undocumented

readTuple(fields, dataType=<class 'float'>, **kwargs)[source]

Converts each field to the requested datatype. Raises an error if it is incompatible, the line is skipped in that case.

separator = ' '
valueFormat = '{0: 14.6E}'
classmethod writeFile(filename, data, **kwargs)[source]

Warning

method ‘datafile.AsciiFile.writeFile’ undocumented

classmethod writeHeaderLine(filename, header)[source]

writes a single-line header to a file consisting of a string or tuple of strings to be joined

class ArrayFile(filename, **kwargs)[source]

Bases: datafile.asciifile.AsciiFile

A data file containing a single array of data, mostly.

classmethod fileFilter()[source]

Warning

method ‘datafile.ArrayFile.fileFilter’ undocumented

getDataObj()[source]

Warning

method ‘datafile.ArrayFile.getDataObj’ undocumented

parseLines(asciiLines, **kwargs)[source]

Parses lines of an ASCII file in order to extract a single array of numbers. Reimplement this in subclasses for different behaviour.

rawArray
class PDHFile(filename, **kwargs)[source]

Bases: datafile.arrayfile.ArrayFile

classmethod fileFilter()[source]

Warning

method ‘datafile.PDHFile.fileFilter’ undocumented

classmethod formatData(data, description=None)[source]

Warning

method ‘datafile.PDHFile.formatData’ undocumented

parseLines(asciiLines, **kwargs)[source]

Warning

method ‘datafile.PDHFile.parseLines’ undocumented

class PDHHeader(dataCount, description=None)[source]

Bases: object

line(index)[source]

Returns the specified line of the header as string.

classmethod maxLines()[source]

Warning

method ‘datafile.PDHHeader.maxLines’ undocumented

getFileFilter()[source]

Returns the file filter text of all available data file formats which can be used with a file selection dialog UI.

mcsas.dataobj package

Submodules

mcsas.dataobj.dataconfig module
class CallbackRegistry[source]

Bases: object

callback(what, *args, **kwargs)[source]

Warning

method ‘dataobj.dataconfig.CallbackRegistry.callback’ undocumented

callbackSlots
register(what, *func)[source]

Warning

method ‘dataobj.dataconfig.CallbackRegistry.register’ undocumented

class DataConfig[source]

Bases: bases.algorithm.algorithmbase.AlgorithmBase, dataobj.dataconfig.CallbackRegistry

callbackSlots
hdfWrite(hdf)[source]

Warning

method ‘dataobj.dataconfig.DataConfig.hdfWrite’ undocumented

is2d
onUpdatedX0(x0)[source]

Sets available range of loaded data.

onUpdatedX1(x1)[source]

Warning

method ‘dataobj.dataconfig.DataConfig.onUpdatedX1’ undocumented

parameters = (None, None, None, None, None, None, None, None)
sampleName
showParams
updateFMasks()[source]

Warning

method ‘dataobj.dataconfig.DataConfig.updateFMasks’ undocumented

updateFuMin()[source]

Warning

method ‘dataobj.dataconfig.DataConfig.updateFuMin’ undocumented

updateX0Limits()[source]

Warning

method ‘dataobj.dataconfig.DataConfig.updateX0Limits’ undocumented

updateX0Unit(newUnit)[source]

Sets the unit of the x0 vector.

updateX1Limits()[source]

Warning

method ‘dataobj.dataconfig.DataConfig.updateX1Limits’ undocumented

updateX1Unit(newUnit)[source]

Warning

method ‘dataobj.dataconfig.DataConfig.updateX1Unit’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘dataobj.dataconfig.Parameter’ undocumented

funcNotInFuncList(f, flst)[source]

Custom predicate for comparing bounded methods: Duplicate only if instance ID and method name match.

mcsas.dataobj.dataconfig_test module
assertDefaults(dc)[source]

Warning

function ‘dataobj.dataconfig_test.assertDefaults’ undocumented

testCallbacks()[source]

Warning

function ‘dataobj.dataconfig_test.testCallbacks’ undocumented

testLimits()[source]

Warning

function ‘dataobj.dataconfig_test.testLimits’ undocumented

testSerialize()[source]

Warning

function ‘dataobj.dataconfig_test.testSerialize’ undocumented

testSetter()[source]

Warning

function ‘dataobj.dataconfig_test.testSetter’ undocumented

mcsas.dataobj.dataobj module

Represents input data associated with a measurement.

class DataObj(**kwargs)[source]

Bases: abc.NewBase

General container for data loaded from file. It offers specialised methods to derive information from the provided data.

accumulate(others)[source]

Warning

method ‘dataobj.dataobj.DataObj.accumulate’ undocumented

config
configType

Returns a compatible DataConfig type.

count
f

The measurement vector.

filename
hasUncertainties

Returns True if this data set has an error bar for its intensities.

hdfWrite(hdf)[source]

Warning

method ‘dataobj.dataobj.DataObj.hdfWrite’ undocumented

initConfig()[source]

Initializes a new data configuration and sets the sample name which is used to differentiate different data objects of the same type later on.

is2d

Returns true if this dataset contains two-dimensional data with psi information available.

modelType

Returns a compatible ScatteringModel type.

sampleName
seriesKey

The Name of the DataObj property to use as series key, hard-coded for now, assuming it exists. It allows to let the user chose from a generated list of properties (todo).

seriesKeyName

Returns the docstring of the property defined by self.seriesKeyProp.

seriesKeyValue

Returns the value of the property defined by self.seriesKeyProp.

setConfig(config=None)[source]

Set the configuration of this data object if the type matches.

setFilename(fn)[source]

Stores the absolute path to this data file. Should be reviewed when data sets can be created from several files.

classmethod sourceName()[source]

Returns the name of the measurement method.

updateConfig()[source]

Updates the config object based on this data set. All callbacks are run right after this method in setConfig().

x0

First sampling vector.

x1

Second sampling vector.

x2

Third sampling vector.

classproperty(func)

Warning

function ‘dataobj.dataobj.classproperty’ undocumented

mcsas.dataobj.datavector module

A class describing a vector with limits, units, mask and uncertainties

class DataVector(name, raw, rawU=None, unit=None)[source]

Bases: object

a class for combining aspects of a particular vector of data. This is intended only as a storage container without additional functionality.

binnedData
binnedDataU
hdfWrite(hdf)[source]

Warning

method ‘dataobj.datavector.DataVector.hdfWrite’ undocumented

limit
limsString
name
rawData
rawDataU
sanitized
sanitizedU
siData
siDataU
unit
validIndices
mcsas.dataobj.sasconfig module
class GaussianSmearing[source]

Bases: dataobj.sasconfig.SmearingConfig

inputValid()[source]

Warning

method ‘dataobj.sasconfig.GaussianSmearing.inputValid’ undocumented

parameters = (None,)
setIntPoints(q)[source]

Sets smearing profile integration points for trapezoidal slit. Top (umbra) of trapezoid has full width xt, bottom of trapezoid (penumbra) has full width. Since the smearing function is assumed to be symmetrical, the integration parameters are calculated in the interval [0, xb/2]

showParams
updatePLimits(pLimit)[source]

Warning

method ‘dataobj.sasconfig.GaussianSmearing.updatePLimits’ undocumented

updatePUnit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.GaussianSmearing.updatePUnit’ undocumented

updateQLimits(qLimit)[source]

Warning

method ‘dataobj.sasconfig.GaussianSmearing.updateQLimits’ undocumented

updateQUnit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.GaussianSmearing.updateQUnit’ undocumented

updateSmearingLimits(q)[source]

Warning

method ‘dataobj.sasconfig.GaussianSmearing.updateSmearingLimits’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘dataobj.sasconfig.Parameter’ undocumented

class SASConfig(*args, **kwargs)[source]

Bases: dataobj.dataconfig.DataConfig

hdfWrite(hdf)[source]

Warning

method ‘dataobj.sasconfig.SASConfig.hdfWrite’ undocumented

onUpdatedX0(x0)[source]

Sets available range of loaded data.

onUpdatedX1(x1)[source]

Warning

method ‘dataobj.sasconfig.SASConfig.onUpdatedX1’ undocumented

prepareSmearing(q)[source]

Warning

method ‘dataobj.sasconfig.SASConfig.prepareSmearing’ undocumented

shortName = 'SAS data configuration'
showParams
smearing
updateX0Unit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.SASConfig.updateX0Unit’ undocumented

updateX1Unit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.SASConfig.updateX1Unit’ undocumented

class SmearingConfig[source]

Bases: bases.algorithm.algorithmbase.AlgorithmBase

Abstract base class, can’t be instantiated.

Creates instances from defined parameters and replaces the class attributes accordingly.

hdfWrite(hdf)[source]

Warning

method ‘dataobj.sasconfig.SmearingConfig.hdfWrite’ undocumented

parameters = (None, None, None)
prepared
qOffset
shortName = 'SAS smearing configuration'
updatePLimits(pLimit)[source]

Warning

method ‘dataobj.sasconfig.SmearingConfig.updatePLimits’ undocumented

updatePUnit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.SmearingConfig.updatePUnit’ undocumented

updateQLimits(qLimit)[source]

Warning

method ‘dataobj.sasconfig.SmearingConfig.updateQLimits’ undocumented

updateQUnit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.SmearingConfig.updateQUnit’ undocumented

updateSmearingLimits(q)[source]

Warning

method ‘dataobj.sasconfig.SmearingConfig.updateSmearingLimits’ undocumented

weights
class TrapezoidSmearing[source]

Bases: dataobj.sasconfig.SmearingConfig

halfTrapzPDF(x, c, d)[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.halfTrapzPDF’ undocumented

inputValid()[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.inputValid’ undocumented

onUmbraUpdate()[source]

Value in umbra will not exceed available q.

parameters = (None, None)
setIntPoints(q)[source]

sets smearing profile integration points for trapezoidal slit. Top (umbra) of trapezoid has full width xt, bottom of trapezoid (penumbra) has full width. Since the smearing function is assumed to be symmetrical, the integration parameters are calculated in the interval [0, xb/2]

showParams
updatePLimits(pLimit)[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.updatePLimits’ undocumented

updatePUnit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.updatePUnit’ undocumented

updateQLimits(qLimit)[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.updateQLimits’ undocumented

updateQUnit(newUnit)[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.updateQUnit’ undocumented

updateSmearingLimits(q)[source]

Warning

method ‘dataobj.sasconfig.TrapezoidSmearing.updateSmearingLimits’ undocumented

mcsas.dataobj.sasconfig_test module
assertDefaults(sc)[source]

Warning

function ‘dataobj.sasconfig_test.assertDefaults’ undocumented

testSerialize()[source]

Warning

function ‘dataobj.sasconfig_test.testSerialize’ undocumented

mcsas.dataobj.sasdata module

Represents data associated with a measurement by small angle scattering (SAS). Some examples and tests.

>>> import numpy
>>> testdata = numpy.random.rand(4,4)
>>> testtitle = "some title"
>>> from sasdata import SASData

Testing >>> first = SASData(testtitle, testdata) >>> first.title == testtitle True >>> numpy.all(first.rawArray == testdata) True

class SASData(**kwargs)[source]

Bases: dataobj.dataobj.DataObj

Represents one set of data from a unique source (a file, for example).

configType
count
dataContent

shows the content of the loaded data: Q, I, IErr, etc

classmethod displayData()[source]

Warning

method ‘dataobj.sasdata.SASData.displayData’ undocumented

classmethod displayDataDescr()[source]

Warning

method ‘dataobj.sasdata.SASData.displayDataDescr’ undocumented

modelType
p

Q-Vector at which the intensities are measured. Provided for convenience use within models.

pLimsString

Properly formatted q-limits for UI label text.

q

Q-Vector at which the intensities are measured. Provided for convenience use within models.

qLimsString

Properly formatted q-limits for UI label text.

rUnit
shannonChannelEst()[source]

Warning

method ‘dataobj.sasdata.SASData.shannonChannelEst’ undocumented

shannonChannelEstText
classmethod sourceName()[source]

The type of data source for UI label text.

sphericalSizeEst()[source]

Warning

method ‘dataobj.sasdata.SASData.sphericalSizeEst’ undocumented

sphericalSizeEstText
updateConfig()[source]

Warning

method ‘dataobj.sasdata.SASData.updateConfig’ undocumented

classproperty(func)

Warning

function ‘dataobj.sasdata.classproperty’ undocumented

Module contents

class DataObj(**kwargs)[source]

Bases: abc.NewBase

General container for data loaded from file. It offers specialised methods to derive information from the provided data.

accumulate(others)[source]

Warning

method ‘dataobj.DataObj.accumulate’ undocumented

config
configType

Returns a compatible DataConfig type.

count
f

The measurement vector.

filename
hasUncertainties

Returns True if this data set has an error bar for its intensities.

hdfWrite(hdf)[source]

Warning

method ‘dataobj.DataObj.hdfWrite’ undocumented

initConfig()[source]

Initializes a new data configuration and sets the sample name which is used to differentiate different data objects of the same type later on.

is2d

Returns true if this dataset contains two-dimensional data with psi information available.

modelType

Returns a compatible ScatteringModel type.

sampleName
seriesKey

The Name of the DataObj property to use as series key, hard-coded for now, assuming it exists. It allows to let the user chose from a generated list of properties (todo).

seriesKeyName

Returns the docstring of the property defined by self.seriesKeyProp.

seriesKeyValue

Returns the value of the property defined by self.seriesKeyProp.

setConfig(config=None)[source]

Set the configuration of this data object if the type matches.

setFilename(fn)[source]

Stores the absolute path to this data file. Should be reviewed when data sets can be created from several files.

classmethod sourceName()[source]

Returns the name of the measurement method.

updateConfig()[source]

Updates the config object based on this data set. All callbacks are run right after this method in setConfig().

x0

First sampling vector.

x1

Second sampling vector.

x2

Third sampling vector.

class SASData(**kwargs)[source]

Bases: dataobj.dataobj.DataObj

Represents one set of data from a unique source (a file, for example).

configType
count
dataContent

shows the content of the loaded data: Q, I, IErr, etc

classmethod displayData()[source]

Warning

method ‘dataobj.SASData.displayData’ undocumented

classmethod displayDataDescr()[source]

Warning

method ‘dataobj.SASData.displayDataDescr’ undocumented

modelType
p

Q-Vector at which the intensities are measured. Provided for convenience use within models.

pLimsString

Properly formatted q-limits for UI label text.

q

Q-Vector at which the intensities are measured. Provided for convenience use within models.

qLimsString

Properly formatted q-limits for UI label text.

rUnit
shannonChannelEst()[source]

Warning

method ‘dataobj.SASData.shannonChannelEst’ undocumented

shannonChannelEstText
classmethod sourceName()[source]

The type of data source for UI label text.

sphericalSizeEst()[source]

Warning

method ‘dataobj.SASData.sphericalSizeEst’ undocumented

sphericalSizeEstText
updateConfig()[source]

Warning

method ‘dataobj.SASData.updateConfig’ undocumented

class DataConfig[source]

Bases: bases.algorithm.algorithmbase.AlgorithmBase, dataobj.dataconfig.CallbackRegistry

callbackSlots
hdfWrite(hdf)[source]

Warning

method ‘dataobj.DataConfig.hdfWrite’ undocumented

is2d
onUpdatedX0(x0)[source]

Sets available range of loaded data.

onUpdatedX1(x1)[source]

Warning

method ‘dataobj.DataConfig.onUpdatedX1’ undocumented

parameters = (None, None, None, None, None, None, None, None)
sampleName
showParams
updateFMasks()[source]

Warning

method ‘dataobj.DataConfig.updateFMasks’ undocumented

updateFuMin()[source]

Warning

method ‘dataobj.DataConfig.updateFuMin’ undocumented

updateX0Limits()[source]

Warning

method ‘dataobj.DataConfig.updateX0Limits’ undocumented

updateX0Unit(newUnit)[source]

Sets the unit of the x0 vector.

updateX1Limits()[source]

Warning

method ‘dataobj.DataConfig.updateX1Limits’ undocumented

updateX1Unit(newUnit)[source]

Warning

method ‘dataobj.DataConfig.updateX1Unit’ undocumented

mcsas.bases package

Subpackages

mcsas.bases.algorithm package
Submodules
mcsas.bases.algorithm.algorithmbase module
class AlgorithmBase[source]

Bases: object

Base class for all data filtering algorithms.

Creates instances from defined parameters and replaces the class attributes accordingly.

factory(*args, **kwargs)

Warning

method ‘bases.algorithm.algorithmbase.AlgorithmBase.factory’ undocumented

hdfWrite(hdf)[source]

Warning

method ‘bases.algorithm.algorithmbase.AlgorithmBase.hdfWrite’ undocumented

classmethod makeDefault()[source]

Warning

method ‘bases.algorithm.algorithmbase.AlgorithmBase.makeDefault’ undocumented

classmethod name()[source]

Warning

method ‘bases.algorithm.algorithmbase.AlgorithmBase.name’ undocumented

param = functools.partial(<function AlgorithmBase.param>, <class 'bases.algorithm.algorithmbase.AlgorithmBase'>)
paramCount = functools.partial(<function AlgorithmBase.paramCount>, <class 'bases.algorithm.algorithmbase.AlgorithmBase'>)
params = functools.partial(<function AlgorithmBase.params>, <class 'bases.algorithm.algorithmbase.AlgorithmBase'>)
classmethod setName(name)[source]

Warning

method ‘bases.algorithm.algorithmbase.AlgorithmBase.setName’ undocumented

setParam = functools.partial(<function AlgorithmBase.setParam>, <class 'bases.algorithm.algorithmbase.AlgorithmBase'>)
classmethod setParams(*parameters)[source]

Expects a list of ParameterBase classes/types and sets them as class attributes to this class. They will become instances later, please see __init__()

showParams

A list of parameter names which defines the parameters and their ordering shown in a UI. To be overridden in sub classes.

update(other)[source]

Copy parameter values from another algorithm of the same type.

exception AlgorithmError[source]

Bases: Exception

exception AlgorithmNameError[source]

Bases: bases.algorithm.algorithmbase.AlgorithmError

exception AlgorithmParameterError[source]

Bases: bases.algorithm.algorithmbase.AlgorithmError

classproperty(func)

Warning

function ‘bases.algorithm.algorithmbase.classproperty’ undocumented

mcsas.bases.algorithm.algorithmbase_test module
class DummyAlgo[source]

Bases: bases.algorithm.algorithmbase.AlgorithmBase

dummy(v)[source]

Warning

method ‘bases.algorithm.algorithmbase_test.DummyAlgo.dummy’ undocumented

parameters = (None, None)
shortName = 'Dummy'
Parameter(*args, **kwargs)

Warning

function ‘bases.algorithm.algorithmbase_test.Parameter’ undocumented

np_array(value)

Warning

function ‘bases.algorithm.algorithmbase_test.np_array’ undocumented

testParam()[source]

Algorithm without parameters allowed

testParam1()[source]

Warning

function ‘bases.algorithm.algorithmbase_test.testParam1’ undocumented

testSerialize()[source]

Warning

function ‘bases.algorithm.algorithmbase_test.testSerialize’ undocumented

testTypeVsInstance()[source]

Warning

function ‘bases.algorithm.algorithmbase_test.testTypeVsInstance’ undocumented

mcsas.bases.algorithm.numbergenerator module
class NumberGenerator[source]

Bases: object

Base class for number generators. Generates numbers in the interval [0, 1]. Scaling is supposed to happen elsewhere.

classmethod get(count=1)[source]

Warning

method ‘bases.algorithm.numbergenerator.NumberGenerator.get’ undocumented

classmethod hdfWrite(hdf)[source]

Warning

method ‘bases.algorithm.numbergenerator.NumberGenerator.hdfWrite’ undocumented

class RandomExponential[source]

Bases: bases.algorithm.numbergenerator.NumberGenerator

classmethod get(count=1)[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomExponential.get’ undocumented

lower = 0.0
upper = 1.0
class RandomExponential1[source]

Bases: bases.algorithm.numbergenerator.RandomExponential

Alias class for RandomExponential

class RandomExponential2[source]

Bases: bases.algorithm.numbergenerator.RandomExponential

Picks values with inverse logarithmic probability over )0, 1( , as if it were spanning two decades.

upper = 2.0
class RandomExponential3[source]

Bases: bases.algorithm.numbergenerator.RandomExponential

Picks values with inverse logarithmic probability over )0, 1( , as if it were spanning three decades.

upper = 3.0
class RandomUniform[source]

Bases: bases.algorithm.numbergenerator.NumberGenerator

classmethod get(count=1)[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomUniform.get’ undocumented

class RandomXorShiftUniform[source]

Bases: bases.algorithm.numbergenerator.NumberGenerator

Implemented according to xorshift1024* at http://xorshift.di.unimi.it

>>> from bases.algorithm.numbergenerator import RandomXorShiftUniform
>>> RandomXorShiftUniform.getSeed()
>>> RandomXorShiftUniform.setSeed()
>>> RandomXorShiftUniform.next()
>>> RandomXorShiftUniform.get()
>>> RandomXorShiftUniform.get(3)
classmethod dtype()[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniform.dtype’ undocumented

classmethod get(count=1)[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniform.get’ undocumented

classmethod getSeed()[source]

Generate seed using numpy.

classmethod next()[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniform.next’ undocumented

p = None
s = None
classmethod setSeed(seedData=None)[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniform.setSeed’ undocumented

class RandomXorShiftUniformTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

Tests RandomXorShiftUniform output against reference C implementation. The full path to the executable has to be specified. Call it like this:

nosetests bases.algorithm.numbergenerator

Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.

classmethod generateTests()[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.generateTests’ undocumented

getRef()[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.getRef’ undocumented

setUp()[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.setUp’ undocumented

tearDown()[source]

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.tearDown’ undocumented

test0()

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.test0’ undocumented

test1()

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.test1’ undocumented

test2()

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.test2’ undocumented

test3()

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.test3’ undocumented

test4()

Warning

method ‘bases.algorithm.numbergenerator.RandomXorShiftUniformTest.test4’ undocumented

lshift(x, s)

Warning

function ‘bases.algorithm.numbergenerator.lshift’ undocumented

rshift(x, s)

Warning

function ‘bases.algorithm.numbergenerator.rshift’ undocumented

mcsas.bases.algorithm.parameter module

This module defines a generic parameter class for algorithms. It contains meta information which allows for automated UI building. Create sub classes by calling factory() in this module. It creates a new sub class type which inherits ParameterBase:

>>> from parameter import factory as paramFactory
>>> ParamType = paramFactory("radius", 1.3, valueRange = (0, 2))

Created a new type RadiusParameter:

>>> print(ParamType)
<class 'parameter.RadiusParameter'>

Using methods on instances work as usual:

>>> p = ParamType()
>>> p.name()
'radius'
>>> p.value()
1.3

Update the instance:

>>> p.setValue(2.4)
>>> p.value()
2.4

Changing class default: >>> ParamType.setValue(3.5) >>> ParamType.value() 3.5

Existing instance keep their values: >>> p.value() 2.4

New instances get the updated defaults: >>> q = ParamType() >>> q.value() 3.5

Parameter attributes are accessible on type/class as well as on the instance. Updating an attribute of an instance changes just that individual instance whereas updating an attribute of the type changes that attribute in general for all new instances to be created which is behaves like a default value.

exception DecimalsError[source]

Bases: bases.algorithm.parameter.ParameterError

exception DefaultValueError[source]

Bases: bases.algorithm.parameter.ParameterError

exception DisplayValuesError[source]

Bases: bases.algorithm.parameter.ParameterError

class ParameterBase[source]

Bases: object

Base class for algorithm parameters providing additional information to ease automated GUI building.

classmethod addAttributes(dictionary, *names, **namesAndValues)[source]

Sets an ordered list of attributes. Initializes the private variable to None and sets a default getter method for each name provided. Additionally, sets attributeNames to return all attribute names.

classmethod attributeNames()[source]

Returns an ordered list of attribute names considering multiple inheritance and maintaining its order.

attributes = functools.partial(<function ParameterBase.attributes>, <class 'bases.algorithm.parameter.ParameterBase'>)
copy()[source]

Warning

method ‘bases.algorithm.parameter.ParameterBase.copy’ undocumented

displayName = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterBase'>)
displayValue = functools.partial(<function ParameterBase.displayValue>, <class 'bases.algorithm.parameter.ParameterBase'>)
classmethod dtype()[source]

Warning

method ‘bases.algorithm.parameter.ParameterBase.dtype’ undocumented

formatDisplayName = functools.partial(<function ParameterBase.formatDisplayName>, <class 'bases.algorithm.parameter.ParameterBase'>)
generate(lower=None, upper=None, count=1)[source]

Returns a list of valid parameter values within given bounds. Accepts vectors of individual bounds for lower and upper limit. This allows for inequality parameter constraints. lower, upper: arrays for lower and upper bounds

classmethod get(key, default=None)[source]

metagetter to get an attribute parameter

hdfStoreAsMember()[source]

Warning

method ‘bases.algorithm.parameter.ParameterBase.hdfStoreAsMember’ undocumented

hdfWrite(hdf)[source]

Warning

method ‘bases.algorithm.parameter.ParameterBase.hdfWrite’ undocumented

classmethod isDataType(value)[source]

Warning

method ‘bases.algorithm.parameter.ParameterBase.isDataType’ undocumented

name = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterBase'>)
onValueUpdate = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterBase'>)
classmethod set(key, value)[source]

metasetter to set an attribute value

setAttributes = functools.partial(<function ParameterBase.setAttributes>, <class 'bases.algorithm.parameter.ParameterBase'>)
setDisplayName = functools.partial(<function ParameterBase.setDisplayName>, <class 'bases.algorithm.parameter.ParameterBase'>)
setDisplayValue = functools.partial(<function ParameterBase.setDisplayValue>, <class 'bases.algorithm.parameter.ParameterBase'>)
classmethod setName(name)[source]

Changing the name is allowed for the class/type only, not for instances.

setOnValueUpdate = functools.partial(<function _makeSetter.<locals>.setter>, <class 'bases.algorithm.parameter.ParameterBase'>)
setValue = functools.partial(<function ParameterBase.setValue>, <class 'bases.algorithm.parameter.ParameterBase'>)
value = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterBase'>)
class ParameterBoolean[source]

Bases: bases.algorithm.parameter.ParameterBase

classmethod dtype()[source]

Warning

method ‘bases.algorithm.parameter.ParameterBoolean.dtype’ undocumented

exception ParameterError[source]

Bases: Exception

class ParameterFloat[source]

Bases: bases.algorithm.parameter.ParameterNumerical

decimals = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterFloat'>)
displayMagnitudeName = functools.partial(<function ParameterFloat.displayMagnitudeName>, <class 'bases.algorithm.parameter.ParameterFloat'>)
displayValue = functools.partial(<function ParameterFloat.displayValue>, <class 'bases.algorithm.parameter.ParameterFloat'>)
displayValueRange = functools.partial(<function ParameterFloat.displayValueRange>, <class 'bases.algorithm.parameter.ParameterFloat'>)
classmethod dtype()[source]

Warning

method ‘bases.algorithm.parameter.ParameterFloat.dtype’ undocumented

hdfStoreAsMember()[source]

Warning

method ‘bases.algorithm.parameter.ParameterFloat.hdfStoreAsMember’ undocumented

classmethod isDataType(value)[source]

Warning

method ‘bases.algorithm.parameter.ParameterFloat.isDataType’ undocumented

setDecimals = functools.partial(<function ParameterFloat.setDecimals>, <class 'bases.algorithm.parameter.ParameterFloat'>)
setDisplayValue = functools.partial(<function ParameterFloat.setDisplayValue>, <class 'bases.algorithm.parameter.ParameterFloat'>)
setSuffix = functools.partial(<function ParameterFloat.setSuffix>, <class 'bases.algorithm.parameter.ParameterFloat'>)
setUnit = functools.partial(<function _makeSetter.<locals>.setter>, <class 'bases.algorithm.parameter.ParameterFloat'>)
suffix = functools.partial(<function ParameterFloat.suffix>, <class 'bases.algorithm.parameter.ParameterFloat'>)
toDisplay = functools.partial(<function ParameterFloat.toDisplay>, <class 'bases.algorithm.parameter.ParameterFloat'>)
toSi = functools.partial(<function ParameterFloat.toSi>, <class 'bases.algorithm.parameter.ParameterFloat'>)
unit = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterFloat'>)
exception ParameterGeneratorError[source]

Bases: bases.algorithm.parameter.ParameterError

class ParameterLog[source]

Bases: bases.algorithm.parameter.ParameterFloat

Used to select an UI input widget with logarithmic behaviour.

exception ParameterNameError[source]

Bases: bases.algorithm.parameter.ParameterError

class ParameterNumerical[source]

Bases: bases.algorithm.parameter.ParameterBase

clip = functools.partial(<function ParameterNumerical.clip>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
displayValues = functools.partial(<function ParameterNumerical.displayValues>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
classmethod dtype()[source]

Warning

method ‘bases.algorithm.parameter.ParameterNumerical.dtype’ undocumented

generate(lower=None, upper=None, count=1)[source]

Warning

method ‘bases.algorithm.parameter.ParameterNumerical.generate’ undocumented

generator = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
hdfStoreAsMember()[source]

Warning

method ‘bases.algorithm.parameter.ParameterNumerical.hdfStoreAsMember’ undocumented

classmethod isDataType(value)[source]

ParameterNumerical is a fallback for all number not being float.

max = functools.partial(<function ParameterNumerical.max>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
min = functools.partial(<function ParameterNumerical.min>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
setDisplayValues = functools.partial(<function ParameterNumerical.setDisplayValues>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
setGenerator = functools.partial(<function ParameterNumerical.setGenerator>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
setStepping = functools.partial(<function ParameterNumerical.setStepping>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
setSuffix = functools.partial(<function ParameterNumerical.setSuffix>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
setValue = functools.partial(<function ParameterNumerical.setValue>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
setValueRange = functools.partial(<function ParameterNumerical.setValueRange>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
stepping = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
suffix = functools.partial(<function _makeGetter.<locals>.getter>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
valueRange = functools.partial(<function ParameterNumerical.valueRange>, <class 'bases.algorithm.parameter.ParameterNumerical'>)
class ParameterString[source]

Bases: bases.algorithm.parameter.ParameterBase

String-based parameter class. The default value should be the first item in the _valueRange list.

classmethod dtype()[source]

Warning

method ‘bases.algorithm.parameter.ParameterString.dtype’ undocumented

classmethod isDataType(value)[source]

Warning

method ‘bases.algorithm.parameter.ParameterString.isDataType’ undocumented

classmethod setValueRange(newRange)[source]

Warning

method ‘bases.algorithm.parameter.ParameterString.setValueRange’ undocumented

valueRange = functools.partial(<function ParameterString.valueRange>, <class 'bases.algorithm.parameter.ParameterString'>)
exception SteppingError[source]

Bases: bases.algorithm.parameter.ParameterError

exception SuffixError[source]

Bases: bases.algorithm.parameter.ParameterError

exception ValueRangeError[source]

Bases: bases.algorithm.parameter.ParameterError

classproperty(func)

Warning

function ‘bases.algorithm.parameter.classproperty’ undocumented

factory(name, value, paramTypes=None, **kwargs)[source]

Generates a new Parameter type derived from one of the predefined base classes choosen by the supplied value: Providing a string value results in a type derived from ParameterBase, providing an integer value produces a ParameterNumerical type and a float value results in a ParameterFloat type. Alternatively, a class type cls can be provided which is used as base class for the resulting Parameter class type. Make sure in this case, all attributes mandatory for this base type are provided too.

  • name: short name of the new parameter without spaces
  • value: default value from which the type is derived if cls is not given

Optional arguments:

  • paramTypes: tuple of available parameter types instead of the default
  • cls: forces a certain Parameter type.
  • description: Updates the __doc__ attribute. May be displayed in the UI
    somewhere.
generateValues(numberGenerator, defaultRange, lower, upper, count)[source]

Warning

function ‘bases.algorithm.parameter.generateValues’ undocumented

mcsas.bases.algorithm.parameter_test module
class Dummy[source]

Bases: object

dummyFunc(value)[source]

Warning

method ‘bases.algorithm.parameter_test.Dummy.dummyFunc’ undocumented

Parameter(*args, **kwargs)

Warning

function ‘bases.algorithm.parameter_test.Parameter’ undocumented

testParameterBaseCopy()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterBaseCopy’ undocumented

testParameterCompare()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterCompare’ undocumented

testParameterFloat()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterFloat’ undocumented

testParameterFloatCopy()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterFloatCopy’ undocumented

testParameterName()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterName’ undocumented

testParameterNumerical()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterNumerical’ undocumented

testParameterNumericalCopy()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterNumericalCopy’ undocumented

testParameterNumericalDisplayValues()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterNumericalDisplayValues’ undocumented

testParameterNumericalStepping()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterNumericalStepping’ undocumented

testParameterNumericalSuffix()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterNumericalSuffix’ undocumented

testParameterNumericalValueRange()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterNumericalValueRange’ undocumented

testParameterSerialize()[source]

Warning

function ‘bases.algorithm.parameter_test.testParameterSerialize’ undocumented

Module contents
Parameter(*args, **kwargs)

Warning

function ‘bases.algorithm.Parameter’ undocumented

mcsas.bases.dataset package
Submodules
mcsas.bases.dataset.dataset module
class DataSet(**kwargs)[source]

Bases: bases.dataset.titlemixin.TitleMixin, bases.dataset.rawarraymixin.RawArrayMixin

Container base class for all kinds of data to be passed around in the UI. Knows its originally loaded (raw) data array and its title to be shown in a UI.

class DisplayMixin(**kwargs)[source]

Bases: object

Provides additional data to display in a list or tree view.

displayData

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
def f(cls, arg1, arg2, ...): ... f = classmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

displayDataDescr

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
def f(cls, arg1, arg2, ...): ... f = classmethod(f)

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.

isRemovable

Returns if this data set may be removed (e.g. from data lists in a GUI)

class ResultMixin(**kwargs)[source]

Bases: object

result

Supposed to return a list of Result types.

classproperty(func)

Warning

function ‘bases.dataset.dataset.classproperty’ undocumented

mcsas.bases.dataset.rawarraymixin module
class RawArrayMixin(rawArray=None, **kwargs)[source]

Bases: object

Memorizes the original data before processing it eventually.

classmethod isValidInput(rawArray)[source]

Warning

method ‘bases.dataset.rawarraymixin.RawArrayMixin.isValidInput’ undocumented

rawArray
setRawArray(rawArray)[source]

Warning

method ‘bases.dataset.rawarraymixin.RawArrayMixin.setRawArray’ undocumented

valid
mcsas.bases.dataset.titlemixin module
class TitleMixin(title=None, **kwargs)[source]

Bases: object

Manages a title of this object for display in a GUI.

title

Data object title

Module contents
mcsas.bases.model package
Submodules
mcsas.bases.model.modeldata module
class ModelData(cumInt, vset, wset, sset, numParams)[source]

Bases: object

chisqrInt

Make the model intensity comparable to the measured intensity. The difference of both will be calculated in BackgroundScalingFit in order to perform the chi-square test.

cumInt

Returns the cumulated model intensity or signal.

hdfWrite(hdf)[source]

Warning

method ‘bases.model.modeldata.ModelData.hdfWrite’ undocumented

numParams

Returns the number of active (fitted) parameters.

sset

Returns the associated set of surfaces.

volumeFraction(scaling)[source]

Returns the volume fraction based on the provided scaling factor to match this model data to the measured data. Assumes that the weights ‘self.wset’ contain the scatterer volume squared.

vset

Returns the associated set of volumes.

wset

Returns the associated set of weights.

class SASModelData(cumInt, vset, wset, sset, numParams)[source]

Bases: bases.model.modeldata.ModelData

mcsas.bases.model.sasmodel module
class SASModel[source]

Bases: bases.model.scatteringmodel.ScatteringModel

calcIntensity(data, compensationExponent=None)[source]

Returns the intensity I, the volume \(v_{abs}\) and the intensity weights w for a single parameter contribution over all q:

\(I(q,r) = F^2(q,r) \cdot w(r)\)

canSmear = False
getQ(dataset)[source]

This is a function that returns Q. In case of smearing, dataset itself is a 2D matrix of Q-values. When smearing is not enabled, dataset.q contains a 1D vector of q.

I do realize that this is not a good way of doing things. This should be replaced at a given point in time by a better solution within sasdata.

modelDataType()[source]

Warning

method ‘bases.model.sasmodel.SASModel.modelDataType’ undocumented

weight()[source]

Calculates an intensity weighting used during fitting. It is based on the scatterers volume. It can be modified by a user-defined compensation exponent c. The default value is \(c={2 \over 3}\)

\(w(r) = v(r)^{2c}\)

mcsas.bases.model.scatteringmodel module
class ScatteringModel[source]

Bases: bases.algorithm.algorithmbase.AlgorithmBase

Creates instances from defined parameters and replaces the class attributes accordingly.

absVolume()[source]

Forwarding to usual volume() by default. Can be overridden to include SLD.

activeParamCount = functools.partial(<function ScatteringModel.activeParamCount>, <class 'bases.model.scatteringmodel.ScatteringModel'>)
activeParamNames = functools.partial(<function ScatteringModel.activeParamNames>, <class 'bases.model.scatteringmodel.ScatteringModel'>)
activeParams = functools.partial(<function ScatteringModel.activeParams>, <class 'bases.model.scatteringmodel.ScatteringModel'>)
calc(data, pset, compensationExponent=None)[source]

Calculates the total intensity and scatterer volume contributions using the current model. pset number columns equals the number of active parameters. Returns a ModelData object for a certain type of measurement.

calcIntensity(data, compensationExponent=None)[source]

Calculates the model intensity which is later compared to the data. Returns a tuple containing an array of the calculated intensities for the grid provided with the data and the volume of a single particle based on the model parameters. Has to be implemented in derived classes specific to a certain type of measurement.

fixTestParams = functools.partial(<function ScatteringModel.fixTestParams>, <class 'bases.model.scatteringmodel.ScatteringModel'>)
formfactor(dataset)[source]

Calculates the Rayleigh function of this model. Reimplement this for new models.

generateParameters(count=1)[source]

Generates a set of parameters for this model using the predefined Parameter.generator. Allows for different random number distributions.

getModelData(cumInt, vset, wset, sset)[source]

Warning

method ‘bases.model.scatteringmodel.ScatteringModel.getModelData’ undocumented

classmethod getParametersFromFilename(filename)[source]

Derives model parameters for testing from reference data file.

hdfWrite(hdf)[source]

Warning

method ‘bases.model.scatteringmodel.ScatteringModel.hdfWrite’ undocumented

modelDataType()[source]

Returns the appropriate ModelData class for this type of model.

surface()[source]

Returns the surface area of a single scatterer. Used for the surface weighted distribution histogram. Returns 0 by default. Reimplement this for a model.

classmethod test(filename)[source]

Regression test of a scattering model. File names are expected to contain the parameter values which produce the provided intensity. Otherwise implement fixTestParams() for the particular model.

  • filename: Name of the file in cls.testDataDir to test against.
  • cls.testRelErr: Acceptable mean of relative error against reference
    intensity. Default: 1e-5
  • cls.testVolExp: Volume compensation exponent, sets the amount of
    volume contribution the intensity is scaled by.
  • cls.testDataDir: Directory of test data relative to program dir.
    Default: “testdata”
update = functools.partial(<function ScatteringModel.update>, <class 'bases.model.scatteringmodel.ScatteringModel'>)
updateParamBounds(bounds)[source]

Warning

method ‘bases.model.scatteringmodel.ScatteringModel.updateParamBounds’ undocumented

volume()[source]

Calculates the volume of this model, taking compensationExponent into account from input or preset parameters. Reimplement this for new models.

weight()[source]

A weighting function for the form factor. With SAXS, it is usually the volume squared.

mcsas.bases.model.scatteringmodel_test module
Module contents

Module contents

mcsas.main module

getScriptPath()[source]

Returns the full path to the current script file which calls this function.

main(argv=None)[source]

Warning

function ‘main.main’ undocumented

makeAbsolutePath(relpath)[source]

Warning

function ‘main.makeAbsolutePath’ undocumented

McSAS

mcsas.cxfreeze module

Overview

Creates a standalone program package for a particular platform to be run by restricted users without installing any additional packages.

This script is executable and has to be run on the platform for which a package shall be created. Please follow the instructions below for each particular platform.

Common Package Dependencies:

In addition to the dependencies of the MCSAS package listed above the cx_Freeze package is used for freezing the python source code structure into a standalone package.

Working with Source Code Repositories

In order to download the latest source code repositories of packages such as MCSAS or cx_Freeze a client to Git and Mercurial is required. There are several available, for both Mac OS X and Windows the SourceTree program is recommended.

Windows

A self-contained archive consisting of MCSAS.exe and all necessary libraries and files is created by the following command executed in the MCSAS folder:

> python cxfreeze.py build_exe
Requirements

On a fresh installation of Windows 7 the following packages are required:

Mac OS X

After installing the required packages below a disk image file (.dmg) consisting of the application bundle is created by:

$ /usr/local/bin/python2 cxfreeze.py bdist_dmg

Alternatively, for testing purposes the bundle can be created without packaging into a disk image by:

$ /usr/local/bin/python2 cxfreeze.py bdist_mac
Requirements

On a fresh installation of OS X 10.8 the following packages are required:

  • Xcode command line tools: for build essentials such as a compiler

    ( xcode461_cltools_10_86938245a.dmg )

  • Python 2.7.9

  • Qt 4.8.6

  • PySide 1.2.1 / Qt 4.8

  • NumPy 1.7.1

  • SciPy 0.12.0

  • matplotlib 1.4.2

    Install it on the command line by:

    $ /usr/local/bin/pip install matplotlib-1.4.2-*.whl
    
  • h5py HDF5 support, install HDF5 from source first:

    $ cd hdf5-src
    $ ./configure --prefix=/usr/local
    $ make && sudo make install
    $
    $ pip2 install h5py
    
  • a modified cx_Freeze 4.3.4 with local modifications for successful app freezing on OS X

    Download the source and install it on the command line by:

    $ hg clone https://bitbucket.org/ibressler/cx_freeze
    $ cd cx_freeze
    $ hg co 4.x
    $ /usr/local/bin/python2 setup.py install
    
Ubuntu/Linux

Similar to the procedure on Windows a self-contained archive containing all necessary libraries and files is created by:

$ python cxfreeze.py build_exe
Requirements

On a fresh installation of Ubuntu Linux 14.04 LTS the following packages are required:

  • apt-get install git build-essential python-setuptools python-dev liblapack-dev libfreetype6-dev tk-dev
  • PySide 1.2.4
  • NumPy 1.7.2
  • SciPy 0.12.1
  • matplotlib 1.4.2
  • cx_Freeze 4.3.4
  • future 0.16.1
  • h5py 2.2.1

Internals

class Archiver[source]

Bases: object

archive(targetPath)[source]

Creates an archive from the given absolute target directory path. The archive file will have the base name of the last directory of the given path.

execName
getLogFilename()[source]

Warning

method ‘cxfreeze.Archiver.getLogFilename’ undocumented

class Archiver7z(filetype='7z')[source]

Bases: cxfreeze.Archiver

archive(targetPath)[source]

Warning

method ‘cxfreeze.Archiver7z.archive’ undocumented

class ArchiverZip[source]

Bases: cxfreeze.Archiver

archive(targetPath)[source]

Expects an absolute target directory path

includeModels(includeFilesLst)[source]

Warning

function ‘cxfreeze.includeModels’ undocumented

sanitizeVersionNumber(number)[source]

Removes non-digits to be compatible with pywin32

mcsas.autobuild module

mcsas.mcsas_test module

getExpectedData(filename)[source]

Warning

function ‘mcsas_test.getExpectedData’ undocumented

getSettings(testfn, expectedfn)[source]

Test settings for mcsas routine. Using number of repetitions and contributions from expected test data to improve comparability.

getTestData(filename)[source]

Warning

function ‘mcsas_test.getTestData’ undocumented

isEqualFloat(a, b, tol=1e-16)[source]

Return TRUE if both float arrays can be considered as equal. tol Tolerance in relative mean difference Supposed to be symmetrical.

storeResultData(filename, result)[source]

Warning

function ‘mcsas_test.storeResultData’ undocumented

test()[source]

Testing the algorithm in 1D. Atm, we just test as much as possible. Testing post-processing routines should be separated later as it’s deterministic and though easier to test.

Indices and tables

How to generate the documentation

Requirements

  • Python, of course
  • Sphinx package
  • For Latex/PDF generation, there should be a latex environment installed

Generate a PDF document

cd <mcsas>/doc
make latexpdf

The resulting McSAS.pdf can be found in <mcsas>/doc/_build/latex/.

Generate HTML pages

cd <mcsas>/doc
make html

The entry point index.html can be found in <mcsas>/doc/_build/html/.

Update Source Code Documentation

cd <mcsas>/doc
make clean
make apidoc

This command automatically generates sphinx documentation files for all source code files in the directory. It assumes the current working directory is the McSAS root directory.

Indices and tables