signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def tctc(data, tau, epsilon, sigma, kappa=<NUM_LIT:0>, largedataset=False, rule='<STR_LIT>', noise=None, raw_signal='<STR_LIT>', output='<STR_LIT>', tempdir=None, njobs=<NUM_LIT:1>, largestonly=False):
<EOL>if largedataset:<EOL><INDENT>raise NotImplementedError(<EOL>'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>N_data = data.shape[<NUM_LIT:1>]<EOL>if noise is not None:<EOL><INDENT>if len(noise.shape) == <NUM_LIT:1>:<EOL><INDENT>noise = np.array(noise, ndmin=<NUM_LIT:2>).transpose()<EOL><DEDENT>N_data = data.shape[<NUM_L...
r""" Runs TCTC community detection Parameters ---------- data : array Multiariate series with dimensions: "time, node" that belong to a network. tau : int tau specifies the minimum number of time-points of each temporal community must last. epsilon : float epsilon specif...
f1957:m1
def temporal_louvain(tnet, resolution=<NUM_LIT:1>, intersliceweight=<NUM_LIT:1>, n_iter=<NUM_LIT:100>, negativeedge='<STR_LIT:ignore>', randomseed=None, consensus_threshold=<NUM_LIT:0.5>, temporal_consensus=True, njobs=<NUM_LIT:1>):
tnet = process_input(tnet, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'], '<STR_LIT>')<EOL>resolution = resolution / tnet.T<EOL>supranet = create_supraadjacency_matrix(<EOL>tnet, intersliceweight=intersliceweight)<EOL>if negativeedge == '<STR_LIT:ignore>':<EOL><INDENT>supranet = supranet[supranet['<STR_LIT>'] > <NUM_LIT:0>...
r""" Louvain clustering for a temporal network. Parameters ----------- tnet : array, dict, TemporalNetwork Input network resolution : int resolution of Louvain clustering ($\gamma$) intersliceweight : int interslice weight of multilayer clustering ($\omega$). Must be pos...
f1958:m0
def make_consensus_matrix(com_membership, th=<NUM_LIT:0.5>):
com_membership = np.array(com_membership)<EOL>D = []<EOL>for i in range(com_membership.shape[<NUM_LIT:0>]):<EOL><INDENT>for j in range(i+<NUM_LIT:1>, com_membership.shape[<NUM_LIT:0>]):<EOL><INDENT>con = np.sum((com_membership[i, :] - com_membership[j, :])<EOL>== <NUM_LIT:0>, axis=-<NUM_LIT:1>) / com_membership.shape[-...
r""" Makes the consensus matrix . Parameters ---------- com_membership : array Shape should be node, time, iteration. th : float threshold to cancel noisey edges Returns ------- D : array consensus matrix
f1958:m2
def make_temporal_consensus(com_membership):
com_membership = np.array(com_membership)<EOL>com_membership[:, <NUM_LIT:0>] = clean_community_indexes(com_membership[:, <NUM_LIT:0>])<EOL>for t in range(<NUM_LIT:1>, com_membership.shape[<NUM_LIT:1>]):<EOL><INDENT>ct, counts_t = np.unique(com_membership[:, t], return_counts=True)<EOL>ct = ct[np.argsort(counts_t)[::-<N...
r""" Matches community labels accross time-points Jaccard matching is in a greedy fashiong. Matching the largest community at t with the community at t-1. Parameters ---------- com_membership : array Shape should be node, time. Returns ------- D : array temporal cons...
f1958:m3
def drop_bids_suffix(fname):
if '<STR_LIT:/>' in fname:<EOL><INDENT>split = fname.split('<STR_LIT:/>')<EOL>dirnames = '<STR_LIT:/>'.join(split[:-<NUM_LIT:1>]) + '<STR_LIT:/>'<EOL>fname = split[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>dirnames = '<STR_LIT>'<EOL><DEDENT>tags = [tag for tag in fname.split('<STR_LIT:_>') if '<STR_LIT:->' in tag]<EO...
Given a filename sub-01_run-01_preproc.nii.gz, it will return ['sub-01_run-01', '.nii.gz'] Parameters ---------- fname : str BIDS filename with suffice. Directories should not be included. Returns ------- fname_head : str BIDS filename with fileformat : str The file format (text after suffix) Note -----...
f1959:m2
def load_tabular_file(fname, return_meta=False, header=True, index_col=True):
if index_col:<EOL><INDENT>index_col = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>index_col = None<EOL><DEDENT>if header:<EOL><INDENT>header = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>header = None<EOL><DEDENT>df = pd.read_csv(fname, header=header, index_col=index_col, sep='<STR_LIT:\t>')<EOL>if return_meta:<EOL><INDENT...
Given a file name loads as a pandas data frame Parameters ---------- fname : str file name and path. Must be tsv. return_meta : header : bool (default True) if there is a header in the tsv file, true will use first row in file. index_col : bool (default None) if there is an index column in the csv or tsv ...
f1959:m4
def get_sidecar(fname, allowedfileformats='<STR_LIT:default>'):
if allowedfileformats == '<STR_LIT:default>':<EOL><INDENT>allowedfileformats = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>for f in allowedfileformats:<EOL><INDENT>fname = fname.split(f)[<NUM_LIT:0>]<EOL><DEDENT>fname += '<STR_LIT>'<EOL>if os.path.exists(fname):<EOL><INDENT>with open(fname) as fs:<EOL><INDENT>sidecar = json...
Loads sidecar or creates one
f1959:m5
def process_exclusion_criteria(exclusion_criteria):
relfun = []<EOL>threshold = []<EOL>for ec in exclusion_criteria:<EOL><INDENT>if ec[<NUM_LIT:0>:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>relfun.append(np.greater_equal)<EOL>threshold.append(float(ec[<NUM_LIT:2>:]))<EOL><DEDENT>elif ec[<NUM_LIT:0>:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>relfun.append(np.less_equal)<EOL>...
Parses an exclusion critera string to get the function and threshold. Parameters ---------- exclusion_criteria : list list of strings where each string is of the format [relation][threshold]. E.g. \'<0.5\' or \'>=1\' Returns ------- relfun : list list of numpy functions for the exclusion crite...
f1959:m7
def graphlet2contact(G, params=None):
<EOL>if params == None:<EOL><INDENT>params = {}<EOL><DEDENT>if G.shape[<NUM_LIT:0>] != G.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>if len(G.shape) == <NUM_LIT:2>:<EOL><INDENT>G = np.atleast_3d(G)<EOL><DEDENT>if len(G.shape) != <NUM_LIT:3>:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT...
Converts graphlet (snapshot) representation of temporal network and converts it to contact representation representation of network. Contact representation are more efficient for memory storing. Also includes metadata which can made it easier for plotting. A contact representation contains all non-zero edges. Paramete...
f1961:m0
def contact2graphlet(C):
<EOL>if '<STR_LIT>' not in C.keys():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if C['<STR_LIT>'] != '<STR_LIT>':<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT>' not in C.keys():<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>if C['<STR_LIT>'] not in {'<STR_LIT>', '<STR_LIT>'...
Converts contact representation to graphlet (snaptshot) representation. Graphlet representation discards all meta information in the contact representation. Parameters ---------- C : dict A contact representation. Must include keys: 'dimord', 'netshape', 'nettype', 'contacts' and, if weighted, 'values'. Returns ...
f1961:m1
def binarize_percent(netin, level, sign='<STR_LIT>', axis='<STR_LIT:time>'):
netin, netinfo = process_input(netin, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])<EOL>netin = set_diagonal(netin, <NUM_LIT:0>)<EOL>if axis == '<STR_LIT>' and netinfo['<STR_LIT>'][-<NUM_LIT:1>] == '<STR_LIT:u>':<EOL><INDENT>triu = np.triu_indices(netinfo['<STR_LIT>'][<NUM_LIT:0>], k=<NUM_LIT:1>)<EOL>netin = netin[triu[<N...
Binarizes a network proprtionally. When axis='time' (only one available at the moment) then the top values for each edge time series are considered. Parameters ---------- netin : array or dict network (graphlet or contact representation), level : float Percent to keep (expressed as decimal, e.g. 0.1 = top 10%...
f1961:m2
def binarize_rdp(netin, level, sign='<STR_LIT>', axis='<STR_LIT:time>'):
netin, netinfo = process_input(netin, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])<EOL>trajectory = rdp(netin, level)<EOL>contacts = []<EOL>for n in range(trajectory['<STR_LIT:index>'].shape[<NUM_LIT:0>]):<EOL><INDENT>if sign == '<STR_LIT>':<EOL><INDENT>sel = trajectory['<STR_LIT>'][n][trajectory['<STR_LIT>']<EOL>[n][tra...
Binarizes a network based on RDP compression. Parameters ---------- netin : array or dict Network (graphlet or contact representation), level : float Delta parameter which is the tolorated error in RDP compression. sign : str, default='pos' States the sign of the thresholding. Can be 'pos', 'neg' or 'both...
f1961:m3
def binarize_magnitude(netin, level, sign='<STR_LIT>'):
netin, netinfo = process_input(netin, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])<EOL>netout = np.zeros(netinfo['<STR_LIT>'])<EOL>if sign == '<STR_LIT>' or sign == '<STR_LIT>':<EOL><INDENT>netout[netin > level] = <NUM_LIT:1><EOL><DEDENT>if sign == '<STR_LIT>' or sign == '<STR_LIT>':<EOL><INDENT>netout[netin < level] = <...
Parameters ---------- netin : array or dict Network (graphlet or contact representation), level : float Magnitude level threshold at. sign : str, default='pos' States the sign of the thresholding. Can be 'pos', 'neg' or 'both'. If "neg", only negative values are thresholded and vice versa. axis : str, defa...
f1961:m4
def binarize(netin, threshold_type, threshold_level, sign='<STR_LIT>', axis='<STR_LIT:time>'):
if threshold_type == '<STR_LIT>':<EOL><INDENT>netout = binarize_percent(netin, threshold_level, sign, axis)<EOL><DEDENT>elif threshold_type == '<STR_LIT>':<EOL><INDENT>netout = binarize_magnitude(netin, threshold_level, sign)<EOL><DEDENT>elif threshold_type == '<STR_LIT>':<EOL><INDENT>netout = binarize_rdp(netin, thres...
Binarizes a network, returning the network. General wrapper function for different binarization functions. Parameters ---------- netin : array or dict Network (graphlet or contact representation), threshold_type : str What type of thresholds to make binarization. Options: 'rdp', 'percent', 'magnitude'. thres...
f1961:m5
def set_diagonal(G, val=<NUM_LIT:0>):
for t in range(<NUM_LIT:0>, G.shape[<NUM_LIT:2>]):<EOL><INDENT>np.fill_diagonal(G[:, :, t], val)<EOL><DEDENT>return G<EOL>
Generally diagonal is set to 0. This function helps set the diagonal across time. Parameters ---------- G : array temporal network (graphlet) val : value to set diagonal to (default 0). Returns ------- G : array Graphlet representation with new diagonal
f1961:m6
def gen_nettype(G, printWarning=<NUM_LIT:0>):
if set(np.unique(G)) == set([<NUM_LIT:0>, <NUM_LIT:1>]):<EOL><INDENT>weights = '<STR_LIT:b>'<EOL><DEDENT>else:<EOL><INDENT>weights = '<STR_LIT:w>'<EOL><DEDENT>if np.allclose(G.transpose(<NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:2>), G):<EOL><INDENT>direction = '<STR_LIT:u>'<EOL><DEDENT>else:<EOL><INDENT>direction = '<STR_LIT:...
Attempts to identify what nettype input graphlet G is. Diagonal is ignored. Paramters --------- G : array temporal network (graphlet) Returns ------- nettype : str \'wu\', \'bu\', \'wd\', or \'bd\'
f1961:m7
def checkInput(netIn, raiseIfU=<NUM_LIT:1>, conMat=<NUM_LIT:0>):
inputIs = '<STR_LIT>'<EOL>if isinstance(netIn, np.ndarray):<EOL><INDENT>netShape = netIn.shape<EOL>if len(netShape) == <NUM_LIT:3> and netShape[<NUM_LIT:0>] == netShape[<NUM_LIT:1>]:<EOL><INDENT>inputIs = '<STR_LIT>'<EOL><DEDENT>elif netShape[<NUM_LIT:0>] == netShape[<NUM_LIT:1>] and conMat == <NUM_LIT:1>:<EOL><INDENT>...
This function checks that netIn input is either graphlet (G) or contact (C). Parameters ---------- netIn : array or dict temporal network, (graphlet or contact). raiseIfU : int, default=1. Options 1 or 0. Error is raised if not found to be G or C conMat : int, default=0. Options 1 or 0. If 1, input is all...
f1961:m8
def getDistanceFunction(requested_metric):
distance_options = {<EOL>'<STR_LIT>': distance.braycurtis,<EOL>'<STR_LIT>': distance.canberra,<EOL>'<STR_LIT>': distance.chebyshev,<EOL>'<STR_LIT>': distance.cityblock,<EOL>'<STR_LIT>': distance.correlation,<EOL>'<STR_LIT>': distance.cosine,<EOL>'<STR_LIT>': distance.euclidean,<EOL>'<STR_LIT>': distance.sqeuclidean,<EO...
This function returns a specified distance function. Paramters --------- requested_metric: str Distance function. Can be any function in: https://docs.scipy.org/doc/scipy/reference/spatial.distance.html. Returns ------- requested_metric : distance function
f1961:m9
def process_input(netIn, allowedformats, outputformat='<STR_LIT>'):
inputtype = checkInput(netIn)<EOL>if inputtype == '<STR_LIT>' and '<STR_LIT>' in allowedformats and outputformat != '<STR_LIT>':<EOL><INDENT>G = netIn.df_to_array()<EOL>netInfo = {'<STR_LIT>': netIn.nettype, '<STR_LIT>': netIn.netshape}<EOL><DEDENT>elif inputtype == '<STR_LIT>' and '<STR_LIT>' in allowedformats and out...
Takes input network and checks what the input is. Parameters ---------- netIn : array, dict, or TemporalNetwork Network (graphlet, contact or object) allowedformats : str Which format of network objects that are allowed. Options: 'C', 'TN', 'G'. outputformat: str, default=G Target output format. Options: ...
f1961:m10
def clean_community_indexes(communityID):
communityID = np.array(communityID)<EOL>cid_shape = communityID.shape<EOL>if len(cid_shape) > <NUM_LIT:1>:<EOL><INDENT>communityID = communityID.flatten()<EOL><DEDENT>new_communityID = np.zeros(len(communityID))<EOL>for i, n in enumerate(np.unique(communityID)):<EOL><INDENT>new_communityID[communityID == n] = i<EOL><DE...
Takes input of community assignments. Returns reindexed community assignment by using smallest numbers possible. Parameters ---------- communityID : array-like list or array of integers. Output from community detection algorithems. Returns ------- new_communityID : array cleaned list going from 0 to len(np....
f1961:m11
def multiple_contacts_get_values(C):
d = collections.OrderedDict()<EOL>for c in C['<STR_LIT>']:<EOL><INDENT>ct = tuple(c)<EOL>if ct in d:<EOL><INDENT>d[ct] += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>d[ct] = <NUM_LIT:1><EOL><DEDENT><DEDENT>new_contacts = []<EOL>new_values = []<EOL>for (key, value) in d.items():<EOL><INDENT>new_values.append(value)<EOL>ne...
Given an contact representation with repeated contacts, this function removes duplicates and creates a value Parameters ---------- C : dict contact representation with multiple repeated contacts. Returns ------- :C_out: dict Contact representation with duplicate contacts removed and the number of duplicat...
f1961:m12
def df_to_array(df, netshape, nettype):
if len(df) > <NUM_LIT:0>:<EOL><INDENT>idx = np.array(list(map(list, df.values)))<EOL>G = np.zeros([netshape[<NUM_LIT:0>], netshape[<NUM_LIT:0>], netshape[<NUM_LIT:1>]])<EOL>if idx.shape[<NUM_LIT:1>] == <NUM_LIT:3>:<EOL><INDENT>if nettype[-<NUM_LIT:1>] == '<STR_LIT:u>':<EOL><INDENT>idx = np.vstack([idx, idx[:, [<NUM_LIT...
Returns a numpy array (snapshot representation) from thedataframe contact list Parameters: df : pandas df pandas df with columns, i,j,t. netshape : tuple network shape, format: (node, time) nettype : str 'wu', 'wd', 'bu', 'bd' Returns: -------- G : array (node,node,time...
f1961:m13
def check_distance_funciton_input(distance_func_name, netinfo):
if distance_func_name == '<STR_LIT:default>' and netinfo['<STR_LIT>'][<NUM_LIT:0>] == '<STR_LIT:b>':<EOL><INDENT>print('<STR_LIT>')<EOL>distance_func_name = '<STR_LIT>'<EOL><DEDENT>elif distance_func_name == '<STR_LIT:default>' and netinfo['<STR_LIT>'][<NUM_LIT:0>] == '<STR_LIT:w>':<EOL><INDENT>distance_func_name = '<S...
Funciton checks distance_func_name, if it is specified as 'default'. Then given the type of the network selects a default distance function. Parameters ---------- distance_func_name : str distance function name. netinfo : dict the output of utils.process_input Returns ------- distance_func_name : str d...
f1961:m14
def load_parcellation_coords(parcellation_name):
path = tenetopath[<NUM_LIT:0>] + '<STR_LIT>' + parcellation_name + '<STR_LIT>'<EOL>parc = np.loadtxt(path, skiprows=<NUM_LIT:1>, delimiter='<STR_LIT:U+002C>', usecols=[<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>])<EOL>return parc<EOL>
Loads coordinates of included parcellations. Parameters ---------- parcellation_name : str options: 'gordon2014_333', 'power2012_264', 'shen2013_278'. Returns ------- parc : array parcellation cordinates
f1961:m15
def make_parcellation(data_path, parcellation, parc_type=None, parc_params=None):
if isinstance(parcellation, str):<EOL><INDENT>parcin = '<STR_LIT>'<EOL>if '<STR_LIT:+>' in parcellation:<EOL><INDENT>parcin = parcellation<EOL>parcellation = parcellation.split('<STR_LIT:+>')[<NUM_LIT:0>]<EOL><DEDENT>if '<STR_LIT>' in parcin:<EOL><INDENT>subcortical = True<EOL><DEDENT>else:<EOL><INDENT>subcortical = No...
Performs a parcellation which reduces voxel space to regions of interest (brain data). Parameters ---------- data_path : str Path to .nii image. parcellation : str Specify which parcellation that you would like to use. For MNI: 'gordon2014_333', 'power2012_264', For TAL: 'shen2013_278'. It is possible to ...
f1961:m16
def create_traj_ranges(start, stop, N):
steps = (<NUM_LIT:1.0>/(N-<NUM_LIT:1>)) * (stop - start)<EOL>if np.isscalar(steps):<EOL><INDENT>return steps*np.arange(N) + start<EOL><DEDENT>else:<EOL><INDENT>return steps[:, None]*np.arange(N) + start[:, None]<EOL><DEDENT>
Fills in the trajectory range. # Adapted from https://stackoverflow.com/a/40624614
f1961:m17
def get_dimord(measure, calc=None, community=None):
if not calc:<EOL><INDENT>calc = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>calc = '<STR_LIT:_>' + calc<EOL><DEDENT>if not community:<EOL><INDENT>community = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>community = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' in calc and '<STR_LIT>' in community:<EOL><INDENT>community = '<STR_LIT...
Get the dimension order of a network measure. Parameters ---------- measure : str Name of funciton in teneto.networkmeasures. calc : str, default=None Calc parameter for the function community : bool, default=None If not null, then community property is assumed to be believed. Returns ------- dimord : s...
f1961:m18
def get_network_when(tnet, i=None, j=None, t=None, ij=None, logic='<STR_LIT>', copy=False, asarray=False):
if isinstance(tnet, pd.DataFrame):<EOL><INDENT>network = tnet<EOL>hdf5 = False<EOL><DEDENT>elif isinstance(tnet, object):<EOL><INDENT>network = tnet.network<EOL>hdf5 = tnet.hdf5<EOL><DEDENT>if ij is not None and (i is not None or j is not None):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if i is not None and...
Returns subset of dataframe that matches index Parameters ---------- tnet : df or TemporalNetwork TemporalNetwork object or pandas dataframe edgelist i : list or int get nodes in column i (source nodes in directed networks) j : list or int get nodes in column j (target nodes in directed networks) t : list ...
f1961:m19
def create_supraadjacency_matrix(tnet, intersliceweight=<NUM_LIT:1>):
newnetwork = tnet.network.copy()<EOL>newnetwork['<STR_LIT:i>'] = (tnet.network['<STR_LIT:i>']) +((tnet.netshape[<NUM_LIT:0>]) * (tnet.network['<STR_LIT:t>']))<EOL>newnetwork['<STR_LIT>'] = (tnet.network['<STR_LIT>']) +((tnet.netshape[<NUM_LIT:0>]) * (tnet.network['<STR_LIT:t>']))<EOL>if '<STR_LIT>' not in newnetwork.co...
Returns a supraadjacency matrix from a temporal network structure Parameters -------- tnet : TemporalNetwork Temporal network (any network type) intersliceweight : int Weight that links the same node from adjacent time-points Returns -------- supranet : dataframe Supraadjacency matrix
f1961:m20
def tnet_to_nx(df, t=None):
if t is not None:<EOL><INDENT>df = get_network_when(df, t=t)<EOL><DEDENT>if '<STR_LIT>' in df.columns:<EOL><INDENT>nxobj = nx.from_pandas_edgelist(<EOL>df, source='<STR_LIT:i>', target='<STR_LIT>', edge_attr='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>nxobj = nx.from_pandas_edgelist(df, source='<STR_LIT:i>', target='<ST...
Creates undirected networkx object
f1962:m0
def gen_report(report, sdir='<STR_LIT>', report_name='<STR_LIT>'):
<EOL>if not os.path.exists(sdir):<EOL><INDENT>os.makedirs(sdir)<EOL><DEDENT>if sdir[-<NUM_LIT:1>] != '<STR_LIT:/>':<EOL><INDENT>sdir += '<STR_LIT:/>'<EOL><DEDENT>report_html = '<STR_LIT>'<EOL>if '<STR_LIT>' in report.keys():<EOL><INDENT>report_html += "<STR_LIT>" + report['<STR_LIT>'] + "<STR_LIT>"<EOL>for i in report[...
Generates report of derivation and postprocess steps in teneto.derive
f1964:m0
def postpro_fisher(data, report=None):
if not report:<EOL><INDENT>report = {}<EOL><DEDENT>data[data < -<NUM_LIT>] = -<NUM_LIT:1><EOL>data[data > <NUM_LIT>] = <NUM_LIT:1><EOL>fisher_data = <NUM_LIT:0.5> * np.log((<NUM_LIT:1> + data) / (<NUM_LIT:1> - data))<EOL>report['<STR_LIT>'] = {}<EOL>report['<STR_LIT>']['<STR_LIT>'] = '<STR_LIT:yes>'<EOL>return fisher_d...
Performs fisher transform on everything in data. If report variable is passed, this is added to the report.
f1965:m0
def postpro_boxcox(data, report=None):
if not report:<EOL><INDENT>report = {}<EOL><DEDENT>mindata = <NUM_LIT:1> - np.nanmin(data)<EOL>data = data + mindata<EOL>ind = np.triu_indices(data.shape[<NUM_LIT:0>], k=<NUM_LIT:1>)<EOL>boxcox_list = np.array([sp.stats.boxcox(np.squeeze(<EOL>data[ind[<NUM_LIT:0>][n], ind[<NUM_LIT:1>][n], :])) for n in range(<NUM_LIT:0...
Performs box cox transform on everything in data. If report variable is passed, this is added to the report.
f1965:m1
def postpro_standardize(data, report=None):
if not report:<EOL><INDENT>report = {}<EOL><DEDENT>data = np.transpose(data, [<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:1>])<EOL>standardized_data = (data - data.mean(axis=<NUM_LIT:0>)) / data.std(axis=<NUM_LIT:0>)<EOL>standardized_data = np.transpose(standardized_data, [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:0>])<EOL>report['<ST...
Standardizes everything in data (along axis -1). If report variable is passed, this is added to the report.
f1965:m2
def postpro_pipeline(data, pipeline, report=None):
postpro_functions = {<EOL>'<STR_LIT>': postpro_fisher,<EOL>'<STR_LIT>': postpro_boxcox,<EOL>'<STR_LIT>': postpro_standardize<EOL>}<EOL>if not report:<EOL><INDENT>report = {}<EOL><DEDENT>if isinstance(pipeline, str):<EOL><INDENT>pipeline = pipeline.split('<STR_LIT:+>')<EOL><DEDENT>report['<STR_LIT>'] = []<EOL>for postpr...
PARAMETERS ----------- data : array pearson correlation values in temporal matrix form (node,node,time) pipeline : list or str (if string, each steps seperated by + sign). :options: 'fisher','boxcox','standardize' Each of the above 3 can be specified. If fisher is used, it must be before boxcox. ...
f1965:m3
def derive_temporalnetwork(data, params):
report = {}<EOL>if '<STR_LIT>' not in params.keys():<EOL><INDENT>params['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in params.keys():<EOL><INDENT>params['<STR_LIT>'] = False<EOL><DEDENT>if '<STR_LIT>' not in params.keys():<EOL><INDENT>params['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in par...
Derives connectivity from the data. A lot of data is inherently built with edges (e.g. communication between two individuals). However other networks are derived from the covariance of time series (e.g. brain networks between two regions). Covariance based metrics deriving time-resolved networks can be done in multi...
f1966:m0
def _weightfun_jackknife(T, report):
weights = np.ones([T, T])<EOL>np.fill_diagonal(weights, <NUM_LIT:0>)<EOL>report['<STR_LIT>'] = '<STR_LIT>'<EOL>report['<STR_LIT>'] = '<STR_LIT>'<EOL>return weights, report<EOL>
Creates the weights for the jackknife method. See func: teneto.derive.derive.
f1966:m1
def _weightfun_sliding_window(T, params, report):
weightat0 = np.zeros(T)<EOL>weightat0[<NUM_LIT:0>:params['<STR_LIT>']] = np.ones(params['<STR_LIT>'])<EOL>weights = np.array([np.roll(weightat0, i)<EOL>for i in range(<NUM_LIT:0>, T + <NUM_LIT:1> - params['<STR_LIT>'])])<EOL>report['<STR_LIT>'] = '<STR_LIT>'<EOL>report['<STR_LIT>'] = params<EOL>report['<STR_LIT>']['<ST...
Creates the weights for the sliding window method. See func: teneto.derive.derive.
f1966:m2
def _weightfun_tapered_sliding_window(T, params, report):
x = np.arange(-(params['<STR_LIT>'] - <NUM_LIT:1>) / <NUM_LIT:2>, (params['<STR_LIT>']) / <NUM_LIT:2>)<EOL>distribution_parameters = '<STR_LIT:U+002C>'.join(map(str, params['<STR_LIT>']))<EOL>taper = eval('<STR_LIT>' + params['<STR_LIT>'] +<EOL>'<STR_LIT>' + distribution_parameters + '<STR_LIT:)>')<EOL>weightat0 = np.z...
Creates the weights for the tapered method. See func: teneto.derive.derive.
f1966:m3
def _weightfun_spatial_distance(data, params, report):
distance = getDistanceFunction(params['<STR_LIT>'])<EOL>weights = np.array([distance(data[n, :], data[t, :]) for n in np.arange(<EOL><NUM_LIT:0>, data.shape[<NUM_LIT:0>]) for t in np.arange(<NUM_LIT:0>, data.shape[<NUM_LIT:0>])])<EOL>weights = np.reshape(weights, [data.shape[<NUM_LIT:0>], data.shape[<NUM_LIT:0>]])<EOL>...
Creates the weights for the spatial distance method. See func: teneto.derive.derive.
f1966:m4
def _temporal_derivative(data, params, report):
<EOL>report = {}<EOL>tdat = data[<NUM_LIT:1>:, :] - data[:-<NUM_LIT:1>, :]<EOL>tdat = tdat / np.std(tdat, axis=<NUM_LIT:0>)<EOL>coupling = np.array([tdat[:, i] * tdat[:, j] for i in np.arange(<NUM_LIT:0>,<EOL>tdat.shape[<NUM_LIT:1>]) for j in np.arange(<NUM_LIT:0>, tdat.shape[<NUM_LIT:1>])])<EOL>coupling = np.reshape(<...
Performs mtd method. See func: teneto.derive.derive.
f1966:m5
def make_dash_table(df):
table = []<EOL>for index, row in df.iterrows():<EOL><INDENT>html_row = []<EOL>for i in range(len(row)):<EOL><INDENT>html_row.append(html.Td([row[i]]))<EOL><DEDENT>table.append(html.Tr(html_row))<EOL><DEDENT>return table<EOL>
Return a dash definitio of an HTML table for a Pandas dataframe
f1984:m0
def _r():
return '<STR_LIT>' % (random.randint(<NUM_LIT:0>, <NUM_LIT:255>), random.randint(<NUM_LIT:0>, <NUM_LIT:255>), random.randint(<NUM_LIT:0>, <NUM_LIT:255>))<EOL>
generate random color
f1996:m0
def align_yaxis_np(axes):
axes = np.array(axes)<EOL>extrema = np.array([ax.get_ylim() for ax in axes])<EOL>for i in range(len(extrema)):<EOL><INDENT>if np.isclose(extrema[i, <NUM_LIT:0>], <NUM_LIT:0.0>):<EOL><INDENT>extrema[i, <NUM_LIT:0>] = -<NUM_LIT:1><EOL><DEDENT>if np.isclose(extrema[i, <NUM_LIT:1>], <NUM_LIT:0.0>):<EOL><INDENT>extrema[i, <...
Align zeros of the two axes, zooming them out by same ratio
f1996:m4
def list_to_cells(lst):
cells = '<STR_LIT>'<EOL>for cell in lst:<EOL><INDENT>to_add = '<STR_LIT>' + '<STR_LIT>'.join(cell) + '<STR_LIT>'<EOL>cells += to_add<EOL><DEDENT>cells = cells[:-<NUM_LIT:1>] + '<STR_LIT>'<EOL>nb = '<STR_LIT:{>' + cells + '<STR_LIT>'<EOL>return nbformat.writes(nbformat.reads(nb, as_version=<NUM_LIT:4>)).encode('<STR_LIT...
convert list of cells to notebook form list should be of the form: [[list of strings representing python code for cell]]
f2007:m0
def set_var(var, set_='<STR_LIT>'):
if isinstance(set_, str):<EOL><INDENT>to_set = json.dumps(set_)<EOL><DEDENT>elif isinstance(set_, dict) or isinstance(set_, list):<EOL><INDENT>try:<EOL><INDENT>to_set = json.dumps(set_)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise Exception('<STR_LI...
set var outside notebook
f2007:m1
def get_var(var, default='<STR_LIT>'):
ret = os.environ.get('<STR_LIT>' + var)<EOL>if ret is None:<EOL><INDENT>return default<EOL><DEDENT>return json.loads(ret)<EOL>
get var inside notebook
f2007:m2
def scrub_output_pre_save(model, **kwargs):
<EOL>if model['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>if model['<STR_LIT:content>']['<STR_LIT>'] != <NUM_LIT:4>:<EOL><INDENT>return<EOL><DEDENT>for cell in model['<STR_LIT:content>']['<STR_LIT>']:<EOL><INDENT>if cell['<STR_LIT>'] != '<STR_LIT:code>':<EOL><INDENT>continue<EOL><DEDENT>cell['<STR_...
scrub output before saving notebooks
f2012:m0
def script_post_save(model, os_path, contents_manager, **kwargs):
from nbconvert.exporters.script import ScriptExporter<EOL>if model['<STR_LIT:type>'] != '<STR_LIT>':<EOL><INDENT>return<EOL><DEDENT>global _script_exporter<EOL>if _script_exporter is None:<EOL><INDENT>_script_exporter = ScriptExporter(parent=contents_manager)<EOL><DEDENT>log = contents_manager.log<EOL>base, ext = os.pa...
convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script`
f2013:m0
def close(self):
if not self.closed:<EOL><INDENT>self._ipython.events.unregister('<STR_LIT>', self._fill)<EOL>self._box.close()<EOL>self.closed = True<EOL><DEDENT>
Close and remove hooks.
f2015:c0:m1
def _fill(self):
types_to_exclude = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT:type>', '<STR_LIT>']<EOL>values = self.namespace.who_ls()<EOL>def eval(expr):<EOL><INDENT>return self.namespace.shell.ev(expr)<EOL><DEDENT>var = [(v,<EOL>type(eval(v)).__name__,<EOL>str(_getsizeof(eval(v))),<EOL>str(_gets...
Fill self with variable information.
f2015:c0:m2
def _ipython_display_(self):
with self._sc:<EOL><INDENT>self._box._ipython_display_()<EOL><DEDENT>
Called when display() or pyout is used to display the Variable Inspector.
f2015:c0:m3
def pivot_pandas_to_excel(soup, show_intermediate_breakdown=False, show_total_breakdown=False):
tables = soup.findAll('<STR_LIT>')<EOL>for table in tables:<EOL><INDENT>table.thead.findChildren('<STR_LIT>')[<NUM_LIT:1>].decompose()<EOL>new_body = Tag(name='<STR_LIT>')<EOL>bc = <NUM_LIT:0><EOL>num_columns_max = max(len(row.findAll()) for row in table.tbody.findAll('<STR_LIT>'))<EOL>num_headers_max = max(len(row.fin...
pandas style pivot to excel style pivot formatting for outlook/html This function is meant to be provided to the email functionality as a postprocessor. It expects a jupyter or pandas exported html table of a dataframe with the following index: example: # a single pivot pt1 = pd.pivot_table(data, ...
f2025:m0
def parse(self, kv):
key, val = kv.split(self.kv_sep, <NUM_LIT:1>)<EOL>keys = key.split(self.keys_sep)<EOL>for k in reversed(keys):<EOL><INDENT>val = {k: val}<EOL><DEDENT>return val<EOL>
Parses key value string into dict Examples: >> parser.parse('test1.test2=value') {'test1': {'test2': 'value'}} >> parser.parse('test=value') {'test': 'value'}
f2032:c0:m1
def read_requirements(filename):
contents = read_file(filename).strip('<STR_LIT:\n>')<EOL>return contents.split('<STR_LIT:\n>') if contents else []<EOL>
Open a requirements file and return list of its lines.
f2033:m0
def read_file(filename):
path = os.path.join(os.path.dirname(__file__), filename)<EOL>with open(path) as f:<EOL><INDENT>return f.read()<EOL><DEDENT>
Open and a file, read it and return its contents.
f2033:m1
def get_metadata(init_file):
return dict(re.findall("<STR_LIT>", init_file))<EOL>
Read metadata from a given file and return a dictionary of them
f2033:m2
@abstractmethod <EOL><INDENT>def send(self, **kwargs):<DEDENT>
Main method which should parse parameters and call transport send method
f2038:c0:m1
def get_api_params(self):
result = self.params<EOL>if type(result) != dict:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>self.__class__.__name__<EOL>)<EOL>)<EOL><DEDENT>return result<EOL>
Dictionary with available API parameters :raises ValueError: If value of __class__.params is not dictionary :return: Should return dict with available pushalot API methods :rtype: dict
f2038:c0:m2
def get_api_required_params(self):
result = self.required_params<EOL>if type(result) != list:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(<EOL>self.__class__.__name__<EOL>)<EOL>)<EOL><DEDENT>return result<EOL>
List with required params :return: Dictionary with API parameters :raises ValueError: If value of __class__.required_params is not list :rtype: list
f2038:c0:m3
@abstractproperty <EOL><INDENT>def params(self):<DEDENT>
Return dictionary with available API params Example of dictionary: { 'token': { 'param': 'AuthorizationToken', 'type': str, 'max_len': 32, }, 'is_important': { 'param': 'IsImportant', 'ty...
f2038:c0:m4
@abstractproperty <EOL><INDENT>def required_params(self):<DEDENT>
Return list with required API methods :return: List with required API methods
f2038:c0:m5
def _build_params_from_kwargs(self, **kwargs):
api_methods = self.get_api_params()<EOL>required_methods = self.get_api_required_params()<EOL>ret_kwargs = {}<EOL>for key, val in kwargs.items():<EOL><INDENT>if key not in api_methods:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'.format(key),<EOL>Warning<EOL>)<EOL>continue<EOL><DEDENT>if key not in required_methods and v...
Builds parameters from passed arguments Search passed parameters in available methods, prepend specified API key, and return dictionary which can be sent directly to API server. :param kwargs: :type param: dict :raises ValueError: If type of specified parameter doesn't...
f2038:c0:m6
def send(self, title, body,<EOL>link_title=None, link=None, is_important=False,<EOL>is_silent=False, image=None, source=None, ttl=None, **kwargs):
params = self._build_params_from_kwargs(<EOL>token=self._token,<EOL>title=title,<EOL>body=body,<EOL>link_title=link_title,<EOL>link=link,<EOL>is_important=is_important,<EOL>is_silent=is_silent,<EOL>image=image,<EOL>source=source,<EOL>ttl=ttl,<EOL>**kwargs<EOL>)<EOL>return self._transport.send(**params)<EOL>
:param token: Service authorization token :type token: str :param title: Message title, up to 250 characters :type title: str :param body: Message body, up to 32768 characters :type body: str :param link_title: Title of the link, up to 100 characters :type link: str :param link: Link URI, up to 1000 characters :type l...
f2038:c1:m0
def send_message(self, title, body):
return self.send(title=title, body=body)<EOL>
Send message :param title: Message title :type title: str :param body: Message body :type body: str :return: True on success :rtype: bool
f2038:c1:m1
def send_silent_message(self, title, body):
return self.send(title=title, body=body, is_silent=True)<EOL>
Send silent message :param title: Message title :type title: str :param body: Message body :type body: str :return: True on success :rtype: bool
f2038:c1:m2
def send_important_message(self, title, body):
return self.send(title=title, body=body, is_important=True)<EOL>
Send important message :param title: Message title :type title: str :param body: Message body :type body: str :return: True on success :rtype: bool
f2038:c1:m3
def send_with_expiry(self, title, body, ttl):
return self.send(title=title, body=body, ttl=ttl)<EOL>
Send message with time to live :param title: Message title :type title: str :param body: Message body :type body: str :param ttl: Time to live in minutes :type ttl: int :return: True on success :rtype: bool
f2038:c1:m4
def send_with_link(self, title, body, link, link_title=None):
link_title = link_title or link<EOL>return self.send(<EOL>title=title,<EOL>body=body,<EOL>link=link,<EOL>link_title=link_title<EOL>)<EOL>
Send message with link If no link title specified, URL used as title. :param title: Message title :type title: str :param body: Message body :type body: str :param link: URL :type link: str :param link_title: URL title :type link_title: str ...
f2038:c1:m5
def send_with_image(self, title, body, image):
return self.send(title=title, body=body, image=image)<EOL>
Send message with image Image thumbnail URL link, has to be properly formatted in absolute form with protocol etc. Recommended image size is 72x72 pixels. Larger images will be scaled down while maintaining aspect ratio. In order to save mobile device data plan, we download images ...
f2038:c1:m6
@abstractmethod <EOL><INDENT>def send(self, **kwargs):<DEDENT>
Send request to API Only this method required. Method receives dictionary with api requests params, and send request. Should return True if request successfully sent, or throw exception on failure. :raises PushalotBadRequestException: Bad parameters sent to API ...
f2040:c0:m0
def lazy_module(modname, error_strings=None, lazy_mod_class=LazyModule,<EOL>level='<STR_LIT>'):
if error_strings is None:<EOL><INDENT>error_strings = {}<EOL><DEDENT>_set_default_errornames(modname, error_strings)<EOL>mod = _lazy_module(modname, error_strings, lazy_mod_class)<EOL>if level == '<STR_LIT>':<EOL><INDENT>return sys.modules[module_basename(modname)]<EOL><DEDENT>elif level == '<STR_LIT>':<EOL><INDENT>ret...
Function allowing lazy importing of a module into the namespace. A lazy module object is created, registered in `sys.modules`, and returned. This is a hollow module; actual loading, and `ImportErrors` if not found, are delayed until an attempt is made to access attributes of the lazy module. A han...
f2043:m1
def lazy_callable(modname, *names, **kwargs):
if not names:<EOL><INDENT>modname, _, name = modname.rpartition("<STR_LIT:.>")<EOL><DEDENT>lazy_mod_class = _setdef(kwargs, '<STR_LIT>', LazyModule)<EOL>lazy_call_class = _setdef(kwargs, '<STR_LIT>', LazyCallable)<EOL>error_strings = _setdef(kwargs, '<STR_LIT>', {})<EOL>_set_default_errornames(modname, error_strings, c...
Performs lazy importing of one or more callables. :func:`lazy_callable` creates functions that are thin wrappers that pass any and all arguments straight to the target module's callables. These can be functions or classes. The full loading of that module is only actually triggered when the returned laz...
f2043:m3
def _load_module(module):
modclass = type(module)<EOL>if not issubclass(modclass, LazyModule):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>with _ImportLockContext():<EOL><INDENT>parent, _, modname = module.__name__.rpartition('<STR_LIT:.>')<EOL>logger.debug("<STR_LIT>".format(modname))<EOL>if not hasattr(modclass, '<STR_LIT>'):<EOL><IN...
Ensures that a module, and its parents, are properly loaded
f2043:m5
def _setdef(argdict, name, defaultvalue):
if not name in argdict or argdict[name] is None:<EOL><INDENT>argdict[name] = defaultvalue<EOL><DEDENT>return argdict[name]<EOL>
Like dict.setdefault but sets the default value also if None is present.
f2043:m6
def _caller_name(depth=<NUM_LIT:2>, default='<STR_LIT>'):
<EOL>try:<EOL><INDENT>return sys._getframe(depth).f_globals['<STR_LIT>']<EOL><DEDENT>except AttributeError:<EOL><INDENT>return default<EOL><DEDENT>
Returns the name of the calling namespace.
f2043:m9
def _clean_lazymodule(module):
modclass = type(module)<EOL>_clean_lazy_submod_refs(module)<EOL>modclass.__getattribute__ = ModuleType.__getattribute__<EOL>modclass.__setattr__ = ModuleType.__setattr__<EOL>cls_attrs = {}<EOL>for cls_attr in _CLS_ATTRS:<EOL><INDENT>try:<EOL><INDENT>cls_attrs[cls_attr] = getattr(modclass, cls_attr)<EOL>delattr(modclass...
Removes all lazy behavior from a module's class, for loading. Also removes all module attributes listed under the module's class deletion dictionaries. Deletion dictionaries are class attributes with names specified in `_DELETION_DICT`. Parameters ---------- module: LazyModule Returns ...
f2043:m10
def _reset_lazymodule(module, cls_attrs):
modclass = type(module)<EOL>del modclass.__getattribute__<EOL>del modclass.__setattr__<EOL>try:<EOL><INDENT>del modclass._LOADING<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for cls_attr in _CLS_ATTRS:<EOL><INDENT>try:<EOL><INDENT>setattr(modclass, cls_attr, cls_attrs[cls_attr])<EOL><DEDENT>except K...
Resets a module's lazy state from cached data.
f2043:m12
def get_deep_search_results(self, address, zipcode):
url = '<STR_LIT>'<EOL>params = {<EOL>'<STR_LIT:address>': address,<EOL>'<STR_LIT>': zipcode,<EOL>'<STR_LIT>': self.api_key<EOL>}<EOL>return self.get_data(url, params)<EOL>
GetDeepSearchResults API
f2049:c0:m1
def get_updated_property_details(self, zpid):
url = '<STR_LIT>'<EOL>params = {<EOL>'<STR_LIT>': zpid,<EOL>'<STR_LIT>': self.api_key<EOL>}<EOL>return self.get_data(url, params)<EOL>
GetUpdatedPropertyDetails API
f2049:c0:m2
@property<EOL><INDENT>def area_unit(self):<DEDENT>
return u'<STR_LIT>'<EOL>
lotSizeSqFt
f2049:c1:m2
@property<EOL><INDENT>def last_sold_price_currency(self):<DEDENT>
return self.data.find(<EOL>self.attribute_mapping['<STR_LIT>']).attrib["<STR_LIT>"]<EOL>
lastSoldPrice currency
f2049:c1:m3
def __init__(self, data, *args, **kwargs):
self.data = data.findall('<STR_LIT>')[<NUM_LIT:0>]<EOL>for attr in self.attribute_mapping.__iter__():<EOL><INDENT>try:<EOL><INDENT>self.__setattr__(attr, self.get_attr(attr))<EOL><DEDENT>except AttributeError:<EOL><INDENT>print ('<STR_LIT>' % attr)<EOL><DEDENT><DEDENT>
Creates instance of GeocoderResult from the provided XML data array
f2049:c2:m0
def __init__(self, data, *args, **kwargs):
self.data = data.findall('<STR_LIT>')[<NUM_LIT:0>]<EOL>for attr in self.attribute_mapping.__iter__():<EOL><INDENT>try:<EOL><INDENT>self.__setattr__(attr, self.get_attr(attr))<EOL><DEDENT>except AttributeError:<EOL><INDENT>print ('<STR_LIT>' % attr)<EOL><DEDENT><DEDENT>
Creates instance of GeocoderResult from the provided XML data array
f2049:c3:m0
def register_images(im0, im1, *, rmMean=True, correctScale=True):
<EOL>im0 = np.asarray(im0, dtype=np.float32)<EOL>im1 = np.asarray(im1, dtype=np.float32)<EOL>if rmMean:<EOL><INDENT>im0 = im0 - im0.mean()<EOL>im1 = im1 - im1.mean()<EOL><DEDENT>f0, f1 = dft_optsize_same(im0, im1)<EOL>angle, scale = find_rotation_scale(f0, f1, isccs=True)<EOL>if not correctScale:<EOL><INDENT>if np.abs(...
Finds the rotation, scaling and translation of im1 relative to im0 Parameters ---------- im0: First image im1: Second image rmMean: Set to true to remove the mean (Default) Returns ------- angle: The angle difference scale: The scale difference [y, x]: The offset im2: The r...
f2052:m0
def find_rotation_scale(im0, im1, isccs=False):
<EOL>im0 = np.asarray(im0, dtype=np.float32)<EOL>im1 = np.asarray(im1, dtype=np.float32)<EOL>truesize = None<EOL>if isccs:<EOL><INDENT>truesize = im0.shape<EOL>im0 = centered_mag_sq_ccs(im0)<EOL>im1 = centered_mag_sq_ccs(im1)<EOL><DEDENT>lp1, log_base = polar_fft(im1, logpolar=True, isshiftdft=isccs,<EOL>logoutput=True...
Compares the images and return the best guess for the rotation angle, and scale difference. Parameters ---------- im0: 2d array First image im1: 2d array Second image isccs: boolean, default False Set to True if the images are alredy DFT and in CCS representation Re...
f2052:m1
def find_shift_dft(im0, im1, isccs=False, subpix=True):
<EOL>im0 = np.asarray(im0, dtype=np.float32)<EOL>im1 = np.asarray(im1, dtype=np.float32)<EOL>if not isccs:<EOL><INDENT>im0, im1 = dft_optsize_same(im0, im1)<EOL><DEDENT>else:<EOL><INDENT>assert(im0.shape == im1.shape)<EOL><DEDENT>mulSpec = cv2.mulSpectrums(im0, im1, flags=<NUM_LIT:0>, conjB=True)<EOL>normccs = cv2.sqrt...
Find the shift between two images using the DFT method Parameters ---------- im0: 2d array First image im1: 2d array Second image isccs: Boolean, default false Set to True if the images are alredy DFT and in CCS representation subpix: boolean, default True Set to...
f2052:m2
def find_shift_cc(im0, im1, ylim=None, xlim=None, subpix=True):
<EOL>im0 = np.asarray(im0, dtype=np.float32)<EOL>im1 = np.asarray(im1, dtype=np.float32)<EOL>im0 = im0 - np.nanmean(im0)<EOL>im1 = im1 - np.nanmean(im1)<EOL>shape0 = np.asarray(im0.shape)<EOL>shape1 = np.asarray(im1.shape)<EOL>offset = <NUM_LIT:1> - shape1<EOL>pad = np.lib.pad(-offset, (<NUM_LIT:1>, <NUM_LIT:1>), mode=...
Finds the best shift between im0 and im1 using cross correlation Parameters ---------- im0: 2d array First image im1: 2d array Second image ylim: 2 numbers, optional The y limits of the search (if None full range is searched) xlim: 2 numbers, optional Ibidem with...
f2052:m3
def combine_images(imgs, register=True):
imgs = np.asarray(imgs, dtype="<STR_LIT:float>")<EOL>if register:<EOL><INDENT>for i in range(<NUM_LIT:1>, imgs.shape[<NUM_LIT:0>]):<EOL><INDENT>ret = register_images(imgs[<NUM_LIT:0>, :, :], imgs[i, :, :])<EOL>imgs[i, :, :] = rotate_scale_shift(imgs[i, :, :], *ret[:<NUM_LIT:3>], np.nan)<EOL><DEDENT><DEDENT>return np.me...
Combine similar images into one to reduce the noise Parameters ---------- imgs: list of 2d array Series of images register: Boolean, default False True if the images should be register before combination Returns ------- im: 2d array The result image Notes -...
f2052:m4
def orientation_angle(im, approxangle=None, *, isshiftdft=False, truesize=None,<EOL>rotateAngle=None):
im = np.asarray(im)<EOL>if rotateAngle is not None and not isshiftdft:<EOL><INDENT>scale = np.sqrt(<NUM_LIT> * (<NUM_LIT:1> + (np.tan(rotateAngle) - <NUM_LIT:1>)**<NUM_LIT:2> /<EOL>(np.tan(rotateAngle) + <NUM_LIT:1>)**<NUM_LIT:2>))<EOL>im = rotate_scale(im, rotateAngle, scale)<EOL><DEDENT>lp = polar_fft(im, isshiftdft=...
Give the highest contribution to the orientation Parameters ---------- im: 2d array The image approxangle: number, optional The approximate angle (None if unknown) isshiftdft: Boolean, default False True if the image has been processed (DFT, fftshift) truesize: 2 numbers...
f2052:m5
def orientation_angle_2(im, nangle=None, isshiftdft=False, rotateAngle=None):
im = np.asarray(im, dtype=np.float32)<EOL>if rotateAngle is not None and not isshiftdft:<EOL><INDENT>scale = np.sqrt(<NUM_LIT> * (<NUM_LIT:1> + (np.tan(rotateAngle) - <NUM_LIT:1>)**<NUM_LIT:2> /<EOL>(np.tan(rotateAngle) + <NUM_LIT:1>)**<NUM_LIT:2>))<EOL>im = rotate_scale(im, rotateAngle, scale)<EOL><DEDENT>else:<EOL><I...
Give the highest contribution to the orientation Parameters ---------- im: 2d array The image nangle: number, optional The number of angles checked for isshiftdft: Boolean, default False True if the image has been processed (DFT, fftshift) rotateAngle: number, optional ...
f2052:m6
def dft_optsize(im, shape=None):
im = np.asarray(im)<EOL>initshape = im.shape<EOL>if shape is None:<EOL><INDENT>ys = cv2.getOptimalDFTSize(initshape[<NUM_LIT:0>])<EOL>xs = cv2.getOptimalDFTSize(initshape[<NUM_LIT:1>])<EOL>shape = [ys, xs]<EOL><DEDENT>im = cv2.copyMakeBorder(im, <NUM_LIT:0>, shape[<NUM_LIT:0>] - initshape[<NUM_LIT:0>],<EOL><NUM_LIT:0>,...
Resize image for optimal DFT and computes it Parameters ---------- im: 2d array The image shape: 2 numbers, optional The shape of the output image (None will optimize the shape) Returns ------- dft: 2d array The dft in CCS representation Notes ----- Th ...
f2052:m7
def dft_optsize_same(im0, im1):
im0 = np.asarray(im0)<EOL>im1 = np.asarray(im1)<EOL>shape0 = im0.shape<EOL>shape1 = im1.shape<EOL>ys = max(cv2.getOptimalDFTSize(shape0[<NUM_LIT:0>]),<EOL>cv2.getOptimalDFTSize(shape1[<NUM_LIT:0>]))<EOL>xs = max(cv2.getOptimalDFTSize(shape0[<NUM_LIT:1>]),<EOL>cv2.getOptimalDFTSize(shape1[<NUM_LIT:1>]))<EOL>shape = [ys,...
Resize 2 image same size for optimal DFT and computes it Parameters ---------- im0: 2d array First image im1: 2d array Second image Returns ------- dft0: 2d array The dft of the first image dft1: 2d array The dft of the second image Notes ----- ...
f2052:m8
def rotate_scale(im, angle, scale, borderValue=<NUM_LIT:0>, interp=cv2.INTER_CUBIC):
im = np.asarray(im, dtype=np.float32)<EOL>rows, cols = im.shape<EOL>M = cv2.getRotationMatrix2D(<EOL>(cols / <NUM_LIT:2>, rows / <NUM_LIT:2>), -angle * <NUM_LIT> / np.pi, <NUM_LIT:1> / scale)<EOL>im = cv2.warpAffine(im, M, (cols, rows),<EOL>borderMode=cv2.BORDER_CONSTANT,<EOL>flags=interp,<EOL>borderValue=borderValue) ...
Rotates and scales the image Parameters ---------- im: 2d array The image angle: number The angle, in radians, to rotate scale: positive number The scale factor borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ...
f2052:m9
def shift_image(im, shift, borderValue=<NUM_LIT:0>):
im = np.asarray(im, dtype=np.float32)<EOL>rows, cols = im.shape<EOL>M = np.asarray([[<NUM_LIT:1>, <NUM_LIT:0>, shift[<NUM_LIT:1>]], [<NUM_LIT:0>, <NUM_LIT:1>, shift[<NUM_LIT:0>]]], dtype=np.float32)<EOL>return cv2.warpAffine(im, M, (cols, rows),<EOL>borderMode=cv2.BORDER_CONSTANT,<EOL>flags=cv2.INTER_CUBIC,<EOL>borderV...
shift the image Parameters ---------- im: 2d array The image shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The value for the pixels outside the border (default 0) Returns ------- im: 2d array The shifted image ...
f2052:m10
def rotate_scale_shift(im, angle, scale, shift, borderValue=<NUM_LIT:0>):
im = np.asarray(im, dtype=np.float32)<EOL>rows, cols = im.shape<EOL>M = cv2.getRotationMatrix2D(<EOL>(cols / <NUM_LIT:2>, rows / <NUM_LIT:2>), -angle * <NUM_LIT> / np.pi, <NUM_LIT:1> / scale)<EOL>M[<NUM_LIT:0>, <NUM_LIT:2>] += shift[<NUM_LIT:1>]<EOL>M[<NUM_LIT:1>, <NUM_LIT:2>] += shift[<NUM_LIT:0>]<EOL>im = cv2.warpAff...
Rotates and scales the image Parameters ---------- im: 2d array The image angle: number The angle, in radians, to rotate scale: positive number The scale factor shift: 2 numbers (y,x) the shift in y and x direction borderValue: number, default 0 The v...
f2052:m11
def polar_fft(im, nangle=None, radiimax=None, *, isshiftdft=False,<EOL>truesize=None, logpolar=False, logoutput=False,<EOL>interpolation='<STR_LIT>'):
im = np.asarray(im, dtype=np.float32)<EOL>if not isshiftdft:<EOL><INDENT>truesize = im.shape<EOL>im = im - im.mean()<EOL>im = centered_mag_sq_ccs(dft_optsize(im))<EOL><DEDENT>assert(truesize is not None)<EOL>qshape = np.asarray([im.shape[<NUM_LIT:0>] // <NUM_LIT:2>, im.shape[<NUM_LIT:1>]])<EOL>center = np.asarray([qsha...
Return dft in polar (or log-polar) units, the angle step (and the log base) Parameters ---------- im: 2d array The image nangle: number, optional The number of angles in the polar representation radiimax: number, optional The number of radius in the polar representation ...
f2052:m12
def pad_img(im, pad):
im = np.asarray(im)<EOL>pad = np.asarray(pad)<EOL>shape = im.shape<EOL>offset = -pad[::<NUM_LIT:2>]<EOL>cut = pad < <NUM_LIT:0><EOL>if cut.any():<EOL><INDENT>cut *= pad<EOL>cut[::<NUM_LIT:2>] *= -<NUM_LIT:1><EOL>cut[<NUM_LIT:1>::<NUM_LIT:2>] += (cut[<NUM_LIT:1>::<NUM_LIT:2>] == <NUM_LIT:0>) * shape<EOL>im = im[cut[<NUM...
Pad positively with 0 or negatively (cut) Parameters ---------- im: 2d array The image pad: 4 numbers (ytop, ybottom, xleft, xright) or (imin, imax, jmin, jmax) Returns ------- im: 2d array The padded (or cropped) image offset: 2 numbers The offset relat...
f2052:m13
def clamp_angle(angle):
return (angle + np.pi / <NUM_LIT:2>) % np.pi - np.pi / <NUM_LIT:2><EOL>
return a between -pi/2 and pi/2 (in fourrier plane, +pi is the same) Parameters ---------- angle: number The angle to be clamped Returns ------- angle: number The clamped angle
f2052:m14
def ccs_normalize(compIM, ccsnorm):
compIM = np.asarray(compIM)<EOL>ccsnorm = np.asarray(ccsnorm)<EOL>ys = ccsnorm.shape[<NUM_LIT:0>]<EOL>xs = ccsnorm.shape[<NUM_LIT:1>]<EOL>ccsnorm[<NUM_LIT:2>::<NUM_LIT:2>, <NUM_LIT:0>] = ccsnorm[<NUM_LIT:1>:ys - <NUM_LIT:1>:<NUM_LIT:2>, <NUM_LIT:0>]<EOL>ccsnorm[:, <NUM_LIT:2>::<NUM_LIT:2>] = ccsnorm[:, <NUM_LIT:1>:xs -...
normalize the ccs representation Parameters ---------- compIM: 2d array The CCS image in CCS representation ccsnorm: 2d array The normalization matrix in ccs representation Returns ------- compIM: 2d array The normalized CCS image Notes ----- (basically...
f2052:m15