sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
`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 code way more easy. This bahaviour is based upon th...
entailment
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*...
**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**: any valid expression of the DSL to be evaluated inside the ...
entailment
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)
Same as `phi.dsl.Expression.List` but any string argument `x` is translated to `Read(x)`.
entailment
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("...
See `phi.dsl.Expression.Read`
entailment
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 ...
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 expression as a whole is a constant functi...
entailment
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...
**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 used. * ***Then** : an expression to be excecuted if ...
entailment
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)
See `phi.dsl.Expression.If`
entailment
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 ...
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 to the `until` argument, if given. This is u...
entailment
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...
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[7:] 'เฎฟ (ni)' >>> grapheme.slice(string, 7) ...
entailment
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...
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 grapheme boundaries. Performance notes: Very fa...
entailment
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...
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. >>> grapheme.startswith("โœŠ๐Ÿพ", "โœŠ") False >>...
entailment
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....
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.endswith("๐Ÿณ๏ธโ€๐ŸŒˆ", "๐ŸŒˆ") False >>>...
entailment
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...
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 to risk breaking existing graphemes. This funct...
entailment
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() ...
Read B1 logfile (*.log) Inputs: filename: the file name Output: A dictionary.
entailment
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...
Write a header structure into a B1 logfile. Inputs: filename: name of the file. data: header dictionary Notes: exceptions pass through to the caller.
entailment
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...
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 'ORG000123.DAT':: header=read...
entailment
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...
Helper function to interpret lines in an EDF file header.
entailment
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...
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
entailment
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...
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 macro from Sylvio Haas.
entailment
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(...
Read a header from a MarResearch .image file.
entailment
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...
Read a header from a SANS file (produced usually by BerSANS)
entailment
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 * ...
Sine function Inputs: ------- ``x``: independent variable ``a``: amplitude ``omega``: circular frequency ``phi``: phase ``y0``: offset Formula: -------- ``a*sin(x*omega + phi)+y0``
entailment
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(...
Cosine function Inputs: ------- ``x``: independent variable ``a``: amplitude ``omega``: circular frequency ``phi``: phase ``y0``: offset Formula: -------- ``a*cos(x*omega + phi)+y0``
entailment
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...
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``
entailment
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: ...
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: -------- ``a*x^3 + b*x^...
entailment
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
Exponential function Inputs: ------- ``x``: independent variable ``a``: scaling factor ``tau``: time constant ``y0``: additive constant Formula: -------- ``a*exp(x/tau)+y0``
entailment
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)...
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)/sigma)^2)+y0``
entailment
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)...
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)/(2*sigma^2)+y0``
entailment
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...
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))
entailment
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...
Radial integration (averaging) on the detector plane Inputs: data: scattering pattern matrix (np.ndarray, dtype: np.double) dataerr: error matrix (np.ndarray, dtype: np.double; or None) bcx, bcy: beam position, counting from 1 mask: mask matrix (np.ndarray, dtype: np.uint8) ...
entailment
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 (...
Azimuthal integration (averaging) on the detector plane Inputs: data: scattering pattern matrix (np.ndarray, dtype: np.double) dataerr: error matrix (np.ndarray, dtype: np.double; or None) bcx, bcy: beam position, counting from 1 mask: mask matrix (np.ndarray, dtype: np.uint8) ...
entailment
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...
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. Examples: >>> find_subdirs('dir',0) # returns just ['d...
entailment
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...
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 be None) position, hwhm, baseline, amplitude: first guesses for the named parameters curve: '...
entailment
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...
Find a (positive or negative) peak in the dataset. Inputs: x, y, dy: abscissa, ordinate and the error of the ordinate (can be None) position, hwhm, baseline, amplitude: first guesses for the named parameters curve: 'Gauss' or 'Lorentz' (default) return_stat: return fitting statistic...
entailment
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...
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 negatives caused by fluctuations, Ntolerance is introduced. It is the number of outlier points to be tolerate...
entailment
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...
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 (case insensitive): if starts with "Lorentz", a Lorentzian curve will be fitted. If starts ...
entailment
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...
Read the next spec scan in the file, which starts at the current position.
entailment
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...
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 should be read. If a number, just the scan with th...
entailment
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...
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.
entailment
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...
X-ray energy
entailment
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
Name of the mask matrix file.
entailment
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...
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
entailment
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 ...
Find beam center with the "slices" method Inputs: data: scattering matrix orig_initial: estimated value for x (row) and y (column) coordinates of the beam center, starting from 1. mask: mask matrix. If None, nothing will be masked. Otherwise it should be of the same ...
entailment
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) ...
Find beam center using azimuthal integration Inputs: data: scattering matrix orig_initial: estimated value for x (row) and y (column) coordinates of the beam center, starting from 1. mask: mask matrix. If None, nothing will be masked. Otherwise it should be of the sa...
entailment
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...
Find beam center using azimuthal integration and folding Inputs: data: scattering matrix orig_initial: estimated value for x (row) and y (column) coordinates of the beam center, starting from 1. mask: mask matrix. If None, nothing will be masked. Otherwise it should ...
entailment
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...
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 column index (ie. A[Y,X] is the element of A from t...
entailment
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 ...
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 mask: mask matrix. Nonzero is non-masked. rmin,rmax: distance from the origin (in pixels) of the peak range. drive_by: 'hwhm' to mi...
entailment
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 ...
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 orig_initial: first guess for the origin mask: mask matrix. Nonzero is non-masked. rmin,rmax: distance fro...
entailment
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...
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 orig_initial: first guess for the origin mask: mask matrix. Nonzero is non-masked. rmin,rmax: distance fro...
entailment
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...
X (column) coordinate of the beam center, pixel units, 0-based.
entailment
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...
Y (row) coordinate of the beam center, pixel units, 0-based.
entailment
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
Name of the mask matrix file.
entailment
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...
Error of the trapezoid formula Inputs: x: the abscissa yerr: the error of the dependent variable Outputs: the error of the integral
entailment
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 ...
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 - ubounds - ytransform - loss - method Returns: the...
entailment
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...
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 returned (true Gaussian error-propagation of the trapez...
entailment
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...
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 determine the common range automatically) qmax: upper cut-off (None...
entailment
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 ...
Insert fixed parameters in a covariance matrix
entailment
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)
Load a mask file.
entailment
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))
Load a radial scattering curve
entailment
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 ...
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 if the binary data is to be loaded. for_nexus: bool if the array s...
entailment
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. """ ...
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.
entailment
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...
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 formats supported: ------------...
entailment
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...
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 error matrix is to be saved) Output ------ None
entailment
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....
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.uint8
entailment
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...
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 ``FloatValue`` is supported right no...
entailment
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 ...
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 extension of the data file bhfext: string, optional ...
entailment
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...
Read a two-dimensional scattering pattern from a MarResearch .image file.
entailment
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...
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 structure (in the same format as loaded by ``readbdfv2()`` bdfext: ...
entailment
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...
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 binning. If True, the matrix will be enlarged, otherwise ...
entailment
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...
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 padding dots. :return: properly padded string :rtype: str
entailment
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...
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 allows to decode both safe and unsafe base64. Therefore th...
entailment
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): ...
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.
entailment
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 =...
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.
entailment
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...
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: positive integer, optional the number of recursions to be done. None is infinte. Outpu...
entailment
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)])
Return a random string of <Nchars> characters. Characters are sampled uniformly from <randstrbase>.
entailment
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() ...
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() whattolist: format specifier for listing. Should be a list of tuples. Each tuple ...
entailment
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] ...
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] Error of the intensity (absolute uncertainty, 1sigma) ...
entailment
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: --...
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: ------- the distribution fu...
entailment
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...
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 search path use_searchpath: use the sastool search path. notfound_is_fatal: if an exception is to be raised if the file ...
entailment
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...
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-detector distance Outputs: the two th...
entailment
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...
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 the same shape as twotheta. The scattering intensity matrix should be...
entailment
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...
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 values sampletodetectordistance: sample-to-detector distance dsampletodetectordistance: absolute error of sample...
entailment
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...
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 twotheta. The scattering intensity matrix should be ...
entailment
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: ...
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: the transmission of the sample (I_after/I_before, or exp(-mu*d)) dtransmissio...
entailment
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...
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 sampletodetectordistance: sample-to-detector distance 1/mu_air and sampletodetectordistance sho...
entailment
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...
Correction for the angle dependent absorption of air in the scattered beam path, with error propagation Inputs: twotheta: matrix of two-theta values dtwotheta: absolute error matrix of two-theta mu_air: the linear absorption coefficient of air dmu_air: error of t...
entailment
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 ...
Find file in the path
entailment
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
Search a file or directory relative to the base path
entailment
def new_from_file(self, filename: str, header_data: Optional[Header] = None, mask_data: Optional[np.ndarray] = None): """Load an exposure from a file."""
Load an exposure from a file.
entailment
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...
Calculate the sum of pixels, not counting the masked ones if only_valid is True.
entailment
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] ...
Calculate the mean of the pixels, not counting the masked ones if only_valid is True.
entailment
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 ...
Calculate the two-theta array
entailment
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...
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-based and calculated from the top left corner.
entailment
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 ...
Plot the matrix (imshow) Keyword arguments [and their default values]: show_crosshair [True]: if a cross-hair marking the beam position is to be plotted. show_mask [True]: if the mask is to be plotted. show_qscale [True]: if the horizontal and vertical axes are to be ...
entailment
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...
Do a radial averaging Inputs: qrange: the q-range. If None, auto-determine. If 'linear', auto-determine with linear spacing (same as None). If 'log', auto-determine with log10 spacing. pixel: do a pixel-integration (instead of q) returnmask: i...
entailment
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))
Extend the mask with the image elements where the intensity is negative.
entailment
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)))
Extend the mask with the image elements where the intensity is NaN.
entailment
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)))
Extend the mask with the image elements where the intensity is NaN.
entailment
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...
Sample-to-detector distance
entailment
def temperature(self) -> Optional[ErrorValue]: """Sample temperature""" try: return ErrorValue(self._data['Temperature'], self._data.setdefault('TemperatureError', 0.0)) except KeyError: return None
Sample temperature
entailment