code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
difference = self.check_state()
if not difference:
return
self.events = []
self.handle_new_events(difference)
self.update_timeval()
self.events.append(self.sync_marker(self.timeval))
self.write_to_pipe(self.events) | def handle_input(self) | Sends differences in the device state to the MicroBitPad
as events. | 7.562782 | 6.740951 | 1.121916 |
while 1:
events = get_mouse()
for event in events:
print(event.ev_type, event.code, event.state) | def main() | Just print out some event infomation when the mouse is used. | 5.282183 | 3.518346 | 1.501326 |
while 1:
events = get_key()
if events:
for event in events:
print(event.ev_type, event.code, event.state) | def main() | Just print out some event infomation when keys are pressed. | 4.703174 | 3.08629 | 1.523892 |
while 1:
events = get_gamepad()
for event in events:
print(event.ev_type, event.code, event.state) | def main() | Just print out some event infomation when the gamepad is used. | 3.503554 | 2.327398 | 1.505352 |
if not gamepad:
gamepad = inputs.devices.gamepads[0]
# Vibrate left
gamepad.set_vibration(1, 0, 1000)
time.sleep(2)
# Vibrate right
gamepad.set_vibration(0, 1, 1000)
time.sleep(2)
# Vibrate Both
gamepad.set_vibration(1, 1, 2000)
time.sleep(2) | def main(gamepad=None) | Vibrate the gamepad. | 2.21359 | 2.076087 | 1.066232 |
errors = []
# Make sure the type validates first.
valid = self._is_valid(value)
if not valid:
errors.append(self.fail(value))
return errors
# Then validate all the constraints second.
for constraint in self._constraints_inst:
... | def validate(self, value) | Check if ``value`` is valid.
:returns: [errors] If ``value`` is invalid, otherwise []. | 4.568671 | 4.559236 | 1.002069 |
schema_flat = util.flatten(schema_dict)
for key, expression in schema_flat.items():
try:
schema_flat[key] = syntax.parse(expression, validators)
except SyntaxError as e:
# Tack on some more context and rethrow.
error = str... | def _process_schema(self, schema_dict, validators) | Go through a schema and construct validators. | 5.094374 | 4.716645 | 1.080084 |
errors = []
if position:
position = '%s.%s' % (position, key)
else:
position = key
try: # Pull value out of data. Data can be a map or a list/sequence
data_item = util.get_value(data, key)
except KeyError: # Oops, that field didn't... | def _validate(self, validator, data, key, position=None, includes=None) | Run through a schema and a data structure,
validating along the way.
Ignores fields that are in the data structure, but not in the schema.
Returns an array of errors. | 5.764927 | 5.599139 | 1.02961 |
errors = []
# Optional field with optional value? Who cares.
if data_item is None and validator.is_optional and validator.can_be_none:
return errors
errors += self._validate_primitive(validator, data_item, position)
if errors:
return errors
... | def _validate_item(self, validator, data_item, position, includes) | Validates a single data item against validator.
Returns an array of errors. | 3.230238 | 3.270467 | 0.987699 |
if not data_path or data_path == '/' or data_path == '.':
return None
directory = os.path.dirname(data_path)
path = glob.glob(os.path.join(directory, schema_name))
if not path:
return _find_schema(directory, schema_name)
return path[0] | def _find_data_path_schema(data_path, schema_name) | Starts in the data file folder and recursively looks
in parents for `schema_name` | 2.580951 | 2.463781 | 1.047557 |
path = glob.glob(schema_name)
for p in path:
if os.path.isfile(p):
return p
return _find_data_path_schema(data_path, schema_name) | def _find_schema(data_path, schema_name) | Checks if `schema_name` is a valid file, if not
searches in `data_path` for it. | 3.861892 | 3.80676 | 1.014483 |
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
if isstr(k):
k = k.replace('.', '_')
if position:
item_position = '%s.%s' % (position, k)
else:
item_position = '%s' % k
if is_iter(v):
child.update(flat... | def flatten(dic, keep_iter=False, position=None) | Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them. | 2.593673 | 2.646879 | 0.979899 |
if _subclasses_yielded is None:
_subclasses_yielded = set()
# If the passed class is old- rather than new-style, raise an exception.
if not hasattr(cls, '__subclasses__'):
raise TypeError('Old-style class "%s" unsupported.' % cls.__name__)
# For each direct subclass of this class... | def get_subclasses(cls, _subclasses_yielded=None) | Generator recursively yielding all subclasses of the passed class (in
depth-first order).
Parameters
----------
cls : type
Class to find all subclasses of.
_subclasses_yielded : set
Private parameter intended to be passed only by recursive invocations of
this function, conta... | 2.736262 | 2.772692 | 0.986861 |
value = self.model_field.__get__(obj, None)
return smart_text(value, strings_only=True) | def to_representation(self, obj) | convert value to representation.
DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method.
This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact.
NB: The argument is whole o... | 6.305928 | 5.246141 | 1.202013 |
try:
self.model_field.validate(value)
except MongoValidationError as e:
raise ValidationError(e.message)
super(DocumentField, self).run_validators(value) | def run_validators(self, value) | validate value.
Uses document field's ``validate()`` | 3.957743 | 3.851933 | 1.027469 |
if html.is_html_input(data):
data = html.parse_html_dict(data)
if not isinstance(data, dict):
self.fail('not_a_dict', input_type=type(data).__name__)
if not self.allow_empty and len(data.keys()) == 0:
message = self.error_messages['empty']
... | def to_internal_value(self, data) | Dicts of native values <- Dicts of primitive datatypes. | 2.580639 | 2.442041 | 1.056755 |
try:
return queryset.get(*args, **kwargs)
except (ValueError, TypeError, DoesNotExist, ValidationError):
raise Http404() | def get_object_or_404(queryset, *args, **kwargs) | replacement of rest_framework.generics and django.shrtcuts analogues | 3.533439 | 3.124526 | 1.130872 |
# me_data is an analogue of validated_data, but contains
# mongoengine EmbeddedDocument instances for nested data structures
# instead of OrderedDicts.
#
# For example:
# validated_data = {'id:, "1", 'embed': OrderedDict({'a': 'b'})}
# me_data = {'id': "1... | def recursive_save(self, validated_data, instance=None) | Recursively traverses validated_data and creates EmbeddedDocuments
of the appropriate subtype from them.
Returns Mongonengine model instance. | 3.400044 | 3.356054 | 1.013108 |
# for EmbeddedDocumentSerializers create initial data
# so that _get_dynamic_data could use them
for field in self._writable_fields:
if isinstance(field, EmbeddedDocumentSerializer) and field.field_name in data:
field.initial_data = data[field.field_name]
... | def to_internal_value(self, data) | Calls super() from DRF, but with an addition.
Creates initial_data and _validated_data for nested
EmbeddedDocumentSerializers, so that recursive_save could make
use of them.
If meets any arbitrary data, not expected by fields,
just silently drops them from validated_data. | 3.33876 | 2.828152 | 1.180545 |
# This method is supposed to be called after self.get_fields(),
# thus it assumes that fields and exclude are mutually exclusive
# and at least one of them is set.
#
# Also, all the sanity checks are left up to nested field's
# get_fields() method, so if somethi... | def get_customization_for_nested_field(self, field_name) | Support of nested fields customization for:
* EmbeddedDocumentField
* NestedReference
* Compound fields with EmbeddedDocument as a child:
* ListField(EmbeddedDocument)/EmbeddedDocumentListField
* MapField(EmbeddedDocument)
Extracts fields, exclude, extra_kwarg... | 3.3627 | 3.227947 | 1.041746 |
# apply fields or exclude
if customization.fields is not None:
if len(customization.fields) == 0:
# customization fields are empty, set Meta.fields to '__all__'
serializer.Meta.fields = ALL_FIELDS
else:
serializer.Meta.fiel... | def apply_customization(self, serializer, customization) | Applies fields customization to a nested or embedded DocumentSerializer. | 2.64268 | 2.70354 | 0.977489 |
ret = super(DynamicDocumentSerializer, self).to_internal_value(data)
dynamic_data = self._get_dynamic_data(ret)
ret.update(dynamic_data)
return ret | def to_internal_value(self, data) | Updates _validated_data with dynamic data, i.e. data,
not listed in fields. | 3.665779 | 2.777268 | 1.319923 |
result = {}
for key in self.initial_data:
if key not in validated_data:
try:
field = self.fields[key]
# no exception? this is either SkipField or error
# in particular, this might be a read-only field
... | def _get_dynamic_data(self, validated_data) | Returns dict of data, not declared in serializer fields.
Should be called after self.is_valid(). | 5.579818 | 5.299282 | 1.052939 |
# Deal with the primary key.
if issubclass(model, mongoengine.EmbeddedDocument):
pk = None
else:
pk = model._fields[model._meta['id_field']]
# Deal with regular fields.
fields = OrderedDict()
# Deal with forward relationships.
# Pass forward relations since there is no... | def get_field_info(model) | Given a model class, returns a `FieldInfo` instance, which is a
`namedtuple`, containing metadata about the various field types on the model
including information about their relationships. | 3.75115 | 3.719635 | 1.008473 |
kwargs = {}
# The following will only be used by ModelField classes.
# Gets removed for everything else.
kwargs['model_field'] = model_field
if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
if h... | def get_field_kwargs(field_name, model_field) | Creating a default instance of a basic non-relational field. | 2.243674 | 2.217426 | 1.011837 |
model_field, related_model = relation_info
kwargs = {}
if related_model and not issubclass(related_model, EmbeddedDocument):
kwargs['queryset'] = related_model.objects
if model_field:
if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):
kwar... | def get_relation_kwargs(field_name, relation_info) | Creating a default instance of a flat relational field. | 2.307058 | 2.229753 | 1.03467 |
kwargs = get_relation_kwargs(field_name, relation_info)
kwargs.pop('queryset')
kwargs.pop('required')
kwargs['read_only'] = True
return kwargs | def get_nested_relation_kwargs(field_name, relation_info) | Creating a default instance of a nested serializer | 3.257339 | 2.822084 | 1.154232 |
'''
Density is the fraction of present connections to possible connections.
Parameters
----------
CIJ : NxN np.ndarray
directed weighted/binary connection matrix
Returns
-------
kden : float
density
N : int
number of vertices
k : int
number of ed... | def density_dir(CIJ) | Density is the fraction of present connections to possible connections.
Parameters
----------
CIJ : NxN np.ndarray
directed weighted/binary connection matrix
Returns
-------
kden : float
density
N : int
number of vertices
k : int
number of edges
Not... | 5.416613 | 1.774659 | 3.052199 |
'''
Density is the fraction of present connections to possible connections.
Parameters
----------
CIJ : NxN np.ndarray
undirected (weighted/binary) connection matrix
Returns
-------
kden : float
density
N : int
number of vertices
k : int
number o... | def density_und(CIJ) | Density is the fraction of present connections to possible connections.
Parameters
----------
CIJ : NxN np.ndarray
undirected (weighted/binary) connection matrix
Returns
-------
kden : float
density
N : int
number of vertices
k : int
number of edges
... | 5.262102 | 1.787529 | 2.943785 |
out = []
if self[name]:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
if prefix:
prefix = '~%s.' % prefix
autosum = []
others = []
for param, param_type, desc in self[name]:
... | def _str_member_list(self, name) | Generate a member listing, autosummary:: table where possible,
and a table where not. | 3.478632 | 3.376159 | 1.030352 |
'''
Node degree is the number of links connected to the node. The indegree
is the number of inward links and the outdegree is the number of
outward links.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connection matrix
Returns
-------
id : Nx1 np.n... | def degrees_dir(CIJ) | Node degree is the number of links connected to the node. The indegree
is the number of inward links and the outdegree is the number of
outward links.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connection matrix
Returns
-------
id : Nx1 np.ndarray
... | 3.289757 | 1.519968 | 2.164359 |
'''
Node degree is the number of links connected to the node.
Parameters
----------
CIJ : NxN np.ndarray
undirected binary/weighted connection matrix
Returns
-------
deg : Nx1 np.ndarray
node degree
Notes
-----
Weight information is discarded.
'''
C... | def degrees_und(CIJ) | Node degree is the number of links connected to the node.
Parameters
----------
CIJ : NxN np.ndarray
undirected binary/weighted connection matrix
Returns
-------
deg : Nx1 np.ndarray
node degree
Notes
-----
Weight information is discarded. | 4.70119 | 2.01598 | 2.331963 |
'''
This function returns a matrix in which the value of each element (u,v)
corresponds to the number of nodes that have u outgoing connections
and v incoming connections.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connnection matrix
Returns
-------... | def jdegree(CIJ) | This function returns a matrix in which the value of each element (u,v)
corresponds to the number of nodes that have u outgoing connections
and v incoming connections.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connnection matrix
Returns
-------
J : ZxZ... | 4.081714 | 2.033333 | 2.0074 |
'''
Node strength is the sum of weights of links connected to the node. The
instrength is the sum of inward link weights and the outstrength is the
sum of outward link weights.
Parameters
----------
CIJ : NxN np.ndarray
directed weighted connection matrix
Returns
-------
... | def strengths_dir(CIJ) | Node strength is the sum of weights of links connected to the node. The
instrength is the sum of inward link weights and the outstrength is the
sum of outward link weights.
Parameters
----------
CIJ : NxN np.ndarray
directed weighted connection matrix
Returns
-------
is : Nx1 n... | 3.672215 | 1.401278 | 2.620618 |
'''
Node strength is the sum of weights of links connected to the node.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
Returns
-------
Spos : Nx1 np.ndarray
nodal strength of positive weights
Sneg : Nx1 np.nd... | def strengths_und_sign(W) | Node strength is the sum of weights of links connected to the node.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
Returns
-------
Spos : Nx1 np.ndarray
nodal strength of positive weights
Sneg : Nx1 np.ndarray
... | 2.613986 | 1.595419 | 1.638432 |
'''
This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "local bridges", i.e.
edges th... | def edge_nei_overlap_bu(CIJ) | This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "local bridges", i.e.
edges that link comp... | 3.803211 | 1.635012 | 2.326106 |
'''
The m-th step generalized topological overlap measure (GTOM) quantifies
the extent to which a pair of nodes have similar m-th step neighbors.
Mth-step neighbors are nodes that are reachable by a path of at most
length m.
This function computes the the M x M generalized topological overlap
... | def gtom(adj, nr_steps) | The m-th step generalized topological overlap measure (GTOM) quantifies
the extent to which a pair of nodes have similar m-th step neighbors.
Mth-step neighbors are nodes that are reachable by a path of at most
length m.
This function computes the the M x M generalized topological overlap
measure (... | 4.74937 | 2.012497 | 2.359939 |
'''
For any two nodes u and v, the matching index computes the amount of
overlap in the connection patterns of u and v. Self-connections and
u-v connections are ignored. The matching index is a symmetric
quantity, similar to a correlation or a dot product.
Parameters
----------
CIJ : Nx... | def matching_ind(CIJ) | For any two nodes u and v, the matching index computes the amount of
overlap in the connection patterns of u and v. Self-connections and
u-v connections are ignored. The matching index is a symmetric
quantity, similar to a correlation or a dot product.
Parameters
----------
CIJ : NxN np.ndarray... | 2.003707 | 1.329492 | 1.507122 |
'''
M0 = MATCHING_IND_UND(CIJ) computes matching index for undirected
graph specified by adjacency matrix CIJ. Matching index is a measure of
similarity between two nodes' connectivity profiles (excluding their
mutual connection, should it exist).
Parameters
----------
CIJ : NxN np.ndar... | def matching_ind_und(CIJ0) | M0 = MATCHING_IND_UND(CIJ) computes matching index for undirected
graph specified by adjacency matrix CIJ. Matching index is a measure of
similarity between two nodes' connectivity profiles (excluding their
mutual connection, should it exist).
Parameters
----------
CIJ : NxN np.ndarray
... | 3.305867 | 2.367112 | 1.396582 |
'''
Calculates pairwise dice similarity for each vertex between two
matrices. Treats the matrices as binary and undirected.
Paramaters
----------
A1 : NxN np.ndarray
Matrix 1
A2 : NxN np.ndarray
Matrix 2
Returns
-------
D : Nx1 np.ndarray
dice similarity... | def dice_pairwise_und(a1, a2) | Calculates pairwise dice similarity for each vertex between two
matrices. Treats the matrices as binary and undirected.
Paramaters
----------
A1 : NxN np.ndarray
Matrix 1
A2 : NxN np.ndarray
Matrix 2
Returns
-------
D : Nx1 np.ndarray
dice similarity vector | 3.120005 | 1.9469 | 1.60255 |
'''
Returns the correlation coefficient between two flattened adjacency
matrices. Only the upper triangular part is used to avoid double counting
undirected matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
undirected matrix 1
A2 : Nx... | def corr_flat_und(a1, a2) | Returns the correlation coefficient between two flattened adjacency
matrices. Only the upper triangular part is used to avoid double counting
undirected matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
undirected matrix 1
A2 : NxN np.ndarray... | 4.063087 | 1.945834 | 2.088096 |
'''
Returns the correlation coefficient between two flattened adjacency
matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
directed matrix 1
A2 : NxN np.ndarray
directed matrix 2
Returns
-------
r : float
Correl... | def corr_flat_dir(a1, a2) | Returns the correlation coefficient between two flattened adjacency
matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
directed matrix 1
A2 : NxN np.ndarray
directed matrix 2
Returns
-------
r : float
Correlation coeffi... | 4.360463 | 2.251961 | 1.936296 |
'''
(X,Y,INDSORT) = GRID_COMMUNITIES(C) takes a vector of community
assignments C and returns three output arguments for visualizing the
communities. The third is INDSORT, which is an ordering of the vertices
so that nodes with the same community assignment are next to one
another. The first two... | def grid_communities(c) | (X,Y,INDSORT) = GRID_COMMUNITIES(C) takes a vector of community
assignments C and returns three output arguments for visualizing the
communities. The third is INDSORT, which is an ordering of the vertices
so that nodes with the same community assignment are next to one
another. The first two arguments a... | 5.789155 | 1.461806 | 3.960275 |
'''
This function reorders the connectivity matrix in order to place more
edges closer to the diagonal. This often helps in displaying community
structure, clusters, etc.
Parameters
----------
MAT : NxN np.ndarray
connection matrix
H : int
number of reordering attempts
... | def reorderMAT(m, H=5000, cost='line') | This function reorders the connectivity matrix in order to place more
edges closer to the diagonal. This often helps in displaying community
structure, clusters, etc.
Parameters
----------
MAT : NxN np.ndarray
connection matrix
H : int
number of reordering attempts
cost : st... | 4.798749 | 2.151283 | 2.230646 |
'''
This function writes a Pajek .net file from a numpy matrix
Parameters
----------
CIJ : NxN np.ndarray
adjacency matrix
fname : str
filename
directed : bool
True if the network is directed and False otherwise. The data format
may be required to know this f... | def writetoPAJ(CIJ, fname, directed) | This function writes a Pajek .net file from a numpy matrix
Parameters
----------
CIJ : NxN np.ndarray
adjacency matrix
fname : str
filename
directed : bool
True if the network is directed and False otherwise. The data format
may be required to know this for some reas... | 2.885186 | 1.668153 | 1.729569 |
'''
This function generates a random, directed network with a specified
number of fully connected modules linked together by evenly distributed
remaining random connections.
Parameters
----------
N : int
number of vertices (must be power of 2)
K : int
number of edges
... | def makeevenCIJ(n, k, sz_cl, seed=None) | This function generates a random, directed network with a specified
number of fully connected modules linked together by evenly distributed
remaining random connections.
Parameters
----------
N : int
number of vertices (must be power of 2)
K : int
number of edges
sz_cl : int... | 5.002484 | 3.068448 | 1.630298 |
'''
This function generates a directed network with a hierarchical modular
organization. All modules are fully connected and connection density
decays as 1/(E^n), with n = index of hierarchical level.
Parameters
----------
mx_lvl : int
number of hierarchical levels, N = 2^mx_lvl
... | def makefractalCIJ(mx_lvl, E, sz_cl, seed=None) | This function generates a directed network with a hierarchical modular
organization. All modules are fully connected and connection density
decays as 1/(E^n), with n = index of hierarchical level.
Parameters
----------
mx_lvl : int
number of hierarchical levels, N = 2^mx_lvl
E : int
... | 4.940172 | 2.511645 | 1.966907 |
'''
This function generates a directed random network with a specified
in-degree and out-degree sequence.
Parameters
----------
inv : Nx1 np.ndarray
in-degree vector
outv : Nx1 np.ndarray
out-degree vector
seed : hashable, optional
If None (default), use the np.r... | def makerandCIJdegreesfixed(inv, outv, seed=None) | This function generates a directed random network with a specified
in-degree and out-degree sequence.
Parameters
----------
inv : Nx1 np.ndarray
in-degree vector
outv : Nx1 np.ndarray
out-degree vector
seed : hashable, optional
If None (default), use the np.random's glob... | 3.436056 | 1.675727 | 2.050487 |
'''
This function generates a directed random network
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.random's global random state to generate random numbers.
Otherwise, use a ne... | def makerandCIJ_dir(n, k, seed=None) | This function generates a directed random network
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.random's global random state to generate random numbers.
Otherwise, use a new np.random.... | 5.304288 | 2.050092 | 2.587341 |
'''
This function generates a directed lattice network with toroidal
boundary counditions (i.e. with ring-like "wrapping around").
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.ran... | def makeringlatticeCIJ(n, k, seed=None) | This function generates a directed lattice network with toroidal
boundary counditions (i.e. with ring-like "wrapping around").
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.random's global... | 4.559684 | 2.061609 | 2.211711 |
'''
This function generates a directed network with a Gaussian drop-off in
edge density with increasing distance from the main diagonal. There are
toroidal boundary counditions (i.e. no ring-like "wrapping around").
Parameters
----------
N : int
number of vertices
K : int
... | def maketoeplitzCIJ(n, k, s, seed=None) | This function generates a directed network with a Gaussian drop-off in
edge density with increasing distance from the main diagonal. There are
toroidal boundary counditions (i.e. no ring-like "wrapping around").
Parameters
----------
N : int
number of vertices
K : int
number of ... | 6.575495 | 2.454883 | 2.678538 |
'''
This function randomizes a directed network, while preserving the in-
and out-degree distributions. In weighted networks, the function
preserves the out-strength but not the in-strength distributions.
Parameters
----------
W : NxN np.ndarray
directed binary/weighted connection m... | def randmio_dir(R, itr, seed=None) | This function randomizes a directed network, while preserving the in-
and out-degree distributions. In weighted networks, the function
preserves the out-strength but not the in-strength distributions.
Parameters
----------
W : NxN np.ndarray
directed binary/weighted connection matrix
it... | 3.468455 | 1.902794 | 1.822823 |
'''
This function randomizes an undirected network, while preserving the
degree distribution. The function does not preserve the strength
distribution in weighted networks.
Parameters
----------
W : NxN np.ndarray
undirected binary/weighted connection matrix
itr : int
re... | def randmio_und(R, itr, seed=None) | This function randomizes an undirected network, while preserving the
degree distribution. The function does not preserve the strength
distribution in weighted networks.
Parameters
----------
W : NxN np.ndarray
undirected binary/weighted connection matrix
itr : int
rewiring param... | 3.291239 | 2.198465 | 1.497062 |
'''
This function randomizes an undirected weighted network with positive
and negative weights, while simultaneously preserving the degree
distribution of positive and negative weights. The function does not
preserve the strength distribution in weighted networks.
Parameters
----------
... | def randmio_und_signed(R, itr, seed=None) | This function randomizes an undirected weighted network with positive
and negative weights, while simultaneously preserving the degree
distribution of positive and negative weights. The function does not
preserve the strength distribution in weighted networks.
Parameters
----------
W : NxN np.n... | 3.45406 | 1.989981 | 1.735725 |
'''
A = RANDOMIZE_GRAPH_PARTIAL_UND(A,B,MAXSWAP) takes adjacency matrices A
and B and attempts to randomize matrix A by performing MAXSWAP
rewirings. The rewirings will avoid any spots where matrix B is
nonzero.
Parameters
----------
A : NxN np.ndarray
undirected adjacency matri... | def randomize_graph_partial_und(A, B, maxswap, seed=None) | A = RANDOMIZE_GRAPH_PARTIAL_UND(A,B,MAXSWAP) takes adjacency matrices A
and B and attempts to randomize matrix A by performing MAXSWAP
rewirings. The rewirings will avoid any spots where matrix B is
nonzero.
Parameters
----------
A : NxN np.ndarray
undirected adjacency matrix to randomi... | 3.51798 | 1.876487 | 1.874769 |
'''
Generates synthetic networks with parameters provided and evaluates their
energy function. The energy function is defined as in Betzel et al. 2016.
Basically it takes the Kolmogorov-Smirnov statistics of 4 network
measures; comparing the degree distributions, clustering coefficients,
between... | def evaluate_generative_model(A, Atgt, D, eta, gamma=None,
model_type='matching', model_var='powerlaw', epsilon=1e-6, seed=None) | Generates synthetic networks with parameters provided and evaluates their
energy function. The energy function is defined as in Betzel et al. 2016.
Basically it takes the Kolmogorov-Smirnov statistics of 4 network
measures; comparing the degree distributions, clustering coefficients,
betweenness central... | 3.6926 | 2.437168 | 1.515119 |
'''
Node betweenness centrality is the fraction of all shortest paths in
the network that contain a given node. Nodes with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
A : NxN np.ndarray
binary directed/undirected conne... | def betweenness_bin(G) | Node betweenness centrality is the fraction of all shortest paths in
the network that contain a given node. Nodes with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
A : NxN np.ndarray
binary directed/undirected connection matrix... | 4.312603 | 2.920793 | 1.476518 |
'''
Node betweenness centrality is the fraction of all shortest paths in
the network that contain a given node. Nodes with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
L : NxN np.ndarray
directed/undirected weighted con... | def betweenness_wei(G) | Node betweenness centrality is the fraction of all shortest paths in
the network that contain a given node. Nodes with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
L : NxN np.ndarray
directed/undirected weighted connection matr... | 4.294555 | 2.598385 | 1.652778 |
'''
The Shannon-entropy based diversity coefficient measures the diversity
of intermodular connections of individual nodes and ranges from 0 to 1.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
ci : Nx1 np.ndarray
com... | def diversity_coef_sign(W, ci) | The Shannon-entropy based diversity coefficient measures the diversity
of intermodular connections of individual nodes and ranges from 0 to 1.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
ci : Nx1 np.ndarray
community affil... | 3.357197 | 2.233328 | 1.503226 |
'''
Edge betweenness centrality is the fraction of all shortest paths in
the network that contain a given edge. Edges with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
A : NxN np.ndarray
binary directed/undirected conne... | def edge_betweenness_bin(G) | Edge betweenness centrality is the fraction of all shortest paths in
the network that contain a given edge. Edges with high values of
betweenness centrality participate in a large number of shortest paths.
Parameters
----------
A : NxN np.ndarray
binary directed/undirected connection matrix... | 3.697997 | 2.677111 | 1.381339 |
'''
Eigenector centrality is a self-referential measure of centrality:
nodes have high eigenvector centrality if they connect to other nodes
that have high eigenvector centrality. The eigenvector centrality of
node i is equivalent to the ith element in the eigenvector
corresponding to the larges... | def eigenvector_centrality_und(CIJ) | Eigenector centrality is a self-referential measure of centrality:
nodes have high eigenvector centrality if they connect to other nodes
that have high eigenvector centrality. The eigenvector centrality of
node i is equivalent to the ith element in the eigenvector
corresponding to the largest eigenvalue... | 4.175122 | 1.635952 | 2.552106 |
'''
Shortcuts are central edges which significantly reduce the
characteristic path length in the network.
Parameters
----------
CIJ : NxN np.ndarray
binary directed connection matrix
Returns
-------
Erange : NxN np.ndarray
range for each edge, i.e. the length of the... | def erange(CIJ) | Shortcuts are central edges which significantly reduce the
characteristic path length in the network.
Parameters
----------
CIJ : NxN np.ndarray
binary directed connection matrix
Returns
-------
Erange : NxN np.ndarray
range for each edge, i.e. the length of the shortest pa... | 5.408083 | 2.406634 | 2.247156 |
'''
Computes the flow coefficient for each node and averaged over the
network, as described in Honey et al. (2007) PNAS. The flow coefficient
is similar to betweenness centrality, but works on a local
neighborhood. It is mathematically related to the clustering
coefficient (cc) at each node as,... | def flow_coef_bd(CIJ) | Computes the flow coefficient for each node and averaged over the
network, as described in Honey et al. (2007) PNAS. The flow coefficient
is similar to betweenness centrality, but works on a local
neighborhood. It is mathematically related to the clustering
coefficient (cc) at each node as, fc+cc <= 1.... | 4.075832 | 2.053342 | 1.984975 |
'''
The gateway coefficient is a variant of participation coefficient.
It is weighted by how critical the connections are to intermodular
connectivity (e.g. if a node is the only connection between its
module and another module, it will have a higher gateway coefficient,
unlike participation coe... | def gateway_coef_sign(W, ci, centrality_type='degree') | The gateway coefficient is a variant of participation coefficient.
It is weighted by how critical the connections are to intermodular
connectivity (e.g. if a node is the only connection between its
module and another module, it will have a higher gateway coefficient,
unlike participation coefficient).
... | 4.683669 | 2.565411 | 1.8257 |
'''
The k-core is the largest subgraph comprising nodes of degree at least
k. The coreness of a node is k if the node belongs to the k-core but
not to the (k+1)-core. This function computes k-coreness of all nodes
for a given binary directed connection matrix.
Parameters
----------
CIJ ... | def kcoreness_centrality_bd(CIJ) | The k-core is the largest subgraph comprising nodes of degree at least
k. The coreness of a node is k if the node belongs to the k-core but
not to the (k+1)-core. This function computes k-coreness of all nodes
for a given binary directed connection matrix.
Parameters
----------
CIJ : NxN np.nda... | 4.033648 | 1.834467 | 2.198812 |
'''
The k-core is the largest subgraph comprising nodes of degree at least
k. The coreness of a node is k if the node belongs to the k-core but
not to the (k+1)-core. This function computes the coreness of all nodes
for a given binary undirected connection matrix.
Parameters
----------
... | def kcoreness_centrality_bu(CIJ) | The k-core is the largest subgraph comprising nodes of degree at least
k. The coreness of a node is k if the node belongs to the k-core but
not to the (k+1)-core. This function computes the coreness of all nodes
for a given binary undirected connection matrix.
Parameters
----------
CIJ : NxN np... | 3.952565 | 2.216538 | 1.783215 |
'''
The within-module degree z-score is a within-module version of degree
centrality.
Parameters
----------
W : NxN np.narray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.array_like
community affiliation vector
flag : int
Graph type. 0: undir... | def module_degree_zscore(W, ci, flag=0) | The within-module degree z-score is a within-module version of degree
centrality.
Parameters
----------
W : NxN np.narray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.array_like
community affiliation vector
flag : int
Graph type. 0: undirected graph ... | 3.321903 | 1.83585 | 1.809463 |
'''
The PageRank centrality is a variant of eigenvector centrality. This
function computes the PageRank centrality of each vertex in a graph.
Formally, PageRank is defined as the stationary distribution achieved
by instantiating a Markov chain on a graph. The PageRank centrality of
a given vert... | def pagerank_centrality(A, d, falff=None) | The PageRank centrality is a variant of eigenvector centrality. This
function computes the PageRank centrality of each vertex in a graph.
Formally, PageRank is defined as the stationary distribution achieved
by instantiating a Markov chain on a graph. The PageRank centrality of
a given vertex, then, is... | 5.255411 | 1.392561 | 3.773919 |
'''
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
F... | def participation_coef(W, ci, degree='undirected') | Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
Flag to descr... | 4.562017 | 2.605152 | 1.751152 |
'''
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection
must be as scipy.sparse.csr matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
Flag to descri... | def participation_coef_sparse(W, ci, degree='undirected') | Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection
must be as scipy.sparse.csr matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
Flag to describe nat... | 4.792876 | 2.563323 | 1.86979 |
'''
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
ci : Nx1 np.ndarray
community affiliation vector
Returns
... | def participation_coef_sign(W, ci) | Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
ci : Nx1 np.ndarray
community affiliation vector
Returns
-------
... | 4.022243 | 2.924196 | 1.375504 |
'''
The subgraph centrality of a node is a weighted sum of closed walks of
different lengths in the network starting and ending at the node. This
function returns a vector of subgraph centralities for each node of the
network.
Parameters
----------
CIJ : NxN np.ndarray
binary ad... | def subgraph_centrality(CIJ) | The subgraph centrality of a node is a weighted sum of closed walks of
different lengths in the network starting and ending at the node. This
function returns a vector of subgraph centralities for each node of the
network.
Parameters
----------
CIJ : NxN np.ndarray
binary adjacency matr... | 5.457863 | 2.484603 | 2.196674 |
'''
Functional motifs are subsets of connection patterns embedded within
anatomical motifs. Motif frequency is the frequency of occurrence of
motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 13xN np.nda... | def motif3funct_bin(A) | Functional motifs are subsets of connection patterns embedded within
anatomical motifs. Motif frequency is the frequency of occurrence of
motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 13xN np.ndarray
... | 3.824968 | 2.998439 | 1.275653 |
'''
Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 13xN np.ndarray
motif frequency matrix
... | def motif3struct_bin(A) | Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 13xN np.ndarray
motif frequency matrix
f : 13x1 n... | 3.263084 | 2.592036 | 1.258888 |
'''
Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 199xN np.ndarray
motif frequency matrix
... | def motif4struct_bin(A) | Structural motifs are patterns of local connectivity. Motif frequency
is the frequency of occurrence of motifs around a node.
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
F : 199xN np.ndarray
motif frequency matrix
f : 199x1... | 2.585649 | 2.190686 | 1.180292 |
'''
This function thresholds the connectivity matrix by absolute weight
magnitude. All weights below the given threshold, and all weights
on the main diagonal (self-self connections) are set to 0.
If copy is not set, this function will *modify W in place.*
Parameters
----------
W : np.... | def threshold_absolute(W, thr, copy=True) | This function thresholds the connectivity matrix by absolute weight
magnitude. All weights below the given threshold, and all weights
on the main diagonal (self-self connections) are set to 0.
If copy is not set, this function will *modify W in place.*
Parameters
----------
W : np.ndarray
... | 4.005501 | 1.47222 | 2.720722 |
'''
W_bin = weight_conversion(W, 'binarize');
W_nrm = weight_conversion(W, 'normalize');
L = weight_conversion(W, 'lengths');
This function may either binarize an input weighted connection matrix,
normalize an input weighted connection matrix or convert an input
weighted connection matrix t... | def weight_conversion(W, wcm, copy=True) | W_bin = weight_conversion(W, 'binarize');
W_nrm = weight_conversion(W, 'normalize');
L = weight_conversion(W, 'lengths');
This function may either binarize an input weighted connection matrix,
normalize an input weighted connection matrix or convert an input
weighted connection matrix to a weighted... | 5.161171 | 1.164079 | 4.433694 |
'''
Binarizes an input weighted connection matrix. If copy is not set, this
function will *modify W in place.*
Parameters
----------
W : NxN np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a copy of the matrix. Otherwise, modifies the matrix
in ... | def binarize(W, copy=True) | Binarizes an input weighted connection matrix. If copy is not set, this
function will *modify W in place.*
Parameters
----------
W : NxN np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a copy of the matrix. Otherwise, modifies the matrix
in place. Defau... | 3.793289 | 1.553915 | 2.441118 |
'''
Normalizes an input weighted connection matrix. If copy is not set, this
function will *modify W in place.*
Parameters
----------
W : np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a copy of the matrix. Otherwise, modifies the matrix
in pla... | def normalize(W, copy=True) | Normalizes an input weighted connection matrix. If copy is not set, this
function will *modify W in place.*
Parameters
----------
W : np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a copy of the matrix. Otherwise, modifies the matrix
in place. Default ... | 3.889712 | 1.58529 | 2.453628 |
'''
Inverts elementwise the weights in an input connection matrix.
In other words, change the from the matrix of internode strengths to the
matrix of internode distances.
If copy is not set, this function will *modify W in place.*
Parameters
----------
W : np.ndarray
weighted c... | def invert(W, copy=True) | Inverts elementwise the weights in an input connection matrix.
In other words, change the from the matrix of internode strengths to the
matrix of internode distances.
If copy is not set, this function will *modify W in place.*
Parameters
----------
W : np.ndarray
weighted connectivity ... | 4.837028 | 1.529413 | 3.162669 |
'''
Fix a bunch of common problems. More specifically, remove Inf and NaN,
ensure exact binariness and symmetry (i.e. remove floating point
instability), and zero diagonal.
Parameters
----------
W : np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a ... | def autofix(W, copy=True) | Fix a bunch of common problems. More specifically, remove Inf and NaN,
ensure exact binariness and symmetry (i.e. remove floating point
instability), and zero diagonal.
Parameters
----------
W : np.ndarray
weighted connectivity matrix
copy : bool
if True, returns a copy of the ... | 3.546703 | 1.7869 | 1.984836 |
'''
Takes as input a set of vertex partitions CI of
dimensions [vertex x partition]. Each column in CI contains the
assignments of each vertex to a class/community/module. This function
aggregates the partitions in CI into a square [vertex x vertex]
agreement matrix D, whose elements indicate th... | def agreement(ci, buffsz=1000) | Takes as input a set of vertex partitions CI of
dimensions [vertex x partition]. Each column in CI contains the
assignments of each vertex to a class/community/module. This function
aggregates the partitions in CI into a square [vertex x vertex]
agreement matrix D, whose elements indicate the number of ... | 4.843616 | 1.665178 | 2.908767 |
'''
D = AGREEMENT_WEIGHTED(CI,WTS) is identical to AGREEMENT, with the
exception that each partitions contribution is weighted according to
the corresponding scalar value stored in the vector WTS. As an example,
suppose CI contained partitions obtained using some heuristic for
maximizing modular... | def agreement_weighted(ci, wts) | D = AGREEMENT_WEIGHTED(CI,WTS) is identical to AGREEMENT, with the
exception that each partitions contribution is weighted according to
the corresponding scalar value stored in the vector WTS. As an example,
suppose CI contained partitions obtained using some heuristic for
maximizing modularity. A possi... | 7.127846 | 1.605926 | 4.438464 |
'''
The clustering coefficient is the fraction of triangles around a node
(equiv. the fraction of nodes neighbors that are neighbors of each other).
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
C : Nx1 np.ndarray
cluster... | def clustering_coef_bd(A) | The clustering coefficient is the fraction of triangles around a node
(equiv. the fraction of nodes neighbors that are neighbors of each other).
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coeffici... | 7.036688 | 1.793374 | 3.923715 |
'''
The clustering coefficient is the fraction of triangles around a node
(equiv. the fraction of nodes neighbors that are neighbors of each other).
Parameters
----------
A : NxN np.ndarray
binary undirected connection matrix
Returns
-------
C : Nx1 np.ndarray
clust... | def clustering_coef_bu(G) | The clustering coefficient is the fraction of triangles around a node
(equiv. the fraction of nodes neighbors that are neighbors of each other).
Parameters
----------
A : NxN np.ndarray
binary undirected connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coeffi... | 4.052508 | 2.102351 | 1.927607 |
'''
The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted directed connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector
Notes
-----
Meth... | def clustering_coef_wd(W) | The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted directed connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector
Notes
-----
Methodological n... | 6.696708 | 2.536321 | 2.640323 |
'''
The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector
'''
K = np.array(np... | def clustering_coef_wu(W) | The weighted clustering coefficient is the average "intensity" of
triangles around a node.
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
C : Nx1 np.ndarray
clustering coefficient vector | 4.874584 | 2.961513 | 1.645978 |
'''
Returns the components of an undirected graph specified by the binary and
undirected adjacency matrix adj. Components and their constitutent nodes
are assigned the same index and stored in the vector, comps. The vector,
comp_sizes, contains the number of nodes beloning to each component.
Pa... | def get_components(A, no_depend=False) | Returns the components of an undirected graph specified by the binary and
undirected adjacency matrix adj. Components and their constitutent nodes
are assigned the same index and stored in the vector, comps. The vector,
comp_sizes, contains the number of nodes beloning to each component.
Parameters
... | 5.171756 | 1.983778 | 2.607024 |
'''
Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
T : float
transitivity scalar
Notes
----... | def transitivity_bd(A) | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
A : NxN np.ndarray
binary directed connection matrix
Returns
-------
T : float
transitivity scalar
Notes
-----
Method... | 7.731163 | 1.705841 | 4.532171 |
'''
Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
A : NxN np.ndarray
binary undirected connection matrix
Returns
-------
T : float
transitivity scalar
'''
tri3 ... | def transitivity_bu(A) | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
A : NxN np.ndarray
binary undirected connection matrix
Returns
-------
T : float
transitivity scalar | 4.89906 | 1.95035 | 2.511887 |
'''
Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
T : int
transitivity scalar
'''
K = n... | def transitivity_wu(W) | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
T : int
transitivity scalar | 5.743527 | 2.695906 | 2.130463 |
'''
Convert from a community index vector to a 2D python list of modules
The list is a pure python list, not requiring numpy.
Parameters
----------
ci : Nx1 np.ndarray
the community index vector
zeroindexed : bool
If True, ci uses zero-indexing (lowest value is 0). Defaults ... | def ci2ls(ci) | Convert from a community index vector to a 2D python list of modules
The list is a pure python list, not requiring numpy.
Parameters
----------
ci : Nx1 np.ndarray
the community index vector
zeroindexed : bool
If True, ci uses zero-indexing (lowest value is 0). Defaults to False.
... | 6.065526 | 2.007501 | 3.021432 |
'''
Convert from a 2D python list of modules to a community index vector.
The list is a pure python list, not requiring numpy.
Parameters
----------
ls : listof(list)
pure python list with lowest value zero-indexed
(regardless of value of zeroindexed parameter)
zeroindexed :... | def ls2ci(ls, zeroindexed=False) | Convert from a 2D python list of modules to a community index vector.
The list is a pure python list, not requiring numpy.
Parameters
----------
ls : listof(list)
pure python list with lowest value zero-indexed
(regardless of value of zeroindexed parameter)
zeroindexed : bool
... | 6.060842 | 2.14356 | 2.827465 |
out = np.squeeze(arr, *args, **kwargs)
if np.ndim(out) == 0:
out = out.reshape((1,))
return out | def _safe_squeeze(arr, *args, **kwargs) | numpy.squeeze will reduce a 1-item array down to a zero-dimensional "array",
which is not necessarily desirable.
This function does the squeeze operation, but ensures that there is at least
1 dimension in the output. | 2.473917 | 2.765452 | 0.89458 |
'''
This function quantifies the distance between pairs of community
partitions with information theoretic measures.
Parameters
----------
cx : Nx1 np.ndarray
community affiliation vector X
cy : Nx1 np.ndarray
community affiliation vector Y
Returns
-------
VIn :... | def partition_distance(cx, cy) | This function quantifies the distance between pairs of community
partitions with information theoretic measures.
Parameters
----------
cx : Nx1 np.ndarray
community affiliation vector X
cy : Nx1 np.ndarray
community affiliation vector Y
Returns
-------
VIn : Nx1 np.ndar... | 2.618316 | 1.442066 | 1.81567 |
'''
The binary reachability matrix describes reachability between all pairs
of nodes. An entry (u,v)=1 means that there exists a path from node u
to node v; alternatively (u,v)=0.
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the le... | def breadthdist(CIJ) | The binary reachability matrix describes reachability between all pairs
of nodes. An entry (u,v)=1 means that there exists a path from node u
to node v; alternatively (u,v)=0.
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the length of shor... | 3.955448 | 1.44159 | 2.743809 |
'''
Implementation of breadth-first search.
Parameters
----------
CIJ : NxN np.ndarray
binary directed/undirected connection matrix
source : int
source vertex
Returns
-------
distance : Nx1 np.ndarray
vector of distances between source and ith vertex (0 for ... | def breadth(CIJ, source) | Implementation of breadth-first search.
Parameters
----------
CIJ : NxN np.ndarray
binary directed/undirected connection matrix
source : int
source vertex
Returns
-------
distance : Nx1 np.ndarray
vector of distances between source and ith vertex (0 for source)
... | 3.548594 | 1.848516 | 1.919699 |
'''
The characteristic path length is the average shortest path length in
the network. The global efficiency is the average inverse shortest path
length in the network.
Parameters
----------
D : NxN np.ndarray
distance matrix
include_diagonal : bool
If True, include the ... | def charpath(D, include_diagonal=False, include_infinite=True) | The characteristic path length is the average shortest path length in
the network. The global efficiency is the average inverse shortest path
length in the network.
Parameters
----------
D : NxN np.ndarray
distance matrix
include_diagonal : bool
If True, include the weights on t... | 4.422065 | 1.776863 | 2.488692 |
'''
Cycles are paths which begin and end at the same node. Cycle
probability for path length d, is the fraction of all paths of length
d-1 that may be extended to form cycles of length d.
Parameters
----------
Pq : NxNxQ np.ndarray
Path matrix with Pq[i,j,q] = number of paths from i... | def cycprob(Pq) | Cycles are paths which begin and end at the same node. Cycle
probability for path length d, is the fraction of all paths of length
d-1 that may be extended to form cycles of length d.
Parameters
----------
Pq : NxNxQ np.ndarray
Path matrix with Pq[i,j,q] = number of paths from i to j of len... | 3.001348 | 1.78748 | 1.679094 |
'''
The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the length of shortest path
from node u to node v. The average shortest path length is the
characteristic path length of the network.
Parameters
----------
A : NxN np.ndarray... | def distance_bin(G) | The distance matrix contains lengths of shortest paths between all
pairs of nodes. An entry (u,v) represents the length of shortest path
from node u to node v. The average shortest path length is the
characteristic path length of the network.
Parameters
----------
A : NxN np.ndarray
bin... | 4.978838 | 2.326567 | 2.139993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.