code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if value: self._dirty = True else: self._dirty = False for extension in self.recipe_extensions: extension.dirty = False
def dirty(self, value)
If dirty is true set the recipe to dirty flag. If false, clear the recipe and all extension dirty flags
5.091969
3.023531
1.684114
query = self.query() return query.subquery(name=name)
def subquery(self, name=None)
The recipe's query as a subquery suitable for use in joins or other queries.
5.936216
4.635981
1.280466
if name is None: name = self._id return alias(self.subquery(), name=name)
def as_table(self, name=None)
Return an alias to a table
8.246964
5.907411
1.396037
starttime = fetchtime = enchanttime = time.time() fetched_from_cache = False if self.dirty or self.all_dirty: query = self.query() self._all = query.all() # If we're using a caching query and that query did not # save new values to cache,...
def all(self)
Return a (potentially cached) list of result objects.
6.381999
6.121424
1.042568
if 'field' in value: operators = self.nonscalar_conditions + self.scalar_conditions matches = sum(1 for k in operators if k in value) if matches == 0: error(field, 'Must contain one of {}'.format(operators)) return False el...
def _validate_condition_keys(self, field, value, error)
Validates that all of the keys in one of the sets of keys are defined as keys of ``value``.
2.747014
2.801057
0.980706
if self.sel == 'tournament': survivors, survivor_index = self.tournament(parents + offspring, self.tourn_size, num_selections = len(parents)) elif self.sel == 'lexicase': survivor_index = self.lexicase(np.vstack((F,F_O)), num_selections = len(parents), survival = True) ...
def survival(self,parents,offspring,elite=None,elite_index=None,X=None,X_O=None,F=None,F_O=None)
routes to the survival method, returns survivors
2.430311
2.420617
1.004005
winners = [] locs = [] if num_selections is None: num_selections = len(individuals) for i in np.arange(num_selections): # sample pool with replacement pool_i = self.random_state.choice(len(individuals),size=tourn_size) pool = [] ...
def tournament(self,individuals,tourn_size, num_selections=None)
conducts tournament selection of size tourn_size
2.862504
2.900455
0.986916
if num_selections is None: num_selections = F.shape[0] winners = [] locs = [] individual_locs = np.arange(F.shape[0]) for i in np.arange(num_selections): can_locs = individual_locs cases = list(np.arange(F.shape[1])) ...
def lexicase(self,F, num_selections=None, survival = False)
conducts lexicase selection for de-aggregated fitness vectors
3.543768
3.497595
1.013201
# pdb.set_trace() if num_selections is None: num_selections = F.shape[0] if self.c: # use c library # define c types locs = np.empty(num_selections,dtype='int32',order='F') # self.lib.epsilon_lexicase(F,F.shape[0],F.shape[1],num_selec...
def epsilon_lexicase(self, F, sizes, num_selections=None, survival = False)
conducts epsilon lexicase selection for de-aggregated fitness vectors
3.347672
3.293941
1.016312
return np.median(np.abs(x - np.median(x, axis)), axis)
def mad(self,x, axis=None)
median absolute deviation statistic
2.297385
2.457689
0.934775
# get children locations produced from crossover cross_children = [i for i,o in enumerate(offspring) if len(o.parentid) > 1] # order offspring so that they are lined up with their most similar parent for c1,c2 in zip(cross_children[::2], cross_children[1::2]): # get ...
def deterministic_crowding(self,parents,offspring,X_parents,X_offspring)
deterministic crowding implementation (for non-steady state). offspring compete against the parent they are most similar to, here defined as the parent they are most correlated with. the offspring only replace their parent if they are more fit.
2.586702
2.540855
1.018044
# only choose crossover points for out_types available in both programs # pdb.set_trace() # determine possible outttypes types_p_i = [t for t in [p.out_type for p in p_i]] types_p_j = [t for t in [p.out_type for p in p_j]] types = set(types_p_i).intersection(type...
def cross(self,p_i,p_j, max_depth = 2)
subtree-like swap crossover between programs p_i and p_j.
2.049942
1.996567
1.026733
def mutate(self,p_i,func_set,term_set): #, max_depth=2 self.point_mutate(p_i,func_set,term_set)
point mutation, addition, removal
null
null
null
# point mutation x = self.random_state.randint(len(p_i)) arity = p_i[x].arity[p_i[x].in_type] # find eligible replacements based on arity and type reps = [n for n in func_set+term_set if n.arity[n.in_type]==arity and n.out_type==p_i[x].out_type ...
def point_mutate(self,p_i,func_set,term_set)
point mutation on individual p_i
3.432938
3.4117
1.006225
# print("p:",p) arities = list(a.arity[a.in_type] for a in p) accu_arities = list(accumulate(arities)) accu_len = list(np.arange(len(p))+1) check = list(a < b for a,b in zip(accu_arities,accu_len)) # print("accu_arities:",accu_arities) # print("accu_len:"...
def is_valid_program(self,p)
checks whether program p makes a syntactically valid tree. checks that the accumulated program length is always greater than the accumulated arities, indicating that the appropriate number of arguments is alway present for functions. It then checks that the sum of arties +1 exactly equa...
3.179694
2.756322
1.1536
# need to check that tmp is categorical x1 = stack_float.pop() x2 = stack_float.pop() # check data is categorical if len(np.unique(x1))<=3 and len(np.unique(x2))<=3: tmp = np.vstack((x1,x2)).transpose() if labels is None: # prediction return n.model.transform(tmp)[...
def run_MDR(n,stack_float,labels=None)
run utility function for MDR nodes.
4.265423
4.235334
1.007104
stack_eqn = [] if p: # if stack is not empty for n in p.stack: self.eval_eqn(n,stack_eqn) return stack_eqn[-1] return []
def stack_2_eqn(self,p)
returns equation string for program stack
5.88154
5.160983
1.139616
if stacks: return list(map(lambda p: self.stack_2_eqn(p), stacks)) else: return []
def stacks_2_eqns(self,stacks)
returns equation strings from stacks
4.103108
3.670762
1.117781
# print("stack:",stack,"max d:",max_d) if max_d == 0: ts = [t for t in term_set if t.out_type==ntype] if not ts: raise ValueError('no ts. ntype:'+ntype+'. term_set out_types:'+ ','.join([t.out_type for t in term_set])) ...
def make_program(self,stack,func_set,term_set,max_d,ntype)
makes a program stack
2.979734
2.962089
1.005957
pop = Pop(self.population_size) seed_with_raw_features = False # make programs if self.seed_with_ml: # initial population is the components of the default ml model if (self.ml_type == 'SVC' or self.ml_type == 'SVR'): # this is needed becau...
def init_pop(self)
initializes population of features as GP stacks.
3.744846
3.70067
1.011937
if inds: # return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype) # for I in inds)).transpose() return np.asarray( [self.out(I,x,labels,self.otype) for I in inds]).transpose() elif self._best_...
def transform(self,x,inds=None,labels = None)
return a transformation of x using population outputs
2.507839
2.446641
1.025013
imp = Imputer(missing_values='NaN', strategy='mean', axis=0) return imp.fit_transform(x)
def impute_data(self,x)
Imputes data set containing Nan values
2.463257
2.555331
0.963968
return x[~np.any(np.isnan(x) | np.isinf(x),axis=1)]
def clean(self,x)
remove nan and inf rows from x
3.850121
2.322918
1.65745
x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0 return x
def clean_with_zeros(self,x)
set nan and inf rows from x to zero
3.46563
2.7057
1.280863
# print("best_inds:",self._best_inds) # print("best estimator size:",self._best_estimator.coef_.shape) if self.clean: testing_features = self.impute_data(testing_features) if self._best_inds: X_transform = self.transform(testing_features) try...
def predict(self, testing_features)
predict on a holdout data set.
4.290083
4.268183
1.005131
self.fit(features, labels) return self.predict(features)
def fit_predict(self, features, labels)
Convenience function that fits a pipeline then predicts on the provided features Parameters ---------- features: array-like {n_samples, n_features} Feature matrix labels: array-like {n_samples} List of class labels for prediction Returns ...
2.884769
7.287222
0.395867
# print("test features shape:",testing_features.shape) # print("testing labels shape:",testing_labels.shape) yhat = self.predict(testing_features) return self.scoring_function(testing_labels,yhat)
def score(self, testing_features, testing_labels)
estimates accuracy on testing set
3.017739
3.026131
0.997227
if self._best_estimator is None: raise ValueError('A model has not been optimized. Please call fit()' ' first.') # Write print_model() to file with open(output_file_name, 'w') as output_file: output_file.write(self.print_model()) ...
def export(self, output_file_name)
exports engineered features Parameters ---------- output_file_name: string String containing the path and file name of the desired output file Returns ------- None
5.604812
5.932771
0.944721
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.named_steps['ml'].best_estimator_ else: ml = self._best_esti...
def print_model(self,sep='\n')
prints model contained in best inds, if ml has a coefficient property. otherwise, prints the features generated by FEW.
3.060066
2.954843
1.03561
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 >= 0)]
def valid_loc(self,F=None)
returns the indices of individuals with valid fitness.
2.176912
1.754527
1.24074
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 in valid_locs] else: return [ind for i,ind in enumerate(self.pop.individuals) if i...
def valid(self,individuals=None,F=None)
returns the sublist of individuals with valid fitness.
2.356948
2.162038
1.090151
# 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])) # pdb.set_trace() self.diversity.append(1-np.mean(feature_correl...
def get_diversity(self,X)
compute mean diversity of individual outputs
3.731888
3.812038
0.978974
if callable(getattr(self.ml, "decision_function", None)): return np.mean([self.scoring_function(labels[test], self.pipeline.fit(features[train],labels[train]). decision_function(features[test])) ...
def roc_auc_cv(self,features,labels)
returns an roc auc score depending on the underlying estimator.
2.874015
2.861745
1.004288
tmp = np.ones(x.shape) nonzero_y = y != 0 tmp[nonzero_y] = x[nonzero_y]/y[nonzero_y] return tmp
def divs(x,y)
safe division
2.906675
3.01053
0.965503
tmp = np.ones(x.shape) nonzero_x = x != 0 tmp[nonzero_x] = np.log(np.abs(x[nonzero_x])) return tmp
def logs(x)
safe log
3.157482
2.979313
1.059802
numerator = (y_true - y_pred) ** 2 denominator = (y_true - np.average(y_true)) ** 2 nonzero_denominator = denominator != 0 nonzero_numerator = numerator != 0 valid_score = nonzero_denominator & nonzero_numerator output_scores = np.ones([y_true.shape[0]]) output_scores[valid_score] = 1...
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)
3.390461
3.441858
0.985067
# 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(X[y==label])) ** 2 else: # return aggregate score inertia = 0 for i,label i...
def inertia(X,y,samples=False)
return the within-class squared distance from the centroid
2.637104
2.446756
1.077796
# 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 label in np.unique(y): for outsider in np.unique(y[y!=label]): separat...
def separation(X,y,samples=False)
return the sum of the between-class squared distance
2.885311
2.830357
1.019416
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]) if not samples: fisher = 0 for c1,c2 in pairwise(classes.astype(int)): ...
def fisher(yhat,y,samples=False)
Fisher criterion
2.792161
2.790279
1.000675
x[x < 0] = self.max_fit x[np.isnan(x)] = self.max_fit x[np.isinf(x)] = self.max_fit return x
def proper(self,x)
cleans fitness vector
2.988649
2.592884
1.152635
x[np.isinf(x)] = 1 x[np.isnan(x)] = 1 return x
def safe(self,x)
removes nans and infs from outputs.
3.055389
2.784775
1.097176
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( self.safe(self.eval_dict[n.name](n,features,stack_float, ...
def evaluate(self,n, features, stack_float, stack_bool,labels=None)
evaluate node in program
2.743333
2.698394
1.016654
# 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 # false positives from overflow in sum method. # Note: this is basically here...
def all_finite(self,X)
returns true if X is finite, false, otherwise
4.014388
4.012783
1.0004
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,features,stack_float,stack_bool,labels) # print("stack_float:",stack_float) ...
def out(self,I,features,labels=None,otype='f')
computes the output for individual I
4.169968
4.189215
0.995406
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](labels, yhat)) for yhat in X], ...
def calc_fitness(self,X,labels,fit_choice,sel)
computes fitness of individual output yhat. yhat: output of a program. labels: correct outputs fit_choice: choice of fitness function
3.217573
3.241482
0.992624
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 = tuple(arr.typecodes) im = numpy.frombuffer( arr.raw_data, dtype=structarray_to_np_ma...
def imagedatadict_to_ndarray(imdict)
Converts the ImageData dictionary, imdict, to an nd image.
5.841672
5.808997
1.005625
ret = {} dm_type = None for k, v in iter(dm_image_dtypes.items()): if v[1] == nparr.dtype.type: dm_type = k break if dm_type is None and nparr.dtype == numpy.uint8 and nparr.shape[-1] in (3, 4): ret["DataType"] = 23 ret["PixelDepth"] = 4 if np...
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.
2.721596
2.601999
1.045964
# filesize is sizeondisk - 16. But we have 8 bytes of zero at the end of # the file. if outdata is not None: # this means we're WRITING to the file if verbose: print("write_dm_header start", f.tell()) ver, file_size, endianness = 3, -1, 1 put_into_file(f, "> l l l",...
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)) copies f to newf
4.073039
3.992291
1.020226
# not isinstance is probably a bit more lenient than 'is' # ie isinstance(x,str) is nicer than type(x) is str. # hence we use isinstance when available if isinstance(typeorobj, type): comparer = lambda test: test is typeorobj else: comparer = lambda test: isinstance(typeorobj, t...
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
4.07885
4.010953
1.016928
nicename, structchar, types = desc def dm_read_x(f, outdata=None): if outdata is not None: # this means we're WRITING to the file if verbose: print("dm_write start", structchar, outdata, "at", f.tell()) put_into_file(f, "<" + structchar, outdata) ...
def standard_dm_read(datatype_num, desc)
datatype_num is the number of the data type, see dm_simple_names above. desc is a (nicename, struct_char) tuple. We return a function that parses the data for us.
3.956289
3.596551
1.100023
kwargs_file = parse_kwargs(kwargs, 'is_ome', 'multifile', '_useframes', 'name', 'offset', 'size', 'multifile_close', 'fastij', 'movie') # legacy kwargs_seq = parse_kwargs(kwargs, 'pattern') if kwargs.get('pages', None) is not None: ...
def imread(files, **kwargs)
Return image data from TIFF file(s) as numpy array. Refer to the TiffFile and TiffSequence classes and their asarray functions for documentation. Parameters ---------- files : str, binary stream, or sequence File name, seekable binary stream, glob pattern, or sequence of file name...
3.996953
3.257866
1.226862
tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder', 'imagej') if data is None: dtype = numpy.dtype(dtype) size = product(shape) * dtype.itemsize byteorder = dtype.byteorder else: try: size = data.nbytes byteorder = data.dtype.byteorde...
def imwrite(file, data=None, shape=None, dtype=None, **kwargs)
Write numpy array to TIFF file. Refer to the TiffWriter class and its asarray function for documentation. A BigTIFF file is created if the data size in bytes is larger than 4 GB minus 32 MB (for metadata), and 'bigtiff' is not specified, and 'imagej' or 'truncate' are not enabled. Parameters ...
3.120824
2.709749
1.151702
if shape is not None and dtype is not None: # create a new, empty array kwargs.update(data=None, shape=shape, dtype=dtype, returnoffset=True, align=TIFF.ALLOCATIONGRANULARITY) result = imwrite(filename, **kwargs) if result is None: # TODO: fail ...
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. If 'shape' and 'dtype' are provided, existing files will be overwritten or appended to depending on the 'append' parameter. Otherwise the ima...
3.816737
3.497746
1.091199
if offsetsize == 4: offsetformat = byteorder+'I' tagnosize = 2 tagnoformat = byteorder+'H' tagsize = 12 tagformat1 = byteorder+'HH' tagformat2 = byteorder+'I4s' elif offsetsize == 8: offsetformat = byteorder+'Q' tagnosize = 8 tagnoform...
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.
2.743107
2.740546
1.000935
exif = read_tags(fh, byteorder, offsetsize, TIFF.EXIF_TAGS, maxifds=1) for name in ('ExifVersion', 'FlashpixVersion'): try: exif[name] = bytes2str(exif[name]) except Exception: pass if 'UserComment' in exif: idcode = exif['UserComment'][:8] try: ...
def read_exif_ifd(fh, byteorder, dtype, count, offsetsize)
Read EXIF tags from file and return as dict.
2.558258
2.508135
1.019984
return read_tags(fh, byteorder, offsetsize, TIFF.GPS_TAGS, maxifds=1)
def read_gps_ifd(fh, byteorder, dtype, count, offsetsize)
Read GPS tags from file and return as dict.
9.703665
8.934313
1.086112
tag_names = {1: 'InteroperabilityIndex'} return read_tags(fh, byteorder, offsetsize, tag_names, maxifds=1)
def read_interoperability_ifd(fh, byteorder, dtype, count, offsetsize)
Read Interoperability tags from file and return as dict.
6.802229
5.99128
1.135355
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 all bytes (%i < %i)', len(data), count) return data
def read_bytes(fh, byteorder, dtype, count, offsetsize)
Read tag data from file and return as byte string.
3.467049
3.414538
1.015379
return fh.read(count).decode('utf-8')
def read_utf8(fh, byteorder, dtype, count, offsetsize)
Read tag data from file and return as unicode string.
6.081414
6.007702
1.01227
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1] return fh.read_array(dtype, count)
def read_numpy(fh, byteorder, dtype, count, offsetsize)
Read tag data from file and return as numpy array.
6.908561
7.404685
0.932999
cmap = fh.read_array(byteorder+dtype[-1], count) cmap.shape = (3, -1) return cmap
def read_colormap(fh, byteorder, dtype, count, offsetsize)
Read ColorMap data from file and return as numpy array.
7.721324
8.090995
0.954311
data = fh.read(count) try: return json.loads(unicode(stripnull(data), 'utf-8')) except ValueError: log.warning('read_json: invalid JSON')
def read_json(fh, byteorder, dtype, count, offsetsize)
Read JSON tag data from file and return as object.
5.448218
5.003476
1.088887
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()) for d in mmh['Dimensions']] d = mmh['GrayChannel'] mmh['GrayChannel'] = ( bytes2str(d[0]).strip()...
def read_mm_header(fh, byteorder, dtype, count, offsetsize)
Read FluoView mm_header tag from file and return as dict.
3.322694
3.241984
1.024895
assert dtype in ('2I', '1I') and byteorder == '<' result = {} if dtype == '2I': # pre MetaMorph 2.5 (not tested) values = fh.read_array('<u4', 2*count).reshape(count, 2) result = {'ZDistance': values[:, 0] / values[:, 1]} elif planecount: for _ in range(count): ...
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.
5.118886
4.789946
1.068673
assert dtype == '2I' and byteorder == '<' values = fh.read_array('<u4', 6*planecount).reshape(planecount, 6) return { 'ZDistance': values[:, 0] / values[:, 1], 'DateCreated': values[:, 2], # julian days 'TimeCreated': values[:, 3], # milliseconds 'DateModified': values...
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize)
Read MetaMorph STK UIC2Tag from file and return as dict.
4.517795
4.468237
1.011091
assert dtype == '1I' and byteorder == '<' result = {} while True: tagid = struct.unpack('<H', fh.read(2))[0] if tagid == 0: break name, value = read_uic_tag(fh, tagid, planecount, offset=False) result[name] = value return result
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize)
Read MetaMorph STK UIC4Tag from file and return as dict.
3.446801
3.476042
0.991588
def read_int(count=1): value = struct.unpack('<%iI' % count, fh.read(4*count)) return value[0] if count == 1 else value try: name, dtype = TIFF.UIC_TAGS[tagid] except IndexError: # unknown tag return '_TagId%i' % tagid, read_int() Fraction = TIFF.UIC_TAGS[4...
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.
2.968944
2.945095
1.008098
# 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(8)) value = value[0] / value[1] else: size = struct.u...
def read_uic_image_property(fh)
Read UIC ImagePropertyEx tag from file and return as dict.
2.399552
2.361455
1.016133
assert byteorder == '<' magic_number, structure_size = struct.unpack('<II', fh.read(8)) if magic_number not in (50350412, 67127628): raise ValueError('invalid CZ_LSMINFO structure') fh.seek(-8, 1) if structure_size < numpy.dtype(TIFF.CZ_LSMINFO).itemsize: # adjust structure acc...
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize)
Read CZ_LSMINFO tag from file and return as dict.
3.430072
3.368326
1.018331
size = struct.unpack('<i', fh.read(4))[0] return fh.read_array('<2f8', count=size)
def read_lsm_floatpairs(fh)
Read LSM sequence of float pairs from file and return as list.
7.488737
7.873135
0.951176
size = struct.unpack('<I', fh.read(4))[0] return fh.read_array('<2f8', count=size)
def read_lsm_positions(fh)
Read LSM positions from file and return as list.
6.964097
7.021581
0.991813
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*count)) return fh.read_array('<f8', count=count)
def read_lsm_timestamps(fh)
Read LSM time stamps from file and return as list.
5.025824
4.731207
1.062271
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))) events.append((etime, etype, etext)) count -= 1 return events
def read_lsm_eventlist(fh)
Read LSM events from file and return as list of (time, type, text).
3.615463
3.137948
1.152174
result = {'Mono': False, 'Colors': [], 'ColorNames': []} pos = fh.tell() (size, ncolors, nnames, coffset, noffset, mono) = struct.unpack('<IIIIII', fh.read(24)) if ncolors != nnames: log.warning( 'read_lsm_channelcolors: invalid LSM ChannelColors structure') return ...
def read_lsm_channelcolors(fh)
Read LSM ChannelColors structure from file and return as dict.
3.404294
3.160886
1.077006
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 structure') return block fh.read(8) while True: entry, dtype, size = unpac...
def read_lsm_scaninfo(fh)
Read LSM ScanInfo structure from file and return as dict.
3.053746
2.973755
1.026899
result = {} (magic, _, minute, hour, day, month, year, _, name, tagcount ) = struct.unpack('<4s6shhhhh6s32sh', fh.read(60)) if magic != b'SIS0': raise ValueError('invalid OlympusSIS structure') result['name'] = bytes2str(stripnull(name)) try: result['datetime'] = datetim...
def read_sis(fh, byteorder, dtype, count, offsetsize)
Read OlympusSIS structure and return as dict. No specification is avaliable. Only few fields are known.
4.282438
4.100701
1.044318
inistr = fh.read(count) inistr = bytes2str(stripnull(inistr)) try: return olympusini_metadata(inistr) except Exception as exc: log.warning('olympusini_metadata: %s: %s', exc.__class__.__name__, exc) return {}
def read_sis_ini(fh, byteorder, dtype, count, offsetsize)
Read OlympusSIS INI string and return as dict.
6.502519
4.921789
1.32117
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['Version'] == 2: header = fh.read_record(TIFF.TVIPS_HEADER_V2, byteorder=byteorder) if header['Magic'] != ...
def read_tvips_header(fh, byteorder, dtype, count, offsetsize)
Read TVIPS EM-MENU headers and return as dict.
3.546612
3.429996
1.033999
result = {} section = {} data = bytes2str(stripnull(fh.read(count))) for line in data.splitlines(): line = line.strip() if line.startswith('['): section = {} result[line[1:-1]] = section continue try: key, value = line.split('=...
def read_fei_metadata(fh, byteorder, dtype, count, offsetsize)
Read FEI SFEG/HELIOS headers and return as dict.
3.135936
3.063741
1.023564
result = {'': ()} key = None data = bytes2str(stripnull(fh.read(count))) for line in data.splitlines(): if line.isupper(): key = line.lower() elif key: try: name, value = line.split('=') except ValueError: try: ...
def read_cz_sem(fh, byteorder, dtype, count, offsetsize)
Read Zeiss SEM tag and return as dict. See https://sourceforge.net/p/gwyddion/mailman/message/29275000/ for unnamed values.
3.199784
3.174917
1.007832
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['UM'][:a['UMsize']] return a
def read_nih_image_header(fh, byteorder, dtype, count, offsetsize)
Read NIH_IMAGE_HEADER tag from file and return as dict.
6.042057
5.298094
1.140421
fh.seek(0) try: byteorder, version = struct.unpack('<2sH', fh.read(4)) if byteorder != b'II' or version != 43: raise Exception fh.seek(16) magic, version, size0, size1 = struct.unpack('<IIII', fh.read(16)) if magic != 117637889 or version != 3: ...
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 valid ScanImage v3 metadata.
5.048478
4.274341
1.181113
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, index_offset, display_header, display_offset, comments_header, comments_offset, summary_header, su...
def read_micromanager_metadata(fh)
Read MicroManager non-TIFF settings from open file and return as dict. The settings can be used to read image data without parsing the TIFF file. Raise ValueError if the file does not contain valid MicroManager metadata.
2.454694
2.391006
1.026637
header = [{'>': b'IJIJ', '<': b'JIJI'}[byteorder]] bytecounts = [0] body = [] def _string(data, byteorder): return data.encode('utf-16' + {'>': 'be', '<': 'le'}[byteorder]) def _doubles(data, byteorder): return struct.pack(byteorder+('d' * len(data)), *data) def _ndarray(...
def imagej_metadata_tag(metadata, byteorder)
Return IJMetadata and IJMetadataByteCounts tags from metadata dict. The tags can be passed to the TiffWriter.save function as extratags. The metadata dict may contain the following keys and values: Info : str Human-readable information as string. Labels : sequence of str ...
2.766207
2.605078
1.061852
def _string(data, byteorder): return data.decode('utf-16' + {'>': 'be', '<': 'le'}[byteorder]) def _doubles(data, byteorder): return struct.unpack(byteorder+('d' * (len(data) // 8)), data) def _lut(data, byteorder): return numpy.frombuffer(data, 'uint8').reshape(-1, 256) ...
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.
2.713104
2.723268
0.996268
def _bool(val): return {'true': True, 'false': False}[val.lower()] result = {} for line in description.splitlines(): try: key, val = line.split('=') except Exception: continue key = key.strip() val = val.strip() for dtype in (int,...
def imagej_description_metadata(description)
Return metatata from ImageJ image description as dict. Raise ValueError if not a valid ImageJ description. >>> description = 'ImageJ=1.11a\\nimages=510\\nhyperstack=true\\n' >>> imagej_description_metadata(description) # doctest: +SKIP {'ImageJ': '1.11a', 'images': 510, 'hyperstack': True}
2.813287
2.542025
1.106711
if colormaped: raise NotImplementedError('ImageJ colormapping not supported') if version is None: version = '1.11a' shape = imagej_shape(shape, rgb=rgb) rgb = shape[-1] in (3, 4) result = ['ImageJ=%s' % version] append = [] result.append('images=%i' % product(shape[:-3]...
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. >>> imagej_description((51, 5, 2, 196, 171)) # doctest: +SKIP ImageJ=1.11a images=510 channels=2 slices=5 frames=51 hyperstack=true mode=grayscale loop=false
2.40458
2.366073
1.016275
shape = tuple(int(i) for i in shape) ndim = len(shape) if 1 > ndim > 6: raise ValueError('invalid ImageJ hyperstack: not 2 to 6 dimensional') if rgb is None: rgb = shape[-1] in (3, 4) and ndim > 2 if rgb and shape[-1] not in (3, 4): raise ValueError('invalid ImageJ hyper...
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)
2.634473
2.552668
1.032047
metadata.update(shape=shape) return json.dumps(metadata)
def json_description(shape, **metadata)
Return JSON image description from data shape and other metadata. Return UTF-8 encoded JSON. >>> json_description((256, 256, 3), axes='YXS') # doctest: +SKIP b'{"shape": [256, 256, 3], "axes": "YXS"}'
5.518804
15.151753
0.364235
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] == '{' and description[-1:] == '}': # JSON description return json.loads(description) ...
def json_description_metadata(description)
Return metatata from JSON formated image description as dict. Raise ValuError if description is of unknown format. >>> description = '{"shape": [256, 256, 3], "axes": "YXS"}' >>> json_description_metadata(description) # doctest: +SKIP {'shape': [256, 256, 3], 'axes': 'YXS'} >>> json_description_m...
4.483684
4.004677
1.119612
if not description.startswith('['): raise ValueError('invalid FluoView image description') if ignoresections is None: ignoresections = {'Region Info (Fields)', 'Protocol Description'} result = {} sections = [result] comment = False for line in description.splitlines(): ...
def fluoview_description_metadata(description, ignoresections=None)
Return metatata from FluoView image description as dict. The FluoView image description format is unspecified. Expect failures. >>> descr = ('[Intensity Mapping]\\nMap Ch0: Range=00000 to 02047\\n' ... '[Intensity Mapping End]') >>> fluoview_description_metadata(descr) {'Intensity Mapping...
3.144772
3.105063
1.012788
result = {} if not description.startswith('# '): return result for c in '#:=,()': description = description.replace(c, ' ') for line in description.split('\n'): if line[:2] != ' ': continue line = line.split() name = line[0] if line[0] no...
def pilatus_description_metadata(description)
Return metatata from Pilatus image description as dict. Return metadata from Pilatus pixel array detectors by Dectris, created by camserver or TVX software. >>> pilatus_description_metadata('# Pixel_size 172e-6 m x 172e-6 m') {'Pixel_size': (0.000172, 0.000172)}
3.262056
3.379574
0.965227
if not description.startswith('Aperio Image Library '): raise ValueError('invalid Aperio image description') result = {} lines = description.split('\n') key, value = lines[0].strip().rsplit(None, 1) # 'Aperio Image Library' result[key.strip()] = value.strip() if len(lines) == 1: ...
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'}
3.483264
2.940733
1.184488
description = description.strip() if not description: return [] try: description = bytes2str(description) except UnicodeDecodeError as exc: log.warning('stk_description_metadata: %s: %s', exc.__class__.__name__, exc) return [] result = [] ...
def stk_description_metadata(description)
Return metadata from MetaMorph image description as list of dict. The MetaMorph image description format is unspecified. Expect failures.
2.534453
2.495113
1.015767
if not description.startswith('<MetaData>'): raise ValueError('invalid MetaSeries image description') from xml.etree import cElementTree as etree # delayed import root = etree.fromstring(description) types = {'float': float, 'int': int, 'bool': lambda x: asbool(x, 'on', 'off'...
def metaseries_description_metadata(description)
Return metatata from MetaSeries image description as dict.
3.440082
3.049982
1.127902
try: return json.loads(artist) except ValueError as exc: log.warning('scanimage_artist_metadata: %s: %s', exc.__class__.__name__, exc)
def scanimage_artist_metadata(artist)
Return metatata from ScanImage artist tag as dict.
3.553391
3.246672
1.094472
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 key = key[:i] return key, index result = {} bands = [] zpos = None tpos = None for line i...
def olympusini_metadata(inistr)
Return OlympusSIS metadata from INI string. No documentation is available.
2.518736
2.495705
1.009228
_, imagedepth, imagelength, imagewidth, _ = out.shape tileddepth, tiledlength, tiledwidth = tiledshape tiledepth, tilelength, tilewidth, samples = tileshape tilesize = tiledepth * tilelength * tilewidth * samples pl = tileindex // (tiledwidth * tiledlength * tileddepth) td = (tileindex // ...
def tile_decode(tile, tileindex, tileshape, tiledshape, lsb2msb, decompress, unpack, unpredict, out)
Decode tile segment bytes into 5D output array.
3.305854
3.299604
1.001894
if bitspersample is None: bitspersample = (5, 6, 5) if dtype is None: dtype = '<B' dtype = numpy.dtype(dtype) bits = int(numpy.sum(bitspersample)) if not (bits <= 32 and all(i <= dtype.itemsize*8 for i in bitspersample)): raise ValueError('sample size not supported: %s' ...
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. Pixels are aligned to 8, 16, or 32 bit boundaries. dtype : numpy.d...
3.015712
3.081342
0.978701
if isinstance(data, (bytes, bytearray)): data = numpy.frombuffer(data, dtype='u1') diff = numpy.diff(data, axis=0) return numpy.insert(diff, 0, data[0]).tobytes() dtype = data.dtype if dtype.kind == 'f': data = data.view('u%i' % dtype.itemsize) diff = numpy.diff(da...
def delta_encode(data, axis=-1, out=None)
Encode Delta.
2.625758
2.599736
1.01001