output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
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: ...
How would you code a function in Python 3 to third order polynomial of a set of terms.
As a Python code translator, you convert algorithms and pseudocode into Python.
Exponential function that returns the log - likelihood of a time - series.
Can you generate a brief explanation for the following Python 3 code def Exponential(x, a, tau, y0): return np.exp(x / tau) * a + y0
You are a Python code architect, reviewing and designing scalable and efficient code
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``
How would you explain what the following Python 3 function does def Lorentzian(x, a, x0, sigma, y0): return a / (1 + ((x - x0) / sigma) ** 2) + y0
As a Python code analyst, you investigate and solve complex coding mysteries
PDF of a log - normal distribution.
Explain what the following Python 3 code does def LogNormal(x, a, mu, sigma): return a / np.sqrt(2 * np.pi * sigma ** 2 * x ** 2) *\ np.exp(-(np.log(x) - mu) ** 2 / (2 * sigma ** 2))
As a Python code translator, you convert algorithms and pseudocode into Python.
Radial integration of a single image on the detector plane.
Can you generate the documentation for the following Python 3 function 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 integrati...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 function that can find all subdirs of a directory.
As a Python code composer, you craft elegant and concise scripts.
This function finds a positive peak in the dataset.
How would you explain what the following Python 3 function does def findpeak(x, y, dy=None, position=None, hwhm=None, baseline=None, amplitude=None, curve='Lorentz'): warnings.warn('Function findpeak() is deprecated, please use findpeak_single() instead.', DeprecationWarning) pos, hwhm, baseline, ampl = findpea...
As a python code expert, you are capable of creating scripts from specifications.
Find a single peak in the dataset.
Can you generate the documentation for the following Python 3 function 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:...
As a Python code composer, you craft elegant and concise scripts.
Find multiple peaks in the dataset given by vectors x and y.
Given the following Python 3 function, write the documentation def findpeak_multi(x, y, dy, N, Ntolerance, Nfit=None, curve='Lorentz', return_xfit=False, return_stat=False): if Nfit is None: Nfit = N # find points where the curve grows for N points before them and # decreases for N points after them...
You are a Python code analyst, evaluating scripts for potential improvements.
This function finds an asymmetric peak in the dataset.
Make a summary of the following Python 3 code def findpeak_asymmetric(x, y, dy=None, curve='Lorentz', return_x=None, init_parameters=None): idx = np.logical_and(np.isfinite(x), np.isfinite(y)) if dy is not None: idx = np.logical_and(idx, np.isfinite(dy)) x=x[idx] y=y[idx] if dy is not None: ...
As a Python code composer, you craft elegant and concise scripts.
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...
Can you implement a function in Python 3 that reads the next spec scan in the file.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you write a function in Python 3 where it opens a SPEC file and read its content into a dict.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 function for reading a file from beamline B1 HASYLAB and return a dictionary. The keys are self - planatory. The values are self - planatory.
You are a Python code architect, reviewing and designing scalable and efficient code
X - ray energy
Explain what the following Python 3 code does def energy(self) -> ErrorValue: 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 / ...
As a Python code analyst, you investigate and solve complex coding mysteries
Name of the mask matrix file.
Given the following Python 3 function, write the documentation def maskname(self) -> Optional[str]: try: maskid = self._data['maskname'] if not maskid.endswith('.mat'): maskid = maskid + '.mat' return maskid except KeyError: return None
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you create a Python 3 function that finds the beam center with the gravity method.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
How would you code a function in Python 3 to find beam center with the slices method.
As a Python code analyst, you investigate and solve complex coding mysteries
This function finds the beam center using azimuthal integration.
Here you have a function in Python 3, explain what it does 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_in...
You are a Python code architect, reviewing and designing scalable and efficient code
This function finds the beam center using azimuthal integration and folding.
Make a summary of the following Python 3 code 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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 script for finding beam with 2D weighting of semitransparent beamstop area.
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 script to find the beam in the radial average.
As a Python code composer, you craft elegant and concise scripts.
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 ...
How would you code a function in Python 3 to find the beam of a Guinier scattering.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 function that can find the beam of a Guinier scattering.
As a Python code composer, you craft elegant and concise scripts.
Name of the mask matrix file.
Can you generate the documentation for the following Python 3 function def maskname(self) -> Optional[str]: mask = self._data['geometry']['mask'] if os.path.abspath(mask): mask = os.path.split(mask)[-1] return mask
As a Python code translator, you convert algorithms and pseudocode into Python.
Perform a nonlinear least - squares fit using sastool. misc. fitter. Fitter. fit
Can you tell what is the following Python 3 function doing def fit(self, fitfunction, parinit, unfittableparameters=(), *args, **kwargs): kwargs['otherparameters'] = unfittableparameters fitter = Fitter(fitfunction, parinit, self.q, self.Intensity, self.qError, self.Error, *args, **kwargs) fixed...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculate the momentum of the object.
Can you tell what is the following Python 3 function doing def momentum(self, exponent=1, errorrequested=True): y = self.Intensity * self.q ** exponent m = np.trapz(y, self.q) if errorrequested: err = self.Error * self.q ** exponent dm = errtrapz(self.q, err) ...
You are a Python code generator, capable of creating scripts from specifications.
Calculates a scaling factor by which this curve is to be multiplied to best fit the other one.
Explain what the following Python 3 code does def scalefactor(self, other, qmin=None, qmax=None, Npoints=None): if qmin is None: qmin = max(self.q.min(), other.q.min()) if qmax is None: xmax = min(self.q.max(), other.q.max()) data1 = self.trim(qmin, qmax) data2 = ...
You are a Python code architect, reviewing and designing scalable and efficient code
Insert fixed parameters in a covariance matrix
Explain what the following Python 3 code does def _substitute_fixed_parameters_covar(self, covar): 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 self....
As a Python code composer, you craft elegant and concise scripts.
Load a mask file.
Given the following Python 3 function, write the documentation def loadmask(self, filename: str) -> np.ndarray: 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)
You are a Python code generator, capable of creating scripts from specifications.
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))
How would you implement a function in Python 3 that loads a radial scattering curve
As a Python code translator, you convert algorithms and pseudocode into Python.
Reads a cbf file from a Dectris PILATUS detector.
Can you generate a brief explanation for the following Python 3 code def readcbf(name, load_header=False, load_data=True, for_nexus=False): with open(name, 'rb') as f: cbfbin = f.read() datastart = cbfbin.find(b'\x0c\x1a\x04\xd5') + 4 hed = [x.strip() for x in cbfbin[:datastart].split(b'\n')] he...
As a Python code analyst, you investigate and solve complex coding mysteries
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. """ ...
Write a Python 3 function for reading a Bessy Data Format v1 file.
As a Python code composer, you craft elegant and concise scripts.
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...
Can you write a function in Python 3 where it reads corrected intensity and error matrices from a file.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Can you implement a function in Python 3 that saves the intensity and error matrices to a file.
As a python code expert, you are capable of creating scripts from specifications.
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....
Create a Python 3 function to try to load a maskfile from a matlab R matrix file.
As a Python code composer, you craft elegant and concise scripts.
Read an ESRF file and return a dict with the data as a numpy array.
Can you generate the documentation for the following Python 3 function def readedf(filename): edf = header.readehf(filename) f = open(filename, 'rb') f.read(edf['EDF_HeaderSize']) # skip header. if edf['DataType'] == 'FloatValue': dtype = np.float32 else: raise NotImplementedError( ...
You are a Python code generator, capable of creating scripts from specifications.
Read a version 2 Bessy Data File
Given the following Python 3 function, write the documentation def readbdfv2(filename, bdfext='.bdf', bhfext='.bhf'): datas = header.readbhfv2(filename, True, bdfext, bhfext) return datas
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you write a function in Python 3 where it reads a two - dimensional scattering pattern from a MarResearch. image file.
You are a Python code generator, capable of creating scripts from specifications.
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...
Create a Python 3 function to write a version 2 BDF file with the given data.
You are a Python code architect, reviewing and designing scalable and efficient code
Re - bin a mask matrix.
Explain what the following Python 3 code does def rebinmask(mask, binx, biny, enlarge=False): if not enlarge and ((mask.shape[0] % binx) or (mask.shape[1] % biny)): raise ValueError( 'The number of pixels of the mask matrix should be divisible by the binning in each direction!') if enlarge: ...
As a python code expert, you are capable of creating scripts from specifications.
Fills up missing padding in a string.
How would you explain what the following Python 3 function does 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. :...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function for decoding a querystringsafe base64 string or a regular base64 string.
You are a Python code generator, capable of creating scripts from specifications.
Check if arg is iterable and if not make a list of it. Numpy arrays are flattened and converted to lists.
Can you generate a brief explanation for the following Python 3 code def normalize_listargument(arg): if isinstance(arg, np.ndarray): return arg.flatten() if isinstance(arg, str): return [arg] if isinstance(arg, list) or isinstance(arg, tuple) or isinstance(arg, dict) or isinstance(arg, set)...
You are a Python code analyst, evaluating scripts for potential improvements.
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 =...
How would you implement a function in Python 3 that tries to auto - detect the numeric type of the value.
You are a Python code generator, capable of creating scripts from specifications.
Flatten a dictionary of hierarchical items.
Explain what the following Python 3 code does def flatten_hierarchical_dict(original_dict, separator='.', max_recursion_depth=None): if max_recursion_depth is not None and max_recursion_depth <= 0: # we reached the maximum recursion depth, refuse to go further return original_dict if max_recursi...
As a Python code analyst, you investigate and solve complex coding mysteries
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)])
How would you implement a function in Python 3 that returns a random string of Nchars characters. Characters are sampled from randstrbase.
As a Python code translator, you convert algorithms and pseudocode into Python.
This function lists the contents of a single file in a single cell.
Can you generate a brief explanation for the following Python 3 code def listB1(fsns, xlsname, dirs, whattolist = None, headerformat = 'org_%05d.header'): if whattolist is None: whattolist = [('FSN', 'FSN'), ('Time', 'MeasTime'), ('Energy', 'Energy'), ('Distance', 'Dist'), ('Position', '...
You are a Python code analyst, evaluating scripts for potential improvements.
This function is used to fit a single object in a set of objects.
Given the following Python 3 function, write the documentation def fit_shullroess(q, Intensity, Error, R0=None, r=None): q = np.array(q) Intensity = np.array(Intensity) Error = np.array(Error) if R0 is None: r0s = np.linspace(1, 2 * np.pi / q.min(), 1000) def naive_fit_chi2(q, Intensity,...
As a Python code composer, you craft elegant and concise scripts.
Maxwellian - like distribution of spherical particles in a single species.
Here you have a function in Python 3, explain what it does def maxwellian(r, r0, n): r0 = ErrorValue(r0) n = ErrorValue(n) expterm = np.exp(-r ** 2 / r0.val ** 2) dmaxdr0 = -2 * r ** n.val * r0.val ** (-n.val - 4) * ((n.val + 1) * r0.val ** 2 - 2 * r ** 2) * expterm / gamma((n.val + 1) * 0.5) dmaxd...
As a Python code analyst, you investigate and solve complex coding mysteries
Find file in multiple directories.
Make a summary of the following Python 3 code def findfileindirs(filename, dirs=None, use_pythonpath=True, use_searchpath=True, notfound_is_fatal=True, notfound_val=None): if os.path.isabs(filename): if os.path.exists(filename): return filename elif notfound_is_fatal: raise I...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you implement a function in Python 3 that calculates the two - theta matrix for a scattering matrix.
You are a Python code analyst, evaluating scripts for potential improvements.
Correction for angle - dependent absorption of the sample Taxonomy
Make a summary of the following Python 3 code def angledependentabsorption(twotheta, transmission): cor = np.ones(twotheta.shape) if transmission == 1: return cor mud = -np.log(transmission) cor[twotheta > 0] = transmission * mud * (1 - 1 / np.cos(twotheta[twotheta > 0])) / (np.exp(-mud / np.co...
You are a Python code architect, reviewing and designing scalable and efficient code
Find the file in the path
Can you generate the documentation for the following Python 3 function def find_file(self, filename: str, strip_path: bool = True, what='exposure') -> str: if what == 'exposure': path = self._path elif what == 'header': path = self._headerpath elif what == 'mask': ...
As a Python code analyst, you investigate and solve complex coding mysteries
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
Can you implement a function in Python 3 that searches a file or directory relative to the base path
You are a Python code architect, reviewing and designing scalable and efficient code
def new_from_file(self, filename: str, header_data: Optional[Header] = None, mask_data: Optional[np.ndarray] = None): """Load an exposure from a file."""
Write a Python 3 script for loading an exposure from a file.
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 function that can calculate the sum of pixels not counting the masked ones.
As a python code expert, you are capable of creating scripts from specifications.
Calculate the mean of the pixels not counting the masked ones.
How would you explain what the following Python 3 function does def mean(self, only_valid=True) -> ErrorValue: if not only_valid: intensity = self.intensity error = self.error else: intensity = self.intensity[self.mask] error = self.error[self.mask] ...
You are a Python code generator, capable of creating scripts from specifications.
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 ...
How would you implement a function in Python 3 that calculates the two - theta array
As a python code expert, you are capable of creating scripts from specifications.
Return the q coordinates of a given pixel.
Given the following Python 3 function, write the documentation def pixel_to_q(self, row: float, column: float): qrow = 4 * np.pi * np.sin( 0.5 * np.arctan( (row - float(self.header.beamcentery)) * float(self.header.pixelsizey) / float(self.header.dista...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 script for plotting the image of the current state of the object.
You are a Python code analyst, evaluating scripts for potential improvements.
This function performs a radial averaging of the current state of the object.
Make a summary of the following Python 3 code 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....
You are a Python code architect, reviewing and designing scalable and efficient code
Extend the mask with the image elements where the intensity is negative.
How would you explain what the following Python 3 function does def mask_negative(self): self.mask = np.logical_and(self.mask, ~(self.intensity < 0))
You are a Python code architect, reviewing and designing scalable and efficient code
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)))
How would you implement a function in Python 3 that extends the mask with the image elements where the intensity is NaN.
As a Python code composer, you craft elegant and concise scripts.
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)))
Write a Python 3 function that can extend the mask with the image elements where the intensity is NaN.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Create a Python 3 function to sample - to - detector distance
As a Python code analyst, you investigate and solve complex coding mysteries
def date(self) -> datetime.datetime: """Date of the experiment (start of exposure)""" return self._data['Date'] - datetime.timedelta(0, float(self.exposuretime), 0)
Can you implement a function in Python 3 that dates of the experiment
You are a Python code architect, reviewing and designing scalable and efficient code
def flux(self) -> ErrorValue: """X-ray flux in photons/sec.""" try: return ErrorValue(self._data['Flux'], self._data.setdefault('FluxError',0.0)) except KeyError: return 1 / self.pixelsizex / self.pixelsizey / ErrorValue(self._data['NormFactor'], ...
Create a Python 3 function to return the flux in photons.
You are a Python code architect, reviewing and designing scalable and efficient code
This function is used to fit a nonlinear least squares problem.
Given the following Python 3 function, write the documentation def nonlinear_leastsquares(x: np.ndarray, y: np.ndarray, dy: np.ndarray, func: Callable, params_init: np.ndarray, verbose: bool = False, **kwargs): """Perform a non-linear least squares fit, return the results as ErrorValu...
You are a Python code architect, reviewing and designing scalable and efficient code
def nonlinear_odr(x, y, dx, dy, func, params_init, **kwargs): """Perform a non-linear orthogonal distance regression, return the results as ErrorValue() instances. Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable ...
Can you create a Python 3 function that performs a non - linear orthogonal distance regression on the given set of elements.
As a Python code translator, you convert algorithms and pseudocode into Python.
A function that fit a set of parameters and return the fitted parameters as instances of ErrorValue.
Explain what the following Python 3 code does def simultaneous_nonlinear_leastsquares(xs, ys, dys, func, params_inits, verbose=False, **kwargs): p, dp, statdict = simultaneous_nlsq_fit(xs, ys, dys, func, params_inits, verbose, **kwargs) params = [[ErrorValue(p_, dp_) ...
You are a Python code generator, capable of creating scripts from specifications.
def nlsq_fit(x, y, dy, func, params_init, verbose=False, **kwargs): """Perform a non-linear least squares fit Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable dy: absolute error (square root of the variance) of t...
Create a Python 3 function to perform a non - linear least squares fit on the base of the unity tree.
You are a Python code generator, capable of creating scripts from specifications.
def simultaneous_nlsq_fit(xs, ys, dys, func, params_inits, verbose=False, **kwargs): """Do a simultaneous nonlinear least-squares fit Input: ------ `xs`: tuple of abscissa vectors (1d numpy ndarrays) `ys`: tuple of ordinate vectors (1d numpy ndarrays) `dys`: tuple o...
Create a Python 3 function to do a simultaneous nonlinear least - squares fit on a single base language tree.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert the ErrorValue object into a string representation.
Given the following Python 3 function, write the documentation def tostring(self: 'ErrorValue', extra_digits: int = 0, plusminus: str = ' +/- ', fmt: str = None) -> str: if isinstance(fmt, str) and fmt.lower().endswith('tex'): return re.subn('(\d*)(\.(\d)*)?[eE]([+-]?\d+)', ...
As a Python code composer, you craft elegant and concise scripts.
Sample a random number of the distribution defined by the error and variance of the object.
Can you generate the documentation for the following Python 3 function def random(self: 'ErrorValue') -> np.ndarray: if isinstance(self.val, np.ndarray): # IGNORE:E1103 return np.random.randn(self.val.shape) * self.err + self.val else: return np.random.randn() * self....
You are a Python code analyst, evaluating scripts for potential improvements.
def evalfunc(cls, func, *args, **kwargs): """Evaluate a function with error propagation. Inputs: ------- ``func``: callable this is the function to be evaluated. Should return either a number or a np.ndarray. ``*args``: other positional ar...
Write a Python 3 function that can evaluate a function with error propagation.
As a Python code analyst, you investigate and solve complex coding mysteries
def Fsphere(q, R): """Scattering form-factor amplitude of a sphere normalized to F(q=0)=V Inputs: ------- ``q``: independent variable ``R``: sphere radius Formula: -------- ``4*pi/q^3 * (sin(qR) - qR*cos(qR))`` """ return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R ...
Implement a Python 3 function for returning the F - factor amplitude of a sphere normalized to F ( q = 0 ) = V
As a Python code analyst, you investigate and solve complex coding mysteries
def GeneralGuinier(q, G, Rg, s): """Generalized Guinier scattering Inputs: ------- ``q``: independent variable ``G``: factor ``Rg``: radius of gyration ``s``: dimensionality parameter (can be 1, 2, 3) Formula: -------- ``G/q**(3-s)*exp(-(q^2*Rg^2)/s)`` "...
Can you create a Python 3 function that generalizes Guinier scattering of a set of variables.
As a Python code analyst, you investigate and solve complex coding mysteries
Empirical Guinier - Porod scattering.
Can you generate a brief explanation for the following Python 3 code def GuinierPorod(q, G, Rg, alpha): return GuinierPorodMulti(q, G, Rg, alpha)
You are a Python code generator, capable of creating scripts from specifications.
Empirical Porod - Guinier - Porod scattering.
Can you generate a brief explanation for the following Python 3 code def PorodGuinierPorod(q, a, alpha, Rg, beta): return PorodGuinierMulti(q, a, alpha, Rg, beta)
You are a Python code generator, capable of creating scripts from specifications.
Empirical Guinier - Porod - Guinier scattering.
Here you have a function in Python 3, explain what it does def GuinierPorodGuinier(q, G, Rg1, alpha, Rg2): return GuinierPorodMulti(q, G, Rg1, alpha, Rg2)
As a python code expert, you are capable of creating scripts from specifications.
def DampedPowerlaw(q, a, alpha, sigma): """Damped power-law Inputs: ------- ``q``: independent variable ``a``: factor ``alpha``: exponent ``sigma``: hwhm of the damping Gaussian Formula: -------- ``a*q^alpha*exp(-q^2/(2*sigma^2))`` """ return a * q *...
Write a Python 3 function for damping power - law of a set of variables.
You are a Python code analyst, evaluating scripts for potential improvements.
def LogNormSpheres(q, A, mu, sigma, N=1000): """Scattering of a population of non-correlated spheres (radii from a log-normal distribution) Inputs: ------- ``q``: independent variable ``A``: scaling factor ``mu``: expectation of ``ln(R)`` ``sigma``: hwhm of ``ln(R)`` No...
Can you implement a function in Python 3 that logs Normal Spheres in the hierarchy of non - correlated spheres.
As a python code expert, you are capable of creating scripts from specifications.
Computes the scattering of non - correlated spheres in a single population of non - correlated spheres.
Can you tell what is the following Python 3 function doing def GaussSpheres(q, A, R0, sigma, N=1000, weighting='intensity'): Rmin = max(0, R0 - 3 * sigma) Rmax = R0 + 3 * sigma R = np.linspace(Rmin, Rmax, N + 1)[1:] P = 1 / np.sqrt(2 * np.pi * sigma ** 2) * np.exp(-(R - R0) ** 2 / (2 * sigma ** 2)) ...
As a Python code composer, you craft elegant and concise scripts.
def PowerlawGuinierPorodConst(q, A, alpha, G, Rg, beta, C): """Sum of a Power-law, a Guinier-Porod curve and a constant. Inputs: ------- ``q``: independent variable (momentum transfer) ``A``: scaling factor of the power-law ``alpha``: power-law exponent ``G``: scaling factor...
Can you implement a function in Python 3 that sums of a Power - law a Guinier - Porod curve and a constant.
As a python code expert, you are capable of creating scripts from specifications.
Empirical multi - part Guinier - Porod scattering.
Explain what the following Python 3 code does def GuinierPorodMulti(q, G, *Rgsalphas): scalefactor = G funcs = [lambda q: Guinier(q, G, Rgsalphas[0])] indices = np.ones_like(q, dtype=np.bool) constraints = [] for i in range(1, len(Rgsalphas)): if i % 2: # Rgsalphas[i] is an expon...
As a python code expert, you are capable of creating scripts from specifications.
def GeneralGuinierPorod(q, factor, *args, **kwargs): """Empirical generalized multi-part Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``factor``: factor for the first branch other arguments (*args): the defining arguments of the consecutive parts...
Write a Python 3 function for generalizing multi - part Guinier - Porod scattering.
You are a Python code generator, capable of creating scripts from specifications.
Returns the scattering form - factor intensity of a Gaussian chain.
How would you explain what the following Python 3 function does def DebyeChain(q, Rg): a = (q * Rg) ** 2 return 2 * (np.exp(-a) - 1 + a) / a ** 2
As a Python code translator, you convert algorithms and pseudocode into Python.
def ExcludedVolumeChain(q, Rg, nu): """Scattering intensity of a generalized excluded-volume Gaussian chain Inputs: ------- ``q``: independent variable ``Rg``: radius of gyration ``nu``: excluded volume exponent Formula: -------- ``(u^(1/nu)*gamma(0.5/nu)*gammainc_l...
Can you write a function in Python 3 where it generalizes excluded - volume Gaussian chain.
As a Python code composer, you craft elegant and concise scripts.
def sample(self, data, interval): '''Sample a patch from the data object Parameters ---------- data : dict A data dict as produced by pumpp.Pump.transform interval : slice The time interval to sample Returns ------- data_slice : ...
Write a Python 3 script for sampling a patch from the data object.
You are a Python code analyst, evaluating scripts for potential improvements.
def indices(self, data): '''Generate patch indices Parameters ---------- data : dict of np.ndarray As produced by pumpp.transform Yields ------ start : int >= 0 The start index of a sample patch ''' duration = self.data_du...
Create a Python 3 function to generate a generator of indices for the set of keys in the data dictionary.
As a Python code translator, you convert algorithms and pseudocode into Python.
def indices(self, data): '''Generate patch start indices Parameters ---------- data : dict of np.ndarray As produced by pumpp.transform Yields ------ start : int >= 0 The start index of a sample patch ''' duration = self.d...
Write a Python 3 script for generating patch start indices for the set of keys in the data dictionary
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a generator of indices for the set of keys in the data dictionary.
Can you generate a brief explanation for the following Python 3 code def indices(self, data): '''Generate patch indices Parameters ---------- data : dict of np.ndarray As produced by pumpp.transform Yields ------ start : int >= 0 The star...
You are a Python code analyst, evaluating scripts for potential improvements.
def scope(self, key): '''Apply the name scope to a key Parameters ---------- key : string Returns ------- `name/key` if `name` is not `None`; otherwise, `key`. ''' if self.name is None: return key return '{:s}/{:s}'.fo...
How would you code a function in Python 3 to apply the name scope to a key.
You are a Python code architect, reviewing and designing scalable and efficient code
def register(self, field, shape, dtype): '''Register a field as a tensor with specified shape and type. A `Tensor` of the given shape and type will be registered in this object's `fields` dict. Parameters ---------- field : str The name of the field ...
Write a Python 3 script for registering a field as a tensor with the given shape and type.
As a python code expert, you are capable of creating scripts from specifications.
def merge(self, data): '''Merge an array of output dictionaries into a single dictionary with properly scoped names. Parameters ---------- data : list of dict Output dicts as produced by `pumpp.task.BaseTaskTransformer.transform` or `pumpp.feature.Feature...
Write a Python 3 script for merging an array of output dicts into a single dictionary with properly scoped names.
As a Python code composer, you craft elegant and concise scripts.
def add(self, operator): '''Add an operator to the Slicer Parameters ---------- operator : Scope (TaskTransformer or FeatureExtractor) The new operator to add ''' if not isinstance(operator, Scope): raise ParameterError('Operator {} must be a Task...
Write a Python 3 function for adding an operator to the Slicer object
You are a Python code architect, reviewing and designing scalable and efficient code
def data_duration(self, data): '''Compute the valid data duration of a dict Parameters ---------- data : dict As produced by pumpp.transform Returns ------- length : int The minimum temporal extent of a dynamic observation in data ...
Write a Python 3 function for computing the valid data duration of a dict
You are a Python code generator, capable of creating scripts from specifications.
Crop a data dictionary down to its common time - like axes truncated to the minimum common duration
Here you have a function in Python 3, explain what it does def crop(self, data): '''Crop a data dictionary down to its common time Parameters ---------- data : dict As produced by pumpp.transform Returns ------- data_cropped : dict Like `...
As a Python code analyst, you investigate and solve complex coding mysteries
def transform_audio(self, y): '''Compute the Mel spectrogram Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_mels) The Mel spectrogram ...
Create a Python 3 function to compute the Mel spectrogram of the audio buffer y.
As a Python code translator, you convert algorithms and pseudocode into Python.
def empty(self, duration): '''Empty vector annotations. This returns an annotation with a single observation vector consisting of all-zeroes. Parameters ---------- duration : number >0 Length of the track Returns ------- ann : jams.A...
Write a Python 3 function for emptying vector annotations. This returns an empty vector annotation with a single observation vector consisting of all - zeroes.
You are a Python code analyst, evaluating scripts for potential improvements.