code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
results = []
cache = {}
tuning_options["scaling"] = False
#build a bounds array as needed for the optimizer
bounds = get_bounds(tuning_options.tune_params)
args = (kernel_options, tuning_options, runner, results, cache)
#call the differential evolution optimizer
opt_result = dif... | def tune(runner, kernel_options, device_options, tuning_options) | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: kernel_tuner.interface.Options
:param device_options... | 5.730134 | 5.440999 | 1.05314 |
results = []
cache = {}
#scale variables in x because PSO works with velocities to visit different configurations
tuning_options["scaling"] = True
#using this instead of get_bounds because scaling is used
bounds, _, _ = get_bounds_x0_eps(tuning_options)
args = (kernel_options, tunin... | def tune(runner, kernel_options, device_options, tuning_options) | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: dict
:param device_options: A dictionary with all op... | 4.167645 | 4.072231 | 1.02343 |
dna_size = len(tuning_options.tune_params.keys())
pop_size = 20
generations = 100
tuning_options["scaling"] = False
tune_params = tuning_options.tune_params
population = random_population(dna_size, pop_size, tune_params)
best_time = 1e20
all_results = []
cache = {}
for ... | def tune(runner, kernel_options, device_options, tuning_options) | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: kernel_tuner.interface.Options
:param device_options... | 3.599841 | 3.392683 | 1.06106 |
random_number = random.betavariate(1, 2.5) #increased probability of selecting members early in the list
#random_number = random.random()
ind = int(random_number*len(population))
ind = min(max(ind, 0), len(population)-1)
return population[ind][0] | def weighted_choice(population) | Randomly select, fitness determines probability of being selected | 5.054161 | 5.038915 | 1.003026 |
population = []
for _ in range(pop_size):
dna = []
for i in range(dna_size):
dna.append(random_val(i, tune_params))
population.append(dna)
return population | def random_population(dna_size, pop_size, tune_params) | create a random population | 2.1866 | 2.098023 | 1.042219 |
key = list(tune_params.keys())[index]
return random.choice(tune_params[key]) | def random_val(index, tune_params) | return a random value for a parameter | 2.964125 | 2.903581 | 1.020852 |
dna_out = []
mutation_chance = 10
for i in range(dna_size):
if int(random.random()*mutation_chance) == 1:
dna_out.append(random_val(i, tune_params))
else:
dna_out.append(dna[i])
return dna_out | def mutate(dna, dna_size, tune_params) | Mutate DNA with 1/mutation_chance chance | 2.692319 | 2.545232 | 1.057789 |
pos = int(random.random()*len(dna1))
if random.random() < 0.5:
return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
else:
return (dna2[:pos]+dna1[pos:], dna1[:pos]+dna2[pos:]) | def crossover(dna1, dna2) | crossover dna1 and dna2 at a random index | 1.704796 | 1.674692 | 1.017976 |
results = []
cache = {}
method = tuning_options.method
#scale variables in x to make 'eps' relevant for multiple variables
tuning_options["scaling"] = True
bounds, x0, _ = get_bounds_x0_eps(tuning_options)
kwargs = setup_method_arguments(method, bounds)
options = setup_method_op... | def tune(runner, kernel_options, device_options, tuning_options) | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: kernel_tuner.interface.Options
:param device_options... | 5.94973 | 5.765334 | 1.031984 |
error_time = 1e20
logging.debug('_cost_func called')
logging.debug('x: ' + str(x))
x_key = ",".join([str(i) for i in x])
if x_key in cache:
return cache[x_key]
#snap values in x to nearest actual value for each parameter unscale x if needed
if tuning_options.scaling:
... | def _cost_func(x, kernel_options, tuning_options, runner, results, cache) | Cost function used by minimize | 3.374675 | 3.346135 | 1.008529 |
values = tuning_options.tune_params.values()
if tuning_options.scaling:
#bounds = [(0, 1) for _ in values]
#x0 = [0.5 for _ in bounds]
eps = numpy.amin([1.0/len(v) for v in values])
#reducing interval from [0, 1] to [0, eps*len(v)]
bounds = [(0, eps*len(v)) for v i... | def get_bounds_x0_eps(tuning_options) | compute bounds, x0 (the initial guess), and eps | 3.046865 | 2.942141 | 1.035594 |
bounds = []
for values in tune_params.values():
sorted_values = numpy.sort(values)
bounds.append((sorted_values[0], sorted_values[-1]))
return bounds | def get_bounds(tune_params) | create a bounds array from the tunable parameters | 2.924216 | 2.637511 | 1.108703 |
kwargs = {}
#pass size of parameter space as max iterations to methods that support it
#it seems not all methods iterpret this value in the same manner
maxiter = numpy.prod([len(v) for v in tuning_options.tune_params.values()])
kwargs['maxiter'] = maxiter
if method in ["Nelder-Mead", "Powe... | def setup_method_options(method, tuning_options) | prepare method specific options | 3.637288 | 3.543112 | 1.02658 |
params = []
for i, k in enumerate(tune_params.keys()):
values = numpy.array(tune_params[k])
idx = numpy.abs(values-x[i]).argmin()
params.append(int(values[idx]))
return params | def snap_to_nearest_config(x, tune_params) | helper func that for each param selects the closest actual value | 2.969938 | 2.858811 | 1.038872 |
x_u = [i for i in x]
for i, v in enumerate(tune_params.values()):
#create an evenly spaced linear space to map [0,1]-interval
#to actual values, giving each value an equal chance
#pad = 0.5/len(v) #use when interval is [0,1]
pad = 0.5*eps #use when interval is [0, eps*... | def unscale_and_snap_to_nearest(x, tune_params, eps) | helper func that snaps a scaled variable to the nearest config | 5.508785 | 5.541311 | 0.99413 |
logging.debug('sequential runner started for ' + kernel_options.kernel_name)
results = []
#iterate over parameter space
for element in parameter_space:
params = OrderedDict(zip(tuning_options.tune_params.keys(), element))
time = self.dev.compile_and_be... | def run(self, parameter_space, kernel_options, tuning_options) | Iterate through the entire parameter space using a single Python process
:param parameter_space: The parameter space as an iterable.
:type parameter_space: iterable
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: kernel_tuner.interface.Options... | 6.654332 | 6.112992 | 1.088556 |
results = []
cache = {}
method = tuning_options.method
#scale variables in x to make 'eps' relevant for multiple variables
tuning_options["scaling"] = True
bounds, x0, eps = get_bounds_x0_eps(tuning_options)
kwargs = setup_method_arguments(method, bounds)
options = setup_method... | def tune(runner, kernel_options, device_options, tuning_options) | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: dict
:param device_options: A dictionary with all op... | 5.02438 | 4.970342 | 1.010872 |
return drv.pagelocked_empty(int(n), dtype, order='C', mem_flags=drv.host_alloc_flags.PORTABLE) | def allocate(n, dtype=numpy.float32) | allocate context-portable pinned host memory | 7.845421 | 7.443726 | 1.053964 |
gpu_args = []
for arg in arguments:
# if arg i is a numpy array copy to device
if isinstance(arg, numpy.ndarray):
alloc = drv.mem_alloc(arg.nbytes)
self.allocations.append(alloc)
gpu_args.append(alloc)
drv.m... | def ready_argument_list(self, arguments) | ready argument list to be passed to the kernel, allocates gpu mem
:param arguments: List of arguments to be passed to the kernel.
The order should match the argument list on the CUDA kernel.
Allowed values are numpy.ndarray, and/or numpy.int32, numpy.float32, and so on.
:type ar... | 3.638385 | 3.171221 | 1.147314 |
try:
no_extern_c = 'extern "C"' in kernel_string
compiler_options = ['-Xcompiler=-Wall']
if self.compiler_options:
compiler_options += self.compiler_options
self.current_module = self.source_mod(kernel_string, options=compiler_options + ... | def compile(self, kernel_name, kernel_string) | call the CUDA compiler to compile the kernel, return the device function
:param kernel_name: The name of the kernel to be compiled, used to lookup the
function after compilation.
:type kernel_name: string
:param kernel_string: The CUDA kernel code that contains the function `kernel... | 4.718875 | 4.620927 | 1.021197 |
start = drv.Event()
end = drv.Event()
time = []
for _ in range(self.iterations):
self.context.synchronize()
start.record()
self.run_kernel(func, gpu_args, threads, grid)
end.record()
self.context.synchronize()
... | def benchmark(self, func, gpu_args, threads, grid, times) | runs the kernel and measures time repeatedly, returns average time
Runs the kernel and measures kernel execution time repeatedly, number of
iterations is set during the creation of CudaFunctions. Benchmark returns
a robust average, from all measurements the fastest and slowest runs are
... | 2.652552 | 2.500003 | 1.061019 |
logging.debug('copy_constant_memory_args called')
logging.debug('current module: ' + str(self.current_module))
for k, v in cmem_args.items():
symbol = self.current_module.get_global(k)[0]
logging.debug('copying to symbol: ' + str(symbol))
logging.debu... | def copy_constant_memory_args(self, cmem_args) | adds constant memory arguments to the most recently compiled module
:param cmem_args: A dictionary containing the data to be passed to the
device constant memory. The format to be used is as follows: A
string key is used to name the constant memory symbol to which the
value ... | 3.243122 | 2.810128 | 1.154083 |
filter_mode_map = { 'point': drv.filter_mode.POINT,
'linear': drv.filter_mode.LINEAR }
address_mode_map = { 'border': drv.address_mode.BORDER,
'clamp': drv.address_mode.CLAMP,
'mirror': drv.address_mode.MIRR... | def copy_texture_memory_args(self, texmem_args) | adds texture memory arguments to the most recently compiled module
:param texmem_args: A dictionary containing the data to be passed to the
device texture memory. TODO | 2.40706 | 2.347945 | 1.025178 |
func(*gpu_args, block=threads, grid=grid, texrefs=self.texrefs) | def run_kernel(self, func, gpu_args, threads, grid) | runs the CUDA kernel passed as 'func'
:param func: A PyCuda kernel compiled for this specific kernel configuration
:type func: pycuda.driver.Function
:param gpu_args: A list of arguments to the kernel, order should match the
order in the code. Allowed values are either variables in... | 5.616081 | 8.725694 | 0.643626 |
drv.memset_d8(allocation, value, size) | def memset(self, allocation, value, size) | set the memory in allocation to the value in value
:param allocation: A GPU memory allocation unit
:type allocation: pycuda.driver.DeviceAllocation
:param value: The value to set the memory to
:type value: a single 8-bit unsigned int
:param size: The size of to the allocation ... | 9.530638 | 13.618479 | 0.699831 |
if isinstance(src, drv.DeviceAllocation):
drv.memcpy_dtoh(dest, src)
else:
dest = src | def memcpy_dtoh(self, dest, src) | perform a device to host memory copy
:param dest: A numpy array in host memory to store the data
:type dest: numpy.ndarray
:param src: A GPU memory allocation unit
:type src: pycuda.driver.DeviceAllocation | 5.52231 | 4.95401 | 1.114715 |
if isinstance(dest, drv.DeviceAllocation):
drv.memcpy_htod(dest, src)
else:
dest = src | def memcpy_htod(self, dest, src) | perform a host to device memory copy
:param dest: A GPU memory allocation unit
:type dest: pycuda.driver.DeviceAllocation
:param src: A numpy array in host memory to store the data
:type src: numpy.ndarray | 5.79091 | 5.098469 | 1.135814 |
results = []
cache = {}
# SA works with real parameter values and does not need scaling
tuning_options["scaling"] = False
args = (kernel_options, tuning_options, runner, results, cache)
tune_params = tuning_options.tune_params
# optimization parameters
T = 1.0
T_min = 0.001
... | def tune(runner, kernel_options, device_options, tuning_options) | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: dict
:param device_options: A dictionary with all op... | 3.896374 | 3.83248 | 1.016672 |
#if start pos is not valid, always move
if old_cost == 1e20:
return 1.0
#if we have found a valid ps before, never move to nonvalid pos
if new_cost == 1e20:
return 0.0
#always move if new cost is better
if new_cost < old_cost:
return 1.0
#maybe move if old cost i... | def acceptance_prob(old_cost, new_cost, T) | annealing equation, with modifications to work towards a lower value | 5.519389 | 5.654478 | 0.976109 |
size = len(pos)
pos_out = []
# random mutation
# expected value is set that values all dimensions attempt to get mutated
for i in range(size):
key = list(tune_params.keys())[i]
values = tune_params[key]
if random.random() < 0.2: #replace with random value
n... | def neighbor(pos, tune_params) | return a random neighbor of pos | 4.208025 | 4.194338 | 1.003263 |
tune_params = tuning_options.tune_params
restrictions = tuning_options.restrictions
verbose = tuning_options.verbose
#compute cartesian product of all tunable parameters
parameter_space = itertools.product(*tune_params.values())
#check for search space restrictions
if restrictions is... | def tune(runner, kernel_options, device_options, tuning_options) | Tune all instances in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: kernel_tuner.interface.Options
:param device_options: A dictionary with all opt... | 4.038055 | 4.162121 | 0.970192 |
ctype_args = [ None for _ in arguments]
for i, arg in enumerate(arguments):
if not isinstance(arg, (numpy.ndarray, numpy.number)):
raise TypeError("Argument is not numpy ndarray or numpy scalar %s" % type(arg))
dtype_str = str(arg.dtype)
data... | def ready_argument_list(self, arguments) | ready argument list to be passed to the C function
:param arguments: List of arguments to be passed to the C function.
The order should match the argument list on the C function.
Allowed values are numpy.ndarray, and/or numpy.int32, numpy.float32, and so on.
:type arguments: lis... | 4.400523 | 4.117949 | 1.06862 |
logging.debug('compiling ' + kernel_name)
if self.lib != None:
self.cleanup_lib()
compiler_options = ["-fPIC"]
#detect openmp
if "#include <omp.h>" in kernel_string or "use omp_lib" in kernel_string:
logging.debug('set using_openmp to true')
... | def compile(self, kernel_name, kernel_string) | call the C compiler to compile the kernel, return the function
:param kernel_name: The name of the kernel to be compiled, used to lookup the
function after compilation.
:type kernel_name: string
:param kernel_string: The C code that contains the function `kernel_name`
:type... | 3.089201 | 3.096159 | 0.997753 |
time = []
for _ in range(self.iterations):
value = self.run_kernel(func, c_args, threads, grid)
#I would like to replace the following with actually capturing
#stderr and detecting the error directly in Python, it proved
#however that capturing s... | def benchmark(self, func, c_args, threads, grid, times) | runs the kernel repeatedly, returns averaged returned value
The C function tuning is a little bit more flexible than direct CUDA
or OpenCL kernel tuning. The C function needs to measure time, or some
other quality metric you wish to tune on, on its own and should
therefore return a sing... | 9.004115 | 8.923889 | 1.00899 |
logging.debug("run_kernel")
logging.debug("arguments=" + str([str(arg.ctypes) for arg in c_args]))
time = func(*[arg.ctypes for arg in c_args])
return time | def run_kernel(self, func, c_args, threads, grid) | runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
order in the code. The list should be prepared using
... | 5.881613 | 5.546748 | 1.060372 |
C.memset(allocation.ctypes, value, size) | def memset(self, allocation, value, size) | set the memory in allocation to the value in value
:param allocation: An Argument for some memory allocation unit
:type allocation: Argument
:param value: The value to set the memory to
:type value: a single 8-bit unsigned int
:param size: The size of to the allocation unit in... | 11.216046 | 48.133305 | 0.23302 |
if not self.using_openmp:
#this if statement is necessary because shared libraries that use
#OpenMP will core dump when unloaded, this is a well-known issue with OpenMP
logging.debug('unloading shared library')
_ctypes.dlclose(self.lib._handle) | def cleanup_lib(self) | unload the previously loaded shared library | 12.056811 | 10.209291 | 1.180965 |
while True:
yield from rpc.notify('clock', str(datetime.datetime.now()))
yield from asyncio.sleep(1) | def clock(rpc) | This task runs forever and notifies all clients subscribed to
'clock' once a second. | 5.169302 | 3.967521 | 1.302905 |
global __already_patched
if not __already_patched:
from django.db import connections
connections._connections = local(connections._connections)
__already_patched = True | def patch_db_connections() | This wraps django.db.connections._connections with a TaskLocal object.
The Django transactions are only thread-safe, using threading.local,
and don't know about coroutines. | 6.461866 | 4.716433 | 1.370075 |
try:
msg_data = json.loads(raw_msg)
except ValueError:
raise RpcParseError
# check jsonrpc version
if 'jsonrpc' not in msg_data or not msg_data['jsonrpc'] == JSONRPC:
raise RpcInvalidRequestError(msg_id=msg_data.get('id', None))
# check requierd fields
if not len... | def decode_msg(raw_msg) | Decodes jsonrpc 2.0 raw message objects into JsonRpcMsg objects.
Examples:
Request:
{
"jsonrpc": "2.0",
"id": 1,
"method": "subtract",
"params": [42, 23]
}
Notification:
{
"jsonrpc":... | 2.066643 | 1.998042 | 1.034334 |
# Lazily load needed functions, as they import django model functions which
# in turn load modules that need settings to be loaded and we can't
# guarantee this module was loaded when the settings were ready.
from .compat import get_public_schema_name, get_tenant_model
old_schema = (connection... | def switch_schema(task, kwargs, **kw) | Switches schema of the task, before it has been run. | 4.214261 | 4.276668 | 0.985407 |
from .compat import get_public_schema_name
schema_name = get_public_schema_name()
include_public = True
if hasattr(task, '_old_schema'):
schema_name, include_public = task._old_schema
# If the schema names match, don't do anything.
if connection.schema_name == schema_name:
... | def restore_schema(task, **kwargs) | Switches the schema back to the one from before running the task. | 3.681491 | 3.528731 | 1.04329 |
id_ = attrs['id']
data = {}
data['directed'] = G.is_directed()
data['graph'] = G.graph
data['nodes'] = [dict(chain(G.node[n].items(), [(id_, n)])) for n in G]
data['links'] = []
for u, v, timeline in G.interactions_iter():
for t in timeline['t']:
for tid in past.bui... | def node_link_data(G, attrs=_attrs) | Return data in node-link format that is suitable for JSON serialization
and use in Javascript documents.
Parameters
----------
G : DyNetx graph
attrs : dict
A dictionary that contains three keys 'id', 'source' and 'target'.
The corresponding values provide the attribute names for ... | 3.695606 | 4.461659 | 0.828303 |
directed = data.get('directed', directed)
graph = dn.DynGraph()
if directed:
graph = graph.to_directed()
id_ = attrs['id']
mapping = []
graph.graph = data.get('graph', {})
c = count()
for d in data['nodes']:
node = d.get(id_, next(c))
mapping.append(node)
... | def node_link_graph(data, directed=False, attrs=_attrs) | Return graph from node-link data format.
Parameters
----------
data : dict
node-link formatted graph data
directed : bool
If True, and direction not specified in data, return a directed graph.
attrs : dict
A dictionary that contains three keys 'id', 'source', 'target'.
... | 3.953047 | 4.223951 | 0.935865 |
tls = sorted(sind_list)
conversion = {val: idx for idx, val in enumerate(tls)}
return conversion | def compact_timeslot(sind_list) | Test method. Compact all snapshots into a single one.
:param sind_list:
:return: | 7.856621 | 9.83035 | 0.799221 |
if t is not None:
return iter([n for n in self.degree(t=t).values() if n > 0])
return iter(self._node) | def nodes_iter(self, t=None, data=False) | Return an iterator over the nodes with respect to a given temporal snapshot.
Parameters
----------
t : snapshot id (default=None).
If None the iterator returns all the nodes of the flattened graph.
data : boolean, optional (default=False)
If False the iterator... | 4.700296 | 7.458717 | 0.630175 |
return list(self.nodes_iter(t=t, data=data)) | def nodes(self, t=None, data=False) | Return a list of the nodes in the graph at a given snapshot.
Parameters
----------
t : snapshot id (default=None)
If None the the method returns all the nodes of the flattened graph.
data : boolean, optional (default=False)
If False return a list of nodes. If... | 4.675714 | 13.904708 | 0.336268 |
seen = {} # helper dict to keep track of multiply stored interactions
if nbunch is None:
nodes_nbrs = self._adj.items()
else:
nodes_nbrs = ((n, self._adj[n]) for n in self.nbunch_iter(nbunch))
for n, nbrs in nodes_nbrs:
for nbr in nbrs:
... | def interactions_iter(self, nbunch=None, t=None) | Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
... | 2.922731 | 3.493886 | 0.836527 |
# set up attribute dict
if t is None:
raise nx.NetworkXError(
"The t argument must be a specified.")
# process ebunch
for ed in ebunch:
self.add_interaction(ed[0], ed[1], t, e) | def add_interactions_from(self, ebunch, t=None, e=None) | Add all the interaction in ebunch at time t.
Parameters
----------
ebunch : container of interaction
Each interaction given in the container will be added to the
graph. The interaction must be given as as 2-tuples (u,v) or
3-tuples (u,v,d) where d is a dictio... | 5.512092 | 7.363664 | 0.748553 |
try:
if t is None:
return list(self._adj[n])
else:
return [i for i in self._adj[n] if self.__presence_test(n, i, t)]
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,)) | def neighbors(self, n, t=None) | Return a list of the nodes connected to the node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned the neighbors of the node on the flattened graph.
Returns
-------
nli... | 3.195108 | 3.846482 | 0.830657 |
try:
if t is None:
return iter(self._adj[n])
else:
return iter([i for i in self._adj[n] if self.__presence_test(n, i, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,)) | def neighbors_iter(self, n, t=None) | Return an iterator over all neighbors of node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned an iterator over the neighbors of the node on the flattened graph.
Examples
-----... | 3.171479 | 4.064692 | 0.780251 |
if nbunch in self: # return a single node
return next(self.degree_iter(nbunch, t))[1]
else: # return a dict
return dict(self.degree_iter(nbunch, t)) | def degree(self, nbunch=None, t=None) | Return the degree of a node or nodes at time t.
The node degree is the number of interaction adjacent to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
... | 4.006824 | 5.043181 | 0.794503 |
if nbunch is None:
nodes_nbrs = self._adj.items()
else:
nodes_nbrs = ((n, self._adj[n]) for n in self.nbunch_iter(nbunch))
if t is None:
for n, nbrs in nodes_nbrs:
deg = len(self._adj[n])
yield (n, deg)
else:
... | def degree_iter(self, nbunch=None, t=None) | Return an iterator for (node, degree) at time t.
The node degree is the number of edges adjacent to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
... | 2.262061 | 2.657543 | 0.851185 |
s = sum(self.degree(t=t).values()) / 2
return int(s) | def size(self, t=None) | Return the number of edges at time t.
Parameters
----------
t : snapshot id (default=None)
If None will be returned the size of the flattened graph.
Returns
-------
nedges : int
The number of edges
See Also
--------
numb... | 8.5558 | 14.470971 | 0.591239 |
if t is None:
return len(self._node)
else:
nds = sum([1 for n in self.degree(t=t).values() if n > 0])
return nds | def number_of_nodes(self, t=None) | Return the number of nodes in the t snpashot of a dynamic graph.
Parameters
----------
t : snapshot id (default=None)
If None return the number of nodes in the flattened graph.
Returns
-------
nnodes : int
The number of nodes in the graph.
... | 4.463794 | 6.090809 | 0.732874 |
if t is None:
try:
return n in self._node
except TypeError:
return False
else:
deg = list(self.degree([n], t).values())
if len(deg) > 0:
return deg[0] > 0
else:
return Fal... | def has_node(self, n, t=None) | Return True if the graph, at time t, contains the node n.
Parameters
----------
n : node
t : snapshot id (default None)
If None return the presence of the node in the flattened graph.
Examples
--------
>>> G = dn.DynGraph() # or DiGraph, MultiG... | 3.190264 | 3.686967 | 0.865281 |
nlist = list(nodes)
v = nlist[0]
interaction = ((v, n) for n in nlist[1:])
self.add_interactions_from(interaction, t) | def add_star(self, nodes, t=None) | Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
See Also
--------
add... | 5.613288 | 8.889803 | 0.63143 |
nlist = list(nodes)
interaction = zip(nlist[:-1], nlist[1:])
self.add_interactions_from(interaction, t) | def add_path(self, nodes, t=None) | Add a path at time t.
Parameters
----------
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
See Also
--------
add_path, add_cycle
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path(... | 6.191546 | 9.405036 | 0.658322 |
from .dyndigraph import DynDiGraph
G = DynDiGraph()
G.name = self.name
G.add_nodes_from(self)
for it in self.interactions_iter():
for t in it[2]['t']:
G.add_interaction(it[0], it[1], t=t[0], e=t[1])
G.graph = deepcopy(self.graph)
... | def to_directed(self) | Return a directed representation of the graph.
Returns
-------
G : DynDiGraph
A dynamic directed graph with the same name, same nodes, and with
each edge (u,v,data) replaced by two directed edges
(u,v,data) and (v,u,data).
Notes
-----
... | 3.678691 | 4.062516 | 0.90552 |
timestamps = sorted(self.time_to_edge.keys())
for t in timestamps:
for e in self.time_to_edge[t]:
yield (e[0], e[1], e[2], t) | def stream_interactions(self) | Generate a temporal ordered stream of interactions.
Returns
-------
nd_iter : an iterator
The iterator returns a 4-tuples of (node, node, op, timestamp).
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.add_path([... | 3.47407 | 3.85467 | 0.901263 |
# create new graph and copy subgraph into it
H = self.__class__()
if t_to is not None:
if t_to < t_from:
raise ValueError("Invalid range: t_to must be grater that t_from")
else:
t_to = t_from
for u, v, ts in self.interactions_ite... | def time_slice(self, t_from, t_to=None) | Return an new graph containing nodes and interactions present in [t_from, t_to].
Parameters
----------
t_from : snapshot id, mandatory
t_to : snapshot id, optional (default=None)
If None t_to will be set equal to t_from
Returns
-... | 2.891008 | 2.90675 | 0.994584 |
if t is None:
return {k: v / 2 for k, v in self.snapshots.items()}
else:
try:
return self.snapshots[t] / 2
except KeyError:
return 0 | def interactions_per_snapshots(self, t=None) | Return the number of interactions within snapshot t.
Parameters
----------
t : snapshot id (default=None)
If None will be returned total number of interactions across all snapshots
Returns
-------
nd : dictionary, or number
A dictionary with sn... | 2.543813 | 3.620372 | 0.702639 |
dist = {}
if u is None:
# global inter event
first = True
delta = None
for ext in self.stream_interactions():
if first:
delta = ext
first = False
continue
... | def inter_event_time_distribution(self, u=None, v=None) | Return the distribution of inter event time.
If u and v are None the dynamic graph intere event distribution is returned.
If u is specified the inter event time distribution of interactions involving u is returned.
If u and v are specified the inter event time distribution of (u, v) interactions... | 2.518634 | 2.464448 | 1.021987 |
if nbunch is None:
nodes_nbrs = ((n, succs, self._pred[n]) for n, succs in self._succ.items())
else:
nodes_nbrs = ((n, self._succ[n], self._pred[n]) for n in self.nbunch_iter(nbunch))
if t is None:
for n, succ, pred in nodes_nbrs:
yi... | def degree_iter(self, nbunch=None, t=None) | Return an iterator for (node, degree) at time t.
The node degree is the number of edges adjacent to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will b... | 2.308757 | 2.307939 | 1.000355 |
seen = {} # helper dict to keep track of multiply stored interactions
if nbunch is None:
nodes_nbrs_succ = self._succ.items()
else:
nodes_nbrs_succ = [(n, self._succ[n]) for n in self.nbunch_iter(nbunch)]
for n, nbrs in nodes_nbrs_succ:
for ... | def interactions_iter(self, nbunch=None, t=None) | Return an iterator over the interaction present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
... | 3.429733 | 4.037752 | 0.849416 |
if nbunch is None:
nodes_nbrs_pred = self._pred.items()
else:
nodes_nbrs_pred = [(n, self._pred[n]) for n in self.nbunch_iter(nbunch)]
for n, nbrs in nodes_nbrs_pred:
for nbr in nbrs:
if t is not None:
if self.__p... | def in_interactions_iter(self, nbunch=None, t=None) | Return an iterator over the in interactions present in a given snapshot.
Edges are returned as tuples in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
... | 2.821266 | 3.434364 | 0.821481 |
if nbunch is None:
nodes_nbrs_succ = self._succ.items()
else:
nodes_nbrs_succ = [(n, self._succ[n]) for n in self.nbunch_iter(nbunch)]
for n, nbrs in nodes_nbrs_succ:
for nbr in nbrs:
if t is not None:
if self.__pr... | def out_interactions_iter(self, nbunch=None, t=None) | Return an iterator over the out interactions present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterat... | 2.415235 | 3.034244 | 0.795992 |
if t is None:
if u is None:
return int(self.size())
elif u is not None and v is not None:
if v in self._succ[u]:
return 1
else:
return 0
else:
if u is None:
... | def number_of_interactions(self, u=None, v=None, t=None) | Return the number of interaction between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all interaction)
If u and v are specified, return the number of interaction between
u and v. Otherwise return the total number of all interaction.
... | 2.367402 | 2.682839 | 0.882424 |
try:
if t is None:
return v in self._succ[u]
else:
return v in self._succ[u] and self.__presence_test(u, v, t)
except KeyError:
return False | def has_interaction(self, u, v, t=None) | Return True if the interaction (u,v) is in the graph at time t.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be retu... | 3.852872 | 6.844769 | 0.562893 |
return self.has_interaction(u, v, t) | def has_successor(self, u, v, t=None) | Return True if node u has successor v at time t (optional).
This is true if graph has the edge u->v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (... | 8.906857 | 11.143475 | 0.799289 |
return self.has_interaction(v, u, t) | def has_predecessor(self, u, v, t=None) | Return True if node u has predecessor v at time t (optional).
This is true if graph has the edge u<-v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id... | 12.078711 | 14.900105 | 0.810646 |
try:
if t is None:
return iter(self._succ[n])
else:
return iter([i for i in self._succ[n] if self.__presence_test(n, i, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,)) | def successors_iter(self, n, t=None) | Return an iterator over successor nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be return... | 3.199892 | 3.164518 | 1.011178 |
try:
if t is None:
return iter(self._pred[n])
else:
return iter([i for i in self._pred[n] if self.__presence_test(i, n, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,)) | def predecessors_iter(self, n, t=None) | Return an iterator over predecessors nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be re... | 3.267306 | 3.323691 | 0.983035 |
if nbunch in self: # return a single node
return next(self.in_degree_iter(nbunch, t))[1]
else: # return a dict
return dict(self.in_degree_iter(nbunch, t)) | def in_degree(self, nbunch=None, t=None) | Return the in degree of a node or nodes at time t.
The node in degree is the number of incoming interaction to that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be itera... | 3.67823 | 4.700075 | 0.78259 |
if nbunch is None:
nodes_nbrs = self._pred.items()
else:
nodes_nbrs = ((n, self._pred[n]) for n in self.nbunch_iter(nbunch))
if t is None:
for n, nbrs in nodes_nbrs:
deg = len(self._pred[n])
yield (n, deg)
else... | def in_degree_iter(self, nbunch=None, t=None) | Return an iterator for (node, in_degree) at time t.
The node degree is the number of edges incoming to the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
... | 2.423767 | 2.817749 | 0.860179 |
if nbunch in self: # return a single node
return next(self.out_degree_iter(nbunch, t))[1]
else: # return a dict
return dict(self.out_degree_iter(nbunch, t)) | def out_degree(self, nbunch=None, t=None) | Return the out degree of a node or nodes at time t.
The node degree is the number of interaction outgoing from that node in a given time frame.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be itera... | 3.750111 | 4.569894 | 0.820612 |
if nbunch is None:
nodes_nbrs = self._succ.items()
else:
nodes_nbrs = ((n, self._succ[n]) for n in self.nbunch_iter(nbunch))
if t is None:
for n, nbrs in nodes_nbrs:
deg = len(self._succ[n])
yield (n, deg)
else... | def out_degree_iter(self, nbunch=None, t=None) | Return an iterator for (node, out_degree) at time t.
The node out degree is the number of interactions outgoing from the node in a given timeframe.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be i... | 2.348552 | 2.697447 | 0.870657 |
from .dyngraph import DynGraph
H = DynGraph()
H.name = self.name
H.add_nodes_from(self)
if reciprocal is True:
for u in self._node:
for v in self._node:
if u >= v:
try:
o... | def to_undirected(self, reciprocal=False) | Return an undirected representation of the dyndigraph.
Parameters
----------
reciprocal : bool (optional)
If True only keep edges that appear in both directions
in the original dyndigraph.
Returns
-------
G : DynGraph
An undirected dynami... | 2.688502 | 2.810768 | 0.956501 |
for line in generate_interactions(G, delimiter):
line += '\n'
path.write(line.encode(encoding)) | def write_interactions(G, path, delimiter=' ', encoding='utf-8') | Write a DyNetx graph in interaction list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
Column delimiter | 4.408297 | 7.541616 | 0.584529 |
ids = None
lines = (line.decode(encoding) for line in path)
if keys:
ids = read_ids(path.name, delimiter=delimiter, timestamptype=timestamptype)
return parse_interactions(lines, comments=comments, directed=directed, delimiter=delimiter, nodetype=nodetype,
times... | def read_interactions(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False) | Read a DyNetx graph from interaction list format.
Parameters
----------
path : basestring
The desired output filename
delimiter : character
Column delimiter | 3.017782 | 4.757212 | 0.634359 |
for line in generate_snapshots(G, delimiter):
line += '\n'
path.write(line.encode(encoding)) | def write_snapshots(G, path, delimiter=' ', encoding='utf-8') | Write a DyNetx graph in snapshot graph list format.
Parameters
----------
G : graph
A DyNetx graph.
path : basestring
The desired output filename
delimiter : character
Column delimiter | 4.565804 | 8.428078 | 0.541737 |
ids = None
lines = (line.decode(encoding) for line in path)
if keys:
ids = read_ids(path.name, delimiter=delimiter, timestamptype=timestamptype)
return parse_snapshots(lines, comments=comments, directed=directed, delimiter=delimiter, nodetype=nodetype,
timestamp... | def read_snapshots(path, comments="#", directed=False, delimiter=None,
nodetype=None, timestamptype=None, encoding='utf-8', keys=False) | Read a DyNetx graph from snapshot graph list format.
Parameters
----------
path : basestring
The desired output filename
delimiter : character
Column delimiter | 3.369744 | 5.134241 | 0.656328 |
return G.number_of_interactions(u, v, t) | def number_of_interactions(G, u=None, v=None, t=None) | Return the number of edges between two nodes at time t.
Parameters
----------
u, v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between
u and v. Otherwise return the total number of all edges.
t : snapshot id (default... | 3.183272 | 9.664195 | 0.329388 |
r
n = number_of_nodes(G, t)
m = number_of_interactions(G, t)
if m == 0 or m is None or n <= 1:
return 0
d = m / (n * (n - 1))
if not G.is_directed():
d *= 2
return d | def density(G, t=None) | r"""Return the density of a graph at timestamp t.
The density for undirected graphs is
.. math::
d = \frac{2m}{n(n-1)},
and for directed graphs is
.. math::
d = \frac{m}{n(n-1)},
where `n` is the number of nodes and `m` is the number of edges in `G`.
... | 3.808434 | 4.27345 | 0.891185 |
counts = Counter(d for n, d in G.degree(t=t).items())
return [counts.get(i, 0) for i in range(max(counts) + 1)] | def degree_histogram(G, t=None) | Return a list of the frequency of each degree value.
Parameters
----------
G : Graph opject
DyNetx graph object
t : snapshot id (default=None)
snapshot id
Returns
-------
hist : list
A list of frequencies of degrees.
... | 2.712159 | 3.695054 | 0.733997 |
G.add_node = frozen
G.add_nodes_from = frozen
G.remove_node = frozen
G.remove_nodes_from = frozen
G.add_edge = frozen
G.add_edges_from = frozen
G.remove_edge = frozen
G.remove_edges_from = frozen
G.clear = frozen
G.frozen = True
return G | def freeze(G) | Modify graph to prevent further change by adding or removing nodes or edges.
Node and edge data can still be modified.
Parameters
----------
G : graph
A NetworkX graph
Notes
-----
To "unfreeze" a graph you must make a copy by creating a ne... | 1.981601 | 2.166039 | 0.91485 |
nlist = iter(nodes)
v = next(nlist)
edges = ((v, n) for n in nlist)
G.add_interactions_from(edges, t, **attr) | def add_star(G, nodes, t, **attr) | Add a star at time t.
The first node in nodes is the middle of the star. It is connected
to all other nodes.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
A container of nodes.
... | 4.592834 | 6.888082 | 0.66678 |
nlist = list(nodes)
edges = zip(nlist[:-1], nlist[1:])
G.add_interactions_from(edges, t, **attr) | def add_path(G, nodes, t, **attr) | Add a path at time t.
Parameters
----------
G : graph
A DyNetx graph
nodes : iterable container
A container of nodes.
t : snapshot id (default=None)
snapshot id
See Also
--------
... | 3.904894 | 6.961126 | 0.560957 |
H = G.__class__()
H.add_nodes_from(G.nodes(data=with_data))
if with_data:
H.graph.update(G.graph)
return H | def create_empty_copy(G, with_data=True) | Return a copy of the graph G with all of the edges removed.
Parameters
----------
G : graph
A DyNetx graph
with_data : bool (default=True)
Include data.
Notes
-----
Graph and edge data is not propagated to the new graph. | 2.293858 | 3.493232 | 0.656658 |
# Set node attributes based on type of `values`
if name is not None: # `values` must not be a dict of dict
try: # `values` is a dict
for n, v in values.items():
try:
G.node[n][name] = values[n]
except KeyError:
pa... | def set_node_attributes(G, values, name=None) | Set node attributes from dictionary of nodes and values
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
values: dict
Dictionary of attribute values keyed by node. If `values` is not a
dictionary, then it is treated as a sing... | 2.547703 | 2.819642 | 0.903555 |
return {n: d[name] for n, d in G.node.items() if name in d} | def get_node_attributes(G, name) | Get node attributes from graph
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node. | 3.386255 | 5.67769 | 0.596414 |
if graph.is_directed():
values = chain(graph.predecessors(node, t=t), graph.successors(node, t=t))
else:
values = graph.neighbors(node, t=t)
return values | def all_neighbors(graph, node, t=None) | Returns all of the neighbors of a node in the graph at time t.
If the graph is directed returns predecessors as well as successors.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
The node whose neighbors will be returne... | 2.483831 | 2.873132 | 0.864503 |
if graph.is_directed():
values = chain(graph.predecessors(node, t=t), graph.successors(node, t=t))
else:
values = graph.neighbors(node, t=t)
nbors = set(values) | {node}
return (nnode for nnode in graph if nnode not in nbors) | def non_neighbors(graph, node, t=None) | Returns the non-neighbors of the node in the graph at time t.
Parameters
----------
graph : DyNetx graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
t : snapshot id (default=None)
If None the non-neighbors... | 3.197639 | 3.459065 | 0.924423 |
# if graph.is_directed():
# for u in graph:
# for v in non_neighbors(graph, u, t):
# yield (u, v)
#else:
nodes = set(graph)
while nodes:
u = nodes.pop()
for v in nodes - set(graph[u]):
yield (u, v) | def non_interactions(graph, t=None) | Returns the non-existent edges in the graph at time t.
Parameters
----------
graph : NetworkX graph.
Graph to find non-existent edges.
t : snapshot id (default=None)
If None the non-existent edges are identified on the flattened graph.
Returns
... | 2.699805 | 3.144074 | 0.858696 |
'''
getMsg - Generate a default message based on parameters to FunctionTimedOut exception'
@return <str> - Message
'''
return 'Function %s (args=%s) (kwargs=%s) timed out after %f seconds.\n' %(self.timedOutFunction.__name__, repr(self.timedOutArgs), repr(self.timedOutKw... | def getMsg(self) | getMsg - Generate a default message based on parameters to FunctionTimedOut exception'
@return <str> - Message | 8.671842 | 3.535726 | 2.452634 |
'''
retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
If a float/int : Will retry th... | def retry(self, timeout=RETRY_SAME_TIMEOUT) | retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
If a float/int : Will retry the function same args wit... | 6.469436 | 2.296365 | 2.817251 |
'''
func_timeout - Runs the given function for up to #timeout# seconds.
Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut
@param timeout <float> - Maximum number of seconds to run #func# before ... | def func_timeout(timeout, func, args=(), kwargs=None) | func_timeout - Runs the given function for up to #timeout# seconds.
Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut
@param timeout <float> - Maximum number of seconds to run #func# before terminating
... | 6.217331 | 3.071887 | 2.023945 |
# initialize path integral
T = 4.
ndT = 8. # use larger ndT to reduce discretization error (goes like 1/ndT**2)
neval = 3e5 # should probably use more evaluations (10x?)
nitn = 6
alpha = 0.1 # damp adaptation
# create integrator and train it (no x0list)
integrand = Pa... | def analyze_theory(V, x0list=[], plot=False) | Extract ground-state energy E0 and psi**2 for potential V. | 5.240754 | 5.002028 | 1.047726 |
'''
_stopThread - @see StoppableThread.stop
'''
if self.isAlive() is False:
return True
self._stderr = open(os.devnull, 'w')
# Create "joining" thread which will raise the provided exception
# on a repeat, until the thread stops.
joinThr... | def _stopThread(self, exception, raiseEvery=2.0) | _stopThread - @see StoppableThread.stop | 7.793274 | 6.68763 | 1.165327 |
'''
run - The thread main. Will attempt to stop and join the attached thread.
'''
# Try to silence default exception printing.
self.otherThread._Thread__stderr = self._stderr
if hasattr(self.otherThread, '_Thread__stop'):
# If py2, call this first to star... | def run(self) | run - The thread main. Will attempt to stop and join the attached thread. | 10.652821 | 7.672526 | 1.388437 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.