output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
prints model contained in best inds if ml has a coefficient property. otherwise prints the features generated by FEW.
Given the following Python 3 function, write the documentation def print_model(self,sep='\n'): model = '' # print('ml type:',self.ml_type) # print('ml:',self._best_estimator) if self._best_inds: if self.ml_type == 'GridSearchCV': ml = self._best_estimator.na...
As a Python code composer, you craft elegant and concise scripts.
returns the indices of individuals with valid fitness.
How would you explain what the following Python 3 function does def valid_loc(self,F=None): if F is not None: return [i for i,f in enumerate(F) if np.all(f < self.max_fit) and np.all(f >= 0)] else: return [i for i,f in enumerate(self.F) if np.all(f < self.max_fit) and np.all(f >=...
You are a Python code analyst, evaluating scripts for potential improvements.
def valid(self,individuals=None,F=None): """returns the sublist of individuals with valid fitness.""" if F: valid_locs = self.valid_loc(F) else: valid_locs = self.valid_loc(self.F) if individuals: return [ind for i,ind in enumerate(individuals) if i i...
How would you implement a function in Python 3 that returns the sublist of individuals with valid fitness.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_diversity(self,X): """compute mean diversity of individual outputs""" # diversity in terms of cosine distances between features feature_correlations = np.zeros(X.shape[0]-1) for i in np.arange(1,X.shape[0]-1): feature_correlations[i] = max(0.0,r2_score(X[0],X[i])) ...
How would you code a function in Python 3 to compute mean diversity of individual outputs
As a Python code analyst, you investigate and solve complex coding mysteries
def roc_auc_cv(self,features,labels): """returns an roc auc score depending on the underlying estimator.""" if callable(getattr(self.ml, "decision_function", None)): return np.mean([self.scoring_function(labels[test], self.pipeline.fit(features[train],labe...
Create a Python 3 function to return an roc auc score depending on the underlying estimator.
You are a Python code analyst, evaluating scripts for potential improvements.
safe division of x and y
How would you explain what the following Python 3 function does def divs(x,y): tmp = np.ones(x.shape) nonzero_y = y != 0 tmp[nonzero_y] = x[nonzero_y]/y[nonzero_y] return tmp
As a Python code translator, you convert algorithms and pseudocode into Python.
def r2_score_vec(y_true,y_pred): """ returns non-aggregate version of r2 score. based on r2_score() function from sklearn (http://sklearn.org) """ numerator = (y_true - y_pred) ** 2 denominator = (y_true - np.average(y_true)) ** 2 nonzero_denominator = denominator != 0 nonzero_numerator =...
Implement a function in Python 3 to return non - aggregate version of r2 score.
As a Python code composer, you craft elegant and concise scripts.
def inertia(X,y,samples=False): """ return the within-class squared distance from the centroid""" # pdb.set_trace() if samples: # return within-class distance for each sample inertia = np.zeros(y.shape) for label in np.unique(y): inertia[y==label] = (X[y==label] - np.mean...
Can you create a Python 3 function that calculates the within - class squared distance from the centroid
As a Python code translator, you convert algorithms and pseudocode into Python.
def separation(X,y,samples=False): """ return the sum of the between-class squared distance""" # pdb.set_trace() num_classes = len(np.unique(y)) total_dist = (X.max()-X.min())**2 if samples: # return intra-class distance for each sample separation = np.zeros(y.shape) for labe...
Write a Python 3 function that can return the sum of the between - class squared distance
You are a Python code analyst, evaluating scripts for potential improvements.
Fisher criterion for the given set of classes y.
Can you generate a brief explanation for the following Python 3 code def fisher(yhat,y,samples=False): classes = np.unique(y) mu = np.zeros(len(classes)) v = np.zeros(len(classes)) # pdb.set_trace() for c in classes.astype(int): mu[c] = np.mean(yhat[y==c]) v[c] = np.var(yhat[y==c]) ...
As a Python code composer, you craft elegant and concise scripts.
cleans fitness vector x
Make a summary of the following Python 3 code def proper(self,x): x[x < 0] = self.max_fit x[np.isnan(x)] = self.max_fit x[np.isinf(x)] = self.max_fit return x
As a python code expert, you are capable of creating scripts from specifications.
removes nans and infs from outputs
Here you have a function in Python 3, explain what it does def safe(self,x): x[np.isinf(x)] = 1 x[np.isnan(x)] = 1 return x
As a python code expert, you are capable of creating scripts from specifications.
evaluate node in program
Explain what the following Python 3 code does def evaluate(self,n, features, stack_float, stack_bool,labels=None): np.seterr(all='ignore') if len(stack_float) >= n.arity['f'] and len(stack_bool) >= n.arity['b']: if n.out_type == 'f': stack_float.append( se...
As a python code expert, you are capable of creating scripts from specifications.
returns true if X is finite false otherwise
Can you generate the documentation for the following Python 3 function def all_finite(self,X): # Adapted from sklearn utils: _assert_all_finite(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent ...
As a python code expert, you are capable of creating scripts from specifications.
def out(self,I,features,labels=None,otype='f'): """computes the output for individual I""" stack_float = [] stack_bool = [] # print("stack:",I.stack) # evaulate stack over rows of features,labels # pdb.set_trace() for n in I.stack: self.evaluate(n,feat...
Create a Python 3 function to compute the output for individual I
As a Python code analyst, you investigate and solve complex coding mysteries
computes fitness of individual output yhat.
Can you tell what is the following Python 3 function doing def calc_fitness(self,X,labels,fit_choice,sel): if 'lexicase' in sel: # return list(map(lambda yhat: self.f_vec[fit_choice](labels,yhat),X)) return np.asarray( [self.proper(self.f_vec[fit_choice](la...
As a Python code composer, you craft elegant and concise scripts.
def imagedatadict_to_ndarray(imdict): """ Converts the ImageData dictionary, imdict, to an nd image. """ arr = imdict['Data'] im = None if isinstance(arr, parse_dm3.array.array): im = numpy.asarray(arr, dtype=arr.typecode) elif isinstance(arr, parse_dm3.structarray): t = tupl...
How would you code a function in Python 3 to convert the ImageData dictionary imdict to an nd image.
As a python code expert, you are capable of creating scripts from specifications.
def ndarray_to_imagedatadict(nparr): """ Convert the numpy array nparr into a suitable ImageList entry dictionary. Returns a dictionary with the appropriate Data, DataType, PixelDepth to be inserted into a dm3 tag dictionary and written to a file. """ ret = {} dm_type = None for k, v in ...
Write a Python 3 function for converting the numpy array nparr into a suitable ImageList entry dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
Loads the image from the file - like object or string file.
Explain what the following Python 3 code does def load_image(file) -> DataAndMetadata.DataAndMetadata: if isinstance(file, str) or isinstance(file, str): with open(file, "rb") as f: return load_image(f) dmtag = parse_dm3.parse_dm_header(file) dmtag = fix_strings(dmtag) # display_keys...
As a python code expert, you are capable of creating scripts from specifications.
Save the image data to a nparray file - like object or string.
Can you tell what is the following Python 3 function doing def save_image(xdata: DataAndMetadata.DataAndMetadata, file): # we need to create a basic DM tree suitable for an image # we'll try the minimum: just an data list # doesn't work. Do we need a ImageSourceList too? # and a DocumentObjectList? ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def parse_dm_header(f, outdata=None): """ This is the start of the DM file. We check for some magic values and then treat the next entry as a tag_root If outdata is supplied, we write instead of read using the dictionary outdata as a source Hopefully parse_dm_header(newf, outdata=parse_dm_header(f)...
Write a Python 3 function for parsing the DM file header and return a new file containing the tag_root entry.
As a python code expert, you are capable of creating scripts from specifications.
def get_structdmtypes_for_python_typeorobject(typeorobj): """ Return structchar, dmtype for the python (or numpy) type or object typeorobj. For more complex types we only return the dm type """ # not isinstance is probably a bit more lenient than 'is' # ie isinstance(x,str) is nicer than typ...
Implement a function in Python 3 to return the dmtype for the python typeorobject typeorobj.
You are a Python code analyst, evaluating scripts for potential improvements.
Read image data from TIFF files and return as numpy array.
Can you generate a brief explanation for the following Python 3 code def imread(files, **kwargs): kwargs_file = parse_kwargs(kwargs, 'is_ome', 'multifile', '_useframes', 'name', 'offset', 'size', 'multifile_close', 'fastij', 'movie') # legacy kwargs...
As a Python code translator, you convert algorithms and pseudocode into Python.
Write numpy array to TIFF file.
Can you generate a brief explanation for the following Python 3 code def imwrite(file, data=None, shape=None, dtype=None, **kwargs): tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder', 'imagej') if data is None: dtype = numpy.dtype(dtype) size = product(shape) * dtype.itemsize ...
You are a Python code architect, reviewing and designing scalable and efficient code
Return memory - mapped numpy array stored in TIFF file.
Make a summary of the following Python 3 code def memmap(filename, shape=None, dtype=None, page=None, series=0, mode='r+', **kwargs): """Return memory-mapped numpy array stored in TIFF file. Memory-mapping requires data stored in native byte order, without tiling, compression, predictors, etc. ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None, maxifds=None): """Read tags from chain of IFDs and return as list of dicts. The file handle position must be at a valid IFD header. """ if offsetsize == 4: offsetformat = byteorder+'I' tagnosize = 2 ...
Can you create a Python 3 function that reads tags from the chain of IFDs and return as list of dicts.
As a Python code translator, you convert algorithms and pseudocode into Python.
def read_exif_ifd(fh, byteorder, dtype, count, offsetsize): """Read EXIF tags from file and return as dict.""" exif = read_tags(fh, byteorder, offsetsize, TIFF.EXIF_TAGS, maxifds=1) for name in ('ExifVersion', 'FlashpixVersion'): try: exif[name] = bytes2str(exif[name]) except Exc...
How would you code a function in Python 3 to read EXIF tags from file and return as dict.
As a Python code translator, you convert algorithms and pseudocode into Python.
Read GPS tags from file and return as dict.
Explain what the following Python 3 code does def read_gps_ifd(fh, byteorder, dtype, count, offsetsize): return read_tags(fh, byteorder, offsetsize, TIFF.GPS_TAGS, maxifds=1)
You are a Python code generator, capable of creating scripts from specifications.
def read_interoperability_ifd(fh, byteorder, dtype, count, offsetsize): """Read Interoperability tags from file and return as dict.""" tag_names = {1: 'InteroperabilityIndex'} return read_tags(fh, byteorder, offsetsize, tag_names, maxifds=1)
Implement a Python 3 function for reading Interoperability tags from file and return as dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_bytes(fh, byteorder, dtype, count, offsetsize): """Read tag data from file and return as byte string.""" dtype = 'B' if dtype[-1] == 's' else byteorder+dtype[-1] count *= numpy.dtype(dtype).itemsize data = fh.read(count) if len(data) != count: log.warning('read_bytes: failed to read...
Can you implement a function in Python 3 that reads tag data from file and return as byte string.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_utf8(fh, byteorder, dtype, count, offsetsize): """Read tag data from file and return as unicode string.""" return fh.read(count).decode('utf-8')
Write a Python 3 function that can read tag data from file and return as unicode string.
As a Python code translator, you convert algorithms and pseudocode into Python.
def read_numpy(fh, byteorder, dtype, count, offsetsize): """Read tag data from file and return as numpy array.""" dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1] return fh.read_array(dtype, count)
Implement a function in Python 3 to read tag data from file and return as numpy array.
You are a Python code generator, capable of creating scripts from specifications.
Read ColorMap data from file and return as numpy array.
Make a summary of the following Python 3 code def read_colormap(fh, byteorder, dtype, count, offsetsize): cmap = fh.read_array(byteorder+dtype[-1], count) cmap.shape = (3, -1) return cmap
As a Python code analyst, you investigate and solve complex coding mysteries
def read_json(fh, byteorder, dtype, count, offsetsize): """Read JSON tag data from file and return as object.""" data = fh.read(count) try: return json.loads(unicode(stripnull(data), 'utf-8')) except ValueError: log.warning('read_json: invalid JSON')
Can you write a function in Python 3 where it reads JSON tag data from file and return as object.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_mm_header(fh, byteorder, dtype, count, offsetsize): """Read FluoView mm_header tag from file and return as dict.""" mmh = fh.read_record(TIFF.MM_HEADER, byteorder=byteorder) mmh = recarray2dict(mmh) mmh['Dimensions'] = [ (bytes2str(d[0]).strip(), d[1], d[2], d[3], bytes2str(d[4]).strip(...
Can you implement a function in Python 3 that reads FluoView mm_header tag from file and return as dict.
You are a Python code analyst, evaluating scripts for potential improvements.
def read_uic1tag(fh, byteorder, dtype, count, offsetsize, planecount=None): """Read MetaMorph STK UIC1Tag from file and return as dict. Return empty dictionary if planecount is unknown. """ assert dtype in ('2I', '1I') and byteorder == '<' result = {} if dtype == '2I': # pre MetaMorph ...
Write a Python 3 script for reading MetaMorph STK UIC1Tag from file and return as dict.
As a python code expert, you are capable of creating scripts from specifications.
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize): """Read MetaMorph STK UIC2Tag from file and return as dict.""" assert dtype == '2I' and byteorder == '<' values = fh.read_array('<u4', 6*planecount).reshape(planecount, 6) return { 'ZDistance': values[:, 0] / values[:, 1], '...
Can you write a function in Python 3 where it reads MetaMorph STK UIC2Tag from file and return as dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize): """Read MetaMorph STK UIC4Tag from file and return as dict.""" assert dtype == '1I' and byteorder == '<' result = {} while True: tagid = struct.unpack('<H', fh.read(2))[0] if tagid == 0: break name, value...
Write a Python 3 function that can read MetaMorph STK UIC4Tag from file and return as dict.
You are a Python code analyst, evaluating scripts for potential improvements.
def read_uic_tag(fh, tagid, planecount, offset): """Read a single UIC tag value from file and return tag name and value. UIC1Tags use an offset. """ def read_int(count=1): value = struct.unpack('<%iI' % count, fh.read(4*count)) return value[0] if count == 1 else value try: ...
Implement a function in Python 3 to read a single UIC tag from file and return tag name and value.
You are a Python code analyst, evaluating scripts for potential improvements.
Read UIC ImagePropertyEx tag from file and return as dict.
Make a summary of the following Python 3 code def read_uic_image_property(fh): # TODO: test this size = struct.unpack('B', fh.read(1))[0] name = struct.unpack('%is' % size, fh.read(size))[0][:-1] flags, prop = struct.unpack('<IB', fh.read(5)) if prop == 1: value = struct.unpack('II', fh.read...
As a Python code composer, you craft elegant and concise scripts.
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize): """Read CZ_LSMINFO tag from file and return as dict.""" assert byteorder == '<' magic_number, structure_size = struct.unpack('<II', fh.read(8)) if magic_number not in (50350412, 67127628): raise ValueError('invalid CZ_LSMINFO structur...
Can you implement a function in Python 3 that reads CZ_LSMINFO tag from file and return as dict.
As a Python code analyst, you investigate and solve complex coding mysteries
def read_lsm_floatpairs(fh): """Read LSM sequence of float pairs from file and return as list.""" size = struct.unpack('<i', fh.read(4))[0] return fh.read_array('<2f8', count=size)
Create a Python 3 function to read LSM sequence of float pairs from file and return as list.
You are a Python code generator, capable of creating scripts from specifications.
Read LSM positions from file and return as list.
Can you generate a brief explanation for the following Python 3 code def read_lsm_positions(fh): size = struct.unpack('<I', fh.read(4))[0] return fh.read_array('<2f8', count=size)
As a Python code composer, you craft elegant and concise scripts.
Read LSM time stamps from file and return as list.
How would you explain what the following Python 3 function does def read_lsm_timestamps(fh): size, count = struct.unpack('<ii', fh.read(8)) if size != (8 + 8 * count): log.warning('read_lsm_timestamps: invalid LSM TimeStamps block') return [] # return struct.unpack('<%dd' % count, fh.read(8*...
You are a Python code architect, reviewing and designing scalable and efficient code
def read_lsm_eventlist(fh): """Read LSM events from file and return as list of (time, type, text).""" count = struct.unpack('<II', fh.read(8))[1] events = [] while count > 0: esize, etime, etype = struct.unpack('<IdI', fh.read(16)) etext = bytes2str(stripnull(fh.read(esize - 16))) ...
How would you implement a function in Python 3 that reads LSM events from file and return as list of ( time type text ).
As a python code expert, you are capable of creating scripts from specifications.
def read_lsm_channelcolors(fh): """Read LSM ChannelColors structure from file and return as dict.""" result = {'Mono': False, 'Colors': [], 'ColorNames': []} pos = fh.tell() (size, ncolors, nnames, coffset, noffset, mono) = struct.unpack('<IIIIII', fh.read(24)) if ncolors != nnames: log...
Can you implement a function in Python 3 that reads LSM ChannelColors structure from file and return as dict.
You are a Python code generator, capable of creating scripts from specifications.
Read LSM ScanInfo structure from file and return as dict.
Can you generate a brief explanation for the following Python 3 code def read_lsm_scaninfo(fh): block = {} blocks = [block] unpack = struct.unpack if struct.unpack('<I', fh.read(4))[0] != 0x10000000: # not a Recording sub block log.warning('read_lsm_scaninfo: invalid LSM ScanInfo structu...
As a python code expert, you are capable of creating scripts from specifications.
Read OlympusSIS structure and return as dict.
Can you generate the documentation for the following Python 3 function def read_sis(fh, byteorder, dtype, count, offsetsize): result = {} (magic, _, minute, hour, day, month, year, _, name, tagcount ) = struct.unpack('<4s6shhhhh6s32sh', fh.read(60)) if magic != b'SIS0': raise ValueError('inva...
You are a Python code architect, reviewing and designing scalable and efficient code
def read_sis_ini(fh, byteorder, dtype, count, offsetsize): """Read OlympusSIS INI string and return as dict.""" inistr = fh.read(count) inistr = bytes2str(stripnull(inistr)) try: return olympusini_metadata(inistr) except Exception as exc: log.warning('olympusini_metadata: %s: %s', ex...
Can you implement a function in Python 3 that reads OlympusSIS INI string and return as dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_tvips_header(fh, byteorder, dtype, count, offsetsize): """Read TVIPS EM-MENU headers and return as dict.""" result = {} header = fh.read_record(TIFF.TVIPS_HEADER_V1, byteorder=byteorder) for name, typestr in TIFF.TVIPS_HEADER_V1: result[name] = header[name].tolist() if header['Versi...
Can you implement a function in Python 3 that reads TVIPS EM - Menu headers and return as dict.
As a Python code composer, you craft elegant and concise scripts.
Read FEI SFEG headers and return as dict.
Here you have a function in Python 3, explain what it does def read_fei_metadata(fh, byteorder, dtype, count, offsetsize): result = {} section = {} data = bytes2str(stripnull(fh.read(count))) for line in data.splitlines(): line = line.strip() if line.startswith('['): section ...
As a python code expert, you are capable of creating scripts from specifications.
Read Zeiss SEM tag and return as dict.
Can you generate a brief explanation for the following Python 3 code def read_cz_sem(fh, byteorder, dtype, count, offsetsize): result = {'': ()} key = None data = bytes2str(stripnull(fh.read(count))) for line in data.splitlines(): if line.isupper(): key = line.lower() elif ke...
As a Python code translator, you convert algorithms and pseudocode into Python.
Read NIH_IMAGE_HEADER tag from file and return as dict.
How would you explain what the following Python 3 function does def read_nih_image_header(fh, byteorder, dtype, count, offsetsize): a = fh.read_record(TIFF.NIH_IMAGE_HEADER, byteorder=byteorder) a = a.newbyteorder(byteorder) a = recarray2dict(a) a['XUnit'] = a['XUnit'][:a['XUnitSize']] a['UM'] = a['...
You are a Python code analyst, evaluating scripts for potential improvements.
def read_scanimage_metadata(fh): """Read ScanImage BigTIFF v3 static and ROI metadata from open file. Return non-varying frame data as dict and ROI group data as JSON. The settings can be used to read image data and metadata without parsing the TIFF file. Raise ValueError if file does not contain...
Write a Python 3 function for reading ScanImage BigTIFF v3 static and ROI metadata from open file.
As a Python code composer, you craft elegant and concise scripts.
Read MicroManager non - TIFF metadata from open file and return as dict.
Can you generate a brief explanation for the following Python 3 code def read_micromanager_metadata(fh): fh.seek(0) try: byteorder = {b'II': '<', b'MM': '>'}[fh.read(2)] except IndexError: raise ValueError('not a MicroManager TIFF file') result = {} fh.seek(8) (index_header, ind...
As a Python code composer, you craft elegant and concise scripts.
Return IJMetadata and IJMetadataByteCounts tags from the metadata dict.
Make a summary of the following Python 3 code def imagej_metadata_tag(metadata, byteorder): header = [{'>': b'IJIJ', '<': b'JIJI'}[byteorder]] bytecounts = [0] body = [] def _string(data, byteorder): return data.encode('utf-16' + {'>': 'be', '<': 'le'}[byteorder]) def _doubles(data, byteor...
As a python code expert, you are capable of creating scripts from specifications.
def imagej_metadata(data, bytecounts, byteorder): """Return IJMetadata tag value as dict. The 'Info' string can have multiple formats, e.g. OIF or ScanImage, that might be parsed into dicts using the matlabstr2py or oiffile.SettingsFile functions. """ def _string(data, byteorder): retu...
Can you create a Python 3 function that returns IJMetadata tag value as dict.
You are a Python code analyst, evaluating scripts for potential improvements.
Return metatata from ImageJ image description as dict.
Can you tell what is the following Python 3 function doing def imagej_description_metadata(description): def _bool(val): return {'true': True, 'false': False}[val.lower()] result = {} for line in description.splitlines(): try: key, val = line.split('=') except Exception:...
You are a Python code architect, reviewing and designing scalable and efficient code
Return ImageJ image description from data shape.
Here you have a function in Python 3, explain what it does def imagej_description(shape, rgb=None, colormaped=False, version=None, hyperstack=None, mode=None, loop=None, **kwargs): """Return ImageJ image description from data shape. ImageJ can handle up to 6 dimensions in order TZCYXS. ...
You are a Python code generator, capable of creating scripts from specifications.
def imagej_shape(shape, rgb=None): """Return shape normalized to 6D ImageJ hyperstack TZCYXS. Raise ValueError if not a valid ImageJ hyperstack shape. >>> imagej_shape((2, 3, 4, 5, 3), False) (2, 3, 4, 5, 3, 1) """ shape = tuple(int(i) for i in shape) ndim = len(shape) if 1 > ndim > 6...
Can you create a Python 3 function that returns shape normalized to 6D ImageJ hyperstack TZCYXS.
As a Python code analyst, you investigate and solve complex coding mysteries
Return JSON image description from data shape and other metadata.
Can you generate a brief explanation for the following Python 3 code def json_description(shape, **metadata): metadata.update(shape=shape) return json.dumps(metadata)
You are a Python code analyst, evaluating scripts for potential improvements.
Return metatata from JSON formated image description as dict.
Given the following Python 3 function, write the documentation def json_description_metadata(description): if description[:6] == 'shape=': # old-style 'shaped' description; not JSON shape = tuple(int(i) for i in description[7:-1].split(',')) return dict(shape=shape) if description[:1] ==...
As a Python code composer, you craft elegant and concise scripts.
Return metatata from FluoView image description as dict.
Can you generate a brief explanation for the following Python 3 code def fluoview_description_metadata(description, ignoresections=None): if not description.startswith('['): raise ValueError('invalid FluoView image description') if ignoresections is None: ignoresections = {'Region Info (Fields)'...
As a python code expert, you are capable of creating scripts from specifications.
Return metatata from Pilatus image description as dict.
How would you explain what the following Python 3 function does def pilatus_description_metadata(description): result = {} if not description.startswith('# '): return result for c in '#:=,()': description = description.replace(c, ' ') for line in description.split('\n'): if line[...
You are a Python code generator, capable of creating scripts from specifications.
def svs_description_metadata(description): """Return metatata from Aperio image description as dict. The Aperio image description format is unspecified. Expect failures. >>> svs_description_metadata('Aperio Image Library v1.0') {'Aperio Image Library': 'v1.0'} """ if not description.startswit...
Create a Python 3 function for returning metatata from Aperio image description as dict.
As a python code expert, you are capable of creating scripts from specifications.
def stk_description_metadata(description): """Return metadata from MetaMorph image description as list of dict. The MetaMorph image description format is unspecified. Expect failures. """ description = description.strip() if not description: return [] try: description = bytes2s...
Write a Python 3 function for returning metadata from MetaMorph image description as list of dict.
As a Python code translator, you convert algorithms and pseudocode into Python.
def metaseries_description_metadata(description): """Return metatata from MetaSeries image description as dict.""" if not description.startswith('<MetaData>'): raise ValueError('invalid MetaSeries image description') from xml.etree import cElementTree as etree # delayed import root = etree.fro...
Create a Python 3 function to return metatata from MetaSeries image description as dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def scanimage_artist_metadata(artist): """Return metatata from ScanImage artist tag as dict.""" try: return json.loads(artist) except ValueError as exc: log.warning('scanimage_artist_metadata: %s: %s', exc.__class__.__name__, exc)
How would you code a function in Python 3 to return metatata from ScanImage artist tag as dict.
You are a Python code architect, reviewing and designing scalable and efficient code
def olympusini_metadata(inistr): """Return OlympusSIS metadata from INI string. No documentation is available. """ def keyindex(key): # split key into name and index index = 0 i = len(key.rstrip('0123456789')) if i < len(key): index = int(key[i:]) - 1 ...
How would you code a function in Python 3 to return OlympusSIS metadata from INI string.
As a Python code translator, you convert algorithms and pseudocode into Python.
def tile_decode(tile, tileindex, tileshape, tiledshape, lsb2msb, decompress, unpack, unpredict, out): """Decode tile segment bytes into 5D output array.""" _, imagedepth, imagelength, imagewidth, _ = out.shape tileddepth, tiledlength, tiledwidth = tiledshape tiledepth, tilelength, tilewi...
Create a Python 3 function for decoding tile segment bytes into 5D output array.
As a Python code composer, you craft elegant and concise scripts.
def unpack_rgb(data, dtype=None, bitspersample=None, rescale=True): """Return array from byte string containing packed samples. Use to unpack RGB565 or RGB555 to RGB888 format. Parameters ---------- data : byte str The data to be decoded. Samples in each pixel are stored consecutively. ...
Create a Python 3 function for unpacking a byte string containing packed RGB samples.
As a Python code translator, you convert algorithms and pseudocode into Python.
Decode data into a byte string or numpy array.
Here you have a function in Python 3, explain what it does def bitorder_decode(data, out=None, _bitorder=[]): if not _bitorder: _bitorder.append( b'\x00\x80@\xc0 \xa0`\xe0\x10\x90P\xd00\xb0p\xf0\x08\x88H\xc8(' b'\xa8h\xe8\x18\x98X\xd88\xb8x\xf8\x04\x84D\xc4$\xa4d\xe4\x14' ...
You are a Python code analyst, evaluating scripts for potential improvements.
def packints_decode(data, dtype, numbits, runlen=0, out=None): """Decompress byte string to array of integers. This implementation only handles itemsizes 1, 8, 16, 32, and 64 bits. Install the imagecodecs package for decoding other integer sizes. Parameters ---------- data : byte str D...
Implement a function in Python 3 to decompress byte string to array of integers.
You are a Python code generator, capable of creating scripts from specifications.
def apply_colormap(image, colormap, contig=True): """Return palette-colored image. The image values are used to index the colormap on axis 1. The returned image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype. Parameters ---------- image : numpy.ndarray Indexes into ...
How would you implement a function in Python 3 that returns the palette - colored image.
As a Python code composer, you craft elegant and concise scripts.
def reorient(image, orientation): """Return reoriented view of image array. Parameters ---------- image : numpy.ndarray Non-squeezed output of asarray() functions. Axes -3 and -2 must be image length and width respectively. orientation : int or str One of TIFF.ORIENTATION na...
Write a Python 3 function that can return a reoriented version of an image array.
As a Python code composer, you craft elegant and concise scripts.
def repeat_nd(a, repeats): """Return read-only view into input array with elements repeated. Zoom nD image by integer factors using nearest neighbor interpolation (box filter). Parameters ---------- a : array_like Input array. repeats : sequence of int The number of repetit...
Can you write a function in Python 3 where it returns read - only view into input array with elements repeated.
As a Python code analyst, you investigate and solve complex coding mysteries
Return image array or shape with at least ndim dimensions.
Can you generate the documentation for the following Python 3 function def reshape_nd(data_or_shape, ndim): is_shape = isinstance(data_or_shape, tuple) shape = data_or_shape if is_shape else data_or_shape.shape if len(shape) >= ndim: return data_or_shape shape = (1,) * (ndim - len(shape)) + shap...
You are a Python code generator, capable of creating scripts from specifications.
Return shape and axes with single - dimensional entries removed.
Make a summary of the following Python 3 code def squeeze_axes(shape, axes, skip=None): if len(shape) != len(axes): raise ValueError('dimensions of axes and shape do not match') if skip is None: skip = 'XY' shape, axes = zip(*(i for i in zip(shape, axes) if i[0] > 1 o...
As a python code expert, you are capable of creating scripts from specifications.
def transpose_axes(image, axes, asaxes=None): """Return image with its axes permuted to match specified axes. A view is returned if possible. >>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape (5, 2, 1, 3, 4) """ for ax in axes: if ax not in asaxes: ...
Create a Python 3 function for returning image with its axes permuted to match specified axes.
You are a Python code architect, reviewing and designing scalable and efficient code
def reshape_axes(axes, shape, newshape, unknown=None): """Return axes matching new shape. By default, unknown dimensions are labelled 'Q'. >>> reshape_axes('YXS', (219, 301, 1), (219, 301)) 'YX' >>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1)) 'QQYQXQ' """ shape = tuple...
Write a Python 3 script for returning axes matching new shape. By default unknown dimensions are labelled Q.
As a Python code composer, you craft elegant and concise scripts.
def stack_pages(pages, out=None, maxworkers=None, **kwargs): """Read data from sequence of TiffPage and stack them vertically. Additional parameters are passsed to the TiffPage.asarray function. """ npages = len(pages) if npages == 0: raise ValueError('no pages') if npages == 1: ...
Write a Python 3 function that can read data from sequence of TiffPage and stack them vertically.
As a Python code composer, you craft elegant and concise scripts.
def clean_offsetscounts(offsets, counts): """Return cleaned offsets and byte counts. Remove zero offsets and counts. Use to sanitize StripOffsets and StripByteCounts tag values. """ # TODO: cythonize this offsets = list(offsets) counts = list(counts) size = len(offsets) if size != ...
Write a Python 3 script for returning cleaned offsets and byte counts.
As a python code expert, you are capable of creating scripts from specifications.
Return iterator over segments read from file.
Can you generate a brief explanation for the following Python 3 code def buffered_read(fh, lock, offsets, bytecounts, buffersize=None): if buffersize is None: buffersize = 2**26 length = len(offsets) i = 0 while i < length: data = [] with lock: size = 0 wh...
As a Python code composer, you craft elegant and concise scripts.
def create_output(out, shape, dtype, mode='w+', suffix=None): """Return numpy array where image data of shape and dtype can be copied. The 'out' parameter may have the following values or types: None An empty array of shape and dtype is created and returned. numpy.ndarray An existing w...
Write a Python 3 script to create an array of numpy arrays of compatible shape and dtype.
You are a Python code generator, capable of creating scripts from specifications.
def matlabstr2py(string): """Return Python object from Matlab string representation. Return str, bool, int, float, list (Matlab arrays or cells), or dict (Matlab structures) types. Use to access ScanImage metadata. >>> matlabstr2py('1') 1 >>> matlabstr2py("['x y z' true false; 1 2.0 -3e4;...
Create a Python 3 function for returning Python object from Matlab string representation.
You are a Python code generator, capable of creating scripts from specifications.
Return string truncated at last byte that is 7 - bit ASCII.
Can you generate a brief explanation for the following Python 3 code def stripascii(string): # TODO: pythonize this i = len(string) while i: i -= 1 if 8 < byte2int(string[i]) < 127: break else: i = -1 return string[:i+1]
As a Python code composer, you craft elegant and concise scripts.
Return string as bool if possible else raise TypeError.
Here you have a function in Python 3, explain what it does def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')): value = value.strip().lower() if value in true: # might raise UnicodeWarning/BytesWarning return True if value in false: return False raise TypeError()
You are a Python code architect, reviewing and designing scalable and efficient code
def astype(value, types=None): """Return argument as one of types if possible. >>> astype('42') 42 >>> astype('3.14') 3.14 >>> astype('True') True >>> astype(b'Neee-Wom') 'Neee-Wom' """ if types is None: types = int, float, asbool, bytes2str for typ in types: ...
How would you implement a function in Python 3 that returns argument as one of types if possible.
As a Python code translator, you convert algorithms and pseudocode into Python.
def format_size(size, threshold=1536): """Return file size as string from byte size. >>> format_size(1234) '1234 B' >>> format_size(12345678901) '11.50 GiB' """ if size < threshold: return "%i B" % size for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'): size /= 1024.0 ...
Implement a Python 3 function for returning file size as string from byte size.
As a python code expert, you are capable of creating scripts from specifications.
def natural_sorted(iterable): """Return human sorted list of strings. E.g. for sorting file names. >>> natural_sorted(['f1', 'f2', 'f10']) ['f1', 'f2', 'f10'] """ def sortkey(x): return [(int(c) if c.isdigit() else c) for c in re.split(numbers, x)] numbers = re.compile(r'(\d+)') ...
Can you create a Python 3 function that returns a list of strings in natural order.
You are a Python code analyst, evaluating scripts for potential improvements.
def excel_datetime(timestamp, epoch=None): """Return datetime object from timestamp in Excel serial format. Convert LSM time stamps. >>> excel_datetime(40237.029999999795) datetime.datetime(2010, 2, 28, 0, 43, 11, 999982) """ if epoch is None: epoch = datetime.datetime.fromordinal(693...
Write a Python 3 function for returning datetime object from timestamp in Excel serial format.
As a python code expert, you are capable of creating scripts from specifications.
Convert Julian dates according to MetaMorph.
Can you generate the documentation for the following Python 3 function def julian_datetime(julianday, milisecond=0): if julianday <= 1721423: # no datetime before year 1 return None a = julianday + 1 if a > 2299160: alpha = math.trunc((a - 1867216.25) / 36524.25) a += 1 + al...
As a Python code composer, you craft elegant and concise scripts.
Return True if byteorder matches the system s byteorder.
Make a summary of the following Python 3 code def byteorder_isnative(byteorder): if byteorder in ('=', sys.byteorder): return True keys = {'big': '>', 'little': '<'} return keys.get(byteorder, byteorder) == keys[sys.byteorder]
You are a Python code generator, capable of creating scripts from specifications.
def recarray2dict(recarray): """Return numpy.recarray as dict.""" # TODO: subarrays result = {} for descr, value in zip(recarray.dtype.descr, recarray): name, dtype = descr[:2] if dtype[1] == 'S': value = bytes2str(stripnull(value)) elif value.ndim < 2: va...
Create a Python 3 function for returning numpy. recarray as dict.
You are a Python code architect, reviewing and designing scalable and efficient code
Return XML as dict.
How would you explain what the following Python 3 function does def xml2dict(xml, sanitize=True, prefix=None): from xml.etree import cElementTree as etree # delayed import at = tx = '' if prefix: at, tx = prefix def astype(value): # return value as int, float, bool, or str for...
You are a Python code generator, capable of creating scripts from specifications.
Return hexdump representation of byte string.
Make a summary of the following Python 3 code def hexdump(bytestr, width=75, height=24, snipat=-2, modulo=2, ellipsis=None): size = len(bytestr) if size < 1 or width < 2 or height < 1: return '' if height == 1: addr = b'' bytesperline = min(modulo * (((width - len(addr)) // 4) // mod...
As a python code expert, you are capable of creating scripts from specifications.
Return True if all characters in string are printable.
Given the following Python 3 function, write the documentation def isprintable(string): string = string.strip() if not string: return True if sys.version_info[0] == 3: try: return string.isprintable() except Exception: pass try: return stri...
You are a Python code analyst, evaluating scripts for potential improvements.
Return string with compressed whitespace.
Make a summary of the following Python 3 code def clean_whitespace(string, compact=False): for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'), ('\t', ' '), (' ', ' ')): string = string.replace(a, b) if compact: for a, b in (('\n', ' '), ('[ ', '['), ...
As a Python code composer, you craft elegant and concise scripts.
def pformat_xml(xml): """Return pretty formatted XML.""" try: from lxml import etree # delayed import if not isinstance(xml, bytes): xml = xml.encode('utf-8') xml = etree.parse(io.BytesIO(xml)) xml = etree.tostring(xml, pretty_print=True, xml_declaration=True, ...
Can you write a function in Python 3 where it returns pretty formatted XML.
As a Python code analyst, you investigate and solve complex coding mysteries
Return pretty formatted representation of object as string.
Given the following Python 3 function, write the documentation def pformat(arg, width=79, height=24, compact=True): if height is None or height < 1: height = 1024 if width is None or width < 1: width = 256 npopt = numpy.get_printoptions() numpy.set_printoptions(threshold=100, linewidth=...
As a Python code translator, you convert algorithms and pseudocode into Python.