id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
500 | wiheto/teneto | teneto/utils/utils.py | load_parcellation_coords | def load_parcellation_coords(parcellation_name):
"""
Loads coordinates of included parcellations.
Parameters
----------
parcellation_name : str
options: 'gordon2014_333', 'power2012_264', 'shen2013_278'.
Returns
-------
parc : array
parcellation cordinates
"""
... | python | def load_parcellation_coords(parcellation_name):
path = tenetopath[0] + '/data/parcellation/' + parcellation_name + '.csv'
parc = np.loadtxt(path, skiprows=1, delimiter=',', usecols=[1, 2, 3])
return parc | [
"def",
"load_parcellation_coords",
"(",
"parcellation_name",
")",
":",
"path",
"=",
"tenetopath",
"[",
"0",
"]",
"+",
"'/data/parcellation/'",
"+",
"parcellation_name",
"+",
"'.csv'",
"parc",
"=",
"np",
".",
"loadtxt",
"(",
"path",
",",
"skiprows",
"=",
"1",
... | Loads coordinates of included parcellations.
Parameters
----------
parcellation_name : str
options: 'gordon2014_333', 'power2012_264', 'shen2013_278'.
Returns
-------
parc : array
parcellation cordinates | [
"Loads",
"coordinates",
"of",
"included",
"parcellations",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L789-L809 |
501 | wiheto/teneto | teneto/utils/utils.py | create_traj_ranges | def create_traj_ranges(start, stop, N):
"""
Fills in the trajectory range.
# Adapted from https://stackoverflow.com/a/40624614
"""
steps = (1.0/(N-1)) * (stop - start)
if np.isscalar(steps):
return steps*np.arange(N) + start
else:
return steps[:, None]*np.arange(N) + start[:... | python | def create_traj_ranges(start, stop, N):
steps = (1.0/(N-1)) * (stop - start)
if np.isscalar(steps):
return steps*np.arange(N) + start
else:
return steps[:, None]*np.arange(N) + start[:, None] | [
"def",
"create_traj_ranges",
"(",
"start",
",",
"stop",
",",
"N",
")",
":",
"steps",
"=",
"(",
"1.0",
"/",
"(",
"N",
"-",
"1",
")",
")",
"*",
"(",
"stop",
"-",
"start",
")",
"if",
"np",
".",
"isscalar",
"(",
"steps",
")",
":",
"return",
"steps"... | Fills in the trajectory range.
# Adapted from https://stackoverflow.com/a/40624614 | [
"Fills",
"in",
"the",
"trajectory",
"range",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L893-L903 |
502 | wiheto/teneto | teneto/utils/utils.py | get_dimord | def get_dimord(measure, calc=None, community=None):
"""
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
... | python | def get_dimord(measure, calc=None, community=None):
if not calc:
calc = ''
else:
calc = '_' + calc
if not community:
community = ''
else:
community = 'community'
if 'community' in calc and 'community' in community:
community = ''
if calc == 'community_avg'... | [
"def",
"get_dimord",
"(",
"measure",
",",
"calc",
"=",
"None",
",",
"community",
"=",
"None",
")",
":",
"if",
"not",
"calc",
":",
"calc",
"=",
"''",
"else",
":",
"calc",
"=",
"'_'",
"+",
"calc",
"if",
"not",
"community",
":",
"community",
"=",
"''"... | 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 believ... | [
"Get",
"the",
"dimension",
"order",
"of",
"a",
"network",
"measure",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L906-L969 |
503 | wiheto/teneto | teneto/utils/utils.py | create_supraadjacency_matrix | def create_supraadjacency_matrix(tnet, intersliceweight=1):
"""
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 t... | python | def create_supraadjacency_matrix(tnet, intersliceweight=1):
newnetwork = tnet.network.copy()
newnetwork['i'] = (tnet.network['i']) + \
((tnet.netshape[0]) * (tnet.network['t']))
newnetwork['j'] = (tnet.network['j']) + \
((tnet.netshape[0]) * (tnet.network['t']))
if 'weight' not in newnet... | [
"def",
"create_supraadjacency_matrix",
"(",
"tnet",
",",
"intersliceweight",
"=",
"1",
")",
":",
"newnetwork",
"=",
"tnet",
".",
"network",
".",
"copy",
"(",
")",
"newnetwork",
"[",
"'i'",
"]",
"=",
"(",
"tnet",
".",
"network",
"[",
"'i'",
"]",
")",
"+... | 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
Su... | [
"Returns",
"a",
"supraadjacency",
"matrix",
"from",
"a",
"temporal",
"network",
"structure"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/utils.py#L1092-L1121 |
504 | wiheto/teneto | teneto/utils/io.py | tnet_to_nx | def tnet_to_nx(df, t=None):
"""
Creates undirected networkx object
"""
if t is not None:
df = get_network_when(df, t=t)
if 'weight' in df.columns:
nxobj = nx.from_pandas_edgelist(
df, source='i', target='j', edge_attr='weight')
else:
nxobj = nx.from_pandas_edg... | python | def tnet_to_nx(df, t=None):
if t is not None:
df = get_network_when(df, t=t)
if 'weight' in df.columns:
nxobj = nx.from_pandas_edgelist(
df, source='i', target='j', edge_attr='weight')
else:
nxobj = nx.from_pandas_edgelist(df, source='i', target='j')
return nxobj | [
"def",
"tnet_to_nx",
"(",
"df",
",",
"t",
"=",
"None",
")",
":",
"if",
"t",
"is",
"not",
"None",
":",
"df",
"=",
"get_network_when",
"(",
"df",
",",
"t",
"=",
"t",
")",
"if",
"'weight'",
"in",
"df",
".",
"columns",
":",
"nxobj",
"=",
"nx",
".",... | Creates undirected networkx object | [
"Creates",
"undirected",
"networkx",
"object"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/io.py#L5-L16 |
505 | wiheto/teneto | teneto/communitydetection/louvain.py | temporal_louvain | def temporal_louvain(tnet, resolution=1, intersliceweight=1, n_iter=100, negativeedge='ignore', randomseed=None, consensus_threshold=0.5, temporal_consensus=True, njobs=1):
r"""
Louvain clustering for a temporal network.
Parameters
-----------
tnet : array, dict, TemporalNetwork
Input netwo... | python | def temporal_louvain(tnet, resolution=1, intersliceweight=1, n_iter=100, negativeedge='ignore', randomseed=None, consensus_threshold=0.5, temporal_consensus=True, njobs=1):
r"""
Louvain clustering for a temporal network.
Parameters
-----------
tnet : array, dict, TemporalNetwork
Input netwo... | [
"def",
"temporal_louvain",
"(",
"tnet",
",",
"resolution",
"=",
"1",
",",
"intersliceweight",
"=",
"1",
",",
"n_iter",
"=",
"100",
",",
"negativeedge",
"=",
"'ignore'",
",",
"randomseed",
"=",
"None",
",",
"consensus_threshold",
"=",
"0.5",
",",
"temporal_co... | 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... | [
"r",
"Louvain",
"clustering",
"for",
"a",
"temporal",
"network",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/communitydetection/louvain.py#L11-L75 |
506 | wiheto/teneto | teneto/communitydetection/louvain.py | make_temporal_consensus | def make_temporal_consensus(com_membership):
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... | python | def make_temporal_consensus(com_membership):
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... | [
"def",
"make_temporal_consensus",
"(",
"com_membership",
")",
":",
"com_membership",
"=",
"np",
".",
"array",
"(",
"com_membership",
")",
"# make first indicies be between 0 and 1.",
"com_membership",
"[",
":",
",",
"0",
"]",
"=",
"clean_community_indexes",
"(",
"com_... | 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... | [
"r",
"Matches",
"community",
"labels",
"accross",
"time",
"-",
"points"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/communitydetection/louvain.py#L123-L167 |
507 | wiheto/teneto | teneto/temporalcommunity/flexibility.py | flexibility | def flexibility(communities):
"""
Amount a node changes community
Parameters
----------
communities : array
Community array of shape (node,time)
Returns
--------
flex : array
Size with the flexibility of each node.
Notes
-----
Flexbility calculates the numb... | python | def flexibility(communities):
# Preallocate
flex = np.zeros(communities.shape[0])
# Go from the second time point to last, compare with time-point before
for t in range(1, communities.shape[1]):
flex[communities[:, t] != communities[:, t-1]] += 1
# Normalize
flex = flex / (communities.sh... | [
"def",
"flexibility",
"(",
"communities",
")",
":",
"# Preallocate",
"flex",
"=",
"np",
".",
"zeros",
"(",
"communities",
".",
"shape",
"[",
"0",
"]",
")",
"# Go from the second time point to last, compare with time-point before",
"for",
"t",
"in",
"range",
"(",
"... | Amount a node changes community
Parameters
----------
communities : array
Community array of shape (node,time)
Returns
--------
flex : array
Size with the flexibility of each node.
Notes
-----
Flexbility calculates the number of times a node switches its community ... | [
"Amount",
"a",
"node",
"changes",
"community"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/temporalcommunity/flexibility.py#L4-L34 |
508 | wiheto/teneto | teneto/utils/bidsutils.py | load_tabular_file | def load_tabular_file(fname, return_meta=False, header=True, index_col=True):
"""
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 fil... | python | def load_tabular_file(fname, return_meta=False, header=True, index_col=True):
if index_col:
index_col = 0
else:
index_col = None
if header:
header = 0
else:
header = None
df = pd.read_csv(fname, header=header, index_col=index_col, sep='\t')
if return_meta:
... | [
"def",
"load_tabular_file",
"(",
"fname",
",",
"return_meta",
"=",
"False",
",",
"header",
"=",
"True",
",",
"index_col",
"=",
"True",
")",
":",
"if",
"index_col",
":",
"index_col",
"=",
"0",
"else",
":",
"index_col",
"=",
"None",
"if",
"header",
":",
... | 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 i... | [
"Given",
"a",
"file",
"name",
"loads",
"as",
"a",
"pandas",
"data",
"frame"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/bidsutils.py#L77-L115 |
509 | wiheto/teneto | teneto/utils/bidsutils.py | get_sidecar | def get_sidecar(fname, allowedfileformats='default'):
"""
Loads sidecar or creates one
"""
if allowedfileformats == 'default':
allowedfileformats = ['.tsv', '.nii.gz']
for f in allowedfileformats:
fname = fname.split(f)[0]
fname += '.json'
if os.path.exists(fname):
wi... | python | def get_sidecar(fname, allowedfileformats='default'):
if allowedfileformats == 'default':
allowedfileformats = ['.tsv', '.nii.gz']
for f in allowedfileformats:
fname = fname.split(f)[0]
fname += '.json'
if os.path.exists(fname):
with open(fname) as fs:
sidecar = json.... | [
"def",
"get_sidecar",
"(",
"fname",
",",
"allowedfileformats",
"=",
"'default'",
")",
":",
"if",
"allowedfileformats",
"==",
"'default'",
":",
"allowedfileformats",
"=",
"[",
"'.tsv'",
",",
"'.nii.gz'",
"]",
"for",
"f",
"in",
"allowedfileformats",
":",
"fname",
... | Loads sidecar or creates one | [
"Loads",
"sidecar",
"or",
"creates",
"one"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/bidsutils.py#L118-L136 |
510 | wiheto/teneto | teneto/utils/bidsutils.py | process_exclusion_criteria | def process_exclusion_criteria(exclusion_criteria):
"""
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\'
Retur... | python | def process_exclusion_criteria(exclusion_criteria):
relfun = []
threshold = []
for ec in exclusion_criteria:
if ec[0:2] == '>=':
relfun.append(np.greater_equal)
threshold.append(float(ec[2:]))
elif ec[0:2] == '<=':
relfun.append(np.less_equal)
... | [
"def",
"process_exclusion_criteria",
"(",
"exclusion_criteria",
")",
":",
"relfun",
"=",
"[",
"]",
"threshold",
"=",
"[",
"]",
"for",
"ec",
"in",
"exclusion_criteria",
":",
"if",
"ec",
"[",
"0",
":",
"2",
"]",
"==",
"'>='",
":",
"relfun",
".",
"append",
... | 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 f... | [
"Parses",
"an",
"exclusion",
"critera",
"string",
"to",
"get",
"the",
"function",
"and",
"threshold",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/utils/bidsutils.py#L166-L201 |
511 | wiheto/teneto | teneto/networkmeasures/reachability_latency.py | reachability_latency | def reachability_latency(tnet=None, paths=None, rratio=1, calc='global'):
"""
Reachability latency. This is the r-th longest temporal path.
Parameters
---------
data : array or dict
Can either be a network (graphlet or contact), binary unidrected only. Alternative can be a paths dictionar... | python | def reachability_latency(tnet=None, paths=None, rratio=1, calc='global'):
if tnet is not None and paths is not None:
raise ValueError('Only network or path input allowed.')
if tnet is None and paths is None:
raise ValueError('No input.')
# if shortest paths are not calculated, calculate them... | [
"def",
"reachability_latency",
"(",
"tnet",
"=",
"None",
",",
"paths",
"=",
"None",
",",
"rratio",
"=",
"1",
",",
"calc",
"=",
"'global'",
")",
":",
"if",
"tnet",
"is",
"not",
"None",
"and",
"paths",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"... | Reachability latency. This is the r-th longest temporal path.
Parameters
---------
data : array or dict
Can either be a network (graphlet or contact), binary unidrected only. Alternative can be a paths dictionary (output of teneto.networkmeasure.shortest_temporal_path)
rratio: float (default... | [
"Reachability",
"latency",
".",
"This",
"is",
"the",
"r",
"-",
"th",
"longest",
"temporal",
"path",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/networkmeasures/reachability_latency.py#L9-L72 |
512 | wiheto/teneto | teneto/temporalcommunity/recruitment.py | recruitment | def recruitment(temporalcommunities, staticcommunities):
"""
Calculates recruitment coefficient for each node. Recruitment coefficient is the average probability of nodes from the
same static communities being in the same temporal communities at other time-points or during different tasks.
Parameters... | python | def recruitment(temporalcommunities, staticcommunities):
# make sure the static and temporal communities have the same number of nodes
if staticcommunities.shape[0] != temporalcommunities.shape[0]:
raise ValueError(
'Temporal and static communities have different dimensions')
alleg =... | [
"def",
"recruitment",
"(",
"temporalcommunities",
",",
"staticcommunities",
")",
":",
"# make sure the static and temporal communities have the same number of nodes",
"if",
"staticcommunities",
".",
"shape",
"[",
"0",
"]",
"!=",
"temporalcommunities",
".",
"shape",
"[",
"0"... | Calculates recruitment coefficient for each node. Recruitment coefficient is the average probability of nodes from the
same static communities being in the same temporal communities at other time-points or during different tasks.
Parameters:
------------
temporalcommunities : array
temporal ... | [
"Calculates",
"recruitment",
"coefficient",
"for",
"each",
"node",
".",
"Recruitment",
"coefficient",
"is",
"the",
"average",
"probability",
"of",
"nodes",
"from",
"the",
"same",
"static",
"communities",
"being",
"in",
"the",
"same",
"temporal",
"communities",
"at... | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/temporalcommunity/recruitment.py#L5-L44 |
513 | wiheto/teneto | teneto/temporalcommunity/integration.py | integration | def integration(temporalcommunities, staticcommunities):
"""
Calculates the integration coefficient for each node. Measures the average probability
that a node is in the same community as nodes from other systems.
Parameters:
------------
temporalcommunities : array
temporal co... | python | def integration(temporalcommunities, staticcommunities):
# make sure the static and temporal communities have the same number of nodes
if staticcommunities.shape[0] != temporalcommunities.shape[0]:
raise ValueError(
'Temporal and static communities have different dimensions')
alleg = al... | [
"def",
"integration",
"(",
"temporalcommunities",
",",
"staticcommunities",
")",
":",
"# make sure the static and temporal communities have the same number of nodes",
"if",
"staticcommunities",
".",
"shape",
"[",
"0",
"]",
"!=",
"temporalcommunities",
".",
"shape",
"[",
"0"... | Calculates the integration coefficient for each node. Measures the average probability
that a node is in the same community as nodes from other systems.
Parameters:
------------
temporalcommunities : array
temporal communities vector (node,time)
staticcommunities : array
... | [
"Calculates",
"the",
"integration",
"coefficient",
"for",
"each",
"node",
".",
"Measures",
"the",
"average",
"probability",
"that",
"a",
"node",
"is",
"in",
"the",
"same",
"community",
"as",
"nodes",
"from",
"other",
"systems",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/temporalcommunity/integration.py#L5-L45 |
514 | wiheto/teneto | teneto/networkmeasures/intercontacttimes.py | intercontacttimes | def intercontacttimes(tnet):
"""
Calculates the intercontacttimes of each edge in a network.
Parameters
-----------
tnet : array, dict
Temporal network (craphlet or contact). Nettype: 'bu', 'bd'
Returns
---------
contacts : dict
Intercontact times as numpy array in di... | python | def intercontacttimes(tnet):
# Process input
tnet = process_input(tnet, ['C', 'G', 'TN'], 'TN')
if tnet.nettype[0] == 'w':
print('WARNING: assuming connections to be binary when computing intercontacttimes')
# Each time series is padded with a 0 at the start and end. Then t[0:-1]-[t:].
# T... | [
"def",
"intercontacttimes",
"(",
"tnet",
")",
":",
"# Process input",
"tnet",
"=",
"process_input",
"(",
"tnet",
",",
"[",
"'C'",
",",
"'G'",
",",
"'TN'",
"]",
",",
"'TN'",
")",
"if",
"tnet",
".",
"nettype",
"[",
"0",
"]",
"==",
"'w'",
":",
"print",
... | Calculates the intercontacttimes of each edge in a network.
Parameters
-----------
tnet : array, dict
Temporal network (craphlet or contact). Nettype: 'bu', 'bd'
Returns
---------
contacts : dict
Intercontact times as numpy array in dictionary. contacts['intercontacttimes']
... | [
"Calculates",
"the",
"intercontacttimes",
"of",
"each",
"edge",
"in",
"a",
"network",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/networkmeasures/intercontacttimes.py#L9-L108 |
515 | wiheto/teneto | teneto/timeseries/report.py | gen_report | def gen_report(report, sdir='./', report_name='report.html'):
"""
Generates report of derivation and postprocess steps in teneto.derive
"""
# Create report directory
if not os.path.exists(sdir):
os.makedirs(sdir)
# Add a slash to file directory if not included to avoid DirNameFleName
... | python | def gen_report(report, sdir='./', report_name='report.html'):
# Create report directory
if not os.path.exists(sdir):
os.makedirs(sdir)
# Add a slash to file directory if not included to avoid DirNameFleName
# instead of DirName/FileName being creaated
if sdir[-1] != '/':
sdir += '/'... | [
"def",
"gen_report",
"(",
"report",
",",
"sdir",
"=",
"'./'",
",",
"report_name",
"=",
"'report.html'",
")",
":",
"# Create report directory",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"sdir",
")",
":",
"os",
".",
"makedirs",
"(",
"sdir",
")",
... | Generates report of derivation and postprocess steps in teneto.derive | [
"Generates",
"report",
"of",
"derivation",
"and",
"postprocess",
"steps",
"in",
"teneto",
".",
"derive"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/timeseries/report.py#L10-L92 |
516 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.add_history | def add_history(self, fname, fargs, init=0):
"""
Adds a processing step to TenetoBIDS.history.
"""
if init == 1:
self.history = []
self.history.append([fname, fargs]) | python | def add_history(self, fname, fargs, init=0):
if init == 1:
self.history = []
self.history.append([fname, fargs]) | [
"def",
"add_history",
"(",
"self",
",",
"fname",
",",
"fargs",
",",
"init",
"=",
"0",
")",
":",
"if",
"init",
"==",
"1",
":",
"self",
".",
"history",
"=",
"[",
"]",
"self",
".",
"history",
".",
"append",
"(",
"[",
"fname",
",",
"fargs",
"]",
")... | Adds a processing step to TenetoBIDS.history. | [
"Adds",
"a",
"processing",
"step",
"to",
"TenetoBIDS",
".",
"history",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L129-L135 |
517 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.derive_temporalnetwork | def derive_temporalnetwork(self, params, update_pipeline=True, tag=None, njobs=1, confound_corr_report=True):
"""
Derive time-varying connectivity on the selected files.
Parameters
----------
params : dict.
See teneto.timeseries.derive_temporalnetwork for the structu... | python | def derive_temporalnetwork(self, params, update_pipeline=True, tag=None, njobs=1, confound_corr_report=True):
if not njobs:
njobs = self.njobs
self.add_history(inspect.stack()[0][3], locals(), 1)
files = self.get_selected_files(quiet=1)
confound_files = self.get_selected_fil... | [
"def",
"derive_temporalnetwork",
"(",
"self",
",",
"params",
",",
"update_pipeline",
"=",
"True",
",",
"tag",
"=",
"None",
",",
"njobs",
"=",
"1",
",",
"confound_corr_report",
"=",
"True",
")",
":",
"if",
"not",
"njobs",
":",
"njobs",
"=",
"self",
".",
... | Derive time-varying connectivity on the selected files.
Parameters
----------
params : dict.
See teneto.timeseries.derive_temporalnetwork for the structure of the param dictionary. Assumes dimord is time,node (output of other TenetoBIDS funcitons)
update_pipeline : bool
... | [
"Derive",
"time",
"-",
"varying",
"connectivity",
"on",
"the",
"selected",
"files",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L164-L219 |
518 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.make_functional_connectivity | def make_functional_connectivity(self, njobs=None, returngroup=False, file_hdr=None, file_idx=None):
"""
Makes connectivity matrix for each of the subjects.
Parameters
----------
returngroup : bool, default=False
If true, returns the group average connectivity matrix... | python | def make_functional_connectivity(self, njobs=None, returngroup=False, file_hdr=None, file_idx=None):
if not njobs:
njobs = self.njobs
self.add_history(inspect.stack()[0][3], locals(), 1)
files = self.get_selected_files(quiet=1)
R_group = []
with ProcessPoolExecutor(... | [
"def",
"make_functional_connectivity",
"(",
"self",
",",
"njobs",
"=",
"None",
",",
"returngroup",
"=",
"False",
",",
"file_hdr",
"=",
"None",
",",
"file_idx",
"=",
"None",
")",
":",
"if",
"not",
"njobs",
":",
"njobs",
"=",
"self",
".",
"njobs",
"self",
... | Makes connectivity matrix for each of the subjects.
Parameters
----------
returngroup : bool, default=False
If true, returns the group average connectivity matrix.
njobs : int
How many parallel jobs to run
file_idx : bool
Default False, true i... | [
"Makes",
"connectivity",
"matrix",
"for",
"each",
"of",
"the",
"subjects",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L360-L398 |
519 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS._save_namepaths_bids_derivatives | def _save_namepaths_bids_derivatives(self, f, tag, save_directory, suffix=None):
"""
Creates output directory and output name
Paramters
---------
f : str
input files, includes the file bids_suffix
tag : str
what should be added to f in the output ... | python | def _save_namepaths_bids_derivatives(self, f, tag, save_directory, suffix=None):
file_name = f.split('/')[-1].split('.')[0]
if tag != '':
tag = '_' + tag
if suffix:
file_name, _ = drop_bids_suffix(file_name)
save_name = file_name + tag
save_name +=... | [
"def",
"_save_namepaths_bids_derivatives",
"(",
"self",
",",
"f",
",",
"tag",
",",
"save_directory",
",",
"suffix",
"=",
"None",
")",
":",
"file_name",
"=",
"f",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
... | Creates output directory and output name
Paramters
---------
f : str
input files, includes the file bids_suffix
tag : str
what should be added to f in the output file.
save_directory : str
additional directory that the output file should go in... | [
"Creates",
"output",
"directory",
"and",
"output",
"name"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L409-L466 |
520 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.get_tags | def get_tags(self, tag, quiet=1):
"""
Returns which tag alternatives can be identified in the BIDS derivatives structure.
"""
if not self.pipeline:
print('Please set pipeline first.')
self.get_pipeline_alternatives(quiet)
else:
if tag == 'sub':... | python | def get_tags(self, tag, quiet=1):
if not self.pipeline:
print('Please set pipeline first.')
self.get_pipeline_alternatives(quiet)
else:
if tag == 'sub':
datapath = self.BIDS_dir + '/derivatives/' + self.pipeline + '/'
tag_alternatives =... | [
"def",
"get_tags",
"(",
"self",
",",
"tag",
",",
"quiet",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"pipeline",
":",
"print",
"(",
"'Please set pipeline first.'",
")",
"self",
".",
"get_pipeline_alternatives",
"(",
"quiet",
")",
"else",
":",
"if",
"t... | Returns which tag alternatives can be identified in the BIDS derivatives structure. | [
"Returns",
"which",
"tag",
"alternatives",
"can",
"be",
"identified",
"in",
"the",
"BIDS",
"derivatives",
"structure",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L468-L497 |
521 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.set_exclusion_file | def set_exclusion_file(self, confound, exclusion_criteria, confound_stat='mean'):
"""
Excludes subjects given a certain exclusion criteria.
Parameters
----------
confound : str or list
string or list of confound name(s) from confound files
exclusi... | python | def set_exclusion_file(self, confound, exclusion_criteria, confound_stat='mean'):
self.add_history(inspect.stack()[0][3], locals(), 1)
if isinstance(confound, str):
confound = [confound]
if isinstance(exclusion_criteria, str):
exclusion_criteria = [exclusion_criteria]
... | [
"def",
"set_exclusion_file",
"(",
"self",
",",
"confound",
",",
"exclusion_criteria",
",",
"confound_stat",
"=",
"'mean'",
")",
":",
"self",
".",
"add_history",
"(",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
",",
"locals",
"(",
"... | Excludes subjects given a certain exclusion criteria.
Parameters
----------
confound : str or list
string or list of confound name(s) from confound files
exclusion_criteria : str or list
for each confound, an exclusion_criteria should be expresse... | [
"Excludes",
"subjects",
"given",
"a",
"certain",
"exclusion",
"criteria",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L650-L719 |
522 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.make_parcellation | def make_parcellation(self, parcellation, parc_type=None, parc_params=None, network='defaults', update_pipeline=True, removeconfounds=False, tag=None, njobs=None, clean_params=None, yeonetworkn=None):
"""
Reduces the data from voxel to parcellation space. Files get saved in a teneto folder in the deriva... | python | def make_parcellation(self, parcellation, parc_type=None, parc_params=None, network='defaults', update_pipeline=True, removeconfounds=False, tag=None, njobs=None, clean_params=None, yeonetworkn=None):
if not njobs:
njobs = self.njobs
self.add_history(inspect.stack()[0][3], locals(), 1)
... | [
"def",
"make_parcellation",
"(",
"self",
",",
"parcellation",
",",
"parc_type",
"=",
"None",
",",
"parc_params",
"=",
"None",
",",
"network",
"=",
"'defaults'",
",",
"update_pipeline",
"=",
"True",
",",
"removeconfounds",
"=",
"False",
",",
"tag",
"=",
"None... | Reduces the data from voxel to parcellation space. Files get saved in a teneto folder in the derivatives with a roi tag at the end.
Parameters
-----------
parcellation : str
specify which parcellation that you would like to use. For MNI: 'power2012_264', 'gordon2014_333'. TAL: 'she... | [
"Reduces",
"the",
"data",
"from",
"voxel",
"to",
"parcellation",
"space",
".",
"Files",
"get",
"saved",
"in",
"a",
"teneto",
"folder",
"in",
"the",
"derivatives",
"with",
"a",
"roi",
"tag",
"at",
"the",
"end",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L847-L930 |
523 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.communitydetection | def communitydetection(self, community_detection_params, community_type='temporal', tag=None, file_hdr=False, file_idx=False, njobs=None):
"""
Calls temporal_louvain_with_consensus on connectivity data
Parameters
----------
community_detection_params : dict
kwargs f... | python | def communitydetection(self, community_detection_params, community_type='temporal', tag=None, file_hdr=False, file_idx=False, njobs=None):
if not njobs:
njobs = self.njobs
self.add_history(inspect.stack()[0][3], locals(), 1)
if not tag:
tag = ''
else:
... | [
"def",
"communitydetection",
"(",
"self",
",",
"community_detection_params",
",",
"community_type",
"=",
"'temporal'",
",",
"tag",
"=",
"None",
",",
"file_hdr",
"=",
"False",
",",
"file_idx",
"=",
"False",
",",
"njobs",
"=",
"None",
")",
":",
"if",
"not",
... | Calls temporal_louvain_with_consensus on connectivity data
Parameters
----------
community_detection_params : dict
kwargs for detection. See teneto.communitydetection.louvain.temporal_louvain_with_consensus
community_type : str
Either 'temporal' or 'static'. If ... | [
"Calls",
"temporal_louvain_with_consensus",
"on",
"connectivity",
"data"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L950-L1001 |
524 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.removeconfounds | def removeconfounds(self, confounds=None, clean_params=None, transpose=None, njobs=None, update_pipeline=True, overwrite=True, tag=None):
"""
Removes specified confounds using nilearn.signal.clean
Parameters
----------
confounds : list
List of confounds. Can be presp... | python | def removeconfounds(self, confounds=None, clean_params=None, transpose=None, njobs=None, update_pipeline=True, overwrite=True, tag=None):
if not njobs:
njobs = self.njobs
self.add_history(inspect.stack()[0][3], locals(), 1)
if not self.confounds and not confounds:
raise ... | [
"def",
"removeconfounds",
"(",
"self",
",",
"confounds",
"=",
"None",
",",
"clean_params",
"=",
"None",
",",
"transpose",
"=",
"None",
",",
"njobs",
"=",
"None",
",",
"update_pipeline",
"=",
"True",
",",
"overwrite",
"=",
"True",
",",
"tag",
"=",
"None",... | Removes specified confounds using nilearn.signal.clean
Parameters
----------
confounds : list
List of confounds. Can be prespecified in set_confounds
clean_params : dict
Dictionary of kawgs to pass to nilearn.signal.clean
transpose : bool (default False)
... | [
"Removes",
"specified",
"confounds",
"using",
"nilearn",
".",
"signal",
".",
"clean"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L1036-L1094 |
525 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.networkmeasures | def networkmeasures(self, measure=None, measure_params=None, tag=None, njobs=None):
"""
Calculates a network measure
For available funcitons see: teneto.networkmeasures
Parameters
----------
measure : str or list
Mame of function(s) from teneto.networkmeasu... | python | def networkmeasures(self, measure=None, measure_params=None, tag=None, njobs=None):
if not njobs:
njobs = self.njobs
self.add_history(inspect.stack()[0][3], locals(), 1)
# measure can be string or list
if isinstance(measure, str):
measure = [measure]
# me... | [
"def",
"networkmeasures",
"(",
"self",
",",
"measure",
"=",
"None",
",",
"measure_params",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"njobs",
"=",
"None",
")",
":",
"if",
"not",
"njobs",
":",
"njobs",
"=",
"self",
".",
"njobs",
"self",
".",
"add_his... | Calculates a network measure
For available funcitons see: teneto.networkmeasures
Parameters
----------
measure : str or list
Mame of function(s) from teneto.networkmeasures that will be run.
measure_params : dict or list of dctionaries)
Containing kwar... | [
"Calculates",
"a",
"network",
"measure"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L1153-L1209 |
526 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.set_bids_suffix | def set_bids_suffix(self, bids_suffix):
"""
The last analysis step is the final tag that is present in files.
"""
self.add_history(inspect.stack()[0][3], locals(), 1)
self.bids_suffix = bids_suffix | python | def set_bids_suffix(self, bids_suffix):
self.add_history(inspect.stack()[0][3], locals(), 1)
self.bids_suffix = bids_suffix | [
"def",
"set_bids_suffix",
"(",
"self",
",",
"bids_suffix",
")",
":",
"self",
".",
"add_history",
"(",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
",",
"locals",
"(",
")",
",",
"1",
")",
"self",
".",
"bids_suffix",
"=",
"bids_su... | The last analysis step is the final tag that is present in files. | [
"The",
"last",
"analysis",
"step",
"is",
"the",
"final",
"tag",
"that",
"is",
"present",
"in",
"files",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L1426-L1431 |
527 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.set_pipeline | def set_pipeline(self, pipeline):
"""
Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string.
"""
self.add_history(inspect.stack()[0][3], locals(), 1)
if not os.path.exists(self.BIDS_dir + '/derivatives/' + pipeline):
p... | python | def set_pipeline(self, pipeline):
self.add_history(inspect.stack()[0][3], locals(), 1)
if not os.path.exists(self.BIDS_dir + '/derivatives/' + pipeline):
print('Specified direvative directory not found.')
self.get_pipeline_alternatives()
else:
# Todo: perform ... | [
"def",
"set_pipeline",
"(",
"self",
",",
"pipeline",
")",
":",
"self",
".",
"add_history",
"(",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
",",
"locals",
"(",
")",
",",
"1",
")",
"if",
"not",
"os",
".",
"path",
".",
"exist... | Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string. | [
"Specify",
"the",
"pipeline",
".",
"See",
"get_pipeline_alternatives",
"to",
"see",
"what",
"are",
"avaialble",
".",
"Input",
"should",
"be",
"a",
"string",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L1433-L1443 |
528 | wiheto/teneto | teneto/classes/bids.py | TenetoBIDS.load_frompickle | def load_frompickle(cls, fname, reload_object=False):
"""
Loaded saved instance of
fname : str
path to pickle object (output of TenetoBIDS.save_aspickle)
reload_object : bool (default False)
reloads object by calling teneto.TenetoBIDS (some information lost, for ... | python | def load_frompickle(cls, fname, reload_object=False):
if fname[-4:] != '.pkl':
fname += '.pkl'
with open(fname, 'rb') as f:
tnet = pickle.load(f)
if reload_object:
reloadnet = teneto.TenetoBIDS(tnet.BIDS_dir, pipeline=tnet.pipeline, pipeline_subdir=tnet.pipeli... | [
"def",
"load_frompickle",
"(",
"cls",
",",
"fname",
",",
"reload_object",
"=",
"False",
")",
":",
"if",
"fname",
"[",
"-",
"4",
":",
"]",
"!=",
"'.pkl'",
":",
"fname",
"+=",
"'.pkl'",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"f",
":",
... | Loaded saved instance of
fname : str
path to pickle object (output of TenetoBIDS.save_aspickle)
reload_object : bool (default False)
reloads object by calling teneto.TenetoBIDS (some information lost, for development)
Returns
-------
self :
... | [
"Loaded",
"saved",
"instance",
"of"
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L1541-L1564 |
529 | wiheto/teneto | teneto/networkmeasures/temporal_closeness_centrality.py | temporal_closeness_centrality | def temporal_closeness_centrality(tnet=None, paths=None):
'''
Returns temporal closeness centrality per node.
Parameters
-----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
paths : pandas dat... | python | def temporal_closeness_centrality(tnet=None, paths=None):
'''
Returns temporal closeness centrality per node.
Parameters
-----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
paths : pandas dat... | [
"def",
"temporal_closeness_centrality",
"(",
"tnet",
"=",
"None",
",",
"paths",
"=",
"None",
")",
":",
"if",
"tnet",
"is",
"not",
"None",
"and",
"paths",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Only network or path input allowed.'",
")",
"if",
... | Returns temporal closeness centrality per node.
Parameters
-----------
Input should be *either* tnet or paths.
data : array or dict
Temporal network input (graphlet or contact). nettype: 'bu', 'bd'.
paths : pandas dataframe
Output of TenetoBIDS.networkmeasure.shortest_temporal_... | [
"Returns",
"temporal",
"closeness",
"centrality",
"per",
"node",
"."
] | 80d7a83a9adc1714589b020627c45bd5b66248ab | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/networkmeasures/temporal_closeness_centrality.py#L9-L52 |
530 | ianlini/flatten-dict | flatten_dict/flatten_dict.py | flatten | def flatten(d, reducer='tuple', inverse=False):
"""Flatten dict-like object.
Parameters
----------
d: dict-like object
The dict that will be flattened.
reducer: {'tuple', 'path', function} (default: 'tuple')
The key joining method. If a function is given, the function will be
... | python | def flatten(d, reducer='tuple', inverse=False):
if isinstance(reducer, str):
reducer = REDUCER_DICT[reducer]
flat_dict = {}
def _flatten(d, parent=None):
for key, value in six.viewitems(d):
flat_key = reducer(parent, key)
if isinstance(value, Mapping):
... | [
"def",
"flatten",
"(",
"d",
",",
"reducer",
"=",
"'tuple'",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"reducer",
",",
"str",
")",
":",
"reducer",
"=",
"REDUCER_DICT",
"[",
"reducer",
"]",
"flat_dict",
"=",
"{",
"}",
"def",
"_fl... | Flatten dict-like object.
Parameters
----------
d: dict-like object
The dict that will be flattened.
reducer: {'tuple', 'path', function} (default: 'tuple')
The key joining method. If a function is given, the function will be
used to reduce.
'tuple': The resulting key wi... | [
"Flatten",
"dict",
"-",
"like",
"object",
"."
] | 77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa | https://github.com/ianlini/flatten-dict/blob/77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa/flatten_dict/flatten_dict.py#L20-L56 |
531 | ianlini/flatten-dict | flatten_dict/flatten_dict.py | nested_set_dict | def nested_set_dict(d, keys, value):
"""Set a value to a sequence of nested keys
Parameters
----------
d: Mapping
keys: Sequence[str]
value: Any
"""
assert keys
key = keys[0]
if len(keys) == 1:
if key in d:
raise ValueError("duplicated key '{}'".format(key))
... | python | def nested_set_dict(d, keys, value):
assert keys
key = keys[0]
if len(keys) == 1:
if key in d:
raise ValueError("duplicated key '{}'".format(key))
d[key] = value
return
d = d.setdefault(key, {})
nested_set_dict(d, keys[1:], value) | [
"def",
"nested_set_dict",
"(",
"d",
",",
"keys",
",",
"value",
")",
":",
"assert",
"keys",
"key",
"=",
"keys",
"[",
"0",
"]",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"if",
"key",
"in",
"d",
":",
"raise",
"ValueError",
"(",
"\"duplicated key ... | Set a value to a sequence of nested keys
Parameters
----------
d: Mapping
keys: Sequence[str]
value: Any | [
"Set",
"a",
"value",
"to",
"a",
"sequence",
"of",
"nested",
"keys"
] | 77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa | https://github.com/ianlini/flatten-dict/blob/77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa/flatten_dict/flatten_dict.py#L59-L76 |
532 | ianlini/flatten-dict | flatten_dict/flatten_dict.py | unflatten | def unflatten(d, splitter='tuple', inverse=False):
"""Unflatten dict-like object.
Parameters
----------
d: dict-like object
The dict that will be unflattened.
splitter: {'tuple', 'path', function} (default: 'tuple')
The key splitting method. If a function is given, the function will... | python | def unflatten(d, splitter='tuple', inverse=False):
if isinstance(splitter, str):
splitter = SPLITTER_DICT[splitter]
unflattened_dict = {}
for flat_key, value in six.viewitems(d):
if inverse:
flat_key, value = value, flat_key
key_tuple = splitter(flat_key)
nested_... | [
"def",
"unflatten",
"(",
"d",
",",
"splitter",
"=",
"'tuple'",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"splitter",
",",
"str",
")",
":",
"splitter",
"=",
"SPLITTER_DICT",
"[",
"splitter",
"]",
"unflattened_dict",
"=",
"{",
"}",
... | Unflatten dict-like object.
Parameters
----------
d: dict-like object
The dict that will be unflattened.
splitter: {'tuple', 'path', function} (default: 'tuple')
The key splitting method. If a function is given, the function will be
used to split.
'tuple': Use each eleme... | [
"Unflatten",
"dict",
"-",
"like",
"object",
"."
] | 77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa | https://github.com/ianlini/flatten-dict/blob/77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa/flatten_dict/flatten_dict.py#L79-L108 |
533 | salu133445/pypianoroll | pypianoroll/plot.py | plot_track | def plot_track(track, filename=None, beat_resolution=None, downbeats=None,
preset='default', cmap='Blues', xtick='auto', ytick='octave',
xticklabel=True, yticklabel='auto', tick_loc=None,
tick_direction='in', label='both', grid='both',
grid_linestyle=':', grid... | python | def plot_track(track, filename=None, beat_resolution=None, downbeats=None,
preset='default', cmap='Blues', xtick='auto', ytick='octave',
xticklabel=True, yticklabel='auto', tick_loc=None,
tick_direction='in', label='both', grid='both',
grid_linestyle=':', grid... | [
"def",
"plot_track",
"(",
"track",
",",
"filename",
"=",
"None",
",",
"beat_resolution",
"=",
"None",
",",
"downbeats",
"=",
"None",
",",
"preset",
"=",
"'default'",
",",
"cmap",
"=",
"'Blues'",
",",
"xtick",
"=",
"'auto'",
",",
"ytick",
"=",
"'octave'",... | Plot the pianoroll or save a plot of the pianoroll.
Parameters
----------
filename :
The filename to which the plot is saved. If None, save nothing.
beat_resolution : int
The number of time steps used to represent a beat. Required and only
effective when `xtick` is 'beat'.
d... | [
"Plot",
"the",
"pianoroll",
"or",
"save",
"a",
"plot",
"of",
"the",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/plot.py#L216-L303 |
534 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.append_track | def append_track(self, track=None, pianoroll=None, program=0, is_drum=False,
name='unknown'):
"""
Append a multitrack.Track instance to the track list or create a new
multitrack.Track object and append it to the track list.
Parameters
----------
trac... | python | def append_track(self, track=None, pianoroll=None, program=0, is_drum=False,
name='unknown'):
if track is not None:
if not isinstance(track, Track):
raise TypeError("`track` must be a pypianoroll.Track instance.")
track.check_validity()
else:
... | [
"def",
"append_track",
"(",
"self",
",",
"track",
"=",
"None",
",",
"pianoroll",
"=",
"None",
",",
"program",
"=",
"0",
",",
"is_drum",
"=",
"False",
",",
"name",
"=",
"'unknown'",
")",
":",
"if",
"track",
"is",
"not",
"None",
":",
"if",
"not",
"is... | Append a multitrack.Track instance to the track list or create a new
multitrack.Track object and append it to the track list.
Parameters
----------
track : pianoroll.Track
A :class:`pypianoroll.Track` instance to be appended to the track
list.
pianoroll :... | [
"Append",
"a",
"multitrack",
".",
"Track",
"instance",
"to",
"the",
"track",
"list",
"or",
"create",
"a",
"new",
"multitrack",
".",
"Track",
"object",
"and",
"append",
"it",
"to",
"the",
"track",
"list",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L143-L180 |
535 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.check_validity | def check_validity(self):
"""
Raise an error if any invalid attribute found.
Raises
------
TypeError
If an attribute has an invalid type.
ValueError
If an attribute has an invalid value (of the correct type).
"""
# tracks
... | python | def check_validity(self):
# tracks
for track in self.tracks:
if not isinstance(track, Track):
raise TypeError("`tracks` must be a list of "
"`pypianoroll.Track` instances.")
track.check_validity()
# tempo
if not isin... | [
"def",
"check_validity",
"(",
"self",
")",
":",
"# tracks",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"not",
"isinstance",
"(",
"track",
",",
"Track",
")",
":",
"raise",
"TypeError",
"(",
"\"`tracks` must be a list of \"",
"\"`pypianoroll.Track` in... | Raise an error if any invalid attribute found.
Raises
------
TypeError
If an attribute has an invalid type.
ValueError
If an attribute has an invalid value (of the correct type). | [
"Raise",
"an",
"error",
"if",
"any",
"invalid",
"attribute",
"found",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L210-L253 |
536 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.clip | def clip(self, lower=0, upper=127):
"""
Clip the pianorolls of all tracks by the given lower and upper bounds.
Parameters
----------
lower : int or float
The lower bound to clip the pianorolls. Defaults to 0.
upper : int or float
The upper bound t... | python | def clip(self, lower=0, upper=127):
for track in self.tracks:
track.clip(lower, upper) | [
"def",
"clip",
"(",
"self",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"127",
")",
":",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"track",
".",
"clip",
"(",
"lower",
",",
"upper",
")"
] | Clip the pianorolls of all tracks by the given lower and upper bounds.
Parameters
----------
lower : int or float
The lower bound to clip the pianorolls. Defaults to 0.
upper : int or float
The upper bound to clip the pianorolls. Defaults to 127. | [
"Clip",
"the",
"pianorolls",
"of",
"all",
"tracks",
"by",
"the",
"given",
"lower",
"and",
"upper",
"bounds",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L255-L268 |
537 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.get_downbeat_steps | def get_downbeat_steps(self):
"""
Return the indices of time steps that contain downbeats.
Returns
-------
downbeat_steps : list
The indices of time steps that contain downbeats.
"""
if self.downbeat is None:
return []
downbeat_st... | python | def get_downbeat_steps(self):
if self.downbeat is None:
return []
downbeat_steps = np.nonzero(self.downbeat)[0].tolist()
return downbeat_steps | [
"def",
"get_downbeat_steps",
"(",
"self",
")",
":",
"if",
"self",
".",
"downbeat",
"is",
"None",
":",
"return",
"[",
"]",
"downbeat_steps",
"=",
"np",
".",
"nonzero",
"(",
"self",
".",
"downbeat",
")",
"[",
"0",
"]",
".",
"tolist",
"(",
")",
"return"... | Return the indices of time steps that contain downbeats.
Returns
-------
downbeat_steps : list
The indices of time steps that contain downbeats. | [
"Return",
"the",
"indices",
"of",
"time",
"steps",
"that",
"contain",
"downbeats",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L324-L337 |
538 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.get_empty_tracks | def get_empty_tracks(self):
"""
Return the indices of tracks with empty pianorolls.
Returns
-------
empty_track_indices : list
The indices of tracks with empty pianorolls.
"""
empty_track_indices = [idx for idx, track in enumerate(self.tracks)
... | python | def get_empty_tracks(self):
empty_track_indices = [idx for idx, track in enumerate(self.tracks)
if not np.any(track.pianoroll)]
return empty_track_indices | [
"def",
"get_empty_tracks",
"(",
"self",
")",
":",
"empty_track_indices",
"=",
"[",
"idx",
"for",
"idx",
",",
"track",
"in",
"enumerate",
"(",
"self",
".",
"tracks",
")",
"if",
"not",
"np",
".",
"any",
"(",
"track",
".",
"pianoroll",
")",
"]",
"return",... | Return the indices of tracks with empty pianorolls.
Returns
-------
empty_track_indices : list
The indices of tracks with empty pianorolls. | [
"Return",
"the",
"indices",
"of",
"tracks",
"with",
"empty",
"pianorolls",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L339-L351 |
539 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.get_merged_pianoroll | def get_merged_pianoroll(self, mode='sum'):
"""
Return the merged pianoroll.
Parameters
----------
mode : {'sum', 'max', 'any'}
A string that indicates the merging strategy to apply along the
track axis. Default to 'sum'.
- In 'sum' mode, the... | python | def get_merged_pianoroll(self, mode='sum'):
stacked = self.get_stacked_pianoroll()
if mode == 'any':
merged = np.any(stacked, axis=2)
elif mode == 'sum':
merged = np.sum(stacked, axis=2)
elif mode == 'max':
merged = np.max(stacked, axis=2)
els... | [
"def",
"get_merged_pianoroll",
"(",
"self",
",",
"mode",
"=",
"'sum'",
")",
":",
"stacked",
"=",
"self",
".",
"get_stacked_pianoroll",
"(",
")",
"if",
"mode",
"==",
"'any'",
":",
"merged",
"=",
"np",
".",
"any",
"(",
"stacked",
",",
"axis",
"=",
"2",
... | Return the merged pianoroll.
Parameters
----------
mode : {'sum', 'max', 'any'}
A string that indicates the merging strategy to apply along the
track axis. Default to 'sum'.
- In 'sum' mode, the merged pianoroll is the sum of all the
pianorolls... | [
"Return",
"the",
"merged",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L371-L407 |
540 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.merge_tracks | def merge_tracks(self, track_indices=None, mode='sum', program=0,
is_drum=False, name='merged', remove_merged=False):
"""
Merge pianorolls of the tracks specified by `track_indices`. The merged
track will have program number as given by `program` and drum indicator
a... | python | def merge_tracks(self, track_indices=None, mode='sum', program=0,
is_drum=False, name='merged', remove_merged=False):
if mode not in ('max', 'sum', 'any'):
raise ValueError("`mode` must be one of {'max', 'sum', 'any'}.")
merged = self[track_indices].get_merged_pianoroll... | [
"def",
"merge_tracks",
"(",
"self",
",",
"track_indices",
"=",
"None",
",",
"mode",
"=",
"'sum'",
",",
"program",
"=",
"0",
",",
"is_drum",
"=",
"False",
",",
"name",
"=",
"'merged'",
",",
"remove_merged",
"=",
"False",
")",
":",
"if",
"mode",
"not",
... | Merge pianorolls of the tracks specified by `track_indices`. The merged
track will have program number as given by `program` and drum indicator
as given by `is_drum`. The merged track will be appended at the end of
the track list.
Parameters
----------
track_indices : li... | [
"Merge",
"pianorolls",
"of",
"the",
"tracks",
"specified",
"by",
"track_indices",
".",
"The",
"merged",
"track",
"will",
"have",
"program",
"number",
"as",
"given",
"by",
"program",
"and",
"drum",
"indicator",
"as",
"given",
"by",
"is_drum",
".",
"The",
"mer... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L486-L538 |
541 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.pad_to_same | def pad_to_same(self):
"""Pad shorter pianorolls with zeros at the end along the time axis to
make the resulting pianoroll lengths the same as the maximum pianoroll
length among all the tracks."""
max_length = self.get_max_length()
for track in self.tracks:
if track.p... | python | def pad_to_same(self):
max_length = self.get_max_length()
for track in self.tracks:
if track.pianoroll.shape[0] < max_length:
track.pad(max_length - track.pianoroll.shape[0]) | [
"def",
"pad_to_same",
"(",
"self",
")",
":",
"max_length",
"=",
"self",
".",
"get_max_length",
"(",
")",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"track",
".",
"pianoroll",
".",
"shape",
"[",
"0",
"]",
"<",
"max_length",
":",
"track",
... | Pad shorter pianorolls with zeros at the end along the time axis to
make the resulting pianoroll lengths the same as the maximum pianoroll
length among all the tracks. | [
"Pad",
"shorter",
"pianorolls",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"to",
"make",
"the",
"resulting",
"pianoroll",
"lengths",
"the",
"same",
"as",
"the",
"maximum",
"pianoroll",
"length",
"among",
"all",
"the",
"tracks",
"."
... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L581-L588 |
542 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.remove_tracks | def remove_tracks(self, track_indices):
"""
Remove tracks specified by `track_indices`.
Parameters
----------
track_indices : list
The indices of the tracks to be removed.
"""
if isinstance(track_indices, int):
track_indices = [track_indi... | python | def remove_tracks(self, track_indices):
if isinstance(track_indices, int):
track_indices = [track_indices]
self.tracks = [track for idx, track in enumerate(self.tracks)
if idx not in track_indices] | [
"def",
"remove_tracks",
"(",
"self",
",",
"track_indices",
")",
":",
"if",
"isinstance",
"(",
"track_indices",
",",
"int",
")",
":",
"track_indices",
"=",
"[",
"track_indices",
"]",
"self",
".",
"tracks",
"=",
"[",
"track",
"for",
"idx",
",",
"track",
"i... | Remove tracks specified by `track_indices`.
Parameters
----------
track_indices : list
The indices of the tracks to be removed. | [
"Remove",
"tracks",
"specified",
"by",
"track_indices",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L815-L828 |
543 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.transpose | def transpose(self, semitone):
"""
Transpose the pianorolls of all tracks by a number of semitones, where
positive values are for higher key, while negative values are for lower
key. The drum tracks are ignored.
Parameters
----------
semitone : int
Th... | python | def transpose(self, semitone):
for track in self.tracks:
if not track.is_drum:
track.transpose(semitone) | [
"def",
"transpose",
"(",
"self",
",",
"semitone",
")",
":",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"not",
"track",
".",
"is_drum",
":",
"track",
".",
"transpose",
"(",
"semitone",
")"
] | Transpose the pianorolls of all tracks by a number of semitones, where
positive values are for higher key, while negative values are for lower
key. The drum tracks are ignored.
Parameters
----------
semitone : int
The number of semitones to transpose the pianorolls. | [
"Transpose",
"the",
"pianorolls",
"of",
"all",
"tracks",
"by",
"a",
"number",
"of",
"semitones",
"where",
"positive",
"values",
"are",
"for",
"higher",
"key",
"while",
"negative",
"values",
"are",
"for",
"lower",
"key",
".",
"The",
"drum",
"tracks",
"are",
... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L954-L968 |
544 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.trim_trailing_silence | def trim_trailing_silence(self):
"""Trim the trailing silences of the pianorolls of all tracks. Trailing
silences are considered globally."""
active_length = self.get_active_length()
for track in self.tracks:
track.pianoroll = track.pianoroll[:active_length] | python | def trim_trailing_silence(self):
active_length = self.get_active_length()
for track in self.tracks:
track.pianoroll = track.pianoroll[:active_length] | [
"def",
"trim_trailing_silence",
"(",
"self",
")",
":",
"active_length",
"=",
"self",
".",
"get_active_length",
"(",
")",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"track",
".",
"pianoroll",
"=",
"track",
".",
"pianoroll",
"[",
":",
"active_length",
... | Trim the trailing silences of the pianorolls of all tracks. Trailing
silences are considered globally. | [
"Trim",
"the",
"trailing",
"silences",
"of",
"the",
"pianorolls",
"of",
"all",
"tracks",
".",
"Trailing",
"silences",
"are",
"considered",
"globally",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L970-L975 |
545 | salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.write | def write(self, filename):
"""
Write the multitrack pianoroll to a MIDI file.
Parameters
----------
filename : str
The name of the MIDI file to which the multitrack pianoroll is
written.
"""
if not filename.endswith(('.mid', '.midi', '.MI... | python | def write(self, filename):
if not filename.endswith(('.mid', '.midi', '.MID', '.MIDI')):
filename = filename + '.mid'
pm = self.to_pretty_midi()
pm.write(filename) | [
"def",
"write",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"(",
"'.mid'",
",",
"'.midi'",
",",
"'.MID'",
",",
"'.MIDI'",
")",
")",
":",
"filename",
"=",
"filename",
"+",
"'.mid'",
"pm",
"=",
"self",
".",
... | Write the multitrack pianoroll to a MIDI file.
Parameters
----------
filename : str
The name of the MIDI file to which the multitrack pianoroll is
written. | [
"Write",
"the",
"multitrack",
"pianoroll",
"to",
"a",
"MIDI",
"file",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L977-L991 |
546 | salu133445/pypianoroll | pypianoroll/utilities.py | check_pianoroll | def check_pianoroll(arr):
"""
Return True if the array is a standard piano-roll matrix. Otherwise,
return False. Raise TypeError if the input object is not a numpy array.
"""
if not isinstance(arr, np.ndarray):
raise TypeError("`arr` must be of np.ndarray type")
if not (np.issubdtype(ar... | python | def check_pianoroll(arr):
if not isinstance(arr, np.ndarray):
raise TypeError("`arr` must be of np.ndarray type")
if not (np.issubdtype(arr.dtype, np.bool_)
or np.issubdtype(arr.dtype, np.number)):
return False
if arr.ndim != 2:
return False
if arr.shape[1] != 128:
... | [
"def",
"check_pianoroll",
"(",
"arr",
")",
":",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`arr` must be of np.ndarray type\"",
")",
"if",
"not",
"(",
"np",
".",
"issubdtype",
"(",
"arr",
".",
... | Return True if the array is a standard piano-roll matrix. Otherwise,
return False. Raise TypeError if the input object is not a numpy array. | [
"Return",
"True",
"if",
"the",
"array",
"is",
"a",
"standard",
"piano",
"-",
"roll",
"matrix",
".",
"Otherwise",
"return",
"False",
".",
"Raise",
"TypeError",
"if",
"the",
"input",
"object",
"is",
"not",
"a",
"numpy",
"array",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L20-L35 |
547 | salu133445/pypianoroll | pypianoroll/utilities.py | pad | def pad(obj, pad_length):
"""
Return a copy of the object with piano-roll padded with zeros at the end
along the time axis.
Parameters
----------
pad_length : int
The length to pad along the time axis with zeros.
"""
_check_supported(obj)
copied = deepcopy(obj)
copied.p... | python | def pad(obj, pad_length):
_check_supported(obj)
copied = deepcopy(obj)
copied.pad(pad_length)
return copied | [
"def",
"pad",
"(",
"obj",
",",
"pad_length",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"pad",
"(",
"pad_length",
")",
"return",
"copied"
] | Return a copy of the object with piano-roll padded with zeros at the end
along the time axis.
Parameters
----------
pad_length : int
The length to pad along the time axis with zeros. | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"piano",
"-",
"roll",
"padded",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L107-L121 |
548 | salu133445/pypianoroll | pypianoroll/utilities.py | pad_to_multiple | def pad_to_multiple(obj, factor):
"""
Return a copy of the object with its piano-roll padded with zeros at the
end along the time axis with the minimal length that make the length of
the resulting piano-roll a multiple of `factor`.
Parameters
----------
factor : int
The value which ... | python | def pad_to_multiple(obj, factor):
_check_supported(obj)
copied = deepcopy(obj)
copied.pad_to_multiple(factor)
return copied | [
"def",
"pad_to_multiple",
"(",
"obj",
",",
"factor",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"pad_to_multiple",
"(",
"factor",
")",
"return",
"copied"
] | Return a copy of the object with its piano-roll padded with zeros at the
end along the time axis with the minimal length that make the length of
the resulting piano-roll a multiple of `factor`.
Parameters
----------
factor : int
The value which the length of the resulting piano-roll will be... | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"its",
"piano",
"-",
"roll",
"padded",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"with",
"the",
"minimal",
"length",
"that",
"make",
"the",
"length",
"of",
"the",
"resulting... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L123-L139 |
549 | salu133445/pypianoroll | pypianoroll/utilities.py | pad_to_same | def pad_to_same(obj):
"""
Return a copy of the object with shorter piano-rolls padded with zeros
at the end along the time axis to the length of the piano-roll with the
maximal length.
"""
if not isinstance(obj, Multitrack):
raise TypeError("Support only `pypianoroll.Multitrack` class o... | python | def pad_to_same(obj):
if not isinstance(obj, Multitrack):
raise TypeError("Support only `pypianoroll.Multitrack` class objects")
copied = deepcopy(obj)
copied.pad_to_same()
return copied | [
"def",
"pad_to_same",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
... | Return a copy of the object with shorter piano-rolls padded with zeros
at the end along the time axis to the length of the piano-roll with the
maximal length. | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"shorter",
"piano",
"-",
"rolls",
"padded",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"to",
"the",
"length",
"of",
"the",
"piano",
"-",
"roll",
"with",
"the",
"maximal",
"... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L141-L152 |
550 | salu133445/pypianoroll | pypianoroll/utilities.py | save | def save(filepath, obj, compressed=True):
"""
Save the object to a .npz file.
Parameters
----------
filepath : str
The path to save the file.
obj: `pypianoroll.Multitrack` objects
The object to be saved.
"""
if not isinstance(obj, Multitrack):
raise TypeError("S... | python | def save(filepath, obj, compressed=True):
if not isinstance(obj, Multitrack):
raise TypeError("Support only `pypianoroll.Multitrack` class objects")
obj.save(filepath, compressed) | [
"def",
"save",
"(",
"filepath",
",",
"obj",
",",
"compressed",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"obj",
".",
"sa... | Save the object to a .npz file.
Parameters
----------
filepath : str
The path to save the file.
obj: `pypianoroll.Multitrack` objects
The object to be saved. | [
"Save",
"the",
"object",
"to",
"a",
".",
"npz",
"file",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L178-L192 |
551 | salu133445/pypianoroll | pypianoroll/utilities.py | write | def write(obj, filepath):
"""
Write the object to a MIDI file.
Parameters
----------
filepath : str
The path to write the MIDI file.
"""
if not isinstance(obj, Multitrack):
raise TypeError("Support only `pypianoroll.Multitrack` class objects")
obj.write(filepath) | python | def write(obj, filepath):
if not isinstance(obj, Multitrack):
raise TypeError("Support only `pypianoroll.Multitrack` class objects")
obj.write(filepath) | [
"def",
"write",
"(",
"obj",
",",
"filepath",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"obj",
".",
"write",
"(",
"filepath",
")"
] | Write the object to a MIDI file.
Parameters
----------
filepath : str
The path to write the MIDI file. | [
"Write",
"the",
"object",
"to",
"a",
"MIDI",
"file",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L222-L234 |
552 | salu133445/pypianoroll | pypianoroll/metrics.py | _validate_pianoroll | def _validate_pianoroll(pianoroll):
"""Raise an error if the input array is not a standard pianoroll."""
if not isinstance(pianoroll, np.ndarray):
raise TypeError("`pianoroll` must be of np.ndarray type.")
if not (np.issubdtype(pianoroll.dtype, np.bool_)
or np.issubdtype(pianoroll.dtype,... | python | def _validate_pianoroll(pianoroll):
if not isinstance(pianoroll, np.ndarray):
raise TypeError("`pianoroll` must be of np.ndarray type.")
if not (np.issubdtype(pianoroll.dtype, np.bool_)
or np.issubdtype(pianoroll.dtype, np.number)):
raise TypeError("The data type of `pianoroll` must ... | [
"def",
"_validate_pianoroll",
"(",
"pianoroll",
")",
":",
"if",
"not",
"isinstance",
"(",
"pianoroll",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`pianoroll` must be of np.ndarray type.\"",
")",
"if",
"not",
"(",
"np",
".",
"issubdtype",
... | Raise an error if the input array is not a standard pianoroll. | [
"Raise",
"an",
"error",
"if",
"the",
"input",
"array",
"is",
"not",
"a",
"standard",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L7-L19 |
553 | salu133445/pypianoroll | pypianoroll/metrics.py | _to_chroma | def _to_chroma(pianoroll):
"""Return the unnormalized chroma features of a pianoroll."""
_validate_pianoroll(pianoroll)
reshaped = pianoroll[:, :120].reshape(-1, 12, 10)
reshaped[..., :8] += pianoroll[:, 120:].reshape(-1, 1, 8)
return np.sum(reshaped, 1) | python | def _to_chroma(pianoroll):
_validate_pianoroll(pianoroll)
reshaped = pianoroll[:, :120].reshape(-1, 12, 10)
reshaped[..., :8] += pianoroll[:, 120:].reshape(-1, 1, 8)
return np.sum(reshaped, 1) | [
"def",
"_to_chroma",
"(",
"pianoroll",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"reshaped",
"=",
"pianoroll",
"[",
":",
",",
":",
"120",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"12",
",",
"10",
")",
"reshaped",
"[",
"...",
",",
":",
... | Return the unnormalized chroma features of a pianoroll. | [
"Return",
"the",
"unnormalized",
"chroma",
"features",
"of",
"a",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L21-L26 |
554 | salu133445/pypianoroll | pypianoroll/metrics.py | empty_beat_rate | def empty_beat_rate(pianoroll, beat_resolution):
"""Return the ratio of empty beats to the total number of beats in a
pianoroll."""
_validate_pianoroll(pianoroll)
reshaped = pianoroll.reshape(-1, beat_resolution * pianoroll.shape[1])
n_empty_beats = np.count_nonzero(reshaped.any(1))
return n_emp... | python | def empty_beat_rate(pianoroll, beat_resolution):
_validate_pianoroll(pianoroll)
reshaped = pianoroll.reshape(-1, beat_resolution * pianoroll.shape[1])
n_empty_beats = np.count_nonzero(reshaped.any(1))
return n_empty_beats / len(reshaped) | [
"def",
"empty_beat_rate",
"(",
"pianoroll",
",",
"beat_resolution",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"reshaped",
"=",
"pianoroll",
".",
"reshape",
"(",
"-",
"1",
",",
"beat_resolution",
"*",
"pianoroll",
".",
"shape",
"[",
"1",
"]",
")... | Return the ratio of empty beats to the total number of beats in a
pianoroll. | [
"Return",
"the",
"ratio",
"of",
"empty",
"beats",
"to",
"the",
"total",
"number",
"of",
"beats",
"in",
"a",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L28-L34 |
555 | salu133445/pypianoroll | pypianoroll/metrics.py | n_pitche_classes_used | def n_pitche_classes_used(pianoroll):
"""Return the number of unique pitch classes used in a pianoroll."""
_validate_pianoroll(pianoroll)
chroma = _to_chroma(pianoroll)
return np.count_nonzero(np.any(chroma, 0)) | python | def n_pitche_classes_used(pianoroll):
_validate_pianoroll(pianoroll)
chroma = _to_chroma(pianoroll)
return np.count_nonzero(np.any(chroma, 0)) | [
"def",
"n_pitche_classes_used",
"(",
"pianoroll",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"chroma",
"=",
"_to_chroma",
"(",
"pianoroll",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"np",
".",
"any",
"(",
"chroma",
",",
"0",
")",
")"
] | Return the number of unique pitch classes used in a pianoroll. | [
"Return",
"the",
"number",
"of",
"unique",
"pitch",
"classes",
"used",
"in",
"a",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L41-L45 |
556 | salu133445/pypianoroll | pypianoroll/metrics.py | polyphonic_rate | def polyphonic_rate(pianoroll, threshold=2):
"""Return the ratio of the number of time steps where the number of pitches
being played is larger than `threshold` to the total number of time steps
in a pianoroll."""
_validate_pianoroll(pianoroll)
n_poly = np.count_nonzero(np.count_nonzero(pianoroll, 1... | python | def polyphonic_rate(pianoroll, threshold=2):
_validate_pianoroll(pianoroll)
n_poly = np.count_nonzero(np.count_nonzero(pianoroll, 1) > threshold)
return n_poly / len(pianoroll) | [
"def",
"polyphonic_rate",
"(",
"pianoroll",
",",
"threshold",
"=",
"2",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"n_poly",
"=",
"np",
".",
"count_nonzero",
"(",
"np",
".",
"count_nonzero",
"(",
"pianoroll",
",",
"1",
")",
">",
"threshold",
"... | Return the ratio of the number of time steps where the number of pitches
being played is larger than `threshold` to the total number of time steps
in a pianoroll. | [
"Return",
"the",
"ratio",
"of",
"the",
"number",
"of",
"time",
"steps",
"where",
"the",
"number",
"of",
"pitches",
"being",
"played",
"is",
"larger",
"than",
"threshold",
"to",
"the",
"total",
"number",
"of",
"time",
"steps",
"in",
"a",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L60-L66 |
557 | salu133445/pypianoroll | pypianoroll/metrics.py | in_scale_rate | def in_scale_rate(pianoroll, key=3, kind='major'):
"""Return the ratio of the number of nonzero entries that lie in a specific
scale to the total number of nonzero entries in a pianoroll. Default to C
major scale."""
if not isinstance(key, int):
raise TypeError("`key` must an integer.")
if k... | python | def in_scale_rate(pianoroll, key=3, kind='major'):
if not isinstance(key, int):
raise TypeError("`key` must an integer.")
if key > 11 or key < 0:
raise ValueError("`key` must be in an integer in between 0 and 11.")
if kind not in ('major', 'minor'):
raise ValueError("`kind` must be o... | [
"def",
"in_scale_rate",
"(",
"pianoroll",
",",
"key",
"=",
"3",
",",
"kind",
"=",
"'major'",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"`key` must an integer.\"",
")",
"if",
"key",
">",
"11",
"o... | Return the ratio of the number of nonzero entries that lie in a specific
scale to the total number of nonzero entries in a pianoroll. Default to C
major scale. | [
"Return",
"the",
"ratio",
"of",
"the",
"number",
"of",
"nonzero",
"entries",
"that",
"lie",
"in",
"a",
"specific",
"scale",
"to",
"the",
"total",
"number",
"of",
"nonzero",
"entries",
"in",
"a",
"pianoroll",
".",
"Default",
"to",
"C",
"major",
"scale",
"... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L100-L123 |
558 | salu133445/pypianoroll | pypianoroll/track.py | Track.assign_constant | def assign_constant(self, value, dtype=None):
"""
Assign a constant value to all nonzeros in the pianoroll. If the
pianoroll is not binarized, its data type will be preserved. If the
pianoroll is binarized, it will be casted to the type of `value`.
Arguments
---------
... | python | def assign_constant(self, value, dtype=None):
if not self.is_binarized():
self.pianoroll[self.pianoroll.nonzero()] = value
return
if dtype is None:
if isinstance(value, int):
dtype = int
elif isinstance(value, float):
dtype ... | [
"def",
"assign_constant",
"(",
"self",
",",
"value",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_binarized",
"(",
")",
":",
"self",
".",
"pianoroll",
"[",
"self",
".",
"pianoroll",
".",
"nonzero",
"(",
")",
"]",
"=",
"value",
... | Assign a constant value to all nonzeros in the pianoroll. If the
pianoroll is not binarized, its data type will be preserved. If the
pianoroll is binarized, it will be casted to the type of `value`.
Arguments
---------
value : int or float
The constant value to be as... | [
"Assign",
"a",
"constant",
"value",
"to",
"all",
"nonzeros",
"in",
"the",
"pianoroll",
".",
"If",
"the",
"pianoroll",
"is",
"not",
"binarized",
"its",
"data",
"type",
"will",
"be",
"preserved",
".",
"If",
"the",
"pianoroll",
"is",
"binarized",
"it",
"will"... | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L76-L99 |
559 | salu133445/pypianoroll | pypianoroll/track.py | Track.binarize | def binarize(self, threshold=0):
"""
Binarize the pianoroll.
Parameters
----------
threshold : int or float
A threshold used to binarize the pianorolls. Defaults to zero.
"""
if not self.is_binarized():
self.pianoroll = (self.pianoroll > ... | python | def binarize(self, threshold=0):
if not self.is_binarized():
self.pianoroll = (self.pianoroll > threshold) | [
"def",
"binarize",
"(",
"self",
",",
"threshold",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"is_binarized",
"(",
")",
":",
"self",
".",
"pianoroll",
"=",
"(",
"self",
".",
"pianoroll",
">",
"threshold",
")"
] | Binarize the pianoroll.
Parameters
----------
threshold : int or float
A threshold used to binarize the pianorolls. Defaults to zero. | [
"Binarize",
"the",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L101-L112 |
560 | salu133445/pypianoroll | pypianoroll/track.py | Track.check_validity | def check_validity(self):
""""Raise error if any invalid attribute found."""
# pianoroll
if not isinstance(self.pianoroll, np.ndarray):
raise TypeError("`pianoroll` must be a numpy array.")
if not (np.issubdtype(self.pianoroll.dtype, np.bool_)
or np.issubdtype... | python | def check_validity(self):
"# pianoroll
if not isinstance(self.pianoroll, np.ndarray):
raise TypeError("`pianoroll` must be a numpy array.")
if not (np.issubdtype(self.pianoroll.dtype, np.bool_)
or np.issubdtype(self.pianoroll.dtype, np.number)):
raise Type... | [
"def",
"check_validity",
"(",
"self",
")",
":",
"# pianoroll",
"if",
"not",
"isinstance",
"(",
"self",
".",
"pianoroll",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`pianoroll` must be a numpy array.\"",
")",
"if",
"not",
"(",
"np",
".... | Raise error if any invalid attribute found. | [
"Raise",
"error",
"if",
"any",
"invalid",
"attribute",
"found",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L114-L138 |
561 | salu133445/pypianoroll | pypianoroll/track.py | Track.clip | def clip(self, lower=0, upper=127):
"""
Clip the pianoroll by the given lower and upper bounds.
Parameters
----------
lower : int or float
The lower bound to clip the pianoroll. Defaults to 0.
upper : int or float
The upper bound to clip the piano... | python | def clip(self, lower=0, upper=127):
self.pianoroll = self.pianoroll.clip(lower, upper) | [
"def",
"clip",
"(",
"self",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"127",
")",
":",
"self",
".",
"pianoroll",
"=",
"self",
".",
"pianoroll",
".",
"clip",
"(",
"lower",
",",
"upper",
")"
] | Clip the pianoroll by the given lower and upper bounds.
Parameters
----------
lower : int or float
The lower bound to clip the pianoroll. Defaults to 0.
upper : int or float
The upper bound to clip the pianoroll. Defaults to 127. | [
"Clip",
"the",
"pianoroll",
"by",
"the",
"given",
"lower",
"and",
"upper",
"bounds",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L140-L152 |
562 | salu133445/pypianoroll | pypianoroll/track.py | Track.is_binarized | def is_binarized(self):
"""
Return True if the pianoroll is already binarized. Otherwise, return
False.
Returns
-------
is_binarized : bool
True if the pianoroll is already binarized; otherwise, False.
"""
is_binarized = np.issubdtype(self.pi... | python | def is_binarized(self):
is_binarized = np.issubdtype(self.pianoroll.dtype, np.bool_)
return is_binarized | [
"def",
"is_binarized",
"(",
"self",
")",
":",
"is_binarized",
"=",
"np",
".",
"issubdtype",
"(",
"self",
".",
"pianoroll",
".",
"dtype",
",",
"np",
".",
"bool_",
")",
"return",
"is_binarized"
] | Return True if the pianoroll is already binarized. Otherwise, return
False.
Returns
-------
is_binarized : bool
True if the pianoroll is already binarized; otherwise, False. | [
"Return",
"True",
"if",
"the",
"pianoroll",
"is",
"already",
"binarized",
".",
"Otherwise",
"return",
"False",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L225-L237 |
563 | salu133445/pypianoroll | pypianoroll/track.py | Track.pad | def pad(self, pad_length):
"""
Pad the pianoroll with zeros at the end along the time axis.
Parameters
----------
pad_length : int
The length to pad with zeros along the time axis.
"""
self.pianoroll = np.pad(
self.pianoroll, ((0, pad_len... | python | def pad(self, pad_length):
self.pianoroll = np.pad(
self.pianoroll, ((0, pad_length), (0, 0)), 'constant') | [
"def",
"pad",
"(",
"self",
",",
"pad_length",
")",
":",
"self",
".",
"pianoroll",
"=",
"np",
".",
"pad",
"(",
"self",
".",
"pianoroll",
",",
"(",
"(",
"0",
",",
"pad_length",
")",
",",
"(",
"0",
",",
"0",
")",
")",
",",
"'constant'",
")"
] | Pad the pianoroll with zeros at the end along the time axis.
Parameters
----------
pad_length : int
The length to pad with zeros along the time axis. | [
"Pad",
"the",
"pianoroll",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L239-L250 |
564 | salu133445/pypianoroll | pypianoroll/track.py | Track.pad_to_multiple | def pad_to_multiple(self, factor):
"""
Pad the pianoroll with zeros at the end along the time axis with the
minimum length that makes the resulting pianoroll length a multiple of
`factor`.
Parameters
----------
factor : int
The value which the length ... | python | def pad_to_multiple(self, factor):
remainder = self.pianoroll.shape[0] % factor
if remainder:
pad_width = ((0, (factor - remainder)), (0, 0))
self.pianoroll = np.pad(self.pianoroll, pad_width, 'constant') | [
"def",
"pad_to_multiple",
"(",
"self",
",",
"factor",
")",
":",
"remainder",
"=",
"self",
".",
"pianoroll",
".",
"shape",
"[",
"0",
"]",
"%",
"factor",
"if",
"remainder",
":",
"pad_width",
"=",
"(",
"(",
"0",
",",
"(",
"factor",
"-",
"remainder",
")"... | Pad the pianoroll with zeros at the end along the time axis with the
minimum length that makes the resulting pianoroll length a multiple of
`factor`.
Parameters
----------
factor : int
The value which the length of the resulting pianoroll will be
a multip... | [
"Pad",
"the",
"pianoroll",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"with",
"the",
"minimum",
"length",
"that",
"makes",
"the",
"resulting",
"pianoroll",
"length",
"a",
"multiple",
"of",
"factor",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L252-L268 |
565 | salu133445/pypianoroll | pypianoroll/track.py | Track.transpose | def transpose(self, semitone):
"""
Transpose the pianoroll by a number of semitones, where positive
values are for higher key, while negative values are for lower key.
Parameters
----------
semitone : int
The number of semitones to transpose the pianoroll.
... | python | def transpose(self, semitone):
if semitone > 0 and semitone < 128:
self.pianoroll[:, semitone:] = self.pianoroll[:, :(128 - semitone)]
self.pianoroll[:, :semitone] = 0
elif semitone < 0 and semitone > -128:
self.pianoroll[:, :(128 + semitone)] = self.pianoroll[:, -sem... | [
"def",
"transpose",
"(",
"self",
",",
"semitone",
")",
":",
"if",
"semitone",
">",
"0",
"and",
"semitone",
"<",
"128",
":",
"self",
".",
"pianoroll",
"[",
":",
",",
"semitone",
":",
"]",
"=",
"self",
".",
"pianoroll",
"[",
":",
",",
":",
"(",
"12... | Transpose the pianoroll by a number of semitones, where positive
values are for higher key, while negative values are for lower key.
Parameters
----------
semitone : int
The number of semitones to transpose the pianoroll. | [
"Transpose",
"the",
"pianoroll",
"by",
"a",
"number",
"of",
"semitones",
"where",
"positive",
"values",
"are",
"for",
"higher",
"key",
"while",
"negative",
"values",
"are",
"for",
"lower",
"key",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L275-L291 |
566 | salu133445/pypianoroll | pypianoroll/track.py | Track.trim_trailing_silence | def trim_trailing_silence(self):
"""Trim the trailing silence of the pianoroll."""
length = self.get_active_length()
self.pianoroll = self.pianoroll[:length] | python | def trim_trailing_silence(self):
length = self.get_active_length()
self.pianoroll = self.pianoroll[:length] | [
"def",
"trim_trailing_silence",
"(",
"self",
")",
":",
"length",
"=",
"self",
".",
"get_active_length",
"(",
")",
"self",
".",
"pianoroll",
"=",
"self",
".",
"pianoroll",
"[",
":",
"length",
"]"
] | Trim the trailing silence of the pianoroll. | [
"Trim",
"the",
"trailing",
"silence",
"of",
"the",
"pianoroll",
"."
] | 6224dc1e29222de2124d249acb80f3d072166917 | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L293-L296 |
567 | dnouri/nolearn | nolearn/lasagne/visualize.py | plot_conv_weights | def plot_conv_weights(layer, figsize=(6, 6)):
"""Plot the weights of a specific layer.
Only really makes sense with convolutional layers.
Parameters
----------
layer : lasagne.layers.Layer
"""
W = layer.W.get_value()
shape = W.shape
nrows = np.ceil(np.sqrt(shape[0])).astype(int)
... | python | def plot_conv_weights(layer, figsize=(6, 6)):
W = layer.W.get_value()
shape = W.shape
nrows = np.ceil(np.sqrt(shape[0])).astype(int)
ncols = nrows
for feature_map in range(shape[1]):
figs, axes = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False)
for ax in axes.flatten():
... | [
"def",
"plot_conv_weights",
"(",
"layer",
",",
"figsize",
"=",
"(",
"6",
",",
"6",
")",
")",
":",
"W",
"=",
"layer",
".",
"W",
".",
"get_value",
"(",
")",
"shape",
"=",
"W",
".",
"shape",
"nrows",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",... | Plot the weights of a specific layer.
Only really makes sense with convolutional layers.
Parameters
----------
layer : lasagne.layers.Layer | [
"Plot",
"the",
"weights",
"of",
"a",
"specific",
"layer",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L26-L54 |
568 | dnouri/nolearn | nolearn/lasagne/visualize.py | plot_conv_activity | def plot_conv_activity(layer, x, figsize=(6, 8)):
"""Plot the acitivities of a specific layer.
Only really makes sense with layers that work 2D data (2D
convolutional layers, 2D pooling layers ...).
Parameters
----------
layer : lasagne.layers.Layer
x : numpy.ndarray
Only takes one ... | python | def plot_conv_activity(layer, x, figsize=(6, 8)):
if x.shape[0] != 1:
raise ValueError("Only one sample can be plotted at a time.")
# compile theano function
xs = T.tensor4('xs').astype(theano.config.floatX)
get_activity = theano.function([xs], get_output(layer, xs))
activity = get_activit... | [
"def",
"plot_conv_activity",
"(",
"layer",
",",
"x",
",",
"figsize",
"=",
"(",
"6",
",",
"8",
")",
")",
":",
"if",
"x",
".",
"shape",
"[",
"0",
"]",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Only one sample can be plotted at a time.\"",
")",
"# comp... | Plot the acitivities of a specific layer.
Only really makes sense with layers that work 2D data (2D
convolutional layers, 2D pooling layers ...).
Parameters
----------
layer : lasagne.layers.Layer
x : numpy.ndarray
Only takes one sample at a time, i.e. x.shape[0] == 1. | [
"Plot",
"the",
"acitivities",
"of",
"a",
"specific",
"layer",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L57-L102 |
569 | dnouri/nolearn | nolearn/lasagne/visualize.py | occlusion_heatmap | def occlusion_heatmap(net, x, target, square_length=7):
"""An occlusion test that checks an image for its critical parts.
In this function, a square part of the image is occluded (i.e. set
to 0) and then the net is tested for its propensity to predict the
correct label. One should expect that this prop... | python | def occlusion_heatmap(net, x, target, square_length=7):
if (x.ndim != 4) or x.shape[0] != 1:
raise ValueError("This function requires the input data to be of "
"shape (1, c, x, y), instead got {}".format(x.shape))
if square_length % 2 == 0:
raise ValueError("Square lengt... | [
"def",
"occlusion_heatmap",
"(",
"net",
",",
"x",
",",
"target",
",",
"square_length",
"=",
"7",
")",
":",
"if",
"(",
"x",
".",
"ndim",
"!=",
"4",
")",
"or",
"x",
".",
"shape",
"[",
"0",
"]",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"This fu... | An occlusion test that checks an image for its critical parts.
In this function, a square part of the image is occluded (i.e. set
to 0) and then the net is tested for its propensity to predict the
correct label. One should expect that this propensity shrinks of
critical parts of the image are occluded.... | [
"An",
"occlusion",
"test",
"that",
"checks",
"an",
"image",
"for",
"its",
"critical",
"parts",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L105-L180 |
570 | dnouri/nolearn | nolearn/lasagne/visualize.py | plot_occlusion | def plot_occlusion(net, X, target, square_length=7, figsize=(9, None)):
"""Plot which parts of an image are particularly import for the
net to classify the image correctly.
See paper: Zeiler, Fergus 2013
Parameters
----------
net : NeuralNet instance
The neural net to test.
X : nump... | python | def plot_occlusion(net, X, target, square_length=7, figsize=(9, None)):
return _plot_heat_map(
net, X, figsize, lambda net, X, n: occlusion_heatmap(
net, X, target[n], square_length)) | [
"def",
"plot_occlusion",
"(",
"net",
",",
"X",
",",
"target",
",",
"square_length",
"=",
"7",
",",
"figsize",
"=",
"(",
"9",
",",
"None",
")",
")",
":",
"return",
"_plot_heat_map",
"(",
"net",
",",
"X",
",",
"figsize",
",",
"lambda",
"net",
",",
"X... | Plot which parts of an image are particularly import for the
net to classify the image correctly.
See paper: Zeiler, Fergus 2013
Parameters
----------
net : NeuralNet instance
The neural net to test.
X : numpy.array
The input data, should be of shape (b, c, 0, 1). Only makes
... | [
"Plot",
"which",
"parts",
"of",
"an",
"image",
"are",
"particularly",
"import",
"for",
"the",
"net",
"to",
"classify",
"the",
"image",
"correctly",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L214-L250 |
571 | dnouri/nolearn | nolearn/metrics.py | multiclass_logloss | def multiclass_logloss(actual, predicted, eps=1e-15):
"""Multi class version of Logarithmic Loss metric.
:param actual: Array containing the actual target classes
:param predicted: Matrix with class predictions, one probability per class
"""
# Convert 'actual' to a binary array if it's not already:... | python | def multiclass_logloss(actual, predicted, eps=1e-15):
# Convert 'actual' to a binary array if it's not already:
if len(actual.shape) == 1:
actual2 = np.zeros((actual.shape[0], predicted.shape[1]))
for i, val in enumerate(actual):
actual2[i, val] = 1
actual = actual2
clip... | [
"def",
"multiclass_logloss",
"(",
"actual",
",",
"predicted",
",",
"eps",
"=",
"1e-15",
")",
":",
"# Convert 'actual' to a binary array if it's not already:",
"if",
"len",
"(",
"actual",
".",
"shape",
")",
"==",
"1",
":",
"actual2",
"=",
"np",
".",
"zeros",
"(... | Multi class version of Logarithmic Loss metric.
:param actual: Array containing the actual target classes
:param predicted: Matrix with class predictions, one probability per class | [
"Multi",
"class",
"version",
"of",
"Logarithmic",
"Loss",
"metric",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/metrics.py#L8-L24 |
572 | dnouri/nolearn | nolearn/lasagne/base.py | objective | def objective(layers,
loss_function,
target,
aggregate=aggregate,
deterministic=False,
l1=0,
l2=0,
get_output_kw=None):
"""
Default implementation of the NeuralNet objective.
:param layers: The underlying laye... | python | def objective(layers,
loss_function,
target,
aggregate=aggregate,
deterministic=False,
l1=0,
l2=0,
get_output_kw=None):
if get_output_kw is None:
get_output_kw = {}
output_layer = layers[-1]
network_out... | [
"def",
"objective",
"(",
"layers",
",",
"loss_function",
",",
"target",
",",
"aggregate",
"=",
"aggregate",
",",
"deterministic",
"=",
"False",
",",
"l1",
"=",
"0",
",",
"l2",
"=",
"0",
",",
"get_output_kw",
"=",
"None",
")",
":",
"if",
"get_output_kw",
... | Default implementation of the NeuralNet objective.
:param layers: The underlying layers of the NeuralNetwork
:param loss_function: The callable loss function to use
:param target: the expected output
:param aggregate: the aggregation function to use
:param deterministic: Whether or not to get a de... | [
"Default",
"implementation",
"of",
"the",
"NeuralNet",
"objective",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L166-L202 |
573 | dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.initialize | def initialize(self):
"""Initializes the network. Checks that no extra kwargs were
passed to the constructor, and compiles the train, predict,
and evaluation functions.
Subsequent calls to this function will return without any action.
"""
if getattr(self, '_initialized'... | python | def initialize(self):
if getattr(self, '_initialized', False):
return
out = getattr(self, '_output_layers', None)
if out is None:
self.initialize_layers()
self._check_for_unused_kwargs()
iter_funcs = self._create_iter_funcs(
self.layers_, sel... | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_initialized'",
",",
"False",
")",
":",
"return",
"out",
"=",
"getattr",
"(",
"self",
",",
"'_output_layers'",
",",
"None",
")",
"if",
"out",
"is",
"None",
":",
"self",
... | Initializes the network. Checks that no extra kwargs were
passed to the constructor, and compiles the train, predict,
and evaluation functions.
Subsequent calls to this function will return without any action. | [
"Initializes",
"the",
"network",
".",
"Checks",
"that",
"no",
"extra",
"kwargs",
"were",
"passed",
"to",
"the",
"constructor",
"and",
"compiles",
"the",
"train",
"predict",
"and",
"evaluation",
"functions",
"."
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L473-L493 |
574 | dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.fit | def fit(self, X, y, epochs=None):
"""
Runs the training loop for a given number of epochs
:param X: The input data
:param y: The ground truth
:param epochs: The number of epochs to run, if `None` runs for the
network's :attr:`max_epochs`
:return:... | python | def fit(self, X, y, epochs=None):
if self.check_input:
X, y = self._check_good_input(X, y)
if self.use_label_encoder:
self.enc_ = LabelEncoder()
y = self.enc_.fit_transform(y).astype(np.int32)
self.classes_ = self.enc_.classes_
self.initialize()
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"epochs",
"=",
"None",
")",
":",
"if",
"self",
".",
"check_input",
":",
"X",
",",
"y",
"=",
"self",
".",
"_check_good_input",
"(",
"X",
",",
"y",
")",
"if",
"self",
".",
"use_label_encoder",
":"... | Runs the training loop for a given number of epochs
:param X: The input data
:param y: The ground truth
:param epochs: The number of epochs to run, if `None` runs for the
network's :attr:`max_epochs`
:return: This instance | [
"Runs",
"the",
"training",
"loop",
"for",
"a",
"given",
"number",
"of",
"epochs"
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L680-L703 |
575 | dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.partial_fit | def partial_fit(self, X, y, classes=None):
"""
Runs a single epoch using the provided data
:return: This instance
"""
return self.fit(X, y, epochs=1) | python | def partial_fit(self, X, y, classes=None):
return self.fit(X, y, epochs=1) | [
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"classes",
"=",
"None",
")",
":",
"return",
"self",
".",
"fit",
"(",
"X",
",",
"y",
",",
"epochs",
"=",
"1",
")"
] | Runs a single epoch using the provided data
:return: This instance | [
"Runs",
"a",
"single",
"epoch",
"using",
"the",
"provided",
"data"
] | 2ef346c869e80fc90247916e4aea5cfa7cf2edda | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L705-L711 |
576 | pennersr/django-trackstats | trackstats/models.py | ByDateQuerySetMixin.narrow | def narrow(self, **kwargs):
"""Up-to including"""
from_date = kwargs.pop('from_date', None)
to_date = kwargs.pop('to_date', None)
date = kwargs.pop('date', None)
qs = self
if from_date:
qs = qs.filter(date__gte=from_date)
if to_date:
qs = q... | python | def narrow(self, **kwargs):
from_date = kwargs.pop('from_date', None)
to_date = kwargs.pop('to_date', None)
date = kwargs.pop('date', None)
qs = self
if from_date:
qs = qs.filter(date__gte=from_date)
if to_date:
qs = qs.filter(date__lte=to_date)
... | [
"def",
"narrow",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
".",
"pop",
"(",
"'from_date'",
",",
"None",
")",
"to_date",
"=",
"kwargs",
".",
"pop",
"(",
"'to_date'",
",",
"None",
")",
"date",
"=",
"kwargs",
".",
"po... | Up-to including | [
"Up",
"-",
"to",
"including"
] | 4c36e769cb02017675a86de405afcd4e10ed3356 | https://github.com/pennersr/django-trackstats/blob/4c36e769cb02017675a86de405afcd4e10ed3356/trackstats/models.py#L230-L242 |
577 | HDE/python-lambda-local | lambda_local/environment_variables.py | set_environment_variables | def set_environment_variables(json_file_path):
"""
Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
... | python | def set_environment_variables(json_file_path):
if json_file_path:
with open(json_file_path) as json_file:
env_vars = json.loads(json_file.read())
export_variables(env_vars) | [
"def",
"set_environment_variables",
"(",
"json_file_path",
")",
":",
"if",
"json_file_path",
":",
"with",
"open",
"(",
"json_file_path",
")",
"as",
"json_file",
":",
"env_vars",
"=",
"json",
".",
"loads",
"(",
"json_file",
".",
"read",
"(",
")",
")",
"export... | Read and set environment variables from a flat json file.
Bear in mind that env vars set this way and later on read using
`os.getenv` function will be strings since after all env vars are just
that - plain strings.
Json file example:
```
{
"FOO": "bar",
"BAZ": true
}
``... | [
"Read",
"and",
"set",
"environment",
"variables",
"from",
"a",
"flat",
"json",
"file",
"."
] | 49ad011a039974f1d8f904435eb8db895558d2d9 | https://github.com/HDE/python-lambda-local/blob/49ad011a039974f1d8f904435eb8db895558d2d9/lambda_local/environment_variables.py#L10-L33 |
578 | HDE/python-lambda-local | lambda_local/context.py | millis_interval | def millis_interval(start, end):
"""start and end are datetime instances"""
diff = end - start
millis = diff.days * 24 * 60 * 60 * 1000
millis += diff.seconds * 1000
millis += diff.microseconds / 1000
return millis | python | def millis_interval(start, end):
diff = end - start
millis = diff.days * 24 * 60 * 60 * 1000
millis += diff.seconds * 1000
millis += diff.microseconds / 1000
return millis | [
"def",
"millis_interval",
"(",
"start",
",",
"end",
")",
":",
"diff",
"=",
"end",
"-",
"start",
"millis",
"=",
"diff",
".",
"days",
"*",
"24",
"*",
"60",
"*",
"60",
"*",
"1000",
"millis",
"+=",
"diff",
".",
"seconds",
"*",
"1000",
"millis",
"+=",
... | start and end are datetime instances | [
"start",
"and",
"end",
"are",
"datetime",
"instances"
] | 49ad011a039974f1d8f904435eb8db895558d2d9 | https://github.com/HDE/python-lambda-local/blob/49ad011a039974f1d8f904435eb8db895558d2d9/lambda_local/context.py#L49-L55 |
579 | locationlabs/mockredis | mockredis/script.py | Script._import_lua | def _import_lua(load_dependencies=True):
"""
Import lua and dependencies.
:param load_dependencies: should Lua library dependencies be loaded?
:raises: RuntimeError if Lua is not available
"""
try:
import lua
except ImportError:
raise Runt... | python | def _import_lua(load_dependencies=True):
try:
import lua
except ImportError:
raise RuntimeError("Lua not installed")
lua_globals = lua.globals()
if load_dependencies:
Script._import_lua_dependencies(lua, lua_globals)
return lua, lua_globals | [
"def",
"_import_lua",
"(",
"load_dependencies",
"=",
"True",
")",
":",
"try",
":",
"import",
"lua",
"except",
"ImportError",
":",
"raise",
"RuntimeError",
"(",
"\"Lua not installed\"",
")",
"lua_globals",
"=",
"lua",
".",
"globals",
"(",
")",
"if",
"load_depen... | Import lua and dependencies.
:param load_dependencies: should Lua library dependencies be loaded?
:raises: RuntimeError if Lua is not available | [
"Import",
"lua",
"and",
"dependencies",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L54-L69 |
580 | locationlabs/mockredis | mockredis/script.py | Script._import_lua_dependencies | def _import_lua_dependencies(lua, lua_globals):
"""
Imports lua dependencies that are supported by redis lua scripts.
The current implementation is fragile to the target platform and lua version
and may be disabled if these imports are not needed.
Included:
- cjson ... | python | def _import_lua_dependencies(lua, lua_globals):
if sys.platform not in ('darwin', 'windows'):
import ctypes
ctypes.CDLL('liblua5.2.so', mode=ctypes.RTLD_GLOBAL)
try:
lua_globals.cjson = lua.eval('require "cjson"')
except RuntimeError:
raise Runtim... | [
"def",
"_import_lua_dependencies",
"(",
"lua",
",",
"lua_globals",
")",
":",
"if",
"sys",
".",
"platform",
"not",
"in",
"(",
"'darwin'",
",",
"'windows'",
")",
":",
"import",
"ctypes",
"ctypes",
".",
"CDLL",
"(",
"'liblua5.2.so'",
",",
"mode",
"=",
"ctypes... | Imports lua dependencies that are supported by redis lua scripts.
The current implementation is fragile to the target platform and lua version
and may be disabled if these imports are not needed.
Included:
- cjson lib.
Pending:
- base lib.
- table li... | [
"Imports",
"lua",
"dependencies",
"that",
"are",
"supported",
"by",
"redis",
"lua",
"scripts",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L72-L96 |
581 | locationlabs/mockredis | mockredis/client.py | MockRedis.lock | def lock(self, key, timeout=0, sleep=0):
"""Emulate lock."""
return MockRedisLock(self, key, timeout, sleep) | python | def lock(self, key, timeout=0, sleep=0):
return MockRedisLock(self, key, timeout, sleep) | [
"def",
"lock",
"(",
"self",
",",
"key",
",",
"timeout",
"=",
"0",
",",
"sleep",
"=",
"0",
")",
":",
"return",
"MockRedisLock",
"(",
"self",
",",
"key",
",",
"timeout",
",",
"sleep",
")"
] | Emulate lock. | [
"Emulate",
"lock",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L77-L79 |
582 | locationlabs/mockredis | mockredis/client.py | MockRedis.keys | def keys(self, pattern='*'):
"""Emulate keys."""
# making sure the pattern is unicode/str.
try:
pattern = pattern.decode('utf-8')
# This throws an AttributeError in python 3, or an
# UnicodeEncodeError in python 2
except (AttributeError, UnicodeEncodeE... | python | def keys(self, pattern='*'):
# making sure the pattern is unicode/str.
try:
pattern = pattern.decode('utf-8')
# This throws an AttributeError in python 3, or an
# UnicodeEncodeError in python 2
except (AttributeError, UnicodeEncodeError):
pass
... | [
"def",
"keys",
"(",
"self",
",",
"pattern",
"=",
"'*'",
")",
":",
"# making sure the pattern is unicode/str.",
"try",
":",
"pattern",
"=",
"pattern",
".",
"decode",
"(",
"'utf-8'",
")",
"# This throws an AttributeError in python 3, or an",
"# UnicodeEncodeError in python ... | Emulate keys. | [
"Emulate",
"keys",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L154-L169 |
583 | locationlabs/mockredis | mockredis/client.py | MockRedis.delete | def delete(self, *keys):
"""Emulate delete."""
key_counter = 0
for key in map(self._encode, keys):
if key in self.redis:
del self.redis[key]
key_counter += 1
if key in self.timeouts:
del self.timeouts[key]
return key... | python | def delete(self, *keys):
key_counter = 0
for key in map(self._encode, keys):
if key in self.redis:
del self.redis[key]
key_counter += 1
if key in self.timeouts:
del self.timeouts[key]
return key_counter | [
"def",
"delete",
"(",
"self",
",",
"*",
"keys",
")",
":",
"key_counter",
"=",
"0",
"for",
"key",
"in",
"map",
"(",
"self",
".",
"_encode",
",",
"keys",
")",
":",
"if",
"key",
"in",
"self",
".",
"redis",
":",
"del",
"self",
".",
"redis",
"[",
"k... | Emulate delete. | [
"Emulate",
"delete",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L171-L180 |
584 | locationlabs/mockredis | mockredis/client.py | MockRedis.do_expire | def do_expire(self):
"""
Expire objects assuming now == time
"""
# Deep copy to avoid RuntimeError: dictionary changed size during iteration
_timeouts = deepcopy(self.timeouts)
for key, value in _timeouts.items():
if value - self.clock.now() < timedelta(0):
... | python | def do_expire(self):
# Deep copy to avoid RuntimeError: dictionary changed size during iteration
_timeouts = deepcopy(self.timeouts)
for key, value in _timeouts.items():
if value - self.clock.now() < timedelta(0):
del self.timeouts[key]
# removing the ... | [
"def",
"do_expire",
"(",
"self",
")",
":",
"# Deep copy to avoid RuntimeError: dictionary changed size during iteration",
"_timeouts",
"=",
"deepcopy",
"(",
"self",
".",
"timeouts",
")",
"for",
"key",
",",
"value",
"in",
"_timeouts",
".",
"items",
"(",
")",
":",
"... | Expire objects assuming now == time | [
"Expire",
"objects",
"assuming",
"now",
"==",
"time"
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L258-L269 |
585 | locationlabs/mockredis | mockredis/client.py | MockRedis.set | def set(self, key, value, ex=None, px=None, nx=False, xx=False):
"""
Set the ``value`` for the ``key`` in the context of the provided kwargs.
As per the behavior of the redis-py lib:
If nx and xx are both set, the function does nothing and None is returned.
If px and ex are both... | python | def set(self, key, value, ex=None, px=None, nx=False, xx=False):
key = self._encode(key)
value = self._encode(value)
if nx and xx:
return None
mode = "nx" if nx else "xx" if xx else None
if self._should_set(key, mode):
expire = None
if ex is n... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"ex",
"=",
"None",
",",
"px",
"=",
"None",
",",
"nx",
"=",
"False",
",",
"xx",
"=",
"False",
")",
":",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"value",
"=",
"self",
".",
... | Set the ``value`` for the ``key`` in the context of the provided kwargs.
As per the behavior of the redis-py lib:
If nx and xx are both set, the function does nothing and None is returned.
If px and ex are both set, the preference is given to px.
If the key is not set for some reason, t... | [
"Set",
"the",
"value",
"for",
"the",
"key",
"in",
"the",
"context",
"of",
"the",
"provided",
"kwargs",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L313-L342 |
586 | locationlabs/mockredis | mockredis/client.py | MockRedis._should_set | def _should_set(self, key, mode):
"""
Determine if it is okay to set a key.
If the mode is None, returns True, otherwise, returns True of false based on
the value of ``key`` and the ``mode`` (nx | xx).
"""
if mode is None or mode not in ["nx", "xx"]:
return ... | python | def _should_set(self, key, mode):
if mode is None or mode not in ["nx", "xx"]:
return True
if mode == "nx":
if key in self.redis:
# nx means set only if key is absent
# false if the key already exists
return False
elif key ... | [
"def",
"_should_set",
"(",
"self",
",",
"key",
",",
"mode",
")",
":",
"if",
"mode",
"is",
"None",
"or",
"mode",
"not",
"in",
"[",
"\"nx\"",
",",
"\"xx\"",
"]",
":",
"return",
"True",
"if",
"mode",
"==",
"\"nx\"",
":",
"if",
"key",
"in",
"self",
"... | Determine if it is okay to set a key.
If the mode is None, returns True, otherwise, returns True of false based on
the value of ``key`` and the ``mode`` (nx | xx). | [
"Determine",
"if",
"it",
"is",
"okay",
"to",
"set",
"a",
"key",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L359-L381 |
587 | locationlabs/mockredis | mockredis/client.py | MockRedis.setex | def setex(self, name, time, value):
"""
Set the value of ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object.
"""
if not self.strict:
# when not strict mode swap value and time args ord... | python | def setex(self, name, time, value):
if not self.strict:
# when not strict mode swap value and time args order
time, value = value, time
return self.set(name, value, ex=time) | [
"def",
"setex",
"(",
"self",
",",
"name",
",",
"time",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"strict",
":",
"# when not strict mode swap value and time args order",
"time",
",",
"value",
"=",
"value",
",",
"time",
"return",
"self",
".",
"set",
... | Set the value of ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object. | [
"Set",
"the",
"value",
"of",
"name",
"to",
"value",
"that",
"expires",
"in",
"time",
"seconds",
".",
"time",
"can",
"be",
"represented",
"by",
"an",
"integer",
"or",
"a",
"Python",
"timedelta",
"object",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L383-L392 |
588 | locationlabs/mockredis | mockredis/client.py | MockRedis.psetex | def psetex(self, key, time, value):
"""
Set the value of ``key`` to ``value`` that expires in ``time``
milliseconds. ``time`` can be represented by an integer or a Python
timedelta object.
"""
return self.set(key, value, px=time) | python | def psetex(self, key, time, value):
return self.set(key, value, px=time) | [
"def",
"psetex",
"(",
"self",
",",
"key",
",",
"time",
",",
"value",
")",
":",
"return",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"px",
"=",
"time",
")"
] | Set the value of ``key`` to ``value`` that expires in ``time``
milliseconds. ``time`` can be represented by an integer or a Python
timedelta object. | [
"Set",
"the",
"value",
"of",
"key",
"to",
"value",
"that",
"expires",
"in",
"time",
"milliseconds",
".",
"time",
"can",
"be",
"represented",
"by",
"an",
"integer",
"or",
"a",
"Python",
"timedelta",
"object",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L394-L400 |
589 | locationlabs/mockredis | mockredis/client.py | MockRedis.setnx | def setnx(self, key, value):
"""Set the value of ``key`` to ``value`` if key doesn't exist"""
return self.set(key, value, nx=True) | python | def setnx(self, key, value):
return self.set(key, value, nx=True) | [
"def",
"setnx",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"nx",
"=",
"True",
")"
] | Set the value of ``key`` to ``value`` if key doesn't exist | [
"Set",
"the",
"value",
"of",
"key",
"to",
"value",
"if",
"key",
"doesn",
"t",
"exist"
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L402-L404 |
590 | locationlabs/mockredis | mockredis/client.py | MockRedis.setbit | def setbit(self, key, offset, value):
"""
Set the bit at ``offset`` in ``key`` to ``value``.
"""
key = self._encode(key)
index, bits, mask = self._get_bits_and_offset(key, offset)
if index >= len(bits):
bits.extend(b"\x00" * (index + 1 - len(bits)))
... | python | def setbit(self, key, offset, value):
key = self._encode(key)
index, bits, mask = self._get_bits_and_offset(key, offset)
if index >= len(bits):
bits.extend(b"\x00" * (index + 1 - len(bits)))
prev_val = 1 if (bits[index] & mask) else 0
if value:
bits[ind... | [
"def",
"setbit",
"(",
"self",
",",
"key",
",",
"offset",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"index",
",",
"bits",
",",
"mask",
"=",
"self",
".",
"_get_bits_and_offset",
"(",
"key",
",",
"offset",
")",
"if",... | Set the bit at ``offset`` in ``key`` to ``value``. | [
"Set",
"the",
"bit",
"at",
"offset",
"in",
"key",
"to",
"value",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L465-L484 |
591 | locationlabs/mockredis | mockredis/client.py | MockRedis.getbit | def getbit(self, key, offset):
"""
Returns the bit value at ``offset`` in ``key``.
"""
key = self._encode(key)
index, bits, mask = self._get_bits_and_offset(key, offset)
if index >= len(bits):
return 0
return 1 if (bits[index] & mask) else 0 | python | def getbit(self, key, offset):
key = self._encode(key)
index, bits, mask = self._get_bits_and_offset(key, offset)
if index >= len(bits):
return 0
return 1 if (bits[index] & mask) else 0 | [
"def",
"getbit",
"(",
"self",
",",
"key",
",",
"offset",
")",
":",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"index",
",",
"bits",
",",
"mask",
"=",
"self",
".",
"_get_bits_and_offset",
"(",
"key",
",",
"offset",
")",
"if",
"index",
">="... | Returns the bit value at ``offset`` in ``key``. | [
"Returns",
"the",
"bit",
"value",
"at",
"offset",
"in",
"key",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L486-L496 |
592 | locationlabs/mockredis | mockredis/client.py | MockRedis.hexists | def hexists(self, hashkey, attribute):
"""Emulate hexists."""
redis_hash = self._get_hash(hashkey, 'HEXISTS')
return self._encode(attribute) in redis_hash | python | def hexists(self, hashkey, attribute):
redis_hash = self._get_hash(hashkey, 'HEXISTS')
return self._encode(attribute) in redis_hash | [
"def",
"hexists",
"(",
"self",
",",
"hashkey",
",",
"attribute",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HEXISTS'",
")",
"return",
"self",
".",
"_encode",
"(",
"attribute",
")",
"in",
"redis_hash"
] | Emulate hexists. | [
"Emulate",
"hexists",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L506-L510 |
593 | locationlabs/mockredis | mockredis/client.py | MockRedis.hget | def hget(self, hashkey, attribute):
"""Emulate hget."""
redis_hash = self._get_hash(hashkey, 'HGET')
return redis_hash.get(self._encode(attribute)) | python | def hget(self, hashkey, attribute):
redis_hash = self._get_hash(hashkey, 'HGET')
return redis_hash.get(self._encode(attribute)) | [
"def",
"hget",
"(",
"self",
",",
"hashkey",
",",
"attribute",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HGET'",
")",
"return",
"redis_hash",
".",
"get",
"(",
"self",
".",
"_encode",
"(",
"attribute",
")",
")"
] | Emulate hget. | [
"Emulate",
"hget",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L512-L516 |
594 | locationlabs/mockredis | mockredis/client.py | MockRedis.hmset | def hmset(self, hashkey, value):
"""Emulate hmset."""
redis_hash = self._get_hash(hashkey, 'HMSET', create=True)
for key, value in value.items():
attribute = self._encode(key)
redis_hash[attribute] = self._encode(value)
return True | python | def hmset(self, hashkey, value):
redis_hash = self._get_hash(hashkey, 'HMSET', create=True)
for key, value in value.items():
attribute = self._encode(key)
redis_hash[attribute] = self._encode(value)
return True | [
"def",
"hmset",
"(",
"self",
",",
"hashkey",
",",
"value",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HMSET'",
",",
"create",
"=",
"True",
")",
"for",
"key",
",",
"value",
"in",
"value",
".",
"items",
"(",
")",
":... | Emulate hmset. | [
"Emulate",
"hmset",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L543-L550 |
595 | locationlabs/mockredis | mockredis/client.py | MockRedis.hmget | def hmget(self, hashkey, keys, *args):
"""Emulate hmget."""
redis_hash = self._get_hash(hashkey, 'HMGET')
attributes = self._list_or_args(keys, args)
return [redis_hash.get(self._encode(attribute)) for attribute in attributes] | python | def hmget(self, hashkey, keys, *args):
redis_hash = self._get_hash(hashkey, 'HMGET')
attributes = self._list_or_args(keys, args)
return [redis_hash.get(self._encode(attribute)) for attribute in attributes] | [
"def",
"hmget",
"(",
"self",
",",
"hashkey",
",",
"keys",
",",
"*",
"args",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HMGET'",
")",
"attributes",
"=",
"self",
".",
"_list_or_args",
"(",
"keys",
",",
"args",
")",
"r... | Emulate hmget. | [
"Emulate",
"hmget",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L552-L557 |
596 | locationlabs/mockredis | mockredis/client.py | MockRedis.hset | def hset(self, hashkey, attribute, value):
"""Emulate hset."""
redis_hash = self._get_hash(hashkey, 'HSET', create=True)
attribute = self._encode(attribute)
attribute_present = attribute in redis_hash
redis_hash[attribute] = self._encode(value)
return long(0) if attribut... | python | def hset(self, hashkey, attribute, value):
redis_hash = self._get_hash(hashkey, 'HSET', create=True)
attribute = self._encode(attribute)
attribute_present = attribute in redis_hash
redis_hash[attribute] = self._encode(value)
return long(0) if attribute_present else long(1) | [
"def",
"hset",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"value",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HSET'",
",",
"create",
"=",
"True",
")",
"attribute",
"=",
"self",
".",
"_encode",
"(",
"attribute... | Emulate hset. | [
"Emulate",
"hset",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L559-L566 |
597 | locationlabs/mockredis | mockredis/client.py | MockRedis.hsetnx | def hsetnx(self, hashkey, attribute, value):
"""Emulate hsetnx."""
redis_hash = self._get_hash(hashkey, 'HSETNX', create=True)
attribute = self._encode(attribute)
if attribute in redis_hash:
return long(0)
else:
redis_hash[attribute] = self._encode(value)... | python | def hsetnx(self, hashkey, attribute, value):
redis_hash = self._get_hash(hashkey, 'HSETNX', create=True)
attribute = self._encode(attribute)
if attribute in redis_hash:
return long(0)
else:
redis_hash[attribute] = self._encode(value)
return long(1) | [
"def",
"hsetnx",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"value",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HSETNX'",
",",
"create",
"=",
"True",
")",
"attribute",
"=",
"self",
".",
"_encode",
"(",
"attri... | Emulate hsetnx. | [
"Emulate",
"hsetnx",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L568-L577 |
598 | locationlabs/mockredis | mockredis/client.py | MockRedis.hincrby | def hincrby(self, hashkey, attribute, increment=1):
"""Emulate hincrby."""
return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment) | python | def hincrby(self, hashkey, attribute, increment=1):
return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment) | [
"def",
"hincrby",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"increment",
"=",
"1",
")",
":",
"return",
"self",
".",
"_hincrby",
"(",
"hashkey",
",",
"attribute",
",",
"'HINCRBY'",
",",
"long",
",",
"increment",
")"
] | Emulate hincrby. | [
"Emulate",
"hincrby",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L579-L582 |
599 | locationlabs/mockredis | mockredis/client.py | MockRedis.hincrbyfloat | def hincrbyfloat(self, hashkey, attribute, increment=1.0):
"""Emulate hincrbyfloat."""
return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment) | python | def hincrbyfloat(self, hashkey, attribute, increment=1.0):
return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment) | [
"def",
"hincrbyfloat",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"increment",
"=",
"1.0",
")",
":",
"return",
"self",
".",
"_hincrby",
"(",
"hashkey",
",",
"attribute",
",",
"'HINCRBYFLOAT'",
",",
"float",
",",
"increment",
")"
] | Emulate hincrbyfloat. | [
"Emulate",
"hincrbyfloat",
"."
] | fd4e3117066ff0c24e86ebca007853a8092e3254 | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L584-L587 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.