Python networkx.__version__() Examples
The following are 23
code examples of networkx.__version__().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 6 votes |
def check6_bsddb3(self): '''bsddb3 - Python Bindings for Oracle Berkeley DB requires Berkeley DB PY_BSDDB3_VER_MIN = (6, 0, 1) # 6.x series at least ''' self.append_text("\n") # Start check try: import bsddb3 as bsddb bsddb_str = bsddb.__version__ # Python adaptation layer # Underlying DB library bsddb_db_str = str(bsddb.db.version()).replace(', ', '.')\ .replace('(', '').replace(')', '') except ImportError: bsddb_str = 'not found' bsddb_db_str = 'not found' result = ("* Berkeley Database library (bsddb3: " + bsddb_db_str + ") (Python-bsddb3 : " + bsddb_str + ")") # End check self.append_text(result)
Example #2
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 6 votes |
def check_fontconfig(self): ''' The python-fontconfig library is used to support the Genealogical Symbols tab of the Preferences. Without it Genealogical Symbols don't work ''' try: import fontconfig vers = fontconfig.__version__ if vers.startswith("0.5."): result = ("* python-fontconfig " + vers + " (Success version 0.5.x is installed.)") else: result = ("* python-fontconfig " + vers + " (Requires version 0.5.x)") except ImportError: result = "* python-fontconfig Not found, (Requires version 0.5.x)" # End check self.append_text(result) #Optional
Example #3
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 6 votes |
def check23_pedigreechart(self): '''PedigreeChart - Can optionally use - NumPy if installed https://github.com/gramps-project/addons-source/blob/master/PedigreeChart/PedigreeChart.py ''' self.append_text("\n") self.render_text("""<b>03. <a href="https://gramps-project.org/wiki""" """/index.php?title=PedigreeChart">""" """Addon:PedigreeChart</a> :</b> """) # Start check try: import numpy numpy_ver = str(numpy.__version__) #print("numpy.__version__ :" + numpy_ver ) # NUMPY_check = True except ImportError: numpy_ver = "Not found" # NUMPY_check = False result = "(NumPy : " + numpy_ver + " )" # End check self.append_text(result) #self.append_text("\n")
Example #4
Source File: test_gexf.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_edge_id_construct(self): G = nx.Graph() G.add_edges_from([(0, 1, {'id': 0}), (1, 2, {'id': 2}), (2, 3)]) expected = """<gexf version="1.2" xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance"> <graph defaultedgetype="undirected" mode="static" name=""> <meta> <creator>NetworkX {}</creator> <lastmodified>{}</lastmodified> </meta> <nodes> <node id="0" label="0" /> <node id="1" label="1" /> <node id="2" label="2" /> <node id="3" label="3" /> </nodes> <edges> <edge id="0" source="0" target="1" /> <edge id="2" source="1" target="2" /> <edge id="1" source="2" target="3" /> </edges> </graph> </gexf>""".format(nx.__version__, time.strftime('%d/%m/%Y')) obtained = '\n'.join(nx.generate_gexf(G)) assert_equal(expected, obtained)
Example #5
Source File: vis_corex.py From bio_corex with Apache License 2.0 | 6 votes |
def trim(g, max_parents=False, max_children=False): if float(nx.__version__) < 2: edgedict = g.edge else: edgedict = g.adj for node in g: if max_parents: parents = list(g.successors(node)) weights = [edgedict[node][parent]['weight'] for parent in parents] for weak_parent in np.argsort(weights)[:-max_parents]: g.remove_edge(node, parents[weak_parent]) if max_children: children = g.predecessors(node) weights = [edgedict[child][node]['weight'] for child in children] for weak_child in np.argsort(weights)[:-max_children]: g.remove_edge(children[weak_child], node) return g
Example #6
Source File: meta.py From quantumflow with Apache License 2.0 | 6 votes |
def print_versions(file: typing.TextIO = None) -> None: """ Print version strings of currently installed dependencies ``> python -m quantumflow.meta`` Args: file: Output stream. Defaults to stdout. """ print('** QuantumFlow dependencies (> python -m quantumflow.meta) **') print('quantumflow \t', qf.__version__, file=file) print('python \t', sys.version[0:5], file=file) print('numpy \t', np.__version__, file=file) print('networkx \t', nx.__version__, file=file) print('cvxpy \t', cvx.__version__, file=file) print('pyquil \t', pyquil.__version__, file=file) print(bk.name, ' \t', bk.version, '(BACKEND)', file=file)
Example #7
Source File: topology.py From vitrage with Apache License 2.0 | 6 votes |
def as_tree(graph, root=OPENSTACK_CLUSTER, reverse=False): if nx.__version__ >= '2.0': linked_graph = json_graph.node_link_graph( graph, attrs={'name': 'graph_index'}) else: linked_graph = json_graph.node_link_graph(graph) if 0 == nx.number_of_nodes(linked_graph): return {} if reverse: linked_graph = linked_graph.reverse() if nx.__version__ >= '2.0': return json_graph.tree_data( linked_graph, root=root, attrs={'id': 'graph_index', 'children': 'children'}) else: return json_graph.tree_data(linked_graph, root=root)
Example #8
Source File: util.py From diffpool with MIT License | 5 votes |
def node_iter(G): if float(nx.__version__)<2.0: return G.nodes() else: return G.nodes
Example #9
Source File: gexf.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def add_meta(self, G, graph_element): # add meta element with creator and date meta_element = Element('meta') SubElement(meta_element, 'creator').text = 'NetworkX {}'.format(nx.__version__) SubElement(meta_element, 'lastmodified').text = time.strftime('%d/%m/%Y') graph_element.append(meta_element)
Example #10
Source File: test_gexf.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_write_with_node_attributes(self): # Addresses #673. G = nx.OrderedGraph() G.add_edges_from([(0, 1), (1, 2), (2, 3)]) for i in range(4): G.nodes[i]['id'] = i G.nodes[i]['label'] = i G.nodes[i]['pid'] = i expected = """<gexf version="1.2" xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance"> <graph defaultedgetype="undirected" mode="static" name=""> <meta> <creator>NetworkX {}</creator> <lastmodified>{}</lastmodified> </meta> <nodes> <node id="0" label="0" pid="0" /> <node id="1" label="1" pid="1" /> <node id="2" label="2" pid="2" /> <node id="3" label="3" pid="3" /> </nodes> <edges> <edge id="0" source="0" target="1" /> <edge id="1" source="1" target="2" /> <edge id="2" source="2" target="3" /> </edges> </graph> </gexf>""".format(nx.__version__, time.strftime('%d/%m/%Y')) obtained = '\n'.join(nx.generate_gexf(G)) assert_equal(expected, obtained)
Example #11
Source File: gexf.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def add_meta(self, G, graph_element): # add meta element with creator and date meta_element = Element('meta') SubElement(meta_element, 'creator').text = 'NetworkX {}'.format(nx.__version__) SubElement(meta_element, 'lastmodified').text = time.strftime('%d/%m/%Y') graph_element.append(meta_element)
Example #12
Source File: test_gexf.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_write_with_node_attributes(self): # Addresses #673. G = nx.OrderedGraph() G.add_edges_from([(0, 1), (1, 2), (2, 3)]) for i in range(4): G.nodes[i]['id'] = i G.nodes[i]['label'] = i G.nodes[i]['pid'] = i G.nodes[i]['start'] = i G.nodes[i]['end'] = i + 1 expected = """<gexf version="1.2" xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance"> <graph defaultedgetype="undirected" mode="dynamic" name="" timeformat="long"> <meta> <creator>NetworkX {}</creator> <lastmodified>{}</lastmodified> </meta> <nodes> <node end="1" id="0" label="0" pid="0" start="0" /> <node end="2" id="1" label="1" pid="1" start="1" /> <node end="3" id="2" label="2" pid="2" start="2" /> <node end="4" id="3" label="3" pid="3" start="3" /> </nodes> <edges> <edge id="0" source="0" target="1" /> <edge id="1" source="1" target="2" /> <edge id="2" source="2" target="3" /> </edges> </graph> </gexf>""".format(nx.__version__, time.strftime('%d/%m/%Y')) obtained = '\n'.join(nx.generate_gexf(G)) assert_equal(expected, obtained)
Example #13
Source File: networkx_graph.py From vitrage with Apache License 2.0 | 5 votes |
def json_output_graph(self, **kwargs): """supports both 1.10<=networkx<2.0 and networx>=2.0 by returning the same json output regardless networx version :return: graph in json format """ # TODO(annarez): when we decide to support networkx 2.0 with # versioning of Vitrage, we can move part of the logic to vitrageclient node_link_data = json_graph.node_link_data(self._g) node_link_data.update(kwargs) vitrage_id_to_index = dict() for index, node in enumerate(node_link_data['nodes']): vitrage_id_to_index[node[VProps.VITRAGE_ID]] = index if VProps.ID in self._g.nodes[node[VProps.ID]]: node[VProps.ID] = self._g.nodes[node[VProps.ID]][VProps.ID] node[VProps.GRAPH_INDEX] = index vers = nx.__version__ if vers >= '2.0': for i in range(len(node_link_data['links'])): node_link_data['links'][i]['source'] = vitrage_id_to_index[ node_link_data['links'][i]['source']] node_link_data['links'][i]['target'] = vitrage_id_to_index[ node_link_data['links'][i]['target']] if kwargs.get('raw', False): return node_link_data else: return json.dumps(node_link_data)
Example #14
Source File: topology.py From vitrage with Apache License 2.0 | 5 votes |
def get_graph(graph_type, depth, query, root, all_tenants): TopologyController._check_input_para(graph_type, depth, query, root, all_tenants) try: graph_data = pecan.request.client.call(pecan.request.context, 'get_topology', graph_type=graph_type, depth=depth, query=query, root=root, all_tenants=all_tenants) graph = decompress_obj(graph_data) if graph_type == 'graph': return graph if graph_type == 'tree': if nx.__version__ >= '2.0': node_id = '' for node in graph['nodes']: if (root and node[VProps.VITRAGE_ID] == root) or \ (not root and node[VProps.ID] == CLUSTER_ID): node_id = node[VProps.GRAPH_INDEX] break else: node_id = CLUSTER_ID if root: for node in graph['nodes']: if node[VProps.VITRAGE_ID] == root: node_id = node[VProps.ID] break return TopologyController.as_tree(graph, node_id) except Exception: LOG.exception('failed to get topology.') abort(404, 'Failed to get topology.')
Example #15
Source File: util.py From diffpool with MIT License | 5 votes |
def node_dict(G): if float(nx.__version__)>2.1: node_dict = G.nodes else: node_dict = G.node return node_dict # ---------------------------
Example #16
Source File: hyperopt_august2013_mod.py From HPOlib with GNU General Public License v3.0 | 5 votes |
def check_dependencies(self): try: import nose self.logger.debug("\tNose: %s\n" % str(nose.__version__)) except ImportError: raise ImportError("Nose cannot be imported. Are you sure it's " "installed?") try: import networkx self.logger.debug("\tnetworkx: %s\n" % str(networkx.__version__)) except ImportError: raise ImportError("Networkx cannot be imported. Are you sure it's " "installed?") try: import pymongo self.logger.debug("\tpymongo: %s\n" % str(pymongo.version)) from bson.objectid import ObjectId except ImportError: raise ImportError("Pymongo cannot be imported. Are you sure it's" " installed?") try: import numpy self.logger.debug("\tnumpy: %s" % str(numpy.__version__)) except ImportError: raise ImportError("Numpy cannot be imported. Are you sure that it's" " installed?") try: import scipy self.logger.debug("\tscipy: %s" % str(scipy.__version__)) except ImportError: raise ImportError("Scipy cannot be imported. Are you sure that it's" " installed?")
Example #17
Source File: random_hyperopt_august2013_mod.py From HPOlib with GNU General Public License v3.0 | 5 votes |
def check_dependencies(self): try: import nose self.logger.debug("\tNose: %s\n" % str(nose.__version__)) except ImportError: raise ImportError("Nose cannot be imported. Are you sure it's " "installed?") try: import networkx self.logger.debug("\tnetworkx: %s\n" % str(networkx.__version__)) except ImportError: raise ImportError("Networkx cannot be imported. Are you sure it's " "installed?") try: import pymongo self.logger.debug("\tpymongo: %s\n" % str(pymongo.version)) from bson.objectid import ObjectId except ImportError: raise ImportError("Pymongo cannot be imported. Are you sure it's" " installed?") try: import numpy self.logger.debug("\tnumpy: %s" % str(numpy.__version__)) except ImportError: raise ImportError("Numpy cannot be imported. Are you sure that it's" " installed?") try: import scipy self.logger.debug("\tscipy: %s" % str(scipy.__version__)) except ImportError: raise ImportError("Scipy cannot be imported. Are you sure that it's" " installed?")
Example #18
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 5 votes |
def check17_pillow(self): '''PILLOW Allows Production of jpg images from non-jpg images in LaTeX documents #TODO prculley mentions that : And PIL (Pillow) is also used by the main Gramps ([]narrativeweb and []other reports for image cropping) as well as [x]editexifmetadata and the new [x]latexdoc type addons (genealogytree). #TODO add check for PILLOW to "gramps -v" section https://github.com/gramps-project/gramps/blob/maintenance/gramps50/gramps/plugins/docgen/latexdoc.py ''' #self.append_text("\n") # Start check try: import PIL # from PIL import Image try: pil_ver = PIL.__version__ except Exception: try: pil_ver = str(PIL.PILLOW_VERSION) except Exception: try: #print(dir(PIL)) pil_ver = str(PIL.VERSION) except Exception: pil_ver = "Installed but does not supply version" except ImportError: pil_ver = "Not found" result = "(PILLOW " + pil_ver + ")" # End check self.append_text(result)
Example #19
Source File: app.py From dataiku-contrib with Apache License 2.0 | 4 votes |
def draw_graph(): #get data project_key = dataiku.default_project_key() similarity = float(request.args.get('similarity')) node_source = request.args.get('node_source') node_target = request.args.get('node_target') interactions = request.args.get('interactions') dataset = request.args.get('dataset') name=project_key+'.'+dataset print name df=dataiku.Dataset(name).get_dataframe() df=df[df[interactions]>similarity] df=df[[node_source,node_target,interactions]] df.columns=['source','target','weight'] print "%d rows" % df.shape[0] G=nx.Graph() G.add_edges_from(zip(df.source,df.target)) print nx.info(G) # degree for node, val in dict(nx.degree(G)).iteritems(): G.node[node]['degree'] = val # pagerank for node, val in dict(nx.pagerank(G)).iteritems(): G.node[node]['pagerank'] = val # connected components components = sorted(nx.connected_components(G), key = len, reverse=True) for component,nodes in enumerate(components): for node in nodes: G.node[node]['cc'] = component # community partition = best_partition(G) for node, cluster in dict(partition).iteritems(): G.node[node]['community'] = cluster # convert to JSON data = json_graph.node_link_data(G) #fix for networkx>=2.0 change of API if nx.__version__ > 2: dict_name_id = {data["nodes"][i]["id"] : i for i in xrange(len(data["nodes"]))} for link in data["links"]: link["source"] = dict_name_id[link["source"]] link["target"] = dict_name_id[link["target"]] return json.dumps({"status" : "ok", "graph": data})
Example #20
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 4 votes |
def check32_phototagginggramplet(self): '''PhotoTaggingGramplet - Gramplet for tagging people in photos If the OpenCV is not found, the automatic face detection feature will be unavailable, but the Gramplet should otherwise function correctly. Automatic detection of faces requires the following to be installed: * OpenCV, its dependencies and Python bindings. This library should be available in common Linux distributions. For example, Debian package python-opencv provides the Python bindings for the library. It will require the core library packages (libopencv-*) and the * python-numpy package. https://gramps-project.org/wiki/index.php?title=Photo_Tagging_Gramplet https://github.com/gramps-project/addons-source/blob/master/PhotoTaggingGramplet/facedetection.py https://github.com/gramps-project/addons-source/tree/master/PhotoTaggingGramplet ...... ubuntu: pip3 install opencv-python import cv2 cv2.__version__ '3.4.0' ''' self.append_text("\n") self.render_text("""<b>12. <a href="https://gramps-project.org/wiki""" """/index.php?title=Photo_Tagging_Gramplet">""" """Addon:Photo Tagging Gramplet</a> :</b> """) # Start check try: import cv2 cv2_ver = cv2.__version__ #print(dir(cv2)) except ImportError: cv2_ver = "Not found" try: import numpy numpy_ver = str(numpy.__version__) #print("numpy.__version__ :" + numpy_ver ) except ImportError: numpy_ver = "Not found" self.append_text("(NumPy: " + numpy_ver + ")") self.append_text("(OpenCV facedetection: %s)" % cv2_ver)
Example #21
Source File: test_gexf.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_numpy_type(self): G = nx.path_graph(4) try: import numpy except ImportError: return nx.set_node_attributes(G, {n:n for n in numpy.arange(4)}, 'number') G[0][1]['edge-number'] = numpy.float64(1.1) expected = """<gexf version="1.2" xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance"> <graph defaultedgetype="undirected" mode="static" name=""> <attributes class="edge" mode="static"> <attribute id="1" title="edge-number" type="float" /> </attributes> <attributes class="node" mode="static"> <attribute id="0" title="number" type="int" /> </attributes> <meta> <creator>NetworkX {}</creator> <lastmodified>{}</lastmodified> </meta> <nodes> <node id="0" label="0"> <attvalues> <attvalue for="0" value="0" /> </attvalues> </node> <node id="1" label="1"> <attvalues> <attvalue for="0" value="1" /> </attvalues> </node> <node id="2" label="2"> <attvalues> <attvalue for="0" value="2" /> </attvalues> </node> <node id="3" label="3"> <attvalues> <attvalue for="0" value="3" /> </attvalues> </node> </nodes> <edges> <edge id="0" source="0" target="1"> <attvalues> <attvalue for="1" value="1.1" /> </attvalues> </edge> <edge id="1" source="1" target="2" /> <edge id="2" source="2" target="3" /> </edges> </graph> </gexf>""".format(nx.__version__, time.strftime('%d/%m/%Y')) obtained = '\n'.join(nx.generate_gexf(G)) assert_equal(expected, obtained)
Example #22
Source File: PrerequisitesCheckerGramplet.py From addons-source with GNU General Public License v2.0 | 4 votes |
def check24_networkchart(self): '''Network Chart - requires networkx 1.11, pygraphviz, (need to add to readme) ''' self.append_text("\n") self.render_text("""<b>04. <a href="https://gramps-project.org/wiki""" """/index.php?title=NetworkChart">""" """Addon:Network Chart</a> :</b> """) # Start check # To get "libcgraph" for pygraphviz you first need to install # the development package of graphviz eg: graphviz-dev try: # import importlib # module1 = importlib.find_loader("networkx") is not None import networkx networkx_ver = str(networkx.__version__) #print("networkx version:" + networkx_ver) except Exception: networkx_ver = "Not installed" # module1 = "Not tested" try: # import importlib # module2 = importlib.find_loader("pydotplus") is not None import pydotplus pydotplus_ver = str(pydotplus.pyparsing_version) #print("pydotplus version:" + pydotplus_ver) except Exception: pydotplus_ver = "Not Installed" # module2 = "Not tested" try: # import importlib # module3 = importlib.find_loader("pygraphviz") is not None import pygraphviz pygraphviz_ver = str(pygraphviz.__version__) #print("pygraphviz version:" + pygraphviz_ver) except Exception: pygraphviz_ver = "Not Installed" # module3 = "Not tested" # End check self.append_text("(networkx " + networkx_ver + ")(") self.check12_graphviz() self.append_text(")\n") self.append_text(" and one of either: (pydotplus: " + pydotplus_ver + ") or (pygraphviz: " + pygraphviz_ver + ")")
Example #23
Source File: __init__.py From strawberryfields with Apache License 2.0 | 4 votes |
def about(): """Strawberry Fields information. Prints the installed version numbers for SF and its dependencies, and some system info. Please include this information in bug reports. **Example:** .. code-block:: pycon >>> sf.about() Strawberry Fields: a Python library for continuous-variable quantum circuits. Copyright 2018-2020 Xanadu Quantum Technologies Inc. Python version: 3.6.8 Platform info: Linux-5.0.0-36-generic-x86_64-with-debian-buster-sid Installation path: /home/josh/Dropbox/Work/Xanadu/sf_cloud/strawberryfields Strawberry Fields version: 0.12.0-dev Numpy version: 1.17.4 Scipy version: 1.3.0 Sympy version: 1.5 NetworkX version: 2.4 The Walrus version: 0.10.0 Blackbird version: 0.2.1 TensorFlow version: 2.0.0 """ # pylint: disable=import-outside-toplevel import sys import platform import os import numpy import scipy import sympy import networkx import thewalrus import blackbird # a QuTiP-style infobox print("\nStrawberry Fields: a Python library for continuous-variable quantum circuits.") print("Copyright 2018-2020 Xanadu Quantum Technologies Inc.\n") print("Python version: {}.{}.{}".format(*sys.version_info[0:3])) print("Platform info: {}".format(platform.platform())) print("Installation path: {}".format(os.path.dirname(__file__))) print("Strawberry Fields version: {}".format(__version__)) print("Numpy version: {}".format(numpy.__version__)) print("Scipy version: {}".format(scipy.__version__)) print("SymPy version: {}".format(sympy.__version__)) print("NetworkX version: {}".format(networkx.__version__)) print("The Walrus version: {}".format(thewalrus.__version__)) print("Blackbird version: {}".format(blackbird.__version__)) try: import tensorflow tf_version = tensorflow.__version__ except ImportError: tf_version = None print("TensorFlow version: {}".format(tf_version))