Search is not available for this dataset
text stringlengths 75 104k |
|---|
def Seq(self, *sequence, **kwargs):
"""
`Seq` is used to express function composition. The expression
Seq(f, g)
be equivalent to
lambda x: g(f(x))
As you see, its a little different from the mathematical definition. Excecution order flow from left to right, this makes reading and reasoning about cod... |
def With(self, context_manager, *body, **kwargs):
"""
**With**
def With(context_manager, *body):
**Arguments**
* **context_manager**: a [context manager](https://docs.python.org/2/reference/datamodel.html#context-managers) object or valid expression from the DSL that returns a context manager.
* ***body*... |
def ReadList(self, *branches, **kwargs):
"""
Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`.
"""
branches = map(lambda x: E.Read(x) if isinstance(x, str) else x, branches)
return self.List(*branches, **kwargs) |
def Write(self, *state_args, **state_dict):
"""See `phi.dsl.Expression.Read`"""
if len(state_dict) + len(state_args) < 1:
raise Exception("Please include at-least 1 state variable, got {0} and {1}".format(state_args, state_dict))
if len(state_dict) > 1:
raise Exception("... |
def Val(self, val, **kwargs):
"""
The expression
Val(a)
is equivalent to the constant function
lambda x: a
All expression in this module interprete values that are not functions as constant functions using `Val`, for example
Seq(1, P + 1)
is equivalent to
Seq(Val(1), P + 1)
The previous ... |
def If(self, condition, *then, **kwargs):
"""
**If**
If(Predicate, *Then)
Having conditionals expressions a necesity in every language, Phi includes the `If` expression for such a purpose.
**Arguments**
* **Predicate** : a predicate expression uses to determine if the `Then` or `Else` branches should be... |
def Else(self, *Else, **kwargs):
"""See `phi.dsl.Expression.If`"""
root = self._root
ast = self._ast
next_else = E.Seq(*Else)._f
ast = _add_else(ast, next_else)
g = _compile_if(ast)
return root.__then__(g, **kwargs) |
def length(string, until=None):
"""
Returns the number of graphemes in the string.
Note that this functions needs to traverse the full string to calculate the length,
unlike `len(string)` and it's time consumption is linear to the length of the string
(up to the `until` value).
Only counts up ... |
def slice(string, start=None, end=None):
"""
Returns a substring of the given string, counting graphemes instead of codepoints.
Negative indices is currently not supported.
>>> string = "tamil நி (ni)"
>>> string[:7]
'tamil ந'
>>> grapheme.slice(string, end=7)
'tamil நி'
>>> string... |
def contains(string, substring):
"""
Returns true if the sequence of graphemes in substring is also present in string.
This differs from the normal python `in` operator, since the python operator will return
true if the sequence of codepoints are withing the other string without considering
graphem... |
def startswith(string, prefix):
"""
Like str.startswith, but also checks that the string starts with the given prefixes sequence of graphemes.
str.startswith may return true for a prefix that is not visually represented as a prefix if a grapheme cluster
is continued after the prefix ends.
>>> grap... |
def endswith(string, suffix):
"""
Like str.endswith, but also checks that the string ends with the given prefixes sequence of graphemes.
str.endswith may return true for a suffix that is not visually represented as a suffix if a grapheme cluster
is initiated before the suffix starts.
>>> grapheme.... |
def safe_split_index(string, max_len):
"""
Returns the highest index up to `max_len` at which the given string can be sliced, without breaking a grapheme.
This is useful for when you want to split or take a substring from a string, and don't really care about
the exact grapheme length, but don't want t... |
def readB1logfile(filename):
"""Read B1 logfile (*.log)
Inputs:
filename: the file name
Output: A dictionary.
"""
dic = dict()
# try to open. If this fails, an exception is raised
with open(filename, 'rt', encoding='utf-8') as f:
for l in f:
l = l.strip()
... |
def writeB1logfile(filename, data):
"""Write a header structure into a B1 logfile.
Inputs:
filename: name of the file.
data: header dictionary
Notes:
exceptions pass through to the caller.
"""
allkeys = list(data.keys())
f = open(filename, 'wt', encoding='utf-8')
fo... |
def readB1header(filename):
"""Read beamline B1 (HASYLAB, Hamburg) header data
Input
-----
filename: string
the file name. If ends with ``.gz``, it is fed through a ``gunzip``
filter
Output
------
A header dictionary.
Examples
--------
read header data from 'OR... |
def _readedf_extractline(left, right):
"""Helper function to interpret lines in an EDF file header.
"""
functions = [int, float, lambda l:float(l.split(None, 1)[0]),
lambda l:int(l.split(None, 1)[0]),
dateutil.parser.parse, lambda x:str(x)]
for f in functions:
t... |
def readehf(filename):
"""Read EDF header (ESRF data format, as of beamline ID01 and ID02)
Input
-----
filename: string
the file name to load
Output
------
the EDF header structure in a dictionary
"""
f = open(filename, 'r')
edf = {}
if not f.readline().strip().star... |
def readbhfv1(filename, load_data=False, bdfext='.bdf', bhfext='.bhf'):
"""Read header data from bdf/bhf file (Bessy Data Format v1)
Input:
filename: the name of the file
load_data: if the matrices are to be loaded
Output:
bdf: the BDF header structure
Adapted the bdf_read.m m... |
def readmarheader(filename):
"""Read a header from a MarResearch .image file."""
with open(filename, 'rb') as f:
intheader = np.fromstring(f.read(10 * 4), np.int32)
floatheader = np.fromstring(f.read(15 * 4), '<f4')
strheader = f.read(24)
f.read(4)
otherstrings = [f.read(... |
def readBerSANS(filename):
"""Read a header from a SANS file (produced usually by BerSANS)"""
hed = {'Comment': ''}
translate = {'Lambda': 'Wavelength',
'Title': 'Owner',
'SampleName': 'Title',
'BeamcenterX': 'BeamPosY',
'BeamcenterY': 'Bea... |
def Sine(x, a, omega, phi, y0):
"""Sine function
Inputs:
-------
``x``: independent variable
``a``: amplitude
``omega``: circular frequency
``phi``: phase
``y0``: offset
Formula:
--------
``a*sin(x*omega + phi)+y0``
"""
return a * np.sin(x * ... |
def Cosine(x, a, omega, phi, y0):
"""Cosine function
Inputs:
-------
``x``: independent variable
``a``: amplitude
``omega``: circular frequency
``phi``: phase
``y0``: offset
Formula:
--------
``a*cos(x*omega + phi)+y0``
"""
return a * np.cos(... |
def Square(x, a, b, c):
"""Second order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the second-order term
``b``: coefficient of the first-order term
``c``: additive constant
Formula:
--------
``a*x^2 + b*x + c``
"""
r... |
def Cube(x, a, b, c, d):
"""Third order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the third-order term
``b``: coefficient of the second-order term
``c``: coefficient of the first-order term
``d``: additive constant
Formula:
... |
def Exponential(x, a, tau, y0):
"""Exponential function
Inputs:
-------
``x``: independent variable
``a``: scaling factor
``tau``: time constant
``y0``: additive constant
Formula:
--------
``a*exp(x/tau)+y0``
"""
return np.exp(x / tau) * a + y0 |
def Lorentzian(x, a, x0, sigma, y0):
"""Lorentzian peak
Inputs:
-------
``x``: independent variable
``a``: scaling factor (extremal value)
``x0``: center
``sigma``: half width at half maximum
``y0``: additive constant
Formula:
--------
``a/(1+((x-x0)... |
def Gaussian(x, a, x0, sigma, y0):
"""Gaussian peak
Inputs:
-------
``x``: independent variable
``a``: scaling factor (extremal value)
``x0``: center
``sigma``: half width at half maximum
``y0``: additive constant
Formula:
--------
``a*exp(-(x-x0)^2)... |
def LogNormal(x, a, mu, sigma):
"""PDF of a log-normal distribution
Inputs:
-------
``x``: independent variable
``a``: amplitude
``mu``: center parameter
``sigma``: width parameter
Formula:
--------
``a/ (2*pi*sigma^2*x^2)^0.5 * exp(-(log(x)-mu)^2/(2*sigma^2... |
def radintpix(data, dataerr, bcx, bcy, mask=None, pix=None, returnavgpix=False,
phi0=0, dphi=0, returnmask=False, symmetric_sector=False,
doslice=False, errorpropagation=2, autoqrange_linear=True):
"""Radial integration (averaging) on the detector plane
Inputs:
data: scatter... |
def azimintpix(data, dataerr, bcx, bcy, mask=None, Ntheta=100, pixmin=0,
pixmax=np.inf, returnmask=False, errorpropagation=2):
"""Azimuthal integration (averaging) on the detector plane
Inputs:
data: scattering pattern matrix (np.ndarray, dtype: np.double)
dataerr: error matrix (... |
def find_subdirs(startdir='.', recursion_depth=None):
"""Find all subdirectory of a directory.
Inputs:
startdir: directory to start with. Defaults to the current folder.
recursion_depth: number of levels to traverse. None is infinite.
Output: a list of absolute names of subfolders.
Ex... |
def findpeak(x, y, dy=None, position=None, hwhm=None, baseline=None, amplitude=None, curve='Lorentz'):
"""Find a (positive) peak in the dataset.
This function is deprecated, please consider using findpeak_single() instead.
Inputs:
x, y, dy: abscissa, ordinate and the error of the ordinate (can... |
def findpeak_single(x, y, dy=None, position=None, hwhm=None, baseline=None, amplitude=None, curve='Lorentz',
return_stat=False, signs=(-1, 1), return_x=None):
"""Find a (positive or negative) peak in the dataset.
Inputs:
x, y, dy: abscissa, ordinate and the error of the ordinate (ca... |
def findpeak_multi(x, y, dy, N, Ntolerance, Nfit=None, curve='Lorentz', return_xfit=False, return_stat=False):
"""Find multiple peaks in the dataset given by vectors x and y.
Points are searched for in the dataset where the N points before and
after have strictly lower values than them. To get rid of false... |
def findpeak_asymmetric(x, y, dy=None, curve='Lorentz', return_x=None, init_parameters=None):
"""Find an asymmetric Lorentzian peak.
Inputs:
x: numpy array of the abscissa
y: numpy array of the ordinate
dy: numpy array of the errors in y (or None if not present)
curve: string (c... |
def readspecscan(f, number=None):
"""Read the next spec scan in the file, which starts at the current position."""
scan = None
scannumber = None
while True:
l = f.readline()
if l.startswith('#S'):
scannumber = int(l[2:].split()[0])
if not ((number is None) or (num... |
def readspec(filename, read_scan=None):
"""Open a SPEC file and read its content
Inputs:
filename: string
the file to open
read_scan: None, 'all' or integer
the index of scan to be read from the file. If None, no scan should be read. If
'all', all scans sho... |
def readabt(filename, dirs='.'):
"""Read abt_*.fio type files from beamline B1, HASYLAB.
Input:
filename: the name of the file.
dirs: directories to search for files in
Output:
A dictionary. The fields are self-explanatory.
"""
# resolve filename
filename = misc.findfil... |
def energy(self) -> ErrorValue:
"""X-ray energy"""
return (ErrorValue(*(scipy.constants.physical_constants['speed of light in vacuum'][0::2])) *
ErrorValue(*(scipy.constants.physical_constants['Planck constant in eV s'][0::2])) /
scipy.constants.nano /
sel... |
def maskname(self) -> Optional[str]:
"""Name of the mask matrix file."""
try:
maskid = self._data['maskname']
if not maskid.endswith('.mat'):
maskid = maskid + '.mat'
return maskid
except KeyError:
return None |
def findbeam_gravity(data, mask):
"""Find beam center with the "gravity" method
Inputs:
data: scattering image
mask: mask matrix
Output:
a vector of length 2 with the x (row) and y (column) coordinates
of the origin, starting from 1
"""
# for each row and column fi... |
def findbeam_slices(data, orig_initial, mask=None, maxiter=0, epsfcn=0.001,
dmin=0, dmax=np.inf, sector_width=np.pi / 9.0, extent=10, callback=None):
"""Find beam center with the "slices" method
Inputs:
data: scattering matrix
orig_initial: estimated value for x (row) and y ... |
def findbeam_azimuthal(data, orig_initial, mask=None, maxiter=100, Ntheta=50,
dmin=0, dmax=np.inf, extent=10, callback=None):
"""Find beam center using azimuthal integration
Inputs:
data: scattering matrix
orig_initial: estimated value for x (row) and y (column)
... |
def findbeam_azimuthal_fold(data, orig_initial, mask=None, maxiter=100,
Ntheta=50, dmin=0, dmax=np.inf, extent=10, callback=None):
"""Find beam center using azimuthal integration and folding
Inputs:
data: scattering matrix
orig_initial: estimated value for x (row) an... |
def findbeam_semitransparent(data, pri, threshold=0.05):
"""Find beam with 2D weighting of semitransparent beamstop area
Inputs:
data: scattering matrix
pri: list of four: [xmin,xmax,ymin,ymax] for the borders of the beam
area under the semitransparent beamstop. X corresponds to the... |
def findbeam_radialpeak(data, orig_initial, mask, rmin, rmax, maxiter=100,
drive_by='amplitude', extent=10, callback=None):
"""Find the beam by minimizing the width of a peak in the radial average.
Inputs:
data: scattering matrix
orig_initial: first guess for the origin
... |
def findbeam_Guinier(data, orig_initial, mask, rmin, rmax, maxiter=100,
extent=10, callback=None):
"""Find the beam by minimizing the width of a Gaussian centered at the
origin (i.e. maximizing the radius of gyration in a Guinier scattering).
Inputs:
data: scattering matrix
... |
def findbeam_powerlaw(data, orig_initial, mask, rmin, rmax, maxiter=100,
drive_by='R2', extent=10, callback=None):
"""Find the beam by minimizing the width of a Gaussian centered at the
origin (i.e. maximizing the radius of gyration in a Guinier scattering).
Inputs:
data: scat... |
def beamcenterx(self) -> ErrorValue:
"""X (column) coordinate of the beam center, pixel units, 0-based."""
try:
return ErrorValue(self._data['geometry']['beamposy'],
self._data['geometry']['beamposy.err'])
except KeyError:
return ErrorValue(s... |
def beamcentery(self) -> ErrorValue:
"""Y (row) coordinate of the beam center, pixel units, 0-based."""
try:
return ErrorValue(self._data['geometry']['beamposx'],
self._data['geometry']['beamposx.err'])
except KeyError:
return ErrorValue(self... |
def maskname(self) -> Optional[str]:
"""Name of the mask matrix file."""
mask = self._data['geometry']['mask']
if os.path.abspath(mask):
mask = os.path.split(mask)[-1]
return mask |
def errtrapz(x, yerr):
"""Error of the trapezoid formula
Inputs:
x: the abscissa
yerr: the error of the dependent variable
Outputs:
the error of the integral
"""
x = np.array(x)
assert isinstance(x, np.ndarray)
yerr = np.array(yerr)
return 0.5 * np.sqrt((x[1] - x... |
def fit(self, fitfunction, parinit, unfittableparameters=(), *args, **kwargs):
"""Perform a nonlinear least-squares fit, using sastool.misc.fitter.Fitter()
Other arguments and keyword arguments will be passed through to the
__init__ method of Fitter. For example, these are:
- lbounds
... |
def momentum(self, exponent=1, errorrequested=True):
"""Calculate momenta (integral of y times x^exponent)
The integration is done by the trapezoid formula (np.trapz).
Inputs:
exponent: the exponent of q in the integration.
errorrequested: True if error should be returne... |
def scalefactor(self, other, qmin=None, qmax=None, Npoints=None):
"""Calculate a scaling factor, by which this curve is to be multiplied to best fit the other one.
Inputs:
other: the other curve (an instance of GeneralCurve or of a subclass of it)
qmin: lower cut-off (None to de... |
def _substitute_fixed_parameters_covar(self, covar):
"""Insert fixed parameters in a covariance matrix"""
covar_resolved = np.empty((len(self._fixed_parameters), len(self._fixed_parameters)))
indices_of_fixed_parameters = [i for i in range(len(self.parameters())) if
... |
def loadmask(self, filename: str) -> np.ndarray:
"""Load a mask file."""
mask = scipy.io.loadmat(self.find_file(filename, what='mask'))
maskkey = [k for k in mask.keys() if not (k.startswith('_') or k.endswith('_'))][0]
return mask[maskkey].astype(np.bool) |
def loadcurve(self, fsn: int) -> classes2.Curve:
"""Load a radial scattering curve"""
return classes2.Curve.new_from_file(self.find_file(self._exposureclass + '_%05d.txt' % fsn)) |
def readcbf(name, load_header=False, load_data=True, for_nexus=False):
"""Read a cbf (crystallographic binary format) file from a Dectris PILATUS
detector.
Inputs
------
name: string
the file name
load_header: bool
if the header data is to be loaded.
load_data: bool
... |
def readbdfv1(filename, bdfext='.bdf', bhfext='.bhf'):
"""Read bdf file (Bessy Data Format v1)
Input
-----
filename: string
the name of the file
Output
------
the BDF structure in a dict
Notes
-----
This is an adaptation of the bdf_read.m macro of Sylvio Haas.
"""
... |
def readint2dnorm(filename):
"""Read corrected intensity and error matrices (Matlab mat or numpy npz
format for Beamline B1 (HASYLAB/DORISIII))
Input
-----
filename: string
the name of the file
Outputs
-------
two ``np.ndarray``-s, the Intensity and the Error matrices
File... |
def writeint2dnorm(filename, Intensity, Error=None):
"""Save the intensity and error matrices to a file
Inputs
------
filename: string
the name of the file
Intensity: np.ndarray
the intensity matrix
Error: np.ndarray, optional
the error matrix (can be ``None``, if no err... |
def readmask(filename, fieldname=None):
"""Try to load a maskfile from a matlab(R) matrix file
Inputs
------
filename: string
the input file name
fieldname: string, optional
field in the mat file. None to autodetect.
Outputs
-------
the mask in a numpy array of type np.... |
def readedf(filename):
"""Read an ESRF data file (measured at beamlines ID01 or ID02)
Inputs
------
filename: string
the input file name
Output
------
the imported EDF structure in a dict. The scattering pattern is under key
'data'.
Notes
-----
Only datatype ``Floa... |
def readbdfv2(filename, bdfext='.bdf', bhfext='.bhf'):
"""Read a version 2 Bessy Data File
Inputs
------
filename: string
the name of the input file. One can give the complete header or datafile
name or just the base name without the extensions.
bdfext: string, optional
the ... |
def readmar(filename):
"""Read a two-dimensional scattering pattern from a MarResearch .image file.
"""
hed = header.readmarheader(filename)
with open(filename, 'rb') as f:
h = f.read(hed['recordlength'])
data = np.fromstring(
f.read(2 * hed['Xsize'] * hed['Ysize']), '<u2').a... |
def writebdfv2(filename, bdf, bdfext='.bdf', bhfext='.bhf'):
"""Write a version 2 Bessy Data File
Inputs
------
filename: string
the name of the output file. One can give the complete header or
datafile name or just the base name without the extensions.
bdf: dict
the BDF str... |
def rebinmask(mask, binx, biny, enlarge=False):
"""Re-bin (shrink or enlarge) a mask matrix.
Inputs
------
mask: np.ndarray
mask matrix.
binx: integer
binning along the 0th axis
biny: integer
binning along the 1st axis
enlarge: bool, optional
direction of bin... |
def fill_padding(padded_string):
# type: (bytes) -> bytes
"""
Fill up missing padding in a string.
This function makes sure that the string has length which is multiplication of 4,
and if not, fills the missing places with dots.
:param str padded_string: string to be decoded that might miss pa... |
def decode(encoded):
# type: (bytes) -> bytes
"""
Decode the result of querystringsafe_base64_encode or a regular base64.
.. note ::
As a regular base64 string does not contain dots, replacing dots with
equal signs does basically noting to it. Also,
base64.urlsafe_b64decode allo... |
def normalize_listargument(arg):
"""Check if arg is an iterable (list, tuple, set, dict, np.ndarray, except
string!). If not, make a list of it. Numpy arrays are flattened and
converted to lists."""
if isinstance(arg, np.ndarray):
return arg.flatten()
if isinstance(arg, str):
... |
def parse_number(val, use_dateutilparser=False):
"""Try to auto-detect the numeric type of the value. First a conversion to
int is tried. If this fails float is tried, and if that fails too, unicode()
is executed. If this also fails, a ValueError is raised.
"""
if use_dateutilparser:
funcs =... |
def flatten_hierarchical_dict(original_dict, separator='.', max_recursion_depth=None):
"""Flatten a dict.
Inputs
------
original_dict: dict
the dictionary to flatten
separator: string, optional
the separator item in the keys of the flattened dictionary
max_recursion_depth: posit... |
def random_str(Nchars=6, randstrbase='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Return a random string of <Nchars> characters. Characters are sampled
uniformly from <randstrbase>.
"""
return ''.join([randstrbase[random.randint(0, len(randstrbase) - 1)] for i in range(Nchars)]) |
def listB1(fsns, xlsname, dirs, whattolist = None, headerformat = 'org_%05d.header'):
""" getsamplenames revisited, XLS output.
Inputs:
fsns: FSN sequence
xlsname: XLS file name to output listing
dirs: either a single directory (string) or a list of directories, a la readheader()
... |
def fit_shullroess(q, Intensity, Error, R0=None, r=None):
"""Do a Shull-Roess fitting on the scattering data.
Inputs:
q: np.ndarray[ndim=1]
vector of the q values (4*pi*sin(theta)/lambda)
Intensity: np.ndarray[ndim=1]
Intensity vector
Error: np.ndarray[ndim=1]
... |
def maxwellian(r, r0, n):
"""Maxwellian-like distribution of spherical particles
Inputs:
-------
r: np.ndarray or scalar
radii
r0: positive scalar or ErrorValue
mean radius
n: positive scalar or ErrorValue
"n" parameter
Output:
--... |
def findfileindirs(filename, dirs=None, use_pythonpath=True, use_searchpath=True, notfound_is_fatal=True, notfound_val=None):
"""Find file in multiple directories.
Inputs:
filename: the file name to be searched for.
dirs: list of folders or None
use_pythonpath: use the Python module sea... |
def twotheta(matrix, bcx, bcy, pixsizeperdist):
"""Calculate the two-theta matrix for a scattering matrix
Inputs:
matrix: only the shape of it is needed
bcx, bcy: beam position (counting from 0; x is row, y is column index)
pixsizeperdist: the pixel size divided by the sample-to-detecto... |
def solidangle(twotheta, sampletodetectordistance, pixelsize=None):
"""Solid-angle correction for two-dimensional SAS images
Inputs:
twotheta: matrix of two-theta values
sampletodetectordistance: sample-to-detector distance
pixelsize: the pixel size in mm
The output matrix is of th... |
def solidangle_errorprop(twotheta, dtwotheta, sampletodetectordistance, dsampletodetectordistance, pixelsize=None):
"""Solid-angle correction for two-dimensional SAS images with error propagation
Inputs:
twotheta: matrix of two-theta values
dtwotheta: matrix of absolute error of two-theta value... |
def angledependentabsorption(twotheta, transmission):
"""Correction for angle-dependent absorption of the sample
Inputs:
twotheta: matrix of two-theta values
transmission: the transmission of the sample (I_after/I_before, or
exp(-mu*d))
The output matrix is of the same shape as... |
def angledependentabsorption_errorprop(twotheta, dtwotheta, transmission, dtransmission):
"""Correction for angle-dependent absorption of the sample with error propagation
Inputs:
twotheta: matrix of two-theta values
dtwotheta: matrix of absolute error of two-theta values
transmission: ... |
def angledependentairtransmission(twotheta, mu_air, sampletodetectordistance):
"""Correction for the angle dependent absorption of air in the scattered
beam path.
Inputs:
twotheta: matrix of two-theta values
mu_air: the linear absorption coefficient of air
sampletodetect... |
def angledependentairtransmission_errorprop(twotheta, dtwotheta, mu_air,
dmu_air, sampletodetectordistance,
dsampletodetectordistance):
"""Correction for the angle dependent absorption of air in the scattered
beam path, with... |
def find_file(self, filename: str, strip_path: bool = True, what='exposure') -> str:
"""Find file in the path"""
if what == 'exposure':
path = self._path
elif what == 'header':
path = self._headerpath
elif what == 'mask':
path = self._maskpath
... |
def get_subpath(self, subpath: str):
"""Search a file or directory relative to the base path"""
for d in self._path:
if os.path.exists(os.path.join(d, subpath)):
return os.path.join(d, subpath)
raise FileNotFoundError |
def new_from_file(self, filename: str, header_data: Optional[Header] = None,
mask_data: Optional[np.ndarray] = None):
"""Load an exposure from a file.""" |
def sum(self, only_valid=True) -> ErrorValue:
"""Calculate the sum of pixels, not counting the masked ones if only_valid is True."""
if not only_valid:
mask = 1
else:
mask = self.mask
return ErrorValue((self.intensity * mask).sum(),
((sel... |
def mean(self, only_valid=True) -> ErrorValue:
"""Calculate the mean of the pixels, not counting the masked ones if only_valid is True."""
if not only_valid:
intensity = self.intensity
error = self.error
else:
intensity = self.intensity[self.mask]
... |
def twotheta(self) -> ErrorValue:
"""Calculate the two-theta array"""
row, column = np.ogrid[0:self.shape[0], 0:self.shape[1]]
rho = (((self.header.beamcentery - row) * self.header.pixelsizey) ** 2 +
((self.header.beamcenterx - column) * self.header.pixelsizex) ** 2) ** 0.5
... |
def pixel_to_q(self, row: float, column: float):
"""Return the q coordinates of a given pixel.
Inputs:
row: float
the row (vertical) coordinate of the pixel
column: float
the column (horizontal) coordinate of the pixel
Coordinates are 0-b... |
def imshow(self, *args, show_crosshair=True, show_mask=True,
show_qscale=True, axes=None, invalid_color='black',
mask_opacity=0.8, show_colorbar=True, **kwargs):
"""Plot the matrix (imshow)
Keyword arguments [and their default values]:
show_crosshair [True]: if a ... |
def radial_average(self, qrange=None, pixel=False, returnmask=False,
errorpropagation=3, abscissa_errorpropagation=3,
raw_result=False) -> Curve:
"""Do a radial averaging
Inputs:
qrange: the q-range. If None, auto-determine. If 'linear', auto-de... |
def mask_negative(self):
"""Extend the mask with the image elements where the intensity is negative."""
self.mask = np.logical_and(self.mask, ~(self.intensity < 0)) |
def mask_nan(self):
"""Extend the mask with the image elements where the intensity is NaN."""
self.mask = np.logical_and(self.mask, ~(np.isnan(self.intensity))) |
def mask_nonfinite(self):
"""Extend the mask with the image elements where the intensity is NaN."""
self.mask = np.logical_and(self.mask, (np.isfinite(self.intensity))) |
def distance(self) -> ErrorValue:
"""Sample-to-detector distance"""
if 'DistCalibrated' in self._data:
dist = self._data['DistCalibrated']
else:
dist = self._data["Dist"]
if 'DistCalibratedError' in self._data:
disterr = self._data['DistCalibratedError... |
def temperature(self) -> Optional[ErrorValue]:
"""Sample temperature"""
try:
return ErrorValue(self._data['Temperature'], self._data.setdefault('TemperatureError', 0.0))
except KeyError:
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.