def test_betweenness(): ''' Check betweenness results for all backends ''' num_nodes = 5 # UNDIRECTED edge_list = [(0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (2, 4), (3, 4)] weights = [0.1, 0.3, 1.5, 0.8, 5.6, 4., 2.3] nb_expect = [0.083333, 0.0, 0.083333, 0.3333333, 0.0] eb_expect = [0.15, 0.2, 0.15, 0.25, 0.15, 0.15, 0.25] nb_exp_wght = [0.5, 2 / 3, 0, 0.5, 0] eb_exp_wght = [0.6, 0.4, 0, 0.6, 0, 0, 0.4] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=False) g.new_edges(edge_list, attributes={"weight": weights}) nb, eb = nngt.analyze_graph["betweenness"](g) assert np.all(np.isclose(nb, nb_expect)) assert np.all(np.isclose(eb, eb_expect)) # weighted nb, eb = nngt.analyze_graph["betweenness"](g, weights=True) assert np.all(np.isclose(nb, nb_exp_wght)) assert np.all(np.isclose(eb, eb_exp_wght)) # DIRECTED edge_list = [(0, 1), (0, 2), (0, 3), (1, 3), (3, 2), (3, 4), (4, 2), (4, 0)] weights = [0.1, 0.3, 1.5, 0.8, 5.6, 4., 2.3, 0.9] nb_expect = [0.25, 0, 0, 1 / 3, 0.25] eb_expect = [0.15, 0.05, 0.15, 0.2, 0.1, 0.3, 0.05, 0.3] nb_exp_wght = [0.5, 0.25, 0, 1 / 3, 5 / 12] eb_exp_wght = [0.3, 0.2, 0, 0.35, 0, 0.4, 0, 0.45] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list, attributes={"weight": weights}) nb, eb = nngt.analyze_graph["betweenness"](g) assert np.all(np.isclose(nb, nb_expect)) assert np.all(np.isclose(eb, eb_expect)) # weighted nb, eb = nngt.analyze_graph["betweenness"](g, weights=True) assert np.all(np.isclose(nb, nb_exp_wght)) assert np.all(np.isclose(eb, eb_exp_wght))
def setup_module(): ''' setup any state specific to the execution of the current module.''' with_plot = nngt.get_config("with_plot") with_nest = nngt.get_config("with_nest") nngt.set_config("with_plot", False) nngt.set_config("with_nest", False)
def test_components(): ''' Check connected components for all backends ''' num_nodes = 8 edge_list = [(0, 1), (0, 2), (1, 2)] for i in range(3, num_nodes - 1): edge_list.append((i, i + 1)) edge_list.append((7, 3)) for bckd in all_backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list) # scc cc, hist = \ nngt.analyze_graph["connected_components"](g, ctype="scc") idx = np.array([i for i in range(num_nodes)], dtype=int) # nodes are assigned to the correct components assert np.all(cc[0] not in cc[1:]) # 3 first are isolated assert np.all(cc[1] not in cc[idx != 1]) # 3 first are isolated assert np.all(cc[2] not in cc[idx != 2]) # 3 first are isolated assert np.all(cc[3:] == cc[3]) # 5 last together # hence counts should be 1, 1, 1, and 5 assert hist[cc[0]] == 1 assert hist[cc[1]] == 1 assert hist[cc[2]] == 1 assert hist[cc[5]] == 5 # wcc cc, hist = \ nngt.analyze_graph["connected_components"](g, ctype="wcc") # nodes are assigned to the correct components assert np.all(cc[:3] == cc[0]) # 3 first together assert np.all(cc[3:] == cc[3]) # 5 last together # hence counts should be 3 and 5 assert hist[cc[0]] == 3 assert hist[cc[5]] == 5 # undirected g = nngt.Graph(nodes=num_nodes, directed=False) g.new_edges(edge_list) cc, hist = \ nngt.analyze_graph["connected_components"](g) # nodes are assigned to the correct components assert np.all(cc[:3] == cc[0]) # 3 first together assert np.all(cc[3:] == cc[3]) # 5 last together # hence counts should be 3 and 5 assert hist[cc[0]] == 3 assert hist[cc[5]] == 5
def test_assortativity(): ''' Check assortativity result for all backends ''' # DIRECTED num_nodes = 5 edge_list = [(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)] weights = [0.53, 0.45, 0.8, 0.125, 0.66, 0.31, 0.78] # expected results assort_unweighted = -0.47140452079103046 assort_weighted = -0.5457956719785911 for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes) g.new_edges(edge_list, attributes={"weight": weights}) assert np.isclose(nngt.analyze_graph["assortativity"](g, "in"), assort_unweighted) # not check weighted version for networkx for now assert np.isclose( nngt.analyze_graph["assortativity"](g, "in", weights=True), assort_weighted) # UNDIRECTED edge_list = [(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3)] weights = weights[:len(edge_list)] # expected results assort_unweighted = -0.33333333333333215 assort_weighted = -0.27351320394915296 for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=False) g.new_edges(edge_list, attributes={"weight": weights}) assert np.isclose(nngt.analyze_graph["assortativity"](g, "in"), assort_unweighted) # not check weighted version for networkx for now if bckd != "networkx": assert np.isclose( nngt.analyze_graph["assortativity"](g, "in", weights=True), assort_weighted)
def test_diameter(): ''' Check connected components for all backends ''' # unconnected num_nodes = 8 edge_list = [(0, 1), (0, 2), (1, 2)] for i in range(3, num_nodes - 1): edge_list.append((i, i + 1)) edge_list.append((7, 3)) weights = [0.58, 0.59, 0.88, 0.8, 0.61, 0.66, 0.62, 0.28] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list, attributes={"weight": weights}) assert np.isinf(nngt.analyze_graph["diameter"](g, weights=None)) assert np.isinf(nngt.analyze_graph["diameter"](g, weights=True)) # connected num_nodes = 5 edge_list = [(0, 1), (0, 3), (1, 3), (2, 0), (3, 2), (3, 4), (4, 2)] weights = [0.58, 0.59, 0.88, 0.8, 0.61, 0.66, 0.28] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list, attributes={"weight": weights}) d = nngt.analyze_graph["diameter"](g) assert nngt.analyze_graph["diameter"](g, weights=None) == 3 assert np.isclose(nngt.analyze_graph["diameter"](g, weights="weight"), 2.29)
def test_connect_switch_distance_rule_max_proba(): num_omp = nngt.get_config("omp") mthread = nngt.get_config("multithreading") # switch multithreading to False nngt.set_config("multithreading", False) pop = nngt.NeuralPop.exc_and_inhib(1000) radius = 100. shape = nngt.geometry.Shape.disk(radius) net = nngt.SpatialNetwork(population=pop, shape=shape) max_proba = 0.1 avg, std = 10., 1.5 weights = {"distribution": "gaussian", "avg": avg, "std": std} ng.connect_nodes(net, pop.inhibitory, pop.excitatory, "distance_rule", scale=5 * radius, max_proba=max_proba, weights=weights) assert net.edge_nb() <= len(pop.inhibitory) * len( pop.excitatory) * max_proba # check weights ww = net.get_weights() assert avg - 0.5 * std < ww.mean() < avg + 0.5 * std assert 0.75 * std < ww.std() < 1.25 * std # restore mt parameters nngt.set_config("mpi", False) nngt.set_config("omp", num_omp) nngt.set_config("multithreading", mthread)
graph_library = environ.get("GL", None) if graph_library == "gt": nngt.use_library("graph-tool") assert nngt.get_config('graph_library') == "graph-tool", \ "Loading graph-tool failed..." elif graph_library == "ig": nngt.use_library("igraph") assert nngt.get_config('graph_library') == "igraph", \ "Loading igraph failed..." elif graph_library == "nx": nngt.use_library("networkx") assert nngt.get_config('graph_library') == "networkx", \ "Loading networkx failed..." omp = int(environ.get("OMP", 1)) nngt.set_config({"omp": omp}) # get the tests current_dir = dirname(abspath(__file__)) dir_files = listdir(current_dir) sys.path.insert(0, current_dir) testfiles = [ fname[:-3] for fname in dir_files if (fname.startswith("test_") and fname.endswith(".py")) ] tests = [importlib.import_module(name) for name in testfiles] #-----------------------------------------------------------------------------# # Run if main #------------------------ #
nngt.use_backend("networkx") assert nngt.get_config('backend') == "networkx", \ "Loading networkx failed..." elif backend == "nngt": nngt.use_backend("nngt") assert nngt.get_config('backend') == "nngt", \ "Loading nngt failed..." # get the arguments for MPI/OpenMP + hide log omp = int(environ.get("OMP", 1)) mpi = bool(environ.get("MPI", False)) nngt.set_config( { "multithreading": omp > 1, "omp": omp, "mpi": mpi, "log_level": "ERROR", }, silent=True) # get the tests current_dir = dirname(abspath(__file__)) dir_files = listdir(current_dir) sys.path.insert(0, current_dir) testfiles = [ fname[:-3] for fname in dir_files if (fname.startswith("test_") and fname.endswith(".py")) ] # remove the MPI test unless we're using it, otherwise remove the examples if not nngt.get_config("mpi"):
from nngt.lib.logger import _log_message from nngt.lib.test_functions import mpi_checker, mpi_random # try to import multithreaded or mpi algorithms using_mt_algorithms = False if nngt.get_config("multithreading"): logger = logging.getLogger(__name__) try: from .cconnect import * from .connect_algorithms import price_network using_mt_algorithms = True _log_message(logger, "DEBUG", "Using multithreaded algorithms compiled on install.") nngt.set_config('multithreading', True, silent=True) except Exception as e: try: import cython import pyximport pyximport.install() from .cconnect import * from .connect_algorithms import price_network using_mt_algorithms = True _log_message( logger, "DEBUG", str(e) + "\n\tCompiled " "multithreaded algorithms on-the-run.") nngt.set_config('multithreading', True, silent=True) except Exception as e2: _log_message(
import numpy as np import matplotlib.pyplot as plt import nngt from nngt.geometry import Shape import pickle import pdb print('PDB DEBUGGER ACTIVATED') # nngt.use_backend("graph-tool") nngt.use_backend("networkx") # nngt.set_config({"omp": 8, "palette": 'RdYlBu'}) nngt.set_config("multithreading", False) nngt.seed(0) ''' Runtime options''' plot_distribution = True # plot of the connectivity distribution plot_graphs = False # graphic output of spatial network simulate_activity = True # whether to run or not a NEST simlation on the model sim_duration = 2000 # simulation duration in ms plot_activity = True # whether to plot simulation activity animation_movie = True # wheter to generate activity on map movie save_spikes = False # whether to save the spikes of all the neurons obstacles = True # set to True for simulation with elevated obstacles print("\n###################\n Runtime options\n------------------") print("Plot of the spatial graph : {0}".format(plot_graphs)) print("Run Nest simulation on the generated graph : {0}".format(
""" Use NNGT to analyze NEST-simulated activity of a random balanced network. """ import numpy as np from scipy.special import lambertw import nngt import nngt.generation as ng # np.random.seed(0) ''' Simulation parameters ''' nngt.set_config("omp", 8) nngt.set_config("seeds", [11, 12, 13, 14, 15, 16, 17, 18]) dt = 0.1 # the resolution in ms simtime = 1000. # Simulation time in ms delay = 1.5 # synaptic delay in ms g = 5.0 # ratio inhibitory weight/excitatory weight eta = 2.0 # external rate relative to threshold rate epsilon = 0.1 # connection probability ''' Tools ''' def ComputePSPnorm(tauMem, CMem, tauSyn):
def use_backend(backend, reloading=True, silent=False): ''' Allows the user to switch to a specific graph library as backend. .. warning :: If :class:`~nngt.Graph` objects have already been created, they will no longer be compatible with NNGT methods. Parameters ---------- backend : string Name of a graph library among 'graph_tool', 'igraph', 'networkx', or 'nngt'. reloading : bool, optional (default: True) Whether the graph objects should be `reload_module`d (this should always be set to True except when NNGT is first initiated!) ''' # save old config except for graph-library data old_config = nngt.get_config(detailed=True) for k in ("graph", "backend", "library"): del old_config[k] # try to switch graph library success = False error = None if backend == "graph-tool": try: success = _set_graph_tool() except Exception as e: error = e elif backend == "igraph": try: success = _set_igraph() except Exception as e: error = e elif backend == "networkx": try: success = _set_networkx() except Exception as e: error = e elif backend == "nngt": try: success = _set_nngt() except Exception as e: error = e else: raise ValueError("Invalid graph library requested.") if reloading: reload_module(sys.modules["nngt"].core.base_graph) reload_module(sys.modules["nngt"].core.gt_graph) reload_module(sys.modules["nngt"].core.ig_graph) reload_module(sys.modules["nngt"].core.nx_graph) reload_module(sys.modules["nngt"].core) reload_module(sys.modules["nngt"].generation) reload_module(sys.modules["nngt"].generation.graph_connectivity) if nngt._config['with_plot']: reload_module(sys.modules["nngt"].plot) if nngt._config['with_nest']: reload_module(sys.modules["nngt"].simulation) reload_module(sys.modules["nngt"].lib) reload_module(sys.modules["nngt"].core.graph_classes) reload_module(sys.modules["nngt"].analysis) from nngt.core.graph_classes import (Graph, SpatialGraph, Network, SpatialNetwork) sys.modules["nngt"].Graph = Graph sys.modules["nngt"].SpatialGraph = SpatialGraph sys.modules["nngt"].Network = Network sys.modules["nngt"].SpatialNetwork = SpatialNetwork # restore old config nngt.set_config(old_config, silent=True) # log if success: if silent: _log_message(logger, "DEBUG", "Successfuly switched to " + backend + ".") else: _log_message(logger, "INFO", "Successfuly switched to " + backend + ".") else: _log_message( logger, "WARNING", "Error, could not switch to " + backend + ": " "{}.".format(error)) if error is not None: raise error
std_e = 5 ng.connect_neural_types(net2, 1, [-1, 1], graph_model="gaussian_degree", avg=avg_e, std=std_e, degree_type="out-degree") avg_i = 100 std_i = 5 ng.connect_neural_types(net2, -1, [-1, 1], graph_model="gaussian_degree", avg=avg_i, std=std_i, degree_type="out-degree") # call only on root process (for mpi) unless using distributed backend if nngt.on_master_process() or nngt.get_config("backend") == "nngt": # check that both networks are equals assert np.all(net1.get_degrees() == net2.get_degrees()) if __name__ == "__main__": import os if os.environ.get("MPI"): nngt.set_config("mpi", True) if os.environ.get("GL", ""): nngt.set_config("backend", os.environ["GL"]) if not nngt.get_config("mpi"): test_fixed() test_gaussian() test_group_vs_type()
def test_plot_config(): ''' Test the default plot configuration ''' nngt.set_config("color_lib", "seaborn") nngt.set_config("palette_discrete", "Set3") nngt.set_config("palette_continuous", "magma")
nngt.use_backend("nngt") assert nngt.get_config('backend') == "nngt", \ "Loading nngt failed..." # get the arguments for MPI/OpenMP + hide log omp = int(environ.get("OMP", 1)) mpi = bool(environ.get("MPI", False)) conf = { "multithreading": omp > 1, "omp": omp, "mpi": mpi, "log_level": "ERROR", } nngt.set_config(conf, silent=True) # get the tests current_dir = dirname(abspath(__file__)) dir_files = listdir(current_dir) sys.path.insert(0, current_dir) testfiles = [ fname[:-3] for fname in dir_files if (fname.startswith("test_") and fname.endswith(".py")) ] # remove the MPI test unless we're using it, otherwise remove the examples if not nngt.get_config("mpi"): idx = None for i, test in enumerate(testfiles): if "test_mpi" in test:
import os import numpy as np from scipy.special import lambertw import nngt import nngt.generation as ng ''' Simulation parameters ''' num_omp = int(os.environ.get("OMP", 8)) nngt.set_config("omp", num_omp) nngt.set_config("seeds", [10 + i for i in range(num_omp)]) dt = 0.1 # the resolution in ms simtime = 1000. # Simulation time in ms delay = 1.5 # synaptic delay in ms g = 4.0 # ratio inhibitory weight/excitatory weight eta = 2.0 # external rate relative to threshold rate epsilon = 0.1 # connection probability ''' Tools '''
def test_weighted_undirected_clustering(): ''' Compare the onnela implementation with networkx and Barrat with igraph. ''' # import networkx and igraph import networkx as nx import igraph as ig # create a pre-defined graph num_nodes = 5 edge_list = [(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 0)] weights = [0.53, 0.45, 0.8, 0.125, 0.66, 0.31, 0.78] # create nx graph and compute reference onnela clustering nx_graph = nx.Graph() nx_graph.add_nodes_from(range(num_nodes)) arr_edges = [e + (w, ) for e, w in zip(edge_list, weights)] nx_graph.add_weighted_edges_from(arr_edges, weight="weight") onnela = list(nx.clustering(nx_graph, weight="weight").values()) triplets = [3, 3, 1, 1, 6] gc_onnela = np.sum(np.multiply(onnela, triplets)) / np.sum(triplets) # create ig graph and compute reference Barrat clustering ig_graph = ig.Graph(num_nodes, directed=False) ig_graph.add_edges(edge_list) ig_graph.es["weight"] = weights barrat = ig_graph.transitivity_local_undirected(mode="zero", weights="weight") strength = np.array(ig_graph.strength(weights='weight')) degree = np.array(ig_graph.degree()) triplets = strength * (degree - 1) gc_barrat = np.sum(np.multiply(barrat, triplets)) / np.sum(triplets) # check for all backends for bckd in all_backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=False) g.new_edges(edge_list, attributes={"weight": weights}) # onnela assert np.all( np.isclose( na.local_clustering(g, weights="weight", method="onnela"), onnela)) assert np.isclose( na.global_clustering(g, weights="weight", method="onnela"), gc_onnela) # barrat assert np.all( np.isclose( na.local_clustering(g, weights="weight", method="barrat"), barrat)) assert np.isclose( na.global_clustering(g, weights="weight", method="barrat"), gc_barrat) # fully reciprocal directed version g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list, attributes={"weight": weights}) g.new_edges(np.array(edge_list, dtype=int)[:, ::-1], attributes={"weight": weights}) assert np.all( np.isclose( na.local_clustering(g, weights="weight", method="onnela"), onnela)) assert np.isclose( na.global_clustering(g, weights="weight", method="onnela"), gc_onnela) assert np.all( np.isclose( na.local_clustering(g, weights="weight", method="barrat"), barrat)) assert np.isclose( na.global_clustering(g, weights="weight", method="barrat"), gc_barrat)
def test_closeness(): ''' Check closeness results for all backends ''' num_nodes = 5 edge_list = [(0, 1), (0, 3), (1, 3), (2, 0), (3, 2), (3, 4), (4, 2)] weights = [0.54881, 0.71518, 0.60276, 0.54488, 0.42365, 0.64589, 0.43758] expected = [2 / 3, 0.5, 0.5, 0.5714285714285714, 0.4444444444444444] weighted = [1.06273031, 0.89905622, 0.83253895, 1.12504606, 0.86040934] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list, attributes={"weight": weights}) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, harmonic=False), expected)) assert np.all( np.isclose( nngt.analyze_graph["closeness"](g, weights=True, harmonic=False), weighted)) # with zero degrees and harmonic implementation # closeness does not work for igraph if some nodes have zero in/out-degrees edge_list = [(0, 1), (0, 2), (0, 3), (1, 3), (3, 2), (3, 4), (4, 2)] # DIRECTED harmonic = [7 / 8, 0.5, 0, 0.5, 1 / 4] arithmetic = [0.8, 0.6, np.NaN, 1., 1.] harmonic_in = [0, 1 / 4, 7 / 8, 0.5, 0.5] arithmetic_in = [np.NaN, 1, 0.8, 1., 0.6] harmonic_wght = [1.42006842, 0.92688794, 0., 0.97717257, 0.5713241] arithmetic_wght = [1.28394428, 1.10939361, np.NaN, 1.86996279, 2.2852964] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=True) g.new_edges(edge_list, attributes={"weight": weights}) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, harmonic=True), harmonic)) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, harmonic=False), arithmetic, equal_nan=True)) assert np.all( np.isclose( nngt.analyze_graph["closeness"](g, mode="in", harmonic=True), harmonic_in)) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, mode="in", harmonic=False), arithmetic_in, equal_nan=True)) assert np.all( np.isclose( nngt.analyze_graph["closeness"](g, weights=True, harmonic=True), harmonic_wght)) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, weights=True, harmonic=False), arithmetic_wght, equal_nan=True)) # UNDIRECTED harmonic = [7 / 8, 3 / 4, 7 / 8, 1., 3 / 4] arithmetic = [0.8, 2 / 3, 0.8, 1., 2 / 3] harmonic_wght = [1.436723, 1.382419, 1.76911934, 1.85074797, 1.38520591] arithmetic_wght = [1.3247182, 1.2296379, 1.5717462, 1.8040934, 1.16720163] for bckd in backends: nngt.set_config("backend", bckd) g = nngt.Graph(nodes=num_nodes, directed=False) g.new_edges(edge_list, attributes={"weight": weights}) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, harmonic=True), harmonic)) assert np.all( np.isclose( nngt.analyze_graph["closeness"](g, weights=True, harmonic=True), harmonic_wght)) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, harmonic=False), arithmetic, equal_nan=True)) assert np.all( np.isclose(nngt.analyze_graph["closeness"](g, weights="weight", harmonic=False), arithmetic_wght, equal_nan=True))
def test_config(): ''' Check get/set_config functions. ''' old_cfg = nngt.get_config(detailed=True) # get config cfg = nngt.get_config() for k, v in cfg.items(): assert v == nngt.get_config(k) cfg_detailed = nngt.get_config(detailed=True) for k, v in cfg_detailed.items(): assert v == nngt.get_config(k) # set config (omp) num_omp = 2 nngt.set_config("omp", num_omp) assert nngt.get_config("multithreading") assert nngt.get_config("omp") == num_omp # set config (mpi) has_mpi = False try: import mpi4py has_mpi = True except: pass if has_mpi: nngt.set_config("mpi", True) assert nngt.get_config("mpi") assert not nngt.get_config("multithreading") assert nngt.get_config("omp") == 1 # key error key_error = False try: nngt.set_config("random_entry", "plop") except KeyError: key_error = True assert key_error # except for palettes nngt.set_config("palette_continuous", "viridis") nngt.set_config("palette_discrete", "Set2") # restore old config nngt.set_config(old_cfg)
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with DeNSE. If not, see <http://www.gnu.org/licenses/>. import os import shutil import time import numpy as np import matplotlib #matplotlib.use("GTK3Agg") import matplotlib.pyplot as plt import nngt nngt.set_config("palette", "Spectral") import dense as ds from dense.units import * try: import seaborn as sns sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)}, font_scale=1.5) except: pass def CleanFolder(tmp_dir, make=True): if os.path.isdir(tmp_dir): shutil.rmtree(tmp_dir) if make:
# terms of the GNU General Public License. """ Test the rewire methods of the :mod:`~nngt.generation` module. """ import os import numpy as np import pytest import nngt import nngt.analysis as na import nngt.generation as ng if os.environ.get("MPI"): nngt.set_config("mpi", True) @pytest.mark.mpi_skip def test_random_rewire(): ''' Check random rewire ''' num_nodes = 10 coord_nb = 2 recip = 0.7 shortcut = 0.2 g = ng.newman_watts(coord_nb, shortcut, reciprocity_circular=recip, nodes=num_nodes)
target = current_directory + "/modules/generation.rst" gen_autosum(source, target, 'nngt.generation', 'summary', dtype="func", ignore=ignore['nngt.generation']) gen_autosum(target, target, 'nngt.generation', 'autofunction', dtype="func") # -- NNGT setup ----------------------------------------------------------- from nngt import __version__ as nngt_version # set database try: import peewee nngt.set_config("use_database", True) except ImportError: pass # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.imgmath', 'sphinx.ext.viewcode',
def teardown_module(): ''' teardown any state that was previously setup with setup_module. ''' nngt.set_config("with_plot", with_plot) nngt.set_config("with_nest", with_nest)
# Distributed as a free software, in the hope that it will be useful, under the # terms of the GNU General Public License. """ Test the random seeding and generation """ import os import numpy as np import pytest import nngt import nngt.generation as ng if os.environ.get("MPI"): nngt.set_config("mpi", True) if os.environ.get("OMP"): nngt.set_config("omp", int(os.environ["OMP"])) def get_num_seeds(): if nngt.get_config("multithreading"): return nngt.get_config("omp") return nngt.num_mpi_processes() # ----- # # Tests # # ----- #
import os from os import environ from os.path import dirname, abspath, isfile, join import unittest from scipy.special import lambertw import nngt # set example dir current_dir = dirname(abspath(__file__)) idx_nngt = current_dir.find('nngt/testing') example_dir = current_dir[:idx_nngt] + 'doc/examples/' # remove plotting and NEST nngt.set_config("with_plot", False) nngt.set_config("with_nest", False) # set globals glob = {"lambertw": lambertw} # ---------- # # Test class # # ---------- # class TestExamples(unittest.TestCase): ''' Class testing saving and loading functions. '''
# terms of the GNU General Public License. """ Test the main methods of the :mod:`~nngt.generation` module. """ import unittest import numpy as np import nngt from nngt.analysis import * from nngt.generation import _compute_connections from base_test import TestBasis, XmlHandler, network_dir from tools_testing import foreach_graph nngt.set_config({"multithreading": False}) #-----------------------------------------------------------------------------# # Test tools #------------------------ # def _get_connections(instruct): nodes = instruct["nodes"] density = instruct.get("density", -1) edges = instruct.get("edges", -1) average_degree = instruct.get("avg_deg", -1) reciprocity = instruct.get("weighted", -1) directed = instruct.get("directed", True) #~ weighted = instruct.get("weighted", True))