signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@property<EOL><INDENT>def canvasCharHeight(self):<DEDENT>
return self.visibleBox.h*<NUM_LIT:4>/self.plotviewBox.h<EOL>
Height in canvas units of a single char in the terminal
f1838:c3:m11
def polyline(self, vertexes, attr=<NUM_LIT:0>, row=None):
self.polylines.append((vertexes, attr, row))<EOL>
adds lines for (x,y) vertexes of a polygon
f1838:c3:m16
def polygon(self, vertexes, attr=<NUM_LIT:0>, row=None):
self.polylines.append((vertexes + [vertexes[<NUM_LIT:0>]], attr, row))<EOL>
adds lines for (x,y) vertexes of a polygon
f1838:c3:m17
def qcurve(self, vertexes, attr=<NUM_LIT:0>, row=None):
assert len(vertexes) == <NUM_LIT:3>, len(vertexes)<EOL>x1, y1 = vertexes[<NUM_LIT:0>]<EOL>x2, y2 = vertexes[<NUM_LIT:1>]<EOL>x3, y3 = vertexes[<NUM_LIT:2>]<EOL>self.point(x1, y1, attr, row)<EOL>self._recursive_bezier(x1, y1, x2, y2, x3, y3, attr, row)<EOL>self.point(x3, y3, attr, row)<EOL>
quadratic curve from vertexes[0] to vertexes[2] with control point at vertexes[1]
f1838:c3:m18
def _recursive_bezier(self, x1, y1, x2, y2, x3, y3, attr, row, level=<NUM_LIT:0>):
m_approximation_scale = <NUM_LIT><EOL>m_distance_tolerance = (<NUM_LIT:0.5> / m_approximation_scale) ** <NUM_LIT:2><EOL>m_angle_tolerance = <NUM_LIT:1> * <NUM_LIT:2>*math.pi/<NUM_LIT> <EOL>curve_angle_tolerance_epsilon = <NUM_LIT><EOL>curve_recursion_limit = <NUM_LIT:32><EOL>curve_collinearity_epsilon = <NUM_LIT><EOL>...
from http://www.antigrain.com/research/adaptive_bezier/
f1838:c3:m19
def fixPoint(self, plotterPoint, canvasPoint):
self.visibleBox.xmin = canvasPoint.x - self.canvasW(plotterPoint.x-self.plotviewBox.xmin)<EOL>self.visibleBox.ymin = canvasPoint.y - self.canvasH(plotterPoint.y-self.plotviewBox.ymin)<EOL>self.refresh()<EOL>
adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint
f1838:c3:m21
def zoomTo(self, bbox):
self.fixPoint(self.plotviewBox.xymin, bbox.xymin)<EOL>self.zoomlevel=max(bbox.w/self.canvasBox.w, bbox.h/self.canvasBox.h)<EOL>
set visible area to bbox, maintaining aspectRatio if applicable
f1838:c3:m22
def checkCursor(self):
if self.cursorBox:<EOL><INDENT>if self.cursorBox.h < self.canvasCharHeight:<EOL><INDENT>self.cursorBox.h = self.canvasCharHeight*<NUM_LIT:3>/<NUM_LIT:4><EOL><DEDENT>if self.cursorBox.w < self.canvasCharWidth:<EOL><INDENT>self.cursorBox.w = self.canvasCharWidth*<NUM_LIT:3>/<NUM_LIT:4><EOL><DEDENT><DEDENT>return False<EO...
override Sheet.checkCursor
f1838:c3:m26
def scaleX(self, x):
return round(self.plotviewBox.xmin+(x-self.visibleBox.xmin)*self.xScaler)<EOL>
returns plotter x coordinate
f1838:c3:m29
def scaleY(self, y):
return round(self.plotviewBox.ymin+(y-self.visibleBox.ymin)*self.yScaler)<EOL>
returns plotter y coordinate
f1838:c3:m30
def canvasW(self, plotter_width):
return plotter_width/self.xScaler<EOL>
plotter X units to canvas units
f1838:c3:m31
def canvasH(self, plotter_height):
return plotter_height/self.yScaler<EOL>
plotter Y units to canvas units
f1838:c3:m32
def refresh(self):
self.needsRefresh = True<EOL>
triggers render() on next draw()
f1838:c3:m33
def render(self, h, w):
self.needsRefresh = False<EOL>cancelThread(*(t for t in self.currentThreads if t.name == '<STR_LIT>'))<EOL>self.labels.clear()<EOL>self.resetCanvasDimensions(h, w)<EOL>self.render_async()<EOL>
resets plotter, cancels previous render threads, spawns a new render
f1838:c3:m34
def render_sync(self):
self.setZoom()<EOL>bb = self.visibleBox<EOL>xmin, ymin, xmax, ymax = bb.xmin, bb.ymin, bb.xmax, bb.ymax<EOL>xfactor, yfactor = self.xScaler, self.yScaler<EOL>plotxmin, plotymin = self.plotviewBox.xmin, self.plotviewBox.ymin<EOL>for vertexes, attr, row in Progress(self.polylines, '<STR_LIT>'):<EOL><INDENT>if len(vertexe...
plots points and lines and text onto the Plotter
f1838:c3:m36
def detect_command(cmdlist):
for platform, command, args in cmdlist:<EOL><INDENT>if platform is None or sys.platform == platform:<EOL><INDENT>path = shutil.which(command)<EOL>if path:<EOL><INDENT>return '<STR_LIT:U+0020>'.join([path, args])<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'<EOL>
Detect available clipboard util and return cmdline to copy data to the system clipboard. cmddict is list of (platform, progname, argstr).
f1839:m0
@functools.lru_cache()<EOL>def clipboard():
if not options.clipboard_copy_cmd:<EOL><INDENT>options.clipboard_copy_cmd = detect_clipboard_command()<EOL><DEDENT>return _Clipboard()<EOL>
Detect cmd and set option at first use, to allow option to be changed by user later.
f1839:m1
def copyToClipboard(value):
clipboard().copy(value)<EOL>status('<STR_LIT>')<EOL>
copy single value to system clipboard
f1839:m2
@asyncthread<EOL>def saveToClipboard(sheet, rows, filetype=None):
filetype = filetype or options.save_filetype<EOL>vs = copy(sheet)<EOL>vs.rows = rows<EOL>status('<STR_LIT>')<EOL>clipboard().save(vs, filetype)<EOL>
copy rows from sheet to system clipboard
f1839:m3
@property<EOL><INDENT>def command(self):<DEDENT>
cmd = options.clipboard_copy_cmd or fail('<STR_LIT>')<EOL>return cmd.split()<EOL>
Return cmdline cmd+args (as list for Popen) to copy data to the system clipboard.
f1839:c0:m0
def copy(self, value):
with tempfile.NamedTemporaryFile() as temp:<EOL><INDENT>with open(temp.name, '<STR_LIT:w>', encoding=options.encoding) as fp:<EOL><INDENT>fp.write(str(value))<EOL><DEDENT>p = subprocess.Popen(<EOL>self.command,<EOL>stdin=open(temp.name, '<STR_LIT:r>', encoding=options.encoding),<EOL>stdout=subprocess.DEVNULL)<EOL>p.com...
Copy a cell to the system clipboard.
f1839:c0:m1
def save(self, vs, filetype):
<EOL>with tempfile.NamedTemporaryFile(suffix='<STR_LIT:.>'+filetype) as temp:<EOL><INDENT>saveSheets(temp.name, vs)<EOL>sync(<NUM_LIT:1>)<EOL>p = subprocess.Popen(<EOL>self.command,<EOL>stdin=open(temp.name, '<STR_LIT:r>', encoding=options.encoding),<EOL>stdout=subprocess.DEVNULL,<EOL>close_fds=True)<EOL>p.communicate(...
Copy rows to the system clipboard.
f1839:c0:m2
@functools.wraps(vd().toplevelTryFunc)<EOL>def threadProfileCode(func, *args, **kwargs):
with ThreadProfiler(threading.current_thread()) as prof:<EOL><INDENT>try:<EOL><INDENT>prof.thread.status = threadProfileCode.__wrapped__(func, *args, **kwargs)<EOL><DEDENT>except EscapeException as e:<EOL><INDENT>prof.thread.status = e<EOL><DEDENT><DEDENT>
Toplevel thread profile wrapper.
f1840:m2
def scaleY(self, canvasY):
plotterY = super().scaleY(canvasY)<EOL>return (self.plotviewBox.ymax-plotterY+<NUM_LIT:4>)<EOL>
returns plotter y coordinate, with y-axis inverted
f1841:c0:m2
def joinSheetnames(*sheetnames):
return '<STR_LIT:_>'.join(str(x) for x in sheetnames)<EOL>
Concatenate sheet names in a standard way
f1843:m0
def moveListItem(L, fromidx, toidx):
r = L.pop(fromidx)<EOL>L.insert(toidx, r)<EOL>return toidx<EOL>
Move element within list `L` and return element's new index.
f1843:m1
def urlcache(url, cachesecs=<NUM_LIT>*<NUM_LIT>*<NUM_LIT>):
p = Path(os.path.join(options.visidata_dir, '<STR_LIT>', urllib.parse.quote(url, safe='<STR_LIT>')))<EOL>if p.exists():<EOL><INDENT>secs = time.time() - p.stat().st_mtime<EOL>if secs < cachesecs:<EOL><INDENT>return p<EOL><DEDENT><DEDENT>if not p.parent.exists():<EOL><INDENT>os.makedirs(p.parent.resolve(), exist_ok=True...
Returns Path object to local cache of url contents.
f1845:m0
@asyncthread<EOL><INDENT>def reload(self):<DEDENT>
self.rows = []<EOL><INDENT>if len(self.origCols) == <NUM_LIT:1> and self.origCols[<NUM_LIT:0>].type in (int, float, currency):<EOL><INDENT>self.numericBinning()<EOL><DEDENT>else:<EOL><DEDENT>self.discreteBinning()<EOL>for c in self.nonKeyVisibleCols:<EOL><INDENT>c._cachedValues = collections.OrderedDict()<EOL><DEDENT>
Generate histrow for each row and then reverse-sort by length.
f1848:c0:m5
def git_all(*args, git=maybeloggit, **kwargs):
try:<EOL><INDENT>cmd = git(*args, _err_to_out=True, _decode_errors='<STR_LIT:replace>', **kwargs)<EOL>out = cmd.stdout<EOL><DEDENT>except sh.ErrorReturnCode as e:<EOL><INDENT>status('<STR_LIT>' % e.exit_code)<EOL>out = e.stdout<EOL><DEDENT>out = out.decode('<STR_LIT:utf-8>')<EOL>return out<EOL>
Return entire output of git command.
f1852:m2
def git_lines(*args, git=maybeloggit, **kwargs):
err = io.StringIO()<EOL>try:<EOL><INDENT>for line in git('<STR_LIT>', _err=err, *args, _decode_errors='<STR_LIT:replace>', _iter=True, _bg_exc=False, **kwargs):<EOL><INDENT>yield line[:-<NUM_LIT:1>] <EOL><DEDENT><DEDENT>except sh.ErrorReturnCode as e:<EOL><INDENT>status('<STR_LIT>' % e.exit_code)<EOL><DEDENT>errlines ...
Generator of stdout lines from given git command
f1852:m3
def git_iter(sep, *args, git=maybeloggit, **kwargs):
bufsize = <NUM_LIT><EOL>err = io.StringIO()<EOL>chunks = []<EOL>try:<EOL><INDENT>for data in git('<STR_LIT>', *args, _decode_errors='<STR_LIT:replace>', _out_bufsize=bufsize, _iter=True, _err=err, **kwargs):<EOL><INDENT>while True:<EOL><INDENT>i = data.find(sep)<EOL>if i < <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>chu...
Generator of chunks of stdout from given git command, delineated by sep character
f1852:m4
def git_status(self, r):
ret = self._cachedStatus.get(r.filename, None) if r else None<EOL>return ret if ret else ["<STR_LIT>", None, None]<EOL>
return tuple of (status, adds, dels). status like !! ?? adds and dels are lists of additions and deletions.
f1852:c3:m4
def getDiffSheet(fn, *refs):
one column per ref
f1854:m0
def amendPrevious(self, targethash):
prevBranch = loggit_all('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>').strip()<EOL>ret = loggit_all('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'+targethash) <EOL>newChanges = loggit_all('<STR_LIT>', '<STR_LIT>').strip()<EOL>ret += loggit_all('<STR_LIT>', '<STR_LIT>', '<STR_LIT>') <EOL>with GitUndo('<STR_LIT>', '<STR_LIT>...
amend targethash with current index, then rebase newer commits on top
f1857:c2:m0
@functools.lru_cache()<EOL>def currency_multiplier(src_currency, dest_currency):
if src_currency == '<STR_LIT>':<EOL><INDENT>return <NUM_LIT:1.0><EOL><DEDENT>usd_mult = currency_rates()[src_currency]<EOL>if dest_currency == '<STR_LIT>':<EOL><INDENT>return usd_mult<EOL><DEDENT>return usd_mult/currency_rates()[dest_currency]<EOL>
returns equivalent value in USD for an amt of currency_code
f1861:m2
def parse_dossier_data(data, ep):
changed = False<EOL>doc_changed = False<EOL>ref = data['<STR_LIT>']['<STR_LIT>']<EOL>logger.debug('<STR_LIT>', ref)<EOL>with transaction.atomic():<EOL><INDENT>try:<EOL><INDENT>dossier = Dossier.objects.get(reference=ref)<EOL><DEDENT>except Dossier.DoesNotExist:<EOL><INDENT>dossier = Dossier(reference=ref)<EOL>logger.de...
Parse data from parltarck dossier export (1 dossier) Update dossier if it existed before, this function goal is to import and update a dossier, not to import all parltrack data
f1865:m0
def parse_vote_data(self, vote_data):
if '<STR_LIT>' not in vote_data.keys():<EOL><INDENT>logger.debug('<STR_LIT>',<EOL>vote_data['<STR_LIT:title>'])<EOL>return<EOL><DEDENT>dossier_pk = self.get_dossier(vote_data['<STR_LIT>'])<EOL>if not dossier_pk:<EOL><INDENT>logger.debug('<STR_LIT>',<EOL>vote_data['<STR_LIT>'])<EOL>return<EOL><DEDENT>return self.parse_p...
Parse data from parltrack votes db dumps (1 proposal)
f1867:c0:m1
@transaction.atomic<EOL><INDENT>def parse_proposal_data(self, proposal_data, dossier_pk):<DEDENT>
proposal_display = '<STR_LIT>'.format(proposal_data['<STR_LIT:title>'].encode(<EOL>'<STR_LIT:utf-8>'), proposal_data.get('<STR_LIT>', '<STR_LIT>').encode('<STR_LIT:utf-8>'))<EOL>if '<STR_LIT>' not in proposal_data.keys():<EOL><INDENT>logger.debug('<STR_LIT>',<EOL>proposal_data['<STR_LIT>'])<EOL>return<EOL><DEDENT>chang...
Get or Create a proposal model from raw data
f1867:c0:m2
def find_dossier(data):
changed = False<EOL>dossier = None<EOL>reffield = None<EOL>for field in [k for k in ('<STR_LIT>', '<STR_LIT>') if k in data]:<EOL><INDENT>try:<EOL><INDENT>dossier = Dossier.objects.get(reference=data[field])<EOL>reffield = field<EOL>break<EOL><DEDENT>except Dossier.DoesNotExist:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if ...
Find dossier with reference matching either 'ref_an' or 'ref_sen', create it if not found. Ensure its reference is 'ref_an' if both fields are present.
f1868:m1
def chambers(self):
<EOL>return set(sorted([d.chamber for d in self.documents.all()]))<EOL>
Return distinct chambers. You probably want to prefetch documents__chamber before calling that.
f1891:c0:m1
def execute_from_file(self, url, file_var):
if isinstance(file_var, file):<EOL><INDENT>f = file_var<EOL><DEDENT>elif isinstance(file_var, str):<EOL><INDENT>try:<EOL><INDENT>f = open(file_var)<EOL><DEDENT>except IOError as e:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>inputs = json.loads(f.read())<EOL>resp =...
Identical to WebPypeClient.execute(), except this function accepts a file path or file type instead of a dictionary.
f1897:c1:m1
def execute_from_url(self, url, input_url):
inputs = self._request(input_url)<EOL>resp = self.execute(url, inputs)<EOL>return resp<EOL>
Identical to WebPypeClient.execute(), except this function accepts a url instead of a dictionary or string.
f1897:c1:m2
def intercontacttimes(tnet):
<EOL>tnet = process_input(tnet, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'], '<STR_LIT>')<EOL>if tnet.nettype[<NUM_LIT:0>] == '<STR_LIT:w>':<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>contacts = np.array([[None] * tnet.netshape[<NUM_LIT:0>]] * tnet.netshape[<NUM_LIT:0>])<EOL>if tnet.nettype[<NUM_LIT:1>] == '<STR_LIT:u>':...
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'] Notes ------ The inter-contact ...
f1924:m0
def fluctuability(netin, calc='<STR_LIT>'):
<EOL>netin, _ = process_input(netin, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])<EOL>netin[netin != <NUM_LIT:0>] = <NUM_LIT:1><EOL>unique_edges = np.sum(netin, axis=<NUM_LIT:2>)<EOL>unique_edges[unique_edges > <NUM_LIT:0>] = <NUM_LIT:1><EOL>unique_edges[unique_edges == <NUM_LIT:0>] = <NUM_LIT:0><EOL>fluct = (np.sum(uniq...
r""" Fluctuability of temporal networks. This is the variation of the network's edges over time. [fluct-1]_ This is the unique number of edges through time divided by the overall number of edges. Parameters ---------- netin : array or dict Temporal network input (graphlet or contact) (net...
f1925:m0
def temporal_betweenness_centrality(tnet=None, paths=None, calc='<STR_LIT:time>'):
if tnet is not None and paths is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is None and paths is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is not None:<EOL><INDENT>paths = shortest_temporal_path(tnet)<EOL><DEDENT>bet = np.zeros([paths[['<STR_LIT>', '<STR_LIT:to>']]...
Returns temporal betweenness centrality per node. Parameters ----------- Input should be *either* tnet or paths. data : array or dict Temporal network input (graphlet or contact). nettype: 'bu', 'bd'. calc : str either 'global' or 'time' paths : pandas dataframe Output of TenetoBIDS.networkmeasure.s...
f1926:m0
def volatility(tnet, distance_func_name='<STR_LIT:default>', calc='<STR_LIT>', communities=None, event_displacement=None):
<EOL>tnet, netinfo = process_input(tnet, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])<EOL>distance_func_name = check_distance_funciton_input(<EOL>distance_func_name, netinfo)<EOL>if not isinstance(distance_func_name, str):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if netinfo['<STR_LIT>'][<NUM_LIT:1>] == '<STR...
r""" Volatility of temporal networks. Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge). Parameters ---------- tnet : array or dict temporal network input (graphlet or contact). Nettype: 'bu','bd','wu','w...
f1927:m0
def sid(tnet, communities, axis=<NUM_LIT:0>, calc='<STR_LIT>', decay=<NUM_LIT:0>):
tnet, netinfo = utils.process_input(tnet, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])<EOL>D = temporal_degree_centrality(<EOL>tnet, calc='<STR_LIT:time>', communities=communities, decay=decay)<EOL>network_ids = np.unique(communities)<EOL>communities_size = np.array([sum(communities == n) for n in network_ids])<EOL>sid =...
r""" Segregation integration difference (SID). An estimation of each community or global difference of within versus between community strength.[sid-1]_ Parameters ---------- tnet: array, dict Temporal network input (graphlet or contact). Allowerd nettype: 'bu', 'bd', 'wu', 'wd' communit...
f1928:m0
def bursty_coeff(data, calc='<STR_LIT>', nodes='<STR_LIT:all>', communities=None, threshold_type=None, threshold_level=None, threshold_params=None):
if threshold_type is not None:<EOL><INDENT>if threshold_params is None: <EOL><INDENT>threshold_params = {}<EOL><DEDENT>data = binarize(data, threshold_type,<EOL>threshold_level, **threshold_params)<EOL><DEDENT>if calc == '<STR_LIT>' and communities is None:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>ict...
r""" Calculates the bursty coefficient.[1][2] Parameters ---------- data : array, dict This is either (1) temporal network input (graphlet or contact) with nettype: 'bu', 'bd'. (2) dictionary of ICTs (output of *intercontacttimes*). A weighted network can be applied if you specify thre...
f1930:m0
def topological_overlap(tnet, calc='<STR_LIT:time>'):
tnet = process_input(tnet, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'])[<NUM_LIT:0>]<EOL>numerator = np.sum(tnet[:, :, :-<NUM_LIT:1>] * tnet[:, :, <NUM_LIT:1>:], axis=<NUM_LIT:1>)<EOL>denominator = np.sqrt(<EOL>np.sum(tnet[:, :, :-<NUM_LIT:1>], axis=<NUM_LIT:1>) * np.sum(tnet[:, :, <NUM_LIT:1>:], axis=<NUM_LIT:1>))<EOL>t...
r""" Topological overlap quantifies the persistency of edges through time. If two consequtive time-points have similar edges, this becomes high (max 1). If there is high change, this becomes 0. References: [topo-1]_, [topo-2]_ Parameters ---------- tnet : array, dict graphlet or contact se...
f1931:m0
def temporal_efficiency(tnet=None, paths=None, calc='<STR_LIT>'):
if tnet is not None and paths is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is None and paths is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is not None:<EOL><INDENT>paths = shortest_temporal_path(tnet)<EOL><DEDENT>pathmat = np.zeros([paths[['<STR_LIT>', '<STR_LIT:to...
r""" Returns temporal efficiency estimate. BU networks only. 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.sho...
f1932:m0
def temporal_degree_centrality(tnet, axis=<NUM_LIT:0>, calc='<STR_LIT>', communities=None, decay=<NUM_LIT:0>, ignorediagonal=True):
<EOL>tnet = process_input(tnet, ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT>'], '<STR_LIT>')<EOL>if axis == <NUM_LIT:1>:<EOL><INDENT>fromax = '<STR_LIT>'<EOL>toax = '<STR_LIT:i>'<EOL><DEDENT>else:<EOL><INDENT>fromax = '<STR_LIT:i>'<EOL>toax = '<STR_LIT>'<EOL><DEDENT>if tnet.nettype[<NUM_LIT:0>] == '<STR_LIT:b>':<EOL><INDENT...
temporal degree of network. Sum of all connections each node has through time. Parameters ----------- net : array, dict Temporal network input (graphlet or contact). Can have nettype: 'bu', 'bd', 'wu', 'wd' axis : int Dimension that is returned 0 or 1 (default 0). Note, only relevant for directed networks...
f1934:m0
def temporal_participation_coeff(tnet, communities=None, decay=None, removeneg=False):
if communities is None:<EOL><INDENT>if isinstance(tnet, dict):<EOL><INDENT>if '<STR_LIT>' in tnet.keys():<EOL><INDENT>communities = tnet['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>tnet = process_input(t...
r''' Temporal participation coefficient is a measure of diversity of connections across communities for individual nodes. Parameters ---------- tnet : array, dict graphlet or contact sequence input. Only positive matrices considered. communities : array community vector. Either 1D (...
f1935:m0
def reachability_latency(tnet=None, paths=None, rratio=<NUM_LIT:1>, calc='<STR_LIT>'):
if tnet is not None and paths is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is None and paths is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is not None:<EOL><INDENT>paths = shortest_temporal_path(tnet)<EOL><DEDENT>pathmat = np.zeros([paths[['<STR_LIT>', '<STR_LIT:to...
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: 1) reachabilit...
f1936:m0
def local_variation(data):
ict = <NUM_LIT:0> <EOL>if isinstance(data, dict):<EOL><INDENT>if [k for k in list(data.keys()) if k == '<STR_LIT>'] == ['<STR_LIT>']:<EOL><INDENT>ict = <NUM_LIT:1><EOL><DEDENT><DEDENT>if ict == <NUM_LIT:0>:<EOL><INDENT>data = intercontacttimes(data)<EOL><DEDENT>if data['<STR_LIT>'][<NUM_LIT:1>] == '<STR_LIT:u>':<EOL><...
r""" Calculates the local variaiont of inter-contact times. [LV-1]_, [LV-2]_ Parameters ---------- data : array, dict This is either (1) temporal network input (graphlet or contact) with nettype: 'bu', 'bd'. (2) dictionary of ICTs (output of *intercontacttimes*). Returns ------- ...
f1937:m0
def temporal_closeness_centrality(tnet=None, paths=None):
if tnet is not None and paths is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is None and paths is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tnet is not None:<EOL><INDENT>paths = shortest_temporal_path(tnet)<EOL><DEDENT>pathmat = np.zeros([paths[['<STR_LIT>', '<STR_LIT:to...
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_paths Returns -------- :c...
f1938:m0
def allegiance(community):
N = community.shape[<NUM_LIT:0>]<EOL>C = community.shape[<NUM_LIT:1>]<EOL>T = P = np.zeros([N, N])<EOL>for t in range(len(community[<NUM_LIT:0>, :])):<EOL><INDENT>for i in range(len(community[:, <NUM_LIT:0>])):<EOL><INDENT>for j in range(len(community[:, <NUM_LIT:0>])):<EOL><INDENT>if i == j:<EOL><INDENT>continue<EOL><...
Computes the allegiance matrix with values representing the probability that nodes i and j were assigned to the same community by time-varying clustering methods. parameters ---------- community : array array of community assignment of size node,time returns ------- P : array module allegiance matrix, with P_...
f1939:m0
def recruitment(temporalcommunities, staticcommunities):
<EOL>if staticcommunities.shape[<NUM_LIT:0>] != temporalcommunities.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError( <EOL>'<STR_LIT>')<EOL><DEDENT>alleg = allegiance(temporalcommunities)<EOL>Rcoeff = np.zeros(len(staticcommunities))<EOL>for i, statcom in enumerate(staticcommunities):<EOL><INDENT>Rcoeff[i] = np.mean(...
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 communities vector (...
f1940:m0
def flexibility(communities):
<EOL>flex = np.zeros(communities.shape[<NUM_LIT:0>])<EOL>for t in range(<NUM_LIT:1>, communities.shape[<NUM_LIT:1>]):<EOL><INDENT>flex[communities[:, t] != communities[:, t-<NUM_LIT:1>]] += <NUM_LIT:1><EOL><DEDENT>flex = flex / (communities.shape[<NUM_LIT:1>] - <NUM_LIT:1>)<EOL>return flex<EOL>
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 label during a time series. It is normalized...
f1941:m0
def integration(temporalcommunities, staticcommunities):
<EOL>if staticcommunities.shape[<NUM_LIT:0>] != temporalcommunities.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>alleg = allegiance(temporalcommunities)<EOL>Icoeff = np.zeros(len(staticcommunities))<EOL>for i, statcom in enumerate(len(staticcommunities)):<EOL><INDENT>Icoeff[i] = np.mea...
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 Static communities vector ...
f1943:m0
def __init__(self, BIDS_dir, pipeline=None, pipeline_subdir=None, parcellation=None, bids_tags=None, bids_suffix=None, bad_subjects=None, confound_pipeline=None, raw_data_exists=True, njobs=None):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>self.contact = []<EOL>if raw_data_exists:<EOL><INDENT>self.BIDS = BIDSLayout(BIDS_dir, validate=False)<EOL><DEDENT>else: <EOL><INDENT>self.BIDS = None<EOL><DEDENT>self.BIDS_dir = os.path.abspath(BIDS_dir)<EOL>self.pipeline = pipeline...
Parameters ---------- BIDS_dir : str string to BIDS directory pipeline : str the directory that is in the BIDS_dir/derivatives/<pipeline>/ pipeline_subdir : str, optional the directory that is in the BIDS_dir/derivatives/<pipeline>/sub-<subjectnr/[ses-<sesnr>]/func/<pipeline_subdir> parcellation : str, opt...
f1946:c0:m0
def add_history(self, fname, fargs, init=<NUM_LIT:0>):
if init == <NUM_LIT:1>:<EOL><INDENT>self.history = []<EOL><DEDENT>self.history.append([fname, fargs])<EOL>
Adds a processing step to TenetoBIDS.history.
f1946:c0:m1
def export_history(self, dirname):
mods = [(m.__name__, m.__version__)<EOL>for m in sys.modules.values() if m if hasattr(m, '<STR_LIT>')]<EOL>with open(dirname + '<STR_LIT>', '<STR_LIT:w>') as f:<EOL><INDENT>for m in mods:<EOL><INDENT>m = list(m)<EOL>if not isinstance(m[<NUM_LIT:1>], str):<EOL><INDENT>m[<NUM_LIT:1>] = m[<NUM_LIT:1>].decode("<STR_LIT:utf...
Exports TenetoBIDShistory.py, tenetoinfo.json, requirements.txt (modules currently imported) to dirname Parameters --------- dirname : str directory to export entire TenetoBIDS history.
f1946:c0:m2
def derive_temporalnetwork(self, params, update_pipeline=True, tag=None, njobs=<NUM_LIT:1>, confound_corr_report=True):
if not njobs:<EOL><INDENT>njobs = self.njobs<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>files = self.get_selected_files(quiet=<NUM_LIT:1>)<EOL>confound_files = self.get_selected_files(quiet=<NUM_LIT:1>, pipeline='<STR_LIT>')<EOL>if confound_files:<EOL><INDENT>conf...
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 If true, the object updates the selecte...
f1946:c0:m3
def _derive_temporalnetwork(self, f, i, tag, params, confounds_exist, confound_files):
data = load_tabular_file(f, index_col=True, header=True)<EOL>fs, _ = drop_bids_suffix(f)<EOL>save_name, save_dir, _ = self._save_namepaths_bids_derivatives(<EOL>fs, tag, '<STR_LIT>', '<STR_LIT>')<EOL>if '<STR_LIT>' in params.keys():<EOL><INDENT>if params['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>fc_files = self.get_sele...
Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing.
f1946:c0:m4
def make_functional_connectivity(self, njobs=None, returngroup=False, file_hdr=None, file_idx=None):
if not njobs:<EOL><INDENT>njobs = self.njobs<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>files = self.get_selected_files(quiet=<NUM_LIT:1>)<EOL>R_group = []<EOL>with ProcessPoolExecutor(max_workers=njobs) as executor:<EOL><INDENT>job = {executor.submit(<EOL>self._r...
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 if to ignore index column in loaded file. file_hdr : bool Def...
f1946:c0:m6
def _save_namepaths_bids_derivatives(self, f, tag, save_directory, suffix=None):
file_name = f.split('<STR_LIT:/>')[-<NUM_LIT:1>].split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL>if tag != '<STR_LIT>':<EOL><INDENT>tag = '<STR_LIT:_>' + tag<EOL><DEDENT>if suffix:<EOL><INDENT>file_name, _ = drop_bids_suffix(file_name)<EOL>save_name = file_name + tag<EOL>save_name += '<STR_LIT:_>' + suffix<EOL><DEDENT>else:<EOL>...
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 suffix : str add new suffix to data Returns ------- save_n...
f1946:c0:m8
def get_tags(self, tag, quiet=<NUM_LIT:1>):
if not self.pipeline:<EOL><INDENT>print('<STR_LIT>')<EOL>self.get_pipeline_alternatives(quiet)<EOL><DEDENT>else:<EOL><INDENT>if tag == '<STR_LIT>':<EOL><INDENT>datapath = self.BIDS_dir + '<STR_LIT>' + self.pipeline + '<STR_LIT:/>'<EOL>tag_alternatives = [<EOL>f.split('<STR_LIT>')[<NUM_LIT:1>] for f in os.listdir(datapa...
Returns which tag alternatives can be identified in the BIDS derivatives structure.
f1946:c0:m9
def get_pipeline_alternatives(self, quiet=<NUM_LIT:0>):
if not os.path.exists(self.BIDS_dir + '<STR_LIT>'):<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>pipeline_alternatives = os.listdir(self.BIDS_dir + '<STR_LIT>')<EOL>if quiet == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>' +<EOL>'<STR_LIT:U+002CU+0020>'.join(pipeline_alternatives))<EOL><DEDENT>return list(...
The pipeline are the different outputs that are placed in the ./derivatives directory. get_pipeline_alternatives gets those which are found in the specified BIDS directory structure.
f1946:c0:m10
def get_pipeline_subdir_alternatives(self, quiet=<NUM_LIT:0>):
if not self.pipeline:<EOL><INDENT>print('<STR_LIT>')<EOL>self.get_pipeline_alternatives()<EOL><DEDENT>else:<EOL><INDENT>pipeline_subdir_alternatives = []<EOL>for s in self.bids_tags['<STR_LIT>']:<EOL><INDENT>derdir_files = os.listdir(<EOL>self.BIDS_dir + '<STR_LIT>' + self.pipeline + '<STR_LIT>' + s + '<STR_LIT>')<EOL>...
Note ----- This function currently returns the wrong folders and will be fixed in the future. This function should return ./derivatives/pipeline/sub-xx/[ses-yy/][func/]/pipeline_subdir But it does not care about ses-yy at the moment.
f1946:c0:m11
def get_selected_files(self, pipeline='<STR_LIT>', forfile=None, quiet=<NUM_LIT:0>, allowedfileformats='<STR_LIT:default>'):
<EOL>file_dict = dict(self.bids_tags)<EOL>if allowedfileformats == '<STR_LIT:default>':<EOL><INDENT>allowedfileformats = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>if forfile:<EOL><INDENT>if isinstance(forfile, str):<EOL><INDENT>forfile = get_bids_tag(forfile, '<STR_LIT:all>')<EOL><DEDENT>for n in forfile.keys():<EOL><INDE...
Parameters ---------- pipeline : string can be \'pipeline\' (main analysis pipeline, self in tnet.set_pipeline) or \'confound\' (where confound files are, set in tnet.set_confonud_pipeline()), \'functionalconnectivity\' quiet: int If 1, prints results. If 0, no results printed. forfile : str or dict A f...
f1946:c0:m12
def set_exclusion_file(self, confound, exclusion_criteria, confound_stat='<STR_LIT>'):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if isinstance(confound, str):<EOL><INDENT>confound = [confound]<EOL><DEDENT>if isinstance(exclusion_criteria, str):<EOL><INDENT>exclusion_criteria = [exclusion_criteria]<EOL><DEDENT>if isinstance(confound_stat, str):<EOL><INDENT>conf...
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 expressed as a string. It starts with >,<,>= or <= then ...
f1946:c0:m13
def set_exclusion_timepoint(self, confound, exclusion_criteria, replace_with, tol=<NUM_LIT:1>, overwrite=True, desc=None):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if isinstance(confound, str):<EOL><INDENT>confound = [confound]<EOL><DEDENT>if isinstance(exclusion_criteria, str):<EOL><INDENT>exclusion_criteria = [exclusion_criteria]<EOL><DEDENT>if len(exclusion_criteria) != len(confound):<EOL><I...
Excludes subjects given a certain exclusion criteria. Does not work on nifti files, only csv, numpy or tsc. Assumes data is node,time Parameters ---------- confound : str or list string or list of confound name(s) from confound files. Assumes data is node,time exclusion_criteria : str or list ...
f1946:c0:m14
def make_parcellation(self, parcellation, parc_type=None, parc_params=None, network='<STR_LIT>', update_pipeline=True, removeconfounds=False, tag=None, njobs=None, clean_params=None, yeonetworkn=None):
if not njobs:<EOL><INDENT>njobs = self.njobs<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>parc_name = parcellation.split('<STR_LIT:_>')[<NUM_LIT:0>].lower()<EOL>if not self.confounds and removeconfounds:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>if ...
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: 'shen2013_278' parc_type : str c...
f1946:c0:m16
def communitydetection(self, community_detection_params, community_type='<STR_LIT>', tag=None, file_hdr=False, file_idx=False, njobs=None):
if not njobs:<EOL><INDENT>njobs = self.njobs<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if not tag:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>tag = '<STR_LIT>' + tag<EOL><DEDENT>if community_type == '<STR_LIT>':<EOL><INDENT>files = self.get_selec...
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 temporal, community is made per time-point for e...
f1946:c0:m18
def removeconfounds(self, confounds=None, clean_params=None, transpose=None, njobs=None, update_pipeline=True, overwrite=True, tag=None):
if not njobs:<EOL><INDENT>njobs = self.njobs<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if not self.confounds and not confounds:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>if not tag:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>tag ...
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) Default removeconfounds works on time,node dimension...
f1946:c0:m20
def networkmeasures(self, measure=None, measure_params=None, tag=None, njobs=None):
if not njobs:<EOL><INDENT>njobs = self.njobs<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if isinstance(measure, str):<EOL><INDENT>measure = [measure]<EOL><DEDENT>if isinstance(measure_params, dict):<EOL><INDENT>measure_params = [measure_params]<EOL><DEDENT>if measu...
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 kwargs for the argument in measure. See note regarding C...
f1946:c0:m22
def set_confound_pipeline(self, confound_pipeline):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if not os.path.exists(self.BIDS_dir + '<STR_LIT>' + confound_pipeline):<EOL><INDENT>print('<STR_LIT>')<EOL>self.get_pipeline_alternatives()<EOL><DEDENT>else:<EOL><INDENT>self.confound_pipeline = confound_pipeline<EOL><DEDENT>
There may be times when the pipeline is updated (e.g. teneto) but you want the confounds from the preprocessing pipieline (e.g. fmriprep). To do this, you set the confound_pipeline to be the preprocessing pipeline where the confound files are. Parameters ---------- confound_pipeline : str Directory in the BIDS_di...
f1946:c0:m26
def set_network_communities(self, parcellation, netn=<NUM_LIT>):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>subcortical = '<STR_LIT>'<EOL>cerebellar = '<STR_LIT>'<EOL>if '<STR_LIT:+>' in parcellation:<EOL><INDENT>parcin = parcellation<EOL>parcellation = parcellation.split('<STR_LIT:+>')[<NUM_LIT:0>]<EOL>if '<STR_LIT>' in parcin:<EOL><INDEN...
parcellation : str path to csv or name of default parcellation. netn : int only when yeo atlas is used, specifies either 7 or 17.
f1946:c0:m28
def set_bids_suffix(self, bids_suffix):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>self.bids_suffix = bids_suffix<EOL>
The last analysis step is the final tag that is present in files.
f1946:c0:m29
def set_pipeline(self, pipeline):
self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>if not os.path.exists(self.BIDS_dir + '<STR_LIT>' + pipeline):<EOL><INDENT>print('<STR_LIT>')<EOL>self.get_pipeline_alternatives()<EOL><DEDENT>else:<EOL><INDENT>self.pipeline = pipeline<EOL><DEDENT>
Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string.
f1946:c0:m30
def print_dataset_summary(self):
print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>if self.raw_data_exists:<EOL><INDENT>if self.BIDS.get_subjects():<EOL><INDENT>print('<STR_LIT>' +<EOL>str(len(self.BIDS.get_subjects())))<EOL>print('<STR_LIT>' +<EOL>'<STR_LIT:U+002CU+0020>'.join(self.BIDS.get_subjects()))<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EO...
Prints information about the the BIDS data and the files currently selected.
f1946:c0:m32
@classmethod<EOL><INDENT>def load_frompickle(cls, fname, reload_object=False):<DEDENT>
if fname[-<NUM_LIT:4>:] != '<STR_LIT>':<EOL><INDENT>fname += '<STR_LIT>'<EOL><DEDENT>with open(fname, '<STR_LIT:rb>') as f:<EOL><INDENT>tnet = pickle.load(f)<EOL><DEDENT>if reload_object:<EOL><INDENT>reloadnet = teneto.TenetoBIDS(tnet.BIDS_dir, pipeline=tnet.pipeline, pipeline_subdir=tnet.pipeline_subdir, bids_tags=tne...
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 : TenetoBIDS instance
f1946:c0:m34
def load_data(self, datatype='<STR_LIT>', tag=None, measure='<STR_LIT>'):
if datatype == '<STR_LIT>' and not measure:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>self.add_history(inspect.stack()[<NUM_LIT:0>][<NUM_LIT:3>], locals(), <NUM_LIT:1>)<EOL>data_list = []<EOL>trialinfo_list = []<EOL>for s in self.bids_tags['<STR_LIT>']:<EOL><INDENT>base_path, file_list, datainfo = self...
Function loads time-varying connectivity estimates created by the TenetoBIDS.derive function. The default grabs all data (in numpy arrays) in the teneto/../func/tvc/ directory. Data is placed in teneto.tvc_data_ Parameters ---------- datatype : str \'tvc\', \'parcellation\', \'participant\', \'temporalnetwork\' ...
f1946:c0:m35
def __init__(self, N=None, T=None, nettype=None, from_df=None, from_array=None, from_dict=None, from_edgelist=None, timetype=None, diagonal=False,<EOL>timeunit=None, desc=None, starttime=None, nodelabels=None, timelabels=None, hdf5=False, hdf5path=None):
<EOL>if nettype:<EOL><INDENT>if nettype not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>inputvars = locals()<EOL>if sum([<NUM_LIT:1> for n in inputvars.keys() if '<STR_LIT>' in n and inputvars[n] is not None]) > <NUM_LIT:1>:<EOL><INDENT>rai...
N : int number of nodes in network T : int number of time-points in network nettype : str description of network. Can be: bu, bd, wu, wd where the letters stand for binary, weighted, undirected and directed. Default is weighted undirected from_df : pandas df input data frame with i,j,t,[weight] columns ...
f1948:c0:m0
def network_from_array(self, array):
if len(array.shape) == <NUM_LIT:2>:<EOL><INDENT>array = np.array(array, ndmin=<NUM_LIT:3>).transpose([<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:0>])<EOL><DEDENT>teneto.utils.check_TemporalNetwork_input(array, '<STR_LIT>')<EOL>uvals = np.unique(array)<EOL>if len(uvals) == <NUM_LIT:2> and <NUM_LIT:1> in uvals and <NUM_LIT:0> in...
impo Defines a network from an array. Parameters ---------- array : array 3D numpy array.
f1948:c0:m2
def network_from_df(self, df):
teneto.utils.check_TemporalNetwork_input(df, '<STR_LIT>')<EOL>self.network = df<EOL>self._update_network()<EOL>
Defines a network from an array. Parameters ---------- array : array Pandas dataframe. Should have columns: \'i\', \'j\', \'t\' where i and j are node indicies and t is the temporal index. If weighted, should also include \'weight\'. Each row is an edge.
f1948:c0:m4
def network_from_edgelist(self, edgelist):
teneto.utils.check_TemporalNetwork_input(edgelist, '<STR_LIT>')<EOL>if len(edgelist[<NUM_LIT:0>]) == <NUM_LIT:4>:<EOL><INDENT>colnames = ['<STR_LIT:i>', '<STR_LIT>', '<STR_LIT:t>', '<STR_LIT>']<EOL><DEDENT>elif len(edgelist[<NUM_LIT:0>]) == <NUM_LIT:3>:<EOL><INDENT>colnames = ['<STR_LIT:i>', '<STR_LIT>', '<STR_LIT:t>']...
Defines a network from an array. Parameters ---------- edgelist : list of lists. A list of lists which are 3 or 4 in length. For binary networks each sublist should be [i, j ,t] where i and j are node indicies and t is the temporal index. For weighted networks each sublist should be [i, j, t, weight].
f1948:c0:m5
def _drop_duplicate_ij(self):
self.network['<STR_LIT>'] = list(map(lambda x: tuple(sorted(x)), list(<EOL>zip(*[self.network['<STR_LIT:i>'].values, self.network['<STR_LIT>'].values]))))<EOL>self.network.drop_duplicates(['<STR_LIT>', '<STR_LIT:t>'], inplace=True)<EOL>self.network.reset_index(inplace=True, drop=True)<EOL>self.network.drop('<STR_LIT>',...
Drops duplicate entries from the network dataframe.
f1948:c0:m7
def _drop_diagonal(self):
self.network = self.network.where(<EOL>self.network['<STR_LIT:i>'] != self.network['<STR_LIT>']).dropna()<EOL>self.network.reset_index(inplace=True, drop=True)<EOL>
Drops self-contacts from the network dataframe.
f1948:c0:m8
def add_edge(self, edgelist):
if not isinstance(edgelist[<NUM_LIT:0>], list):<EOL><INDENT>edgelist = [edgelist]<EOL><DEDENT>teneto.utils.check_TemporalNetwork_input(edgelist, '<STR_LIT>')<EOL>if len(edgelist[<NUM_LIT:0>]) == <NUM_LIT:4>:<EOL><INDENT>colnames = ['<STR_LIT:i>', '<STR_LIT>', '<STR_LIT:t>', '<STR_LIT>']<EOL><DEDENT>elif len(edgelist[<N...
Adds an edge from network. Parameters ---------- edgelist : list a list (or list of lists) containing the i,j and t indicies to be added. For weighted networks list should also contain a 'weight' key. Returns -------- Updates TenetoBIDS.network dataframe with new edge
f1948:c0:m10
def drop_edge(self, edgelist):
if not isinstance(edgelist[<NUM_LIT:0>], list):<EOL><INDENT>edgelist = [edgelist]<EOL><DEDENT>teneto.utils.check_TemporalNetwork_input(edgelist, '<STR_LIT>')<EOL>if self.hdf5:<EOL><INDENT>with pd.HDFStore(self.network) as hdf:<EOL><INDENT>for e in edgelist:<EOL><INDENT>hdf.remove(<EOL>'<STR_LIT>', '<STR_LIT>' + str(e[<...
Removes an edge from network. Parameters ---------- edgelist : list a list (or list of lists) containing the i,j and t indicies to be removes. Returns -------- Updates TenetoBIDS.network dataframe
f1948:c0:m11
def calc_networkmeasure(self, networkmeasure, **measureparams):
availablemeasures = [f for f in dir(<EOL>teneto.networkmeasures) if not f.startswith('<STR_LIT>')]<EOL>if networkmeasure not in availablemeasures:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' + '<STR_LIT:U+002CU+0020>'.join(availablemeasures))<EOL><DEDENT>funs = inspect.getmembers(teneto.networkmeasures)<EOL>funs = {m...
Calculate network measure. Parameters ----------- networkmeasure : str Function to call. Functions available are in teneto.networkmeasures measureparams : kwargs kwargs for teneto.networkmeasure.[networkmeasure]
f1948:c0:m12
def generatenetwork(self, networktype, **networkparams):
availabletypes = [f for f in dir(<EOL>teneto.generatenetwork) if not f.startswith('<STR_LIT>')]<EOL>if networktype not in availabletypes:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' + '<STR_LIT:U+002CU+0020>'.join(availabletypes))<EOL><DEDENT>funs = inspect.getmembers(teneto.generatenetwork)<EOL>funs = {m[<NUM_LIT:0>...
Generate a network Parameters ----------- networktype : str Function to call. Functions available are in teneto.generatenetwork measureparams : kwargs kwargs for teneto.generatenetwork.[networktype] Returns -------- TenetoBIDS.network is made with the generated network.
f1948:c0:m13
def save_aspickle(self, fname):
if fname[-<NUM_LIT:4>:] != '<STR_LIT>':<EOL><INDENT>fname += '<STR_LIT>'<EOL><DEDENT>with open(fname, '<STR_LIT:wb>') as f:<EOL><INDENT>pickle.dump(self, f, pickle.HIGHEST_PROTOCOL)<EOL><DEDENT>
Saves object as pickle. fname : str file path.
f1948:c0:m15
def rand_poisson(nnodes, ncontacts, lam=<NUM_LIT:1>, nettype='<STR_LIT>', netinfo=None, netrep='<STR_LIT>'):
if isinstance(ncontacts, list):<EOL><INDENT>if len(ncontacts) != nnodes:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if isinstance(lam, list):<EOL><INDENT>if len(lam) != nnodes:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if isinstance(lam, list) and not isinstance(ncontact...
Generate a random network where intervals between contacts are distributed by a poisson distribution Parameters ---------- nnodes : int Number of nodes in networks ncontacts : int or list Number of expected contacts (i.e. edges). If list, number of contacts for each node. Any zeros drawn are ignored so r...
f1949:m0
def rand_binomial(size, prob, netrep='<STR_LIT>', nettype='<STR_LIT>', initialize='<STR_LIT>', netinfo=None, randomseed=None):
size = np.atleast_1d(size)<EOL>prob = np.atleast_1d(prob)<EOL>if len(size) == <NUM_LIT:2> or (len(size) == <NUM_LIT:3> and size[<NUM_LIT:0>] == size[<NUM_LIT:1>]):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(prob) > <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>...
Creates a random binary network following a binomial distribution. Parameters ---------- size : list or array of length 2 or 3. Input [n,t] generates n number of nodes and t number of time points. Can also be of length 3 (node x node x time) but number of nodes in 3-tuple must be identical. prob : int or li...
f1950:m0
def slice_plot(netin, ax, nodelabels=None, timelabels=None, communities=None, plotedgeweights=False, edgeweightscalar=<NUM_LIT:1>, timeunit='<STR_LIT>', linestyle='<STR_LIT>', cmap=None, nodesize=<NUM_LIT:100>, nodekwargs=None, edgekwargs=None):
<EOL>inputType = checkInput(netin)<EOL>if inputType == '<STR_LIT>':<EOL><INDENT>netin = graphlet2contact(netin)<EOL>inputType = '<STR_LIT:C>'<EOL><DEDENT>edgelist = [tuple(np.array(e[<NUM_LIT:0>:<NUM_LIT:2>]) + e[<NUM_LIT:2>] * netin['<STR_LIT>'][<NUM_LIT:0>])<EOL>for e in netin['<STR_LIT>']]<EOL>if nodelabels is not N...
r''' Fuction draws "slice graph" and exports axis handles Parameters ---------- netin : array, dict temporal network input (graphlet or contact) ax : matplotlib figure handles. nodelabels : list nodes labels. List of strings. timelabels : list labels of dimension ...
f1953:m0
def circle_plot(netIn, ax, nodelabels=None, linestyle='<STR_LIT>', nodesize=<NUM_LIT:1000>, cmap='<STR_LIT>'):
<EOL>inputType = checkInput(netIn, conMat=<NUM_LIT:1>)<EOL>if nodelabels is None:<EOL><INDENT>nodelabels = []<EOL><DEDENT>if inputType == '<STR_LIT:M>':<EOL><INDENT>shape = np.shape(netIn)<EOL>edg = np.where(np.abs(netIn) > <NUM_LIT:0>)<EOL>contacts = [tuple([edg[<NUM_LIT:0>][i], edg[<NUM_LIT:1>][i]])<EOL>for i in rang...
r''' Function draws "circle plot" and exports axis handles Parameters ------------- netIn : temporal network input (graphlet or contact) ax : matplotlib ax handles. nodelabels : list nodes labels. List of strings linestyle : str line style nodesize : int size of...
f1954:m0
def graphlet_stack_plot(netin, ax, q=<NUM_LIT:10>, cmap='<STR_LIT>', gridcolor='<STR_LIT:k>', borderwidth=<NUM_LIT:2>, bordercolor=None, Fs=<NUM_LIT:1>, timeunit='<STR_LIT>', t0=<NUM_LIT:1>, sharpen='<STR_LIT:yes>', vminmax='<STR_LIT>'):
<EOL>inputType = checkInput(netin)<EOL>if inputType == '<STR_LIT>':<EOL><INDENT>netin = netin.contact<EOL>inputType = '<STR_LIT:C>'<EOL><DEDENT>if inputType == '<STR_LIT:C>':<EOL><INDENT>if timeunit == '<STR_LIT>':<EOL><INDENT>timeunit = netin['<STR_LIT>']<EOL><DEDENT>if t0 == <NUM_LIT:1>:<EOL><INDENT>t0 = netin['<STR_...
r''' Returns matplotlib axis handle for graphlet_stack_plot. This is a row of transformed connectivity matrices to look like a 3D stack. Parameters ---------- netin : array, dict network input (graphlet or contact) ax : matplotlib ax handles. q : int Quality. Increaseing this w...
f1955:m0
def partition_inference(tctc_mat, comp, tau, sigma, kappa):
communityinfo = {}<EOL>communityinfo['<STR_LIT>'] = []<EOL>communityinfo['<STR_LIT:start>'] = np.empty(<NUM_LIT:0>)<EOL>communityinfo['<STR_LIT:end>'] = np.empty(<NUM_LIT:0>)<EOL>communityinfo['<STR_LIT:size>'] = np.empty(<NUM_LIT:0>)<EOL>for i, tcomp in enumerate(comp):<EOL><INDENT>if len(tcomp) > <NUM_LIT:0>:<EOL><IN...
r""" Takes tctc trajectory matrix and returns dataframe where all multi-label communities are listed Can take a little bit of time with large datasets and optimizaiton could remove some for loops.
f1957:m0