code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
tseries = sdat.tseries_between(tstart, tend) rbot, rtop = misc.get_rbounds(sdat.steps.last) if rbot != 0: # spherical coefsurf = (rtop / rbot)**2 volume = rbot * ((rtop / rbot)**3 - 1) / 3 else: coefsurf = 1. volume = 1. dtdt, time = dt_dt(sdat, tstart, tend) ...
def ebalance(sdat, tstart=None, tend=None)
Energy balance. Compute Nu_t - Nu_b + V*dT/dt as a function of time using an explicit Euler scheme. This should be zero if energy is conserved. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. tstart (float): time at which the computation should start. Use the ...
6.236872
6.142149
1.015422
tseries = sdat.tseries_between(tstart, tend) steps = sdat.steps[tseries.index[0]:tseries.index[-1]] time = [] mob = [] for step in steps.filter(rprof=True): time.append(step.timeinfo['t']) mob.append(step.rprof.iloc[-1].loc['vrms'] / step.timeinfo['vrms']) return np.array(mo...
def mobility(sdat, tstart=None, tend=None)
Plates mobility. Compute the ratio vsurf / vrms. Args: sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance. tstart (float): time at which the computation should start. Use the beginning of the time series data if set to None. tend (float): time at which the...
4.981141
4.989347
0.998355
rbot, rtop = misc.get_rbounds(step) centers = step.rprof.loc[:, 'r'].values + rbot # assume walls are mid-way between T-nodes # could be T-nodes at center between walls edges = (centers[:-1] + centers[1:]) / 2 edges = np.insert(edges, 0, rbot) edges = np.append(edges, rtop) return e...
def r_edges(step)
Cell border. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the position of the bottom and top walls of the cells. The two elements of the tuple are identical.
7.307153
7.288114
1.002612
rbot, rtop = misc.get_rbounds(step) if rbot == 0: # not spherical return rprof if rad is None: rad = step.rprof['r'].values + rbot return rprof * (2 * rad / (rtop + rbot))**2
def _scale_prof(step, rprof, rad=None)
Scale profile to take sphericity into account
6.640684
5.925059
1.120779
rbot, rtop = misc.get_rbounds(step) rad = step.rprof['r'].values + rbot tprof = step.rprof['Tmean'].values diff = (tprof[:-1] - tprof[1:]) / (rad[1:] - rad[:-1]) # assume tbot = 1 diff = np.insert(diff, 0, (1 - tprof[0]) / (rad[0] - rbot)) # assume ttop = 0 diff = np.append(diff, tp...
def diff_prof(step)
Diffusion. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the diffusion and the radial position at which it is evaluated.
4.280924
4.123141
1.038268
diff, rad = diff_prof(step) return _scale_prof(step, diff, rad), rad
def diffs_prof(step)
Scaled diffusion. This computation takes sphericity into account if necessary. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the diffusion and the radial position at which it is evaluated.
12.384502
14.297961
0.866173
diff, rad = diffs_prof(step) adv, _ = advts_prof(step) return (diff + np.append(adv, 0)), rad
def energy_prof(step)
Energy flux. This computation takes sphericity into account if necessary. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the energy flux and the radial position at which it is evaluated.
14.666398
18.061361
0.812032
rbot, rtop = misc.get_rbounds(step) rmean = 0.5 * (rbot + rtop) rad = step.rprof['r'].values + rbot radio = step.timeinfo['H_int'] if rbot != 0: # spherical th_adv = -(rtop**3 - rad**3) / rmean**2 / 3 else: th_adv = rad - rtop th_adv *= radio th_adv += step.timeinfo...
def advth(step)
Theoretical advection. This compute the theoretical profile of total advection as function of radius. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array` and None: the theoretical advection. The sec...
9.019684
7.836684
1.150957
rbot, rtop = misc.get_rbounds(step) xieut = step.sdat.par['tracersin']['fe_eut'] k_fe = step.sdat.par['tracersin']['k_fe'] xi0l = step.sdat.par['tracersin']['fe_cont'] xi0s = k_fe * xi0l xired = xi0l / xieut rsup = (rtop**3 - xired**(1 / (1 - k_fe)) * (rtop**3 - rbot**3))**(...
def init_c_overturn(step)
Initial concentration. This compute the resulting composition profile if fractional crystallization of a SMO is assumed. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array`: the composition and the radial p...
5.395443
4.960905
1.087593
rbot, rtop = misc.get_rbounds(step) cinit, rad = init_c_overturn(step) radf = (rtop**3 + rbot**3 - rad**3)**(1 / 3) return cinit, radf
def c_overturned(step)
Theoretical overturned concentration. This compute the resulting composition profile if fractional crystallization of a SMO is assumed and then a purely radial overturn happens. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tu...
8.821602
8.186582
1.077568
if step.geom.twod_yz: x_coord = step.geom.y_coord v_x = step.fields['v2'][0, :, :, 0] v_z = step.fields['v3'][0, :, :, 0] shape = (1, v_x.shape[0], v_x.shape[1], 1) elif step.geom.twod_xz and step.geom.cartesian: x_coord = step.geom.x_coord v_x = step.fields[...
def stream_function(step)
Stream function. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: :class:`numpy.array`: the stream function field, with four dimensions: x-direction, y-direction, z-direction and block.
2.517414
2.490723
1.010716
if self._last is UNDETERMINED: # not necessarily the last one... self._last = self.sdat.tseries.index[-1] return self[self._last]
def last(self)
Last time step available. Example: >>> sdat = StagyyData('path/to/run') >>> assert(sdat.steps.last is sdat.steps[-1])
10.805317
11.880307
0.909515
self._isteps[isnap] = istep self.sdat.steps[istep].isnap = isnap
def bind(self, isnap, istep)
Register the isnap / istep correspondence. Users of :class:`StagyyData` should not use this method. Args: isnap (int): snapshot index. istep (int): time step index.
8.65495
7.972576
1.08559
okf = True okf = okf and (not self._flt['snap'] or step.isnap is not None) okf = okf and (not self._flt['rprof'] or step.rprof is not None) okf = okf and all(f in step.fields for f in self._flt['fields']) okf = okf and bool(self._flt['func'](step)) return okf
def _pass(self, step)
Check whether a :class:`~stagpy._step.Step` passes the filters.
4.461105
3.890269
1.146734
for flt, val in self._flt.items(): self._flt[flt] = filters.pop(flt, val) if filters: raise error.UnknownFiltersError(filters.keys()) return self
def filter(self, **filters)
Update filters with provided arguments. Note that filters are only resolved when the view is iterated, and hence they do not compose. Each call to filter merely updates the relevant filters. For example, with this code:: view = sdat.steps[500:].filter(rprof=True, fields=['T']) ...
5.422068
7.289135
0.743856
if self._rundir['hdf5'] is UNDETERMINED: h5_folder = self.path / self.par['ioin']['hdf5_output_folder'] if (h5_folder / 'Data.xmf').is_file(): self._rundir['hdf5'] = h5_folder else: self._rundir['hdf5'] = None return self._rund...
def hdf5(self)
Path of output hdf5 folder if relevant, None otherwise.
4.305034
4.139362
1.040024
if self._stagdat['tseries'] is UNDETERMINED: timefile = self.filename('TimeSeries.h5') self._stagdat['tseries'] = stagyyparsers.time_series_h5( timefile, list(phyvars.TIME.keys())) if self._stagdat['tseries'] is not None: return self._...
def tseries(self)
Time series data. This is a :class:`pandas.DataFrame` with istep as index and variable names as columns.
4.682847
4.78594
0.978459
if self._rundir['ls'] is UNDETERMINED: out_stem = pathlib.Path(self.par['ioin']['output_file_stem'] + '_') out_dir = self.path / out_stem.parent if out_dir.is_dir(): self._rundir['ls'] = set(out_dir.iterdir()) else: self._r...
def files(self)
Set of found binary files output by StagYY.
4.923235
4.688023
1.050173
if conf.core.snapshots is not None: return self.snaps[conf.core.snapshots] elif conf.core.timesteps is not None: return self.steps[conf.core.timesteps] return self.snaps[-1:]
def walk(self)
Return view on configured steps slice. Other Parameters: conf.core.snapshots: the slice of snapshots. conf.core.timesteps: the slice of timesteps.
5.175135
2.503193
2.067414
if self.par['switches']['dimensional_units'] or \ not conf.scaling.dimensional or \ unit == '1': return data, '' scaling = phyvars.SCALES[unit](self.scales) factor = conf.scaling.factors.get(unit, ' ') if conf.scaling.time_in_y and unit == 's': ...
def scale(self, data, unit)
Scales quantity to obtain dimensionful quantity. Args: data (numpy.array): the quantity that should be scaled. dim (str): the dimension of data as defined in phyvars. Return: (float, str): scaling factor and unit string. Other Parameters: conf.sca...
6.262585
5.313454
1.178628
if self.tseries is None: return None ndat = self.tseries.shape[0] if tstart is None: istart = 0 else: igm = 0 igp = ndat - 1 while igp - igm > 1: istart = igm + (igp - igm) // 2 if self...
def tseries_between(self, tstart=None, tend=None)
Return time series data between requested times. Args: tstart (float): starting time. Set to None to start at the beginning of available data. tend (float): ending time. Set to None to stop at the end of available data. Returns: :class...
1.773443
1.763353
1.005722
if timestep is not None: fname += '{:05d}'.format(timestep) fname += suffix if not force_legacy and self.hdf5: fpath = self.hdf5 / fname else: fpath = self.par['ioin']['output_file_stem'] + '_' + fname fpath = self.path / fpath ...
def filename(self, fname, timestep=None, suffix='', force_legacy=False)
Return name of StagYY output file. Args: fname (str): name stem. timestep (int): snapshot number, set to None if this is not relevant. suffix (str): optional suffix of file name. force_legacy (bool): force returning the legacy output path. ...
4.309366
4.202372
1.02546
possible_files = set(self.filename(fstem, isnap, force_legacy=True) for fstem in phyvars.FIELD_FILES) return possible_files & self.files
def binfiles_set(self, isnap)
Set of existing binary files at a given snap. Args: isnap (int): snapshot index. Returns: set of pathlib.Path: the set of output files available for this snapshot number.
16.440462
16.871586
0.974447
if len(names) < nnames and extra_names is not None: names.extend(extra_names) names.extend(range(nnames - len(names))) del names[nnames:]
def _tidy_names(names, nnames, extra_names=None)
Truncate or extend names so that its len is nnames. The list is modified, this function returns nothing. Args: names (list): list of names. nnames (int): desired number of names. extra_names (list of str): list of names to be used to extend the list if needed. If this list ...
3.206518
3.359034
0.954595
if not timefile.is_file(): return None data = pd.read_csv(timefile, delim_whitespace=True, dtype=str, header=None, skiprows=1, index_col=0, engine='c', memory_map=True, error_bad_lines=False, warn_bad_lines=False) data = data....
def time_series(timefile, colnames)
Read temporal series text file. If :data:`colnames` is too long, it will be truncated. If it is too short, additional numeric column names from 0 to N-1 will be attributed to the N extra columns present in :data:`timefile`. Args: timefile (:class:`pathlib.Path`): path of the time.dat file. ...
2.953458
2.98534
0.989321
if not timefile.is_file(): return None with h5py.File(timefile, 'r') as h5f: dset = h5f['tseries'] _, ncols = dset.shape ncols -= 1 # first is istep h5names = map(bytes.decode, h5f['names'][len(colnames) + 1:]) _tidy_names(colnames, ncols, h5names) d...
def time_series_h5(timefile, colnames)
Read temporal series HDF5 file. If :data:`colnames` is too long, it will be truncated. If it is too short, additional column names will be deduced from the content of the file. Args: timefile (:class:`pathlib.Path`): path of the TimeSeries.h5 file. colnames (list of names): names of the va...
4.156861
4.329532
0.960118
step_regex = re.compile(r'^\*+step:\s*(\d+) ; time =\s*(\S+)') isteps = [] # list of (istep, time, nz) rows_to_del = set() line = ' ' with rproffile.open() as stream: while line[0] != '*': line = stream.readline() match = step_regex.match(line) istep = int(m...
def _extract_rsnap_isteps(rproffile)
Extract istep and compute list of rows to delete
2.771722
2.573292
1.077111
if not rproffile.is_file(): return None, None data = pd.read_csv(rproffile, delim_whitespace=True, dtype=str, header=None, comment='*', skiprows=1, engine='c', memory_map=True, error_bad_lines=False, warn_bad_lines=False) data...
def rprof(rproffile, colnames)
Extract radial profiles data If :data:`colnames` is too long, it will be truncated. If it is too short, additional numeric column names from 0 to N-1 will be attributed to the N extra columns present in :data:`timefile`. Args: rproffile (:class:`pathlib.Path`): path of the rprof.dat file. ...
3.665533
3.472759
1.05551
if not rproffile.is_file(): return None, None isteps = [] with h5py.File(rproffile) as h5f: dnames = sorted(dname for dname in h5f.keys() if dname.startswith('rprof_')) ncols = h5f['names'].shape[0] h5names = map(bytes.decode, h5f['names'][len(col...
def rprof_h5(rproffile, colnames)
Extract radial profiles data If :data:`colnames` is too long, it will be truncated. If it is too short, additional column names will be deduced from the content of the file. Args: rproffile (:class:`pathlib.Path`): path of the rprof.dat file. colnames (list of names): names of the variable...
2.88851
2.836722
1.018256
if fmt in 'if': fmt += '8' if file64 else '4' elts = np.fromfile(fid, fmt, nwords) if unpack and len(elts) == 1: elts = elts[0] return elts
def _readbin(fid, fmt='i', nwords=1, file64=False, unpack=True)
Read n words of 4 or 8 bytes with fmt format. fmt: 'i' or 'f' or 'b' (integer or float or bytes) 4 or 8 bytes: depends on header Return an array of elements if more than one element. Default: read 1 word formatted as an integer.
2.737769
2.92402
0.936303
if not tracersfile.is_file(): return None tra = {} with tracersfile.open('rb') as fid: readbin = partial(_readbin, fid) magic = readbin() if magic > 8000: # 64 bits magic -= 8000 readbin() readbin = partial(readbin, file64=True) ...
def tracers(tracersfile)
Extract tracers data. Args: tracersfile (:class:`pathlib.Path`): path of the binary tracers file. Returns: dict of list of numpy.array: Tracers data organized by attribute and block.
5.673582
5.528303
1.026279
with h5py.File(filename, 'r') as h5f: data = h5f[groupname][()] return data
def _read_group_h5(filename, groupname)
Return group content. Args: filename (:class:`pathlib.Path`): path of hdf5 file. groupname (str): name of group to read. Returns: :class:`numpy.array`: content of group.
2.323146
3.17103
0.732615
shp = list(field.shape) if twod and 'X' in twod: shp.insert(1, 1) elif twod: shp.insert(0, 1) return field.reshape(shp)
def _make_3d(field, twod)
Add a dimension to field if necessary. Args: field (numpy.array): the field that need to be 3d. twod (str): 'XZ', 'YZ' or None depending on what is relevant. Returns: numpy.array: reshaped field.
3.204943
2.612158
1.226933
nnpb = len(meshes) # number of nodes per block nns = [1, 1, 1] # number of nodes in x, y, z directions if twod is None or 'X' in twod: while (nnpb > 1 and meshes[nns[0]]['X'][0, 0, 0] == meshes[nns[0] - 1]['X'][-1, 0, 0]): nns[0] += 1 nnpb...
def _ncores(meshes, twod)
Compute number of nodes in each direction.
2.028691
1.951125
1.039755
meshout = {} npc = header['nts'] // header['ncs'] shp = [val + 1 if val != 1 else 1 for val in header['nts']] x_p = int(shp[0] != 1) y_p = int(shp[1] != 1) for coord in meshin[0]: meshout[coord] = np.zeros(shp) for icore in range(np.prod(header['ncs'])): ifs = [icore // ...
def _conglomerate_meshes(meshin, header)
Conglomerate meshes from several cores into one.
3.259253
3.137483
1.038811
meshes = [] for h5file, shape in zip(files, shapes): meshes.append({}) with h5py.File(h5file, 'r') as h5f: for coord, mesh in h5f.items(): # for some reason, the array is transposed! meshes[-1][coord] = mesh[()].reshape(shape).T me...
def _read_coord_h5(files, shapes, header, twod)
Read all coord hdf5 files of a snapshot. Args: files (list of pathlib.Path): list of NodeCoordinates files of a snapshot. shapes (list of (int,int)): shape of mesh grids. header (dict): geometry info. twod (str): 'XZ', 'YZ' or None depending on what is relevant.
2.707719
2.724762
0.993745
shp = _get_dim(data_item) h5file, group = data_item.text.strip().split(':/', 1) icore = int(group.split('_')[-2]) - 1 fld = _read_group_h5(xdmf_file.parent / h5file, group).reshape(shp) return icore, fld
def _get_field(xdmf_file, data_item)
Extract field from data item.
7.426566
7.442503
0.997859
maybe_item = elt.find(item) if maybe_item is not None: maybe_item = maybe_item.get(info) if conversion is not None: maybe_item = conversion(maybe_item) return maybe_item
def _maybe_get(elt, item, info, conversion=None)
Extract and convert info if item is present.
2.228612
2.059146
1.082299
header = {} xdmf_root = xmlET.parse(str(xdmf_file)).getroot() if snapshot is None: return None, xdmf_root # Domain, Temporal Collection, Snapshot # should check that this is indeed the required snapshot elt_snap = xdmf_root[0][0][snapshot] header['ti_ad'] = float(elt_snap.find(...
def read_geom_h5(xdmf_file, snapshot)
Extract geometry information from hdf5 files. Args: xdmf_file (:class:`pathlib.Path`): path of the xdmf file. snapshot (int): snapshot number. Returns: (dict, root): geometry information and root of xdmf document.
4.979748
4.964269
1.003118
cth = np.cos(header['t_mesh'][:, :, :-1]) sth = np.sin(header['t_mesh'][:, :, :-1]) cph = np.cos(header['p_mesh'][:, :, :-1]) sph = np.sin(header['p_mesh'][:, :, :-1]) fout = np.copy(flds) fout[0] = cth * cph * flds[0] + cth * sph * flds[1] - sth * flds[2] fout[1] = sph * flds[0] - cph ...
def _to_spherical(flds, header)
Convert vector field to spherical.
2.221152
2.115146
1.050117
shp = list(header['nts']) shp.append(header['ntb']) # probably a better way to handle this if fieldname == 'Velocity': shp.insert(0, 3) # extra points header['xp'] = int(header['nts'][0] != 1) shp[1] += header['xp'] header['yp'] = int(header['nts'][1] != 1) ...
def _flds_shape(fieldname, header)
Compute shape of flds variable.
2.998911
2.912197
1.029776
if flds.shape[0] >= 3 and header['rcmb'] > 0: # spherical vector header['p_mesh'] = np.roll( np.arctan2(header['y_mesh'], header['x_mesh']), -1, 1) for ibk in range(header['ntb']): flds[..., ibk] = _to_spherical(flds[..., ibk], header) header['p_mesh'] = ...
def _post_read_flds(flds, header)
Process flds to handle sphericity.
4.235242
3.884086
1.090409
if header is None: header, xdmf_root = read_geom_h5(xdmf_file, snapshot) else: xdmf_root = xmlET.parse(str(xdmf_file)).getroot() npc = header['nts'] // header['ncs'] # number of grid point per node flds = np.zeros(_flds_shape(fieldname, header)) data_found = False for elt...
def read_field_h5(xdmf_file, fieldname, snapshot, header=None)
Extract field data from hdf5 files. Args: xdmf_file (:class:`pathlib.Path`): path of the xdmf file. fieldname (str): name of field to extract. snapshot (int): snapshot number. header (dict): geometry information. Returns: (dict, numpy.array): geometry information and fie...
3.663451
3.65575
1.002106
xdmf_root = xmlET.parse(str(xdmf_file)).getroot() tra = {} tra[infoname] = [{}, {}] # two blocks, ordered by cores if position: for axis in 'xyz': tra[axis] = [{}, {}] for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'): ibk = int(elt_subdomain.get('Name'...
def read_tracers_h5(xdmf_file, infoname, snapshot, position)
Extract tracers data from hdf5 files. Args: xdmf_file (:class:`pathlib.Path`): path of the xdmf file. infoname (str): name of information to extract. snapshot (int): snapshot number. position (bool): whether to extract position of tracers. Returns: dict of list of numpy....
3.674162
3.694559
0.994479
with h5py.File(h5folder / 'time_botT.h5', 'r') as h5f: for name, dset in h5f.items(): yield int(name[-5:]), int(dset[2])
def read_time_h5(h5folder)
Iterate through (isnap, istep) recorded in h5folder/'time_botT.h5'. Args: h5folder (:class:`pathlib.Path`): directory of HDF5 output files. Yields: tuple of int: (isnap, istep).
4.974935
2.981216
1.66876
shape = self._par['geometry']['shape'].lower() aspect = self._header['aspect'] if self.rcmb is not None and self.rcmb >= 0: # curvilinear self._shape['cyl'] = self.twod_xz and (shape == 'cylindrical' or aspect[0]...
def _init_shape(self)
Determine shape of geometry
4.256054
4.134984
1.029279
# try legacy first, then hdf5 filestem = '' for filestem, list_fvar in self._files.items(): if name in list_fvar: break fieldfile = self.step.sdat.filename(filestem, self.step.isnap, force_legacy=True) ...
def _get_raw_data(self, name)
Find file holding data and return its content.
4.564125
4.539401
1.005447
if self._header is UNDETERMINED: binfiles = self.step.sdat.binfiles_set(self.step.isnap) if binfiles: self._header = stagyyparsers.fields(binfiles.pop(), only_header=True) elif self.step.sdat.hdf5: ...
def geom(self)
Geometry information. :class:`_Geometry` instance holding geometry information. It is issued from binary files holding field information. It is set to None if not available for this time step.
5.187885
4.696295
1.104676
if self.istep not in self.sdat.tseries.index: return None return self.sdat.tseries.loc[self.istep]
def timeinfo(self)
Time series data of the time step. Set to None if no time series data is available for this time step.
7.194943
5.291352
1.359755
if self.istep not in self.sdat.rprof.index.levels[0]: return None return self.sdat.rprof.loc[self.istep]
def rprof(self)
Radial profiles data of the time step. Set to None if no radial profiles data is available for this time step.
5.261652
4.647823
1.132068
if self._isnap is UNDETERMINED: istep = None isnap = -1 # could be more efficient if do 0 and -1 then bisection # (but loose intermediate <- would probably use too much # memory for what it's worth if search algo is efficient) whil...
def isnap(self)
Snapshot index corresponding to time step. It is set to None if no snapshot exists for the time step.
10.569514
10.463472
1.010134
# type: (...) -> Dict[str, Any] version = dict['version'] if version != 1: raise ValueError('Version {} not 1'.format(version)) clk_config = dict['clkConfig'] k = clk_config['k'] clk_hash = clk_config['hash'] def convert_feature(f): if 'ignored' in f: retur...
def convert_v1_to_v2( dict # type: Dict[str, Any] )
Convert v1 schema dict to v2 schema dict. :param dict: v1 schema dict :return: v2 schema dict
3.179066
3.455215
0.920078
# type: (Dict[str, Any], bool) -> Schema if validate: # This raises iff the schema is invalid. validate_schema_dict(dct) version = dct['version'] if version == 1: dct = convert_v1_to_v2(dct) if validate: validate_schema_dict(dct) elif version != 2: ...
def from_json_dict(dct, validate=True)
Create a Schema for v1 or v2 according to dct :param dct: This dictionary must have a `'features'` key specifying the columns of the dataset. It must have a `'version'` key containing the master schema version that this schema conforms to. It must have a `'hash'` key...
2.489472
2.602553
0.95655
# type: (TextIO, bool) -> Schema try: schema_dict = json.load(schema_file) except ValueError as e: # In Python 3 we can be more specific # with json.decoder.JSONDecodeError, # but that doesn't exist in Python 2. msg = 'The schema is not a valid JSON file.' raise...
def from_json_file(schema_file, validate=True)
Load a Schema object from a json file. :param schema_file: A JSON file containing the schema. :param validate: (default True) Raise an exception if the schema does not conform to the master schema. :raises SchemaError: When the schema is invalid. :return: the Schema
3.582707
4.39805
0.814613
# type: (Hashable) -> bytes try: file_name = MASTER_SCHEMA_FILE_NAMES[version] except (TypeError, KeyError) as e: msg = ('Schema version {} is not supported. ' 'Consider updating clkhash.').format(version) raise_from(SchemaError(msg), e) try: schema_b...
def _get_master_schema(version)
Loads the master schema of given version as bytes. :param version: The version of the master schema whose path we wish to retrieve. :raises SchemaError: When the schema version is unknown. This usually means that either (a) clkhash is out of date, or (b) the schema v...
3.362523
3.443638
0.976445
# type: (Dict[str, Any]) -> None if not isinstance(schema, dict): msg = ('The top level of the schema file is a {}, whereas a dict is ' 'expected.'.format(type(schema).__name__)) raise SchemaError(msg) if 'version' in schema: version = schema['version'] else:...
def validate_schema_dict(schema)
Validate the schema. This raises iff either the schema or the master schema are invalid. If it's successful, it returns nothing. :param schema: The schema to validate, as parsed by `json`. :raises SchemaError: When the schema is invalid. :raises MasterSchemaError: When the mast...
2.691804
2.755769
0.976788
# type: (str) -> bitarray ba = bitarray() ba.frombytes(base64.b64decode(ser.encode(encoding='UTF-8', errors='strict'))) return ba
def deserialize_bitarray(ser)
Deserialize a base 64 encoded string to a bitarray (bloomfilter)
3.165277
3.261101
0.970616
def analyze_image(image, apis=DEFAULT_APIS, **kwargs): cloud = kwargs.pop('cloud', None) batch = kwargs.pop('batch', False) api_key = kwargs.pop('api_key', None) return multi( data=data_preprocess(image, batch=batch), datatype="image", cloud=cloud, batch=b...
Given input image, returns the results of specified image apis. Possible apis include: ['fer', 'facial_features', 'image_features'] Example usage: .. code-block:: python >>> import indicoio >>> import numpy as np >>> face = np.zeros((48,48)).tolist() >>> results = in...
null
null
null
# type: (int, bool) -> float namelist = NameList(num) os_fd, tmpfile_name = tempfile.mkstemp(text=True) schema = NameList.SCHEMA header_row = ','.join([f.identifier for f in schema.fields]) with open(tmpfile_name, 'wt') as f: f.write(header_row) f.write('\n') for ...
def compute_hash_speed(num, quiet=False)
Hash time.
3.517846
3.504803
1.003721
schema_object = clkhash.schema.from_json_file(schema_file=schema) header = True if not check_header: header = 'ignore' if no_header: header = False try: clk_data = clk.generate_clk_from_csv( pii_csv, keys, schema_object, validate=validate, ...
def hash(pii_csv, keys, schema, clk_json, quiet, no_header, check_header, validate)
Process data to create CLKs Given a file containing CSV data as PII_CSV, and a JSON document defining the expected schema, verify the schema, then hash the data to create CLKs writing them as JSON to CLK_JSON. Note the CSV file should contain a header row - however this row is not used by this tool...
4.649131
4.75244
0.978262
if verbose: log("Connecting to Entity Matching Server: {}".format(server)) service_status = server_get_status(server) if verbose: log("Status: {}".format(service_status['status'])) print(json.dumps(service_status), file=output)
def status(server, output, verbose)
Connect to an entity matching server and check the service status. Use "-" to output status to stdout.
5.31321
4.176896
1.272048
if verbose: log("Entity Matching Server: {}".format(server)) if schema is not None: schema_json = json.load(schema) # Validate the schema clkhash.schema.validate_schema_dict(schema_json) else: raise ValueError("Schema must be provided when creating new linkage p...
def create_project(type, schema, server, name, output, verbose)
Create a new project on an entity matching server. See entity matching service documentation for details on mapping type and schema Returns authentication details for the created project.
5.292787
5.014477
1.055501
if verbose: log("Entity Matching Server: {}".format(server)) if threshold is None: raise ValueError("Please provide a threshold") # Create a new run try: response = run_create(server, project, apikey, threshold, name) except ServiceError as e: log("Unexpected r...
def create(server, name, project, apikey, output, threshold, verbose)
Create a new run on an entity matching server. See entity matching service documentation for details on threshold. Returns details for the created run.
5.295158
4.785869
1.106415
if verbose: log("Uploading CLK data from {}".format(clk_json.name)) log("To Entity Matching Server: {}".format(server)) log("Project ID: {}".format(project)) log("Uploading CLK data to the server") response = project_upload_clks(server, project, apikey, clk_json) if ve...
def upload(clk_json, project, apikey, server, output, verbose)
Upload CLK data to entity matching server. Given a json file containing hashed clk data as CLK_JSON, upload to the entity resolution service. Use "-" to read from stdin.
4.811223
4.501235
1.068867
status = run_get_status(server, project, run, apikey) log(format_run_status(status)) if watch: for status in watch_run_status(server, project, run, apikey, 24*60*60): log(format_run_status(status)) if status['state'] == 'completed': log("Downloading result") re...
def results(project, apikey, run, watch, server, output)
Check to see if results are available for a particular mapping and if so download. Authentication is carried out using the --apikey option which must be provided. Depending on the server operating mode this may return a mask, a linkage table, or a permutation. Consult the entity service documentati...
2.734101
2.978192
0.918041
pii_data = randomnames.NameList(size) if schema is not None: raise NotImplementedError randomnames.save_csv( pii_data.names, [f.identifier for f in pii_data.SCHEMA.fields], output)
def generate(size, output, schema)
Generate fake PII data for testing
9.056391
7.773489
1.165036
original_path = os.path.join(os.path.dirname(__file__), 'data', 'randomnames-schema.json') shutil.copyfile(original_path, output)
def generate_default_schema(output)
Get default schema for fake PII
4.801104
4.549613
1.055277
docx = docx_preprocess(docx, batch=batch) url_params = {"batch": batch, "api_key": api_key, "version": version} results = api_handler(docx, cloud=cloud, api="docxextraction", url_params=url_params, **kwargs) return results
def docx_extraction(docx, cloud=None, batch=False, api_key=None, version=None, **kwargs)
Given a .docx file, returns the raw text associated with the given .docx file. The .docx file may be provided as base64 encoded data or as a filepath. Example usage: .. code-block:: python >>> from indicoio import docx_extraction >>> results = docx_extraction(docx_file) :param docx: Th...
3.337129
4.436878
0.752134
def facial_features(image, cloud=None, batch=False, api_key=None, version=None, **kwargs): image = data_preprocess(image, batch=batch, size=None if kwargs.get("detect") else (48, 48)) url_params = {"batch": batch, "api_key": api_key, "version": version} return api_handler(image, cloud=cloud, api="f...
Given an grayscale input image of a face, returns a 48 dimensional feature vector explaining that face. Useful as a form of feature engineering for face oriented tasks. Input should be in a list of list format, resizing will be attempted internally but for best performance, images should be already sized...
null
null
null
for status in watch_run_status(server, project, run, apikey, timeout, update_period): pass return status
def wait_for_run(server, project, run, apikey, timeout=None, update_period=1)
Monitor a linkage run and return the final status updates. If a timeout is provided and the run hasn't entered a terminal state (error or completed) when the timeout is reached a TimeoutError will be raised. :param server: Base url of the upstream server. :param project: :param run: :param apik...
4.448455
5.171175
0.860241
start_time = time.time() status = old_status = run_get_status(server, project, run, apikey) yield status def time_not_up(): return ( (timeout is None) or (time.time() - start_time < timeout) ) while time_not_up(): if status['state'] in {'error'...
def watch_run_status(server, project, run, apikey, timeout=None, update_period=1)
Monitor a linkage run and yield status updates. Will immediately yield an update and then only yield further updates when the status object changes. If a timeout is provided and the run hasn't entered a terminal state (error or completed) when the timeout is reached, updates will cease and a TimeoutError wi...
3.555298
3.609884
0.984879
if batch: return [docx_preprocess(doc, batch=False) for doc in docx] if os.path.isfile(docx): # a filepath is provided, read and encode return b64encode(open(docx, 'rb').read()) else: # assume doc is already b64 encoded return docx
def docx_preprocess(docx, batch=False)
Load docx files from local filepath if not already b64 encoded
3.67305
2.986882
1.229727
url_params = {"batch": batch, "api_key": api_key, "version": version} kwargs['queries'] = queries kwargs['synonyms'] = False return api_handler(data, cloud=cloud, api="relevance", url_params=url_params, **kwargs)
def relevance(data, queries, cloud=None, batch=False, api_key=None, version=None, **kwargs)
Given input text and a list of query terms / phrases, returns how relevant the query is to the input text. Example usage: .. code-block:: python >>> import indicoio >>> text = 'On Monday, president Barack Obama will be giving his keynote address at...' >>> relevance = indicoio.releva...
3.689589
5.391613
0.68432
if not isinstance(self.scope, ModuleScope): return super().ASSIGN(node) for target in node.targets: self.handleNode(target, node) self.deferHandleNode(node.value, node)
def ASSIGN(self, node)
This is a custom implementation of ASSIGN derived from handleChildren() in pyflakes 1.3.0. The point here is that on module level, there's type aliases that we want to bind eagerly, but defer computation of the values of the assignments (the type aliases might have forward references).
5.468822
5.217773
1.048114
if node.value: # Only bind the *target* if the assignment has value. # Otherwise it's not really ast.Store and shouldn't silence # UndefinedLocal warnings. self.handleNode(node.target, node) if not isinstance(self.scope, FunctionScope): ...
def ANNASSIGN(self, node)
Annotated assignments don't have annotations evaluated on function scope, hence the custom implementation. Compared to the pyflakes version, we defer evaluation of the annotations (and values on module level).
6.13945
5.426634
1.131355
self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode super().LAMBDA(node) self.handleNode, self.deferHandleNode = self.deferHandleNode, self.handleNode
def LAMBDA(self, node)
This is likely very brittle, currently works for pyflakes 1.3.0. Deferring annotation handling depends on the fact that during calls to LAMBDA visiting the function's body is already deferred and the only eager calls to `handleNode` are for annotations.
3.58416
2.569238
1.395029
# type: (...) -> bitarray key_sha1, key_md5 = keys bf = bitarray(l) bf.setall(False) for m, k in zip(ngrams, ks): sha1hm = int( hmac.new(key_sha1, m.encode(encoding=encoding), sha1).hexdigest(), 16) % l md5hm = int( hmac.new(key_md5, m.encode...
def double_hash_encode_ngrams(ngrams, # type: Iterable[str] keys, # type: Sequence[bytes] ks, # type: Sequence[int] l, # type: int encoding # type: str ...
Computes the double hash encoding of the ngrams with the given keys. Using the method from: Schnell, R., Bachteler, T., & Reiher, J. (2011). A Novel Error-Tolerant Anonymous Linking Code. http://grlc.german-microsimulation.de/wp-content/uploads/2017/05/downloadwp-grlc-20...
3.013329
2.963287
1.016887
# type: (...) -> bitarray.bitarray key_sha1, key_md5 = keys bf = bitarray(l) bf.setall(False) for m, k in zip(ngrams, ks): m_bytes = m.encode(encoding=encoding) sha1hm_bytes = hmac.new(key_sha1, m_bytes, sha1).digest() md5hm_bytes = hmac.new(key_md5, m_bytes, md5).diges...
def double_hash_encode_ngrams_non_singular(ngrams, # type: Iterable[str] keys, # type: Sequence[bytes] ks, # type: Sequence[int] l, # type: int ...
computes the double hash encoding of the n-grams with the given keys. The original construction of [Schnell2011]_ displays an abnormality for certain inputs: An n-gram can be encoded into just one bit irrespective of the number of k. Their construction goes as follows:...
2.322227
2.177017
1.066701
# type: (...) -> bitarray.bitarray key, = keys # Unpack. log_l = int(math.log(l, 2)) if not 2 ** log_l == l: raise ValueError( 'parameter "l" has to be a power of two for the BLAKE2 encoding, ' 'but was: {}'.format( l)) bf = bitarray(l) bf.s...
def blake_encode_ngrams(ngrams, # type: Iterable[str] keys, # type: Sequence[bytes] ks, # type: Sequence[int] l, # type: int encoding # type: str )
Computes the encoding of the ngrams using the BLAKE2 hash function. We deliberately do not use the double hashing scheme as proposed in [ Schnell2011]_, because this would introduce an exploitable structure into the Bloom filter. For more details on the weakness, see [Kroll2015]...
3.973507
4.085786
0.97252
# type: (...) -> Callable[[Iterable[str], Sequence[bytes], Sequence[int], int, str], bitarray] if fhp.hash_type == 'doubleHash': if fhp.prevent_singularity: return double_hash_encode_ngrams_non_singular else: return double_hash_encode_ngrams elif fhp.hash_type ==...
def hashing_function_from_properties( fhp # type: FieldHashingProperties )
Get the hashing function for this field :param fhp: hashing properties for this field :return: the hashing function
3.708619
4.761527
0.778872
# type: (...) -> bitarray if len(bloomfilter) % 2 ** folds != 0: msg = ('The length of the bloom filter is {length}. It is not ' 'divisible by 2 ** {folds}, so it cannot be folded {folds} ' 'times.' .format(length=len(bloomfilter), folds=folds)) ...
def fold_xor(bloomfilter, # type: bitarray folds # type: int )
Performs XOR folding on a Bloom filter. If the length of the original Bloom filter is n and we perform r folds, then the length of the resulting filter is n / 2 ** r. :param bloomfilter: Bloom filter to fold :param folds: number of folds :return: folded bloom filter
2.34636
2.65452
0.883911
# type: (...) -> Tuple[bitarray, Text, int] hash_l = schema.l * 2 ** schema.xor_folds bloomfilter = bitarray(hash_l) bloomfilter.setall(False) for (entry, tokenize, field, key) \ in zip(record, tokenizers, schema.fields, keys): fhp = field.hashing_properties if fhp...
def crypto_bloom_filter(record, # type: Sequence[Text] tokenizers, # type: List[Callable[[Text, Optional[Text]], Iterable[Text]]] schema, # type: Schema keys # type: Sequence[Sequence[bytes]] )
Computes the composite Bloom filter encoding of a record. Using the method from http://www.record-linkage.de/-download=wp-grlc-2011-02.pdf :param record: plaintext record tuple. E.g. (index, name, dob, gender) :param tokenizers: A list of tokenizers. A tokenizer is a function that ...
5.27353
6.016765
0.876473
# type: (...) -> Iterable[Tuple[bitarray, Text, int]] tokenizers = [tokenizer.get_tokenizer(field.hashing_properties) for field in schema.fields] return (crypto_bloom_filter(s, tokenizers, schema, keys) for s in dataset)
def stream_bloom_filters(dataset, # type: Iterable[Sequence[Text]] keys, # type: Sequence[Sequence[bytes]] schema # type: Schema )
Compute composite Bloom filters (CLKs) for every record in an iterable dataset. :param dataset: An iterable of indexable records. :param schema: An instantiated Schema instance :param keys: A tuple of two lists of secret keys used in the HMAC. :return: Generator yielding bloom f...
7.553309
10.242352
0.737458
# type: (AnyStr, int) -> Pattern # Don't worry, this short-circuits. assert type(pattern) is str or type(pattern) is unicode # type: ignore return re.compile(r'(?:{})\Z'.format(pattern), flags=flags)
def re_compile_full(pattern, flags=0)
Create compiled regular expression such that it matches the entire string. Calling re.match on the output of this function is equivalent to calling re.fullmatch on its input. This is needed to support Python 2. (On Python 3, we would just call re.fullmatch.) Kudos: https://stack...
5.24423
7.185169
0.729869
# Encode temporarily as UTF-8: utf8_csv_data = _utf_8_encoder(unicode_csv_data) # Now we can parse! csv_reader = csv.reader(utf8_csv_data, dialect=dialect, **kwargs) # Decode UTF-8 back to Unicode, cell by cell: return ([unicode(cell, 'utf-8') for cell in row] for row in csv_reader)
def _p2_unicode_reader(unicode_csv_data, dialect=csv.excel, **kwargs)
Encode Unicode as UTF-8 and parse as CSV. This is needed since Python 2's `csv` doesn't do Unicode. Kudos: https://docs.python.org/2/library/csv.html#examples :param unicode_csv_data: The Unicode stream to parse. :param dialect: The CSV dialect to use. :param kwargs: Any other...
3.092603
3.59441
0.860392
try: return os.path.isfile(filename) except (UnicodeDecodeError, UnicodeEncodeError, ValueError): return False
def file_exists(filename)
Check if a file exists (and don't error out on unicode inputs)
3.945717
3.187894
1.237719
if batch: return [data_preprocess(el, size=size, min_axis=min_axis, batch=False) for el in data] if isinstance(data, string_types): if file_exists(data): # probably a path to an image preprocessed = Image.open(data) else: # base 64 encoded image ...
def data_preprocess(data, size=None, min_axis=None, batch=False)
Takes data and prepares it for sending to the api including resizing and image data/structure standardizing.
3.775865
3.707641
1.018401
if isinstance(_list, list) or isinstance(_list, tuple): return [len(_list)] + get_list_dimensions(_list[0]) return []
def get_list_dimensions(_list)
Takes a nested list and returns the size of each dimension followed by the element type in the list
2.560556
2.753029
0.930087
elem = _list for _ in range(len(dimens)): elem = elem[0] return type(elem)
def get_element_type(_list, dimens)
Given the dimensions of a nested list and the list, returns the type of the elements in the inner list.
3.535641
3.39986
1.039937
image = data_preprocess(image, batch=batch, size=144, min_axis=True) url_params = {"batch": batch, "api_key": api_key, "version": version} return api_handler(image, cloud=cloud, api="imagerecognition", url_params=url_params, **kwargs)
def image_recognition(image, cloud=None, batch=False, api_key=None, version=None, **kwargs)
Given an input image, returns a dictionary of image classifications with associated scores * Input can be either grayscale or rgb color and should either be a numpy array or nested list format. * Input data should be either uint8 0-255 range values or floating point between 0 and 1. * Large images (i.e. 10...
4.446903
5.11463
0.869448
def multi(data, datatype, apis, accepted_apis, batch=False,**kwargs): # Client side api name checking - strictly only accept func name api invalid_apis = [api for api in apis if api not in accepted_apis or api in MULTIAPI_NOT_SUPPORTED] if invalid_apis: raise IndicoError( "The...
Helper to make multi requests of different types. :param data: Data to be sent in API request :param datatype: String type of API request :param apis: List of apis to use. :param batch: Is this a batch request? :rtype: Dictionary of api responses
null
null
null
def analyze_text(input_text, apis=DEFAULT_APIS, **kwargs): cloud = kwargs.pop('cloud', None) batch = kwargs.pop('batch', False) api_key = kwargs.pop('api_key', None) return multi( data=input_text, datatype="text", cloud=cloud, batch=batch, api_key...
Given input text, returns the results of specified text apis. Possible apis include: [ 'text_tags', 'political', 'sentiment', 'language' ] Example usage: .. code-block:: python >>> import indicoio >>> text = 'Monday: Delightful with mostly sunny skies. Highs in the low 70s.' ...
null
null
null
# type: (...) -> FieldHashingProperties h = json_dict.get('hash', {'type': 'blakeHash'}) num_bits = json_dict.get('numBits') k = json_dict.get('k') if not num_bits and not k: num_bits = 200 # default for v2 schema return FieldHashingProperties( ngram=json_dict['ngram'], ...
def fhp_from_json_dict( json_dict # type: Dict[str, Any] )
Make a :class:`FieldHashingProperties` object from a dictionary. :param dict json_dict: The dictionary must have have an 'ngram' key and one of k or num_bits. It may have 'positional' key; if missing a default is used. The encoding is always set to th...
3.932522
3.471907
1.132669
# type: (...) -> FieldSpec if 'ignored' in json_dict: return Ignore(json_dict['identifier']) type_str = json_dict['format']['type'] spec_type = cast(FieldSpec, FIELD_TYPE_MAP[type_str]) return spec_type.from_json_dict(json_dict)
def spec_from_json_dict( json_dict # type: Dict[str, Any] )
Turns a dictionary into the appropriate object. :param dict json_dict: A dictionary with properties. :returns: An initialised instance of the appropriate FieldSpec subclass.
4.273695
5.605765
0.762375
# type (int) -> [int] if self.num_bits: k = int(self.num_bits / num_ngrams) residue = self.num_bits % num_ngrams return ([k + 1] * residue) + ([k] * (num_ngrams - residue)) else: return [self.k if self.k else 0] * num_ngrams
def ks(self, num_ngrams)
Provide a k for each ngram in the field value. :param num_ngrams: number of ngrams in the field value :return: [ k, ... ] a k value for each of num_ngrams such that the sum is exactly num_bits
3.485996
3.32914
1.047116
# type: (Text) -> Text if self.missing_value is None: return str_in elif self.missing_value.sentinel == str_in: return self.missing_value.replace_with else: return str_in
def replace_missing_value(self, str_in)
returns 'str_in' if it is not equals to the 'sentinel' as defined in the missingValue section of the schema. Else it will return the 'replaceWith' value. :param str_in: :return: str_in or the missingValue replacement value
3.450748
3.445365
1.001562
# type: (...) -> StringSpec # noinspection PyCompatibility result = cast(StringSpec, # Go away, Mypy. super().from_json_dict(json_dict)) format_ = json_dict['format'] if 'encoding' in format_ and result.hashing_properties: result.hashi...
def from_json_dict(cls, json_dict # type: Dict[str, Any] )
Make a StringSpec object from a dictionary containing its properties. :param dict json_dict: This dictionary must contain an `'encoding'` key associated with a Python-conformant encoding. It must also contain a `'hashing'` key, whose contents are ...
4.106556
3.732038
1.100352
# type: (Text) -> None if self.is_missing_value(str_in): return # noinspection PyCompatibility super().validate(str_in) # Validate encoding. if self.regex_based: match = self.regex.match(str_in) if match is None: e = ...
def validate(self, str_in)
Validates an entry in the field. Raises `InvalidEntryError` iff the entry is invalid. An entry is invalid iff (1) a pattern is part of the specification of the field and the string does not match it; (2) the string does not match the provided casing, minimum...
2.057294
2.030101
1.013395
# type: (...) -> IntegerSpec # noinspection PyCompatibility result = cast(IntegerSpec, # For Mypy. super().from_json_dict(json_dict)) format_ = json_dict['format'] result.minimum = format_.get('minimum') result.maximum = format_.get('maxim...
def from_json_dict(cls, json_dict # type: Dict[str, Any] )
Make a IntegerSpec object from a dictionary containing its properties. :param dict json_dict: This dictionary may contain `'minimum'` and `'maximum'` keys. In addition, it must contain a `'hashing'` key, whose contents are passed to :class:`FieldH...
4.993242
6.110563
0.817149
# type: (Text) -> None if self.is_missing_value(str_in): return # noinspection PyCompatibility super().validate(str_in) try: value = int(str_in, base=10) except ValueError as e: msg = "Invalid integer. Read '{}'.".format(str_i...
def validate(self, str_in)
Validates an entry in the field. Raises `InvalidEntryError` iff the entry is invalid. An entry is invalid iff (1) the string does not represent a base-10 integer; (2) the integer is not between `self.minimum` and `self.maximum`, if those exist; or (3) the in...
2.748596
2.851339
0.963967