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 = differential_evolution(_cost_func, bounds, args, maxiter=1,
polish=False, disp=tuning_options.verbose)
if tuning_options.verbose:
print(opt_result.message)
return results, runner.dev.get_environment()
|
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: A dictionary with all options for the device
on which the kernel should be tuned.
:type device_options: kernel_tuner.interface.Options
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: kernel_tuner.interface.Options
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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, tuning_options, runner, results, cache)
num_particles = 20
maxiter = 100
best_time_global = 1e20
best_position_global = []
# init particle swarm
swarm = []
for i in range(0, num_particles):
swarm.append(Particle(bounds, args))
for i in range(maxiter):
if tuning_options.verbose:
print("start iteration ", i, "best time global", best_time_global)
# evaluate particle positions
for j in range(num_particles):
swarm[j].evaluate(_cost_func)
# update global best if needed
if swarm[j].time <= best_time_global:
best_position_global = swarm[j].position
best_time_global = swarm[j].time
# update particle velocities and positions
for j in range(0, num_particles):
swarm[j].update_velocity(best_position_global)
swarm[j].update_position(bounds)
if tuning_options.verbose:
print('Final result:')
print(best_position_global)
print(best_time_global)
return results, runner.dev.get_environment()
|
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 options for the device
on which the kernel should be tuned.
:type device_options: dict
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: dict
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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 generation in range(generations):
if tuning_options.verbose:
print("Generation %d, best_time %f" % (generation, best_time))
#determine fitness of population members
weighted_population = []
for dna in population:
time = _cost_func(dna, kernel_options, tuning_options, runner, all_results, cache)
weighted_population.append((dna, time))
population = []
#'best_time' is used only for printing
if tuning_options.verbose and all_results:
best_time = min(all_results, key=lambda x: x["time"])["time"]
#population is sorted such that better configs have higher chance of reproducing
weighted_population.sort(key=lambda x: x[1])
#crossover and mutate
for _ in range(pop_size//2):
ind1 = weighted_choice(weighted_population)
ind2 = weighted_choice(weighted_population)
ind1, ind2 = crossover(ind1, ind2)
population.append(mutate(ind1, dna_size, tune_params))
population.append(mutate(ind2, dna_size, tune_params))
return all_results, runner.dev.get_environment()
|
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: A dictionary with all options for the device
on which the kernel should be tuned.
:type device_options: kernel_tuner.interface.Options
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: kernel_tuner.interface.Options
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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_options(method, tuning_options)
#not all methods support 'disp' option
if not method in ['TNC']:
options['disp'] = tuning_options.verbose
args = (kernel_options, tuning_options, runner, results, cache)
opt_result = scipy.optimize.minimize(_cost_func, x0, args=args, method=method, options=options, **kwargs)
if tuning_options.verbose:
print(opt_result.message)
return results, runner.dev.get_environment()
|
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: A dictionary with all options for the device
on which the kernel should be tuned.
:type device_options: kernel_tuner.interface.Options
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: kernel_tuner.interface.Options
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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:
params = unscale_and_snap_to_nearest(x, tuning_options.tune_params, tuning_options.eps)
else:
params = snap_to_nearest_config(x, tuning_options.tune_params)
logging.debug('params ' + str(params))
x_int = ",".join([str(i) for i in params])
if x_int in cache:
return cache[x_int]
#check if this is a legal (non-restricted) parameter instance
if tuning_options.restrictions:
legal = util.check_restrictions(tuning_options.restrictions, params, tuning_options.tune_params.keys(), tuning_options.verbose)
if not legal:
cache[x_int] = error_time
cache[x_key] = error_time
return error_time
#compile and benchmark this instance
res, _ = runner.run([params], kernel_options, tuning_options)
#append to tuning results
if res:
results.append(res[0])
cache[x_int] = res[0]['time']
cache[x_key] = res[0]['time']
return res[0]['time']
cache[x_int] = error_time
cache[x_key] = error_time
return error_time
|
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 in values]
x0 = [0.5*eps*len(v) for v in values]
else:
bounds = get_bounds(tuning_options.tune_params)
x0 = [(min_v+max_v)/2.0 for (min_v, max_v) in bounds]
eps = 1e9
for v_list in values:
vals = numpy.sort(v_list)
eps = min(eps, numpy.amin(numpy.gradient(vals)))
tuning_options["eps"] = eps
logging.debug('get_bounds_x0_eps called')
logging.debug('bounds ' + str(bounds))
logging.debug('x0 ' + str(x0))
logging.debug('eps ' + str(eps))
return bounds, x0, eps
|
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", "Powell"]:
kwargs['maxfev'] = maxiter
elif method == "L-BFGS-B":
kwargs['maxfun'] = maxiter
#pass eps to methods that support it
if method in ["CG", "BFGS", "L-BFGS-B", "TNC", "SLSQP"]:
kwargs['eps'] = tuning_options.eps
elif method == "COBYLA":
kwargs['rhobeg'] = tuning_options.eps
return kwargs
|
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*len(v)]
linspace = numpy.linspace(pad, (eps*len(v))-pad, len(v))
#snap value to nearest point in space, store index
idx = numpy.abs(linspace-x[i]).argmin()
#safeguard that should not be needed
idx = min(max(idx, 0), len(v)-1)
#use index into array of actual values
x_u[i] = v[idx]
return x_u
|
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_benchmark(self.gpu_args, params, kernel_options, tuning_options)
if time is None:
logging.debug('received time is None, kernel configuration was skipped silently due to compile or runtime failure')
continue
#print and append to results
params['time'] = time
output_string = get_config_string(params, self.units)
logging.debug(output_string)
if not self.quiet:
print(output_string)
results.append(params)
return results, self.dev.get_environment()
|
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
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: kernel_tuner.iterface.Options
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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_options(method, tuning_options)
kwargs['options'] = options
args = (kernel_options, tuning_options, runner, results, cache)
minimizer_kwargs = dict(**kwargs)
minimizer_kwargs["method"] = method
minimizer_kwargs["args"] = args
opt_result = scipy.optimize.basinhopping(_cost_func, x0, stepsize=eps, minimizer_kwargs=minimizer_kwargs, disp=tuning_options.verbose)
if tuning_options.verbose:
print(opt_result.message)
return results, runner.dev.get_environment()
|
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 options for the device
on which the kernel should be tuned.
:type device_options: dict
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: dict
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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.memcpy_htod(gpu_args[-1], arg)
else: # if not an array, just pass argument along
gpu_args.append(arg)
return gpu_args
|
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 arguments: list(numpy objects)
:returns: A list of arguments that can be passed to an CUDA kernel.
:rtype: list( pycuda.driver.DeviceAllocation, numpy.int32, ... )
| 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 + ["-e", kernel_name],
arch=('compute_' + self.cc) if self.cc != "00" else None,
code=('sm_' + self.cc) if self.cc != "00" else None,
cache_dir=False, no_extern_c=no_extern_c)
func = self.current_module.get_function(kernel_name)
return func
except drv.CompileError as e:
if "uses too much shared data" in e.stderr:
raise Exception("uses too much shared data")
else:
raise e
|
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_name`
:type kernel_string: string
:returns: An CUDA kernel that can be called directly.
:rtype: pycuda.driver.Function
| 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()
time.append(end.time_since(start))
time = sorted(time)
if times:
return time
else:
if self.iterations > 4:
return numpy.mean(time[1:-1])
else:
return numpy.mean(time)
|
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
discarded and the rest is included in the returned average. The reason for
this is to be robust against initialization artifacts and other exceptional
cases.
: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 global memory
or single values passed by value.
:type gpu_args: list( pycuda.driver.DeviceAllocation, numpy.int32, ...)
:param threads: A tuple listing the number of threads in each dimension of
the thread block
:type threads: tuple(int, int, int)
:param grid: A tuple listing the number of thread blocks in each dimension
of the grid
:type grid: tuple(int, int)
:param times: Return the execution time of all iterations.
:type times: bool
:returns: All execution times, if times=True, or a robust average for the
kernel execution time.
:rtype: float
| 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.debug('array to be copied: ')
logging.debug(v.nbytes)
logging.debug(v.dtype)
logging.debug(v.flags)
drv.memcpy_htod(symbol, v)
|
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 needs to be copied. Similar to regular arguments, these need
to be numpy objects, such as numpy.ndarray or numpy.int32, and so on.
:type cmem_args: dict( string: numpy.ndarray, ... )
| 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.MIRROR,
'wrap': drv.address_mode.WRAP }
logging.debug('copy_texture_memory_args called')
logging.debug('current module: ' + str(self.current_module))
self.texrefs = []
for k, v in texmem_args.items():
tex = self.current_module.get_texref(k)
self.texrefs.append(tex)
logging.debug('copying to texture: ' + str(k))
if not isinstance(v, dict):
data = v
else:
data = v['array']
logging.debug('texture to be copied: ')
logging.debug(data.nbytes)
logging.debug(data.dtype)
logging.debug(data.flags)
drv.matrix_to_texref(data, tex, order="C")
if isinstance(v, dict):
if 'address_mode' in v and v['address_mode'] is not None:
# address_mode is set per axis
amode = v['address_mode']
if not isinstance(amode, list):
amode = [ amode ] * data.ndim
for i, m in enumerate(amode):
try:
if m is not None:
tex.set_address_mode(i, address_mode_map[m])
except KeyError:
raise ValueError('Unknown address mode: ' + m)
if 'filter_mode' in v and v['filter_mode'] is not None:
fmode = v['filter_mode']
try:
tex.set_filter_mode(filter_mode_map[fmode])
except KeyError:
raise ValueError('Unknown filter mode: ' + fmode)
if 'normalized_coordinates' in v and v['normalized_coordinates']:
tex.set_flags(tex.get_flags() | drv.TRSF_NORMALIZED_COORDINATES)
|
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 global memory
or single values passed by value.
:type gpu_args: list( pycuda.driver.DeviceAllocation, numpy.int32, ...)
:param threads: A tuple listing the number of threads in each dimension of
the thread block
:type threads: tuple(int, int, int)
:param grid: A tuple listing the number of thread blocks in each dimension
of the grid
:type grid: tuple(int, int)
| 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 unit in bytes
:type size: int
| 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
alpha = 0.9
niter = 20
# generate random starting point and evaluate cost
pos = []
for i, _ in enumerate(tune_params.keys()):
pos.append(random_val(i, tune_params))
old_cost = _cost_func(pos, *args)
if tuning_options.verbose:
c = 0
# main optimization loop
while T > T_min:
if tuning_options.verbose:
print("iteration: ", c, "T", T, "cost: ", old_cost)
c += 1
for i in range(niter):
new_pos = neighbor(pos, tune_params)
new_cost = _cost_func(new_pos, *args)
ap = acceptance_prob(old_cost, new_cost, T)
r = random.random()
if ap > r:
if tuning_options.verbose:
print("new position accepted", new_pos, new_cost, 'old:', pos, old_cost, 'ap', ap, 'r', r, 'T', T)
pos = new_pos
old_cost = new_cost
T = T * alpha
return results, runner.dev.get_environment()
|
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 options for the device
on which the kernel should be tuned.
:type device_options: dict
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: dict
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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 is better than new cost depending on T and random value
return np.exp(((old_cost-new_cost)/old_cost)/T)
|
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
new_value = random_val(i, tune_params)
else: #adjacent value
ind = values.index(pos[i])
if random.random() > 0.5:
ind += 1
else:
ind -= 1
ind = min(max(ind, 0), len(values)-1)
new_value = values[ind]
pos_out.append(new_value)
return pos_out
|
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 not None:
parameter_space = filter(lambda p: util.check_restrictions(restrictions, p, tune_params.keys(), verbose), parameter_space)
results, env = runner.run(parameter_space, kernel_options, tuning_options)
return results, env
|
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 options for the device
on which the kernel should be tuned.
:type device_options: kernel_tuner.interface.Options
:param tuning_options: A dictionary with all options regarding the tuning
process.
:type tuning_options: kernel_tuner.interface.Options
:returns: A list of dictionaries for executed kernel configurations and their
execution times. And a dictionary that contains a information
about the hardware/software environment on which the tuning took place.
:rtype: list(dict()), dict()
| 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 = arg.copy()
if isinstance(arg, numpy.ndarray):
if dtype_str in dtype_map.keys():
# In numpy <= 1.15, ndarray.ctypes.data_as does not itself keep a reference
# to its underlying array, so we need to store a reference to arg.copy()
# in the Argument object manually to avoid it being deleted.
# (This changed in numpy > 1.15.)
data_ctypes = data.ctypes.data_as(C.POINTER(dtype_map[dtype_str]))
else:
raise TypeError("unknown dtype for ndarray")
elif isinstance(arg, numpy.generic):
data_ctypes = dtype_map[dtype_str](arg)
ctype_args[i] = Argument(numpy=data, ctypes=data_ctypes)
return ctype_args
|
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: list(numpy objects)
:returns: A list of arguments that can be passed to the C function.
:rtype: list(Argument)
| 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')
self.using_openmp = True
if self.compiler == "pgfortran":
compiler_options.append("-mp")
else:
compiler_options.append("-fopenmp")
#select right suffix based on compiler
suffix = ".cc"
#detect whether to use nvcc as default instead of g++, may overrule an explicitly passed g++
if ("#include <cuda" in kernel_string) or ("cudaMemcpy" in kernel_string):
if self.compiler == "g++" and self.nvcc_available:
self.compiler = "nvcc"
#if contains device code suffix .cu is required by nvcc
if self.compiler == "nvcc" and "__global__" in kernel_string:
suffix = ".cu"
if self.compiler in ["gfortran", "pgfortran", "ftn", "ifort"]:
suffix = ".F90"
if self.compiler == "nvcc":
compiler_options = ["-Xcompiler=" + c for c in compiler_options]
if ".c" in suffix:
if not "extern \"C\"" in kernel_string:
kernel_string = "extern \"C\" {\n" + kernel_string + "\n}"
#copy user specified compiler options to current list
if self.compiler_options:
compiler_options += self.compiler_options
lib_args = []
if "CL/cl.h" in kernel_string:
lib_args = ["-lOpenCL"]
logging.debug('using compiler ' + self.compiler)
logging.debug('compiler_options ' + " ".join(compiler_options))
logging.debug('lib_args ' + " ".join(lib_args))
source_file = get_temp_filename(suffix=suffix)
filename = ".".join(source_file.split(".")[:-1])
#detect Fortran modules
match = re.search(r"\s*module\s+([a-zA-Z_]*)", kernel_string)
if match:
if self.compiler == "gfortran":
kernel_name = "__" + match.group(1) + "_MOD_" + kernel_name
elif self.compiler in ["ftn", "ifort"]:
kernel_name = match.group(1) + "_mp_" + kernel_name + "_"
elif self.compiler == "pgfortran":
kernel_name = match.group(1) + "_" + kernel_name + "_"
try:
write_file(source_file, kernel_string)
lib_extension = ".so"
if platform.system() == "Darwin":
lib_extension = ".dylib"
subprocess.check_call([self.compiler, "-c", source_file] + compiler_options + ["-o", filename + ".o"])
subprocess.check_call([self.compiler, filename + ".o"] + compiler_options + ["-shared", "-o", filename + lib_extension] + lib_args)
self.lib = numpy.ctypeslib.load_library(filename, '.')
func = getattr(self.lib, kernel_name)
func.restype = C.c_float
finally:
delete_temp_file(source_file)
delete_temp_file(filename+".o")
delete_temp_file(filename+".so")
delete_temp_file(filename+".dylib")
return func
|
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 kernel_string: string
:returns: An ctypes function that can be called directly.
:rtype: ctypes._FuncPtr
| 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 stderr for non-Python functions from Python
#is a rather difficult thing to do
#
#The current, less than ideal, scheme uses the convention that a
#negative time indicates a 'too many resources requested for launch'
if value < 0.0:
raise Exception("too many resources requested for launch")
time.append(value)
time = sorted(time)
if times:
return time
else:
if self.iterations > 4:
return numpy.mean(time[1:-1])
else:
return numpy.mean(time)
|
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 single floating-point value.
Benchmark runs the C function repeatedly and returns the average of the
values returned by the C function. The number of iterations is set
during the creation of the CFunctions object. For all measurements the
lowest and highest values are discarded and the rest is included in the
average. The reason for this is to be robust against initialization
artifacts and other exceptional cases.
: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
ready_argument_list().
:type c_args: list(Argument)
:param threads: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type threads: any
:param grid: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type grid: any
:param times: Return the execution time of all iterations.
:type times: bool
:returns: All execution times, if times=True, or a robust average for the
kernel execution time.
:rtype: float
| 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
ready_argument_list().
:type c_args: list(Argument)
:param threads: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type threads: any
:param grid: Ignored, but left as argument for now to have the same
interface as CudaFunctions and OpenCLFunctions.
:type grid: any
:returns: A robust average of values returned by the C function.
:rtype: float
| 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 bytes
:type size: int
| 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(set(['error', 'result', 'method']) & set(msg_data)) == 1:
raise RpcInvalidRequestError(msg_id=msg_data.get('id', None))
# find message type
if 'method' in msg_data:
if 'id' in msg_data and msg_data['id'] is not None:
msg_type = JsonRpcMsgTyp.REQUEST
else:
msg_type = JsonRpcMsgTyp.NOTIFICATION
elif 'result' in msg_data:
msg_type = JsonRpcMsgTyp.RESULT
elif 'error' in msg_data:
msg_type = JsonRpcMsgTyp.ERROR
# Request Objects
if msg_type in (JsonRpcMsgTyp.REQUEST, JsonRpcMsgTyp.NOTIFICATION):
# 'method' fields have to be strings
if type(msg_data['method']) is not str:
raise RpcInvalidRequestError
# set empty 'params' if not set
if 'params' not in msg_data:
msg_data['params'] = None
# set empty 'id' if not set
if 'id' not in msg_data:
msg_data['id'] = None
# Response Objects
if msg_type in (JsonRpcMsgTyp.RESULT, JsonRpcMsgTyp.ERROR):
# every Response object has to define an id
if 'id' not in msg_data:
raise RpcInvalidRequestError(msg_id=msg_data.get('id', None))
# Error objects
if msg_type == JsonRpcMsgTyp.ERROR:
# the error field has to be a dict
if type(msg_data['error']) is not dict:
raise RpcInvalidRequestError(msg_id=msg_data.get('id', None))
# the error field has to define 'code' and 'message'
if not len(set(['code', 'message']) & set(msg_data['error'])) == 2:
raise RpcInvalidRequestError(msg_id=msg_data.get('id', None))
# the error code has to be in the specified ranges
if not msg_data['error']['code'] in RpcError.lookup_table.keys():
raise RpcInvalidRequestError(msg_id=msg_data.get('id', None))
# set empty 'data' field if not set
if 'data' not in msg_data['error']:
msg_data['error']['data'] = None
return JsonRpcMsg(msg_type, msg_data)
|
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.0",
"method": "clock",
"params": "12:00",
}
Response:
{
"jsonrpc": "2.0",
"id": 1,
"result": 0,
}
Error:
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32600,
"message": "Invalid request",
"data": null
}
}
| 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.schema_name, connection.include_public_schema)
setattr(task, '_old_schema', old_schema)
schema = (
get_schema_name_from_task(task, kwargs) or
get_public_schema_name()
)
# If the schema has not changed, don't do anything.
if connection.schema_name == schema:
return
if connection.schema_name != get_public_schema_name():
connection.set_schema_to_public()
if schema == get_public_schema_name():
return
tenant = get_tenant_model().objects.get(schema_name=schema)
connection.set_tenant(tenant, include_public=True)
|
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:
return
connection.set_schema(schema_name, include_public=include_public)
|
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.builtins.xrange(t[0], t[-1]+1):
data['links'].append({"source": u, "target": v, "time": tid})
return data
|
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 storing
DyNetx-internal graph data. The values should be unique. Default
value:
:samp:`dict(id='id', source='source', target='target')`.
Returns
-------
data : dict
A dictionary with node-link formatted data.
Examples
--------
>>> from dynetx.readwrite import json_graph
>>> G = dn.DynGraph([(1,2)])
>>> data = json_graph.node_link_data(G)
To serialize with json
>>> import json
>>> s = json.dumps(data)
Notes
-----
Graph, node, and link attributes are stored in this format. Note that
attribute keys will be converted to strings in order to comply with
JSON.
See Also
--------
node_link_graph
| 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)
nodedata = dict((make_str(k), v) for k, v in d.items() if k != id_)
graph.add_node(node, **nodedata)
for d in data['links']:
graph.add_interaction(d['source'], d["target"], d['time'])
return graph
|
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'.
The corresponding values provide the attribute names for storing
Dynetx-internal graph data. Default value:
:samp:`dict(id='id', source='source', target='target')`.
Returns
-------
G : DyNetx graph
A DyNetx graph object
Examples
--------
>>> from dynetx.readwrite import json_graph
>>> G = dn.DynGraph([(1,2)])
>>> data = json_graph.node_link_data(G)
>>> H = json_graph.node_link_graph(data)
See Also
--------
node_link_data
| 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 returns nodes. If True
return a two-tuple of node and node data dictionary
Returns
-------
niter : iterator
An iterator over nodes. If data=True the iterator gives
two-tuples containing (node, node data, dictionary)
Examples
--------
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], 0)
>>> [n for n, d in G.nodes_iter(t=0)]
[0, 1, 2]
| 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 True return a
two-tuple of node and node data dictionary
Returns
-------
nlist : list
A list of nodes. If data=True a list of two-tuples containing
(node, node data dictionary).
Examples
--------
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], 0)
>>> G.nodes(t=0)
[0, 1, 2]
>>> G.add_edge(1, 4, t=1)
>>> G.nodes(t=0)
[0, 1, 2]
| 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:
if t is not None:
if nbr not in seen and self.__presence_test(n, nbr, t):
yield (n, nbr, {"t": [t]})
else:
if nbr not in seen:
yield (n, nbr, self._adj[n][nbr])
seen[n] = 1
del seen
|
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
through once.
t : snapshot id (default=None)
If None the the method returns an iterator over the edges of the flattened graph.
Returns
-------
edge_iter : iterator
An iterator of (u,v) tuples of interaction.
See Also
--------
interaction : return a list of interaction
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-interaction.
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2], 0)
>>> G.add_interaction(2,3,1)
>>> [e for e in G.interactions_iter(t=0)]
[(0, 1), (1, 2)]
>>> list(G.interactions_iter())
[(0, 1), (1, 2), (2, 3)]
| 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 dictionary containing interaction
data.
t : appearance snapshot id, mandatory
e : vanishing snapshot id, optional
See Also
--------
add_edge : add a single interaction
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_edges_from([(0,1),(1,2)], t=0)
| 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
-------
nlist : list
A list of nodes that are adjacent to n.
Raises
------
NetworkXError
If the node n is not in the graph.
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.neighbors(0, t=0)
[1]
>>> G.neighbors(0, t=1)
[]
| 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
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> [n for n in G.neighbors_iter(0, t=0)]
[1]
| 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
through once.
t : snapshot id (default=None)
If None will be returned the degree of nodes on the flattened graph.
Returns
-------
nd : dictionary, or number
A dictionary with nodes as keys and degree as values or
a number if a single node is specified.
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.degree(0, t=0)
1
>>> G.degree([0,1], t=1)
{0: 0, 1: 0}
>>> list(G.degree([0,1], t=0).values())
[1, 2]
| 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:
for n, nbrs in nodes_nbrs:
edges_t = len([v for v in nbrs.keys() if self.__presence_test(n, v, t)])
if edges_t > 0:
yield (n, edges_t)
else:
yield (n, 0)
|
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
through once.
t : snapshot id (default=None)
If None will be returned an iterator over the degree of nodes on the flattened graph.
Returns
-------
nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See Also
--------
degree
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> list(G.degree_iter(0, t=0))
[(0, 1)]
>>> list(G.degree_iter([0,1], t=0))
[(0, 1), (1, 2)]
| 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
--------
number_of_edges
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.size(t=0)
3
| 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.
See Also
--------
order which is identical
Examples
--------
>>> G = dn.DynGraph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], t=0)
>>> G.number_of_nodes(0)
3
| 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 False
|
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, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2], t=0)
>>> G.has_node(0, t=0)
True
It is more readable and simpler to use
>>> 0 in G
True
| 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_path, add_cycle
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_star([0,1,2,3], t=0)
| 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([0,1,2,3], t=0)
| 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)
G._node = deepcopy(self._node)
return G
|
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
-----
This returns a "deepcopy" of the edge, node, and
graph attributes which attempts to completely copy
all of the data and references.
This is in contrast to the similar D=DynDiGraph(G) which returns a
shallow copy of the data.
See the Python copy module for more information on shallow
and deep copies, http://docs.python.org/library/copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the
data structure, those changes do not transfer to the DynDiGraph
created by this method.
Examples
--------
>>> G = dn.DynGraph() # or MultiGraph, etc
>>> G.add_path([0,1])
>>> H = G.to_directed()
>>> H.edges()
[(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = dn.DynDiGraph() # or MultiDiGraph, etc
>>> G.add_path([0,1])
>>> H = G.to_directed()
>>> H.edges()
[(0, 1)]
| 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,4,5,6], t=1)
>>> list(G.stream_interactions())
[(0, 1, '+', 0), (1, 2, '+', 0), (2, 3, '+', 0), (3, 4, '+', 1), (4, 5, '+', 1), (5, 6, '+', 1)]
| 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_iter():
I = t_to
F = t_from
for a, b in ts['t']:
if I <= a and b <= F:
H.add_interaction(u, v, a, b)
elif a <= I and F <= b:
H.add_interaction(u, v, I, F)
elif a <= I <= b and b <= F:
H.add_interaction(u, v, I, b)
elif I <= a <= F and F <= b:
H.add_interaction(u, v, a, F)
return H
|
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
-------
H : a DynGraph object
the graph described by interactions in [t_from, t_to]
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.add_path([0,4,5,6], t=1)
>>> G.add_path([7,1,2,3], t=2)
>>> H = G.time_slice(0)
>>> H.interactions()
[(0, 1), (1, 2), (1, 3)]
>>> H = G.time_slice(0, 1)
>>> H.interactions()
[(0, 1), (1, 2), (1, 3), (0, 4), (4, 5), (5, 6)]
| 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 snapshot ids as keys and interaction count as values or
a number if a single snapshot id is specified.
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.add_path([0,4,5,6], t=1)
>>> G.add_path([7,1,2,3], t=2)
>>> G.interactions_per_snapshots(t=0)
3
>>> G.interactions_per_snapshots()
{0: 3, 1: 3, 2: 3}
| 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
disp = ext[-1] - delta[-1]
delta = ext
if disp in dist:
dist[disp] += 1
else:
dist[disp] = 1
elif u is not None and v is None:
# node inter event
delta = (0, 0, 0, 0)
flag = False
for ext in self.stream_interactions():
if ext[0] == u or ext[1] == u:
if flag:
disp = ext[-1] - delta[-1]
delta = ext
if disp in dist:
dist[disp] += 1
else:
dist[disp] = 1
else:
delta = ext
flag = True
else:
# interaction inter event
evt = self._adj[u][v]['t']
delta = []
for i in evt:
if i[0] != i[1]:
for j in [0, 1]:
delta.append(i[j])
else:
delta.append(i[0])
if len(delta) == 2 and delta[0] == delta[1]:
return {}
for i in range(0, len(delta) - 1):
e = delta[i + 1] - delta[i]
if e not in dist:
dist[e] = 1
else:
dist[e] += 1
return dist
|
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 is returned
Parameters
----------
u : node id
v : node id
Returns
-------
nd : dictionary
A dictionary from inter event time to number of occurrences
| 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:
yield (n, len(succ) + len(pred))
else:
for n, succ, pred in nodes_nbrs:
edges_succ = len([v for v in succ.keys() if self.__presence_test(n, v, t)])
edges_pred = len([v for v in pred.keys() if self.__presence_test(v, n, t)])
yield (n, edges_succ + edges_pred)
|
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
through once.
t : snapshot id (default=None)
If None will be returned an iterator over the degree of nodes on the flattened graph.
Returns
-------
nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See Also
--------
degree
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0, 1, t=0)
>>> list(G.degree_iter(0, t=0))
[(0, 1)]
>>> list(G.degree_iter([0,1], t=0))
[(0, 1), (1, 1)]
| 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 nbr in nbrs:
if t is not None:
if nbr not in seen and self.__presence_test(n, nbr, t):
yield (n, nbr, {"t": [t]})
else:
if nbr not in seen:
yield (nbr, n, self._succ[n][nbr])
seen[n] = 1
del seen
|
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
through once.
t : snapshot id (default=None)
If None the the method returns an iterator over the edges of the flattened graph.
Returns
-------
edge_iter : iterator
An iterator of (u,v) tuples of interaction.
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-interaction.
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0,1, 0)
>>> G.add_interaction(1,2, 0)
>>> G.add_interaction(2,3,1)
>>> [e for e in G.interactions_iter(t=0)]
[(0, 1), (1, 2)]
>>> list(G.interactions_iter())
[(0, 1), (1, 2), (2, 3)]
| 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.__presence_test(nbr, n, t):
yield (nbr, n, {"t": [t]})
else:
if nbr in self._pred[n]:
yield (nbr, n, self._pred[n][nbr])
|
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
through once.
t : snapshot id (default=None)
If None the the method returns an iterator over the edges of the flattened graph.
Returns
-------
edge_iter : iterator
An iterator of (u,v) tuples of interaction.
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-interaction.
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0,1, 0)
>>> G.add_interaction(1,2, 0)
>>> G.add_interaction(2,3,1)
>>> [e for e in G.in_interactions_iter(t=0)]
[(0, 1), (1, 2)]
>>> list(G.in_interactions_iter())
[(0, 1), (1, 2), (2, 3)]
| 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.__presence_test(n, nbr, t):
yield (n, nbr, {"t": [t]})
else:
if nbr in self._succ[n]:
yield (n, nbr, self._succ[n][nbr])
|
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 iterated
through once.
t : snapshot id (default=None)
If None the the method returns an iterator over the edges of the flattened graph.
Returns
-------
edge_iter : iterator
An iterator of (u,v) tuples of interaction.
Notes
-----
Nodes in nbunch that are not in the graph will be (quietly) ignored.
For directed graphs this returns the out-interaction.
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0,1, 0)
>>> G.add_interaction(1,2, 0)
>>> G.add_interaction(2,3,1)
>>> [e for e in G.out_interactions_iter(t=0)]
[(0, 1), (1, 2)]
>>> list(G.out_interactions_iter())
[(0, 1), (1, 2), (2, 3)]
| 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:
return int(self.size(t))
elif u is not None and v is not None:
if v in self._succ[u]:
if self.__presence_test(u, v, t):
return 1
else:
return 0
|
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.
t : snapshot id (default=None)
If None will be returned the number of edges on the flattened graph.
Returns
-------
nedges : int
The number of interaction in the graph. If nodes u and v are specified
return the number of interaction between those nodes. If a single node is specified return None.
See Also
--------
size
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.number_of_interactions()
3
>>> G.number_of_interactions(0,1, t=0)
1
>>> G.add_edge(3, 4, t=1)
>>> G.number_of_interactions()
4
| 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 returned the presence of the interaction on the flattened graph.
Returns
-------
edge_ind : bool
True if interaction is in the graph, False otherwise.
Examples
--------
Can be called either using two nodes u,v or interaction tuple (u,v)
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0,1, t=0)
>>> G.add_interaction(1,2, t=0)
>>> G.add_interaction(2,3, t=0)
>>> G.has_interaction(0,1, t=0)
True
>>> G.has_interaction(0,1, t=1)
False
| 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 (default=None)
If None will be returned the presence of the interaction on the flattened graph.
| 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 (default=None)
If None will be returned the presence of the interaction on the flattened graph.
| 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 returned the presence of the interaction on the flattened graph.
| 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 returned the presence of the interaction on the flattened graph.
| 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 iterated
through once.
t : snapshot id (default=None)
If None will be returned the degree of nodes on the flattened graph.
Returns
-------
nd : dictionary, or number
A dictionary with nodes as keys and degree as values or
a number if a single node is specified.
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0,1, t=0)
>>> G.add_interaction(1,2, t=0)
>>> G.add_interaction(2,3, t=0)
>>> G.in_degree(0, t=0)
1
>>> G.in_degree([0,1], t=1)
{0: 0, 1: 0}
>>> list(G.in_degree([0,1], t=0).values())
[1, 2]
| 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:
for n, nbrs in nodes_nbrs:
edges_t = len([v for v in nbrs.keys() if self.__presence_test(v, n, t)])
if edges_t > 0:
yield (n, edges_t)
else:
yield (n, 0)
|
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
through once.
t : snapshot id (default=None)
If None will be returned an iterator over the degree of nodes on the flattened graph.
Returns
-------
nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See Also
--------
degree
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0, 1, t=0)
>>> list(G.in_degree_iter(0, t=0))
[(0, 0)]
>>> list(G.in_degree_iter([0,1], t=0))
[(0, 0), (1, 1)]
| 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 iterated
through once.
t : snapshot id (default=None)
If None will be returned the degree of nodes on the flattened graph.
Returns
-------
nd : dictionary, or number
A dictionary with nodes as keys and degree as values or
a number if a single node is specified.
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interactions(0,1, t=0)
>>> G.add_interactions(1,2, t=0)
>>> G.add_interactions(2,3, t=0)
>>> G.out_degree(0, t=0)
1
>>> G.out_degree([0,1], t=1)
{0: 0, 1: 0}
>>> list(G.out_degree([0,1], t=0).values())
[1, 2]
| 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:
for n, nbrs in nodes_nbrs:
edges_t = len([v for v in nbrs.keys() if self.__presence_test(n, v, t)])
if edges_t > 0:
yield (n, edges_t)
else:
yield (n, 0)
|
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 iterated
through once.
t : snapshot id (default=None)
If None will be returned an iterator over the degree of nodes on the flattened graph.
Returns
-------
nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See Also
--------
degree
Examples
--------
>>> G = dn.DynDiGraph()
>>> G.add_interaction(0, 1, t=0)
>>> list(G.out_degree_iter(0, t=0))
[(0, 1)]
>>> list(G.out_degree_iter([0,1], t=0))
[(0, 1)]
| 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:
outc = self._succ[u][v]['t']
intc = self._pred[u][v]['t']
for o in outc:
r = set(range(o[0], o[1]+1))
for i in intc:
r2 = set(range(i[0], i[1]+1))
inter = list(r & r2)
if len(inter) == 1:
H.add_interaction(u, v, t=inter[0])
elif len(inter) > 1:
H.add_interaction(u, v, t=inter[0], e=inter[-1])
except:
pass
else:
for it in self.interactions_iter():
for t in it[2]['t']:
H.add_interaction(it[0], it[1], t=t[0], e=t[1])
H.graph = deepcopy(self.graph)
H._node = deepcopy(self._node)
return H
|
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 dynamic graph with the same name and nodes and
with edge (u,v,data) if either (u,v,data) or (v,u,data)
is in the dyndigraph. If both edges exist in dyndigraph and
their edge data is different, only one edge is created
with an arbitrary choice of which edge data to use.
You must check and correct for this manually if desired.
Notes
-----
If edges in both directions (u,v) and (v,u) exist in the
graph, attributes for the new undirected edge will be a combination of
the attributes of the directed edges. The edge data is updated
in the (arbitrary) order that the edges are encountered. For
more customized control of the edge attributes use add_edge().
This returns a "deepcopy" of the edge, node, and
graph attributes which attempts to completely copy
all of the data and references.
This is in contrast to the similar G=DynDiGraph(D) which returns a
shallow copy of the data.
See the Python copy module for more information on shallow
and deep copies, http://docs.python.org/library/copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects
in the data structure, those changes do not transfer to the Graph
created by this method.
| 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,
timestamptype=timestamptype, keys=ids)
|
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,
timestamptype=timestamptype, keys=ids)
|
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=None)
If None will be returned the number of edges on the flattened graph.
Returns
-------
nedges : int
The number of edges in the graph. If nodes u and v are specified
return the number of edges between those nodes.
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> dn.number_of_interactions(G, t=0)
| 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`.
Parameters
----------
G : Graph opject
DyNetx graph object
t : snapshot id (default=None)
If None the density will be computed on the flattened graph.
Notes
-----
The density is 0 for a graph without edges and 1 for a complete graph.
Self loops are counted in the total number of edges so graphs with self
loops can have density higher than 1.
| 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.
The degree values are the index in the list.
Notes
-----
Note: the bins are width one, hence len(list) can be large
(Order(number_of_edges))
| 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 new graph object.
See Also
--------
is_frozen
| 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.
t : snapshot id (default=None)
snapshot id
See Also
--------
add_path, add_cycle
Examples
--------
>>> G = dn.DynGraph()
>>> dn.add_star(G, [0,1,2,3], t=0)
| 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
--------
add_path, add_cycle
Examples
--------
>>> G = dn.DynGraph()
>>> dn.add_path(G, [0,1,2,3], t=0)
| 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:
pass
except AttributeError: # `values` is a constant
for n in G:
G.node[n][name] = values
else: # `values` must be dict of dict
for n, d in values.items():
try:
G.node[n].update(d)
except KeyError:
pass
|
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 single attribute value that is then
applied to every node in `G`.
| 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 returned.
t : snapshot id (default=None)
If None the neighbors are identified on the flattened graph.
Returns
-------
neighbors : iterator
Iterator of neighbors
| 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 are identified on the flattened graph.
Returns
-------
non_neighbors : iterator
Iterator of nodes in the graph that are not neighbors of the node.
| 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
-------
non_edges : iterator
Iterator of edges that are not in the graph.
| 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.timedOutKwargs), self.timedOutAfter)
|
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 the function same args with provided timeout
If None : Will retry function same args no timeout
@return - Returnval from function
'''
if timeout is None:
return self.timedOutFunction(*(self.timedOutArgs), **self.timedOutKwargs)
from .dafunc import func_timeout
if timeout == RETRY_SAME_TIMEOUT:
timeout = self.timedOutAfter
return func_timeout(timeout, self.timedOutFunction, args=self.timedOutArgs, kwargs=self.timedOutKwargs)
|
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 with provided timeout
If None : Will retry function same args no timeout
@return - Returnval from function
| 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 terminating
@param func <function> - The function to call
@param args <tuple> - Any ordered arguments to pass to the function
@param kwargs <dict/None> - Keyword arguments to pass to the function.
@raises - FunctionTimedOut if #timeout# is exceeded, otherwise anything #func# could raise will be raised
If the timeout is exceeded, FunctionTimedOut will be raised within the context of the called function every two seconds until it terminates,
but will not block the calling thread (a new thread will be created to perform the join). If possible, you should try/except FunctionTimedOut
to return cleanly, but in most cases it will 'just work'.
@return - The return value that #func# gives
'''
if not kwargs:
kwargs = {}
if not args:
args = ()
ret = []
exception = []
isStopped = False
def funcwrap(args2, kwargs2):
try:
ret.append( func(*args2, **kwargs2) )
except FunctionTimedOut:
# Don't print traceback to stderr if we time out
pass
except Exception as e:
exc_info = sys.exc_info()
if isStopped is False:
# Assemble the alternate traceback, excluding this function
# from the trace (by going to next frame)
# Pytohn3 reads native from __traceback__,
# python2 has a different form for "raise"
e.__traceback__ = exc_info[2].tb_next
exception.append( e )
thread = StoppableThread(target=funcwrap, args=(args, kwargs))
thread.daemon = True
thread.start()
thread.join(timeout)
stopException = None
if thread.isAlive():
isStopped = True
class FunctionTimedOutTempType(FunctionTimedOut):
def __init__(self):
return FunctionTimedOut.__init__(self, '', timeout, func, args, kwargs)
FunctionTimedOutTemp = type('FunctionTimedOut' + str( hash( "%d_%d_%d_%d" %(id(timeout), id(func), id(args), id(kwargs))) ), FunctionTimedOutTempType.__bases__, dict(FunctionTimedOutTempType.__dict__))
stopException = FunctionTimedOutTemp
thread._stopThread(stopException)
thread.join(min(.1, timeout / 50.0))
raise FunctionTimedOut('', timeout, func, args, kwargs)
else:
# We can still cleanup the thread here..
# Still give a timeout... just... cuz..
thread.join(.5)
if exception:
raise_exception(exception)
if ret:
return ret[0]
|
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
@param func <function> - The function to call
@param args <tuple> - Any ordered arguments to pass to the function
@param kwargs <dict/None> - Keyword arguments to pass to the function.
@raises - FunctionTimedOut if #timeout# is exceeded, otherwise anything #func# could raise will be raised
If the timeout is exceeded, FunctionTimedOut will be raised within the context of the called function every two seconds until it terminates,
but will not block the calling thread (a new thread will be created to perform the join). If possible, you should try/except FunctionTimedOut
to return cleanly, but in most cases it will 'just work'.
@return - The return value that #func# gives
| 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 = PathIntegrand(V=V, T=T, ndT=ndT)
integ = vegas.Integrator(integrand.region, alpha=alpha)
integ(integrand, neval=neval, nitn=nitn / 2, alpha=2 * alpha)
# evaluate path integral with trained integrator and x0list
integrand = PathIntegrand(V=V, x0list=x0list, T=T, ndT=ndT)
results = integ(integrand, neval=neval, nitn=nitn, alpha=alpha)
print(results.summary())
E0 = -np.log(results['exp(-E0*T)']) / T
print('Ground-state energy = %s Q = %.2f\n' % (E0, results.Q))
if len(x0list) <= 0:
return E0
psi2 = results['exp(-E0*T) * psi(x0)**2'] / results['exp(-E0*T)']
print('%5s %-12s %-10s' % ('x', 'psi**2', 'sho-exact'))
print(27 * '-')
for i, (x0i, psi2i) in enumerate(zip(x0list, psi2)):
exact = np.exp(- x0i ** 2) / np.sqrt(np.pi) #* np.exp(-T / 2.)
print(
"%5.1f %-12s %-10.5f"
% (x0i, psi2i, exact)
)
if plot:
plot_results(E0, x0list, psi2, T)
return E0
|
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.
joinThread = JoinThread(self, exception, repeatEvery=raiseEvery)
# Try to prevent spurrious prints
joinThread._stderr = self._stderr
joinThread.start()
joinThread._stderr = self._stderr
|
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 start thread termination cleanly.
# Python3 does not need such ( nor does it provide.. )
self.otherThread._Thread__stop()
while self.otherThread.isAlive():
# We loop raising exception incase it's caught hopefully this breaks us far out.
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.otherThread.ident), ctypes.py_object(self.exception))
self.otherThread.join(self.repeatEvery)
try:
self._stderr.close()
except:
pass
|
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.