本文整理汇总了Python中networkx.adjacency_matrix函数的典型用法代码示例。如果您正苦于以下问题:Python adjacency_matrix函数的具体用法?Python adjacency_matrix怎么用?Python adjacency_matrix使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了adjacency_matrix函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: env_init
def env_init(self):
"""
Based on the levin model, the dispersion probability is initialized.
"""
self.dispersionModel = InvasiveUtility.Levin
notDirectedG = networkx.Graph(self.simulationParameterObj.graph)
adjMatrix = adjacency_matrix(notDirectedG)
edges = self.simulationParameterObj.graph.edges()
simulationParameterObj = self.simulationParameterObj
if self.dispersionModel == InvasiveUtility.Levin:
parameters = InvasiveUtility.calculatePath(notDirectedG,adjMatrix, edges, simulationParameterObj.downStreamRate,
simulationParameterObj.upStreamRate)
C = (1 - simulationParameterObj.upStreamRate * simulationParameterObj.downStreamRate) / (
(1 - 2 * simulationParameterObj.upStreamRate) * (1 - simulationParameterObj.downStreamRate))
self.dispertionTable = np.dot(1 / C, parameters)
self.germinationObj = GerminationDispersionParameterClass(1, 1)
#calculating the worst case fully invaded rivers cost
worst_case = repmat(1, 1, self.simulationParameterObj.nbrReaches * self.simulationParameterObj.habitatSize)[0]
cost_state_unit = InvasiveUtility.get_unit_invaded_reaches(worst_case,
self.simulationParameterObj.habitatSize) * self.actionParameterObj.costPerReach
stateCost = cost_state_unit + InvasiveUtility.get_invaded_reaches(
worst_case) * self.actionParameterObj.costPerTree
stateCost = stateCost + InvasiveUtility.get_empty_slots(worst_case) * self.actionParameterObj.emptyCost
costAction = InvasiveUtility.get_budget_cost_actions(repmat(3, 1, self.simulationParameterObj.nbrReaches)[0],
worst_case, self.actionParameterObj)
networkx.adjacency_matrix(self.simulationParameterObj.graph)
return "VERSION RL-Glue-3.0 PROBLEMTYPE non-episodic DISCOUNTFACTOR " + str(
self.discountFactor) + " OBSERVATIONS INTS (" + str(
self.simulationParameterObj.nbrReaches * self.simulationParameterObj.habitatSize) + " 1 3) ACTIONS INTS (" + str(
self.simulationParameterObj.nbrReaches) + " 1 4) REWARDS (" + str(self.Bad_Action_Penalty)+" "+str(
-1 * (costAction + stateCost)) + ") EXTRA "+str(self.simulationParameterObj.graph.edges()) + " BUDGET "+str(self.actionParameterObj.budget) +" by Majid Taleghan."
示例2: dsd_matrix
def dsd_matrix(G, nodeList, npyFile, LMsetSize=50, centralityFunc='degree', **kwargs):
"""
any kwargs, if specified, will be passed into centrality function call.
"""
# if npy path not entered, or file does not exist, compute D
if not npyFile or not os.path.isfile(npyFile):
#
# construct hemat
#
adjMatrix = np.array(nx.adjacency_matrix(G,nodeList))
if np.shape(adjMatrix) == ():
adjMatrix = np.array(nx.adjacency_matrix(G,nodeList).todense())
HEmatrix = dsd.hematrix(adjMatrix)
# construct DSD
LMset = get_LMset(G, nodeList, LMsetSize, centralityFunc, **kwargs)
D = dsd.DSD(HEmatrix,LMset)
if npyFile:
try:
np.save(npyFile, D)
except IOError:
os.makedirs(npyFile[:npyFile.rfind('/')])
np.save(npyFile, D)
# otherwise just load and return it
else:
D = np.load(npyFile)
return D
示例3: nsim_bvd04
def nsim_bvd04(G1, G2, max_iter=100, eps=1e-4):
"""
Algorithm to calculate node-node similarity matrix of
two directed graphs.
Return
------
A 2d similarity matrix of |V1| x |V2|.
Reference
---------
Blondel, Vincent D. et al. "A Measure of Similarity between Graph Vertices:
Applications to Synonym Extraction and Web Searching." SIAM Review (2004)
"""
N = len(G1.nodes())
M = len(G2.nodes())
A = nx.adjacency_matrix(G1).todense()
B = nx.adjacency_matrix(G2).todense()
nsim_prev = np.zeros((M, N))
nsim = np.ones((M, N))
for i in range(max_iter):
if np.allclose(nsim, nsim_prev, atol=eps):
break
nsim_prev = np.copy(nsim)
nsim = np.dot(np.dot(B, nsim_prev), A.T) + \
np.dot(np.dot(B.T, nsim_prev), A)
fnorm = np.linalg.norm(nsim, ord='fro')
nsim = nsim / fnorm
print("Converge after %d iterations (eps=%f)." % (i, eps))
return nsim.T
示例4: are_isomorphic
def are_isomorphic(G, H):
"""Check whether two graphs G and H are isomorphic.
Note: This function is brute force and very slow.
args:
G: a networkx Graph
H: a networkx Graph
returns:
True if G and H are isomorphic.
False if G and H are not isomorphic.
"""
n = len(G.nodes())
m = len(H.nodes())
if n != m:
return False
if sorted(G.degree().values()) != sorted(H.degree().values()):
return False
else:
a_g = nx.adjacency_matrix(G)
vertex_perms = list(permutations(H.nodes(), m))
for i in vertex_perms:
a_h = nx.adjacency_matrix(H, i)
if (a_h == a_g).all():
#print(list(zip(G.nodes(), i)), "is an isomorphism")
return True
return False
示例5: lesion_graph_degree_thresh
def lesion_graph_degree_thresh(graph, threshold):
"""
Remove vertices from a graph with degree greater than or equal to
threshold.
Parameters:
-----------
graph: NetworkX graph to be lesioned.
threshold: Degree above which to remove nodes.
Returns:
--------
G: NetworkX graph
A: Adjacency matrix for graph
"""
# Error checking
G = deepcopy(graph)
assert threshold >= 0, " In percolation, `threshold` must be >= 0."
# Check if lesioning is necessary for threshold
if threshold > max(G.degree().values()):
return G, nx.adjacency_matrix(G)
# Identify all node indices >= threshold
node_inds = np.where(np.asarray(G.degree().values()) >= threshold)[0]
# Eliminate these nodes
G.remove_nodes_from(node_inds)
if G.order() > 0:
return G, nx.adjacency_matrix(G)
else:
#print 'Graph completely lesioned.'
return None, None
示例6: similarity
def similarity(self, G=None, H=None, iters=1000):
""" Returns the graph similarity based on
:param G: networkx graph of original graph (default: self.G)
:param H: networkx graph of inferred graph (default: self.H)
:param iter: number of iterations (default: 20)
:return: float
"""
if G is None:
G = self.G
if H is None:
H = self.H
n = len(G)
gA = nx.adjacency_matrix(G)
hA = nx.adjacency_matrix(H)
s = np.identity(n) # initial condition
for i in range(iters):
temp = (np.kron(gA, hA) + np.kron(gA.T, hA.T)) * s + \
np.identity(n) * 0.0000001
s = temp / np.linalg.norm(temp)
a = np.trace(s)
temp = (np.kron(gA, hA) + np.kron(gA.T, hA.T)) * s
s = temp / np.linalg.norm(temp)
a += np.trace(s)
return a / 2
示例7: lesion_graph_degree
def lesion_graph_degree(graph, num_lesions):
"""
Remove vertices from a graph according to degree.
Args:
graph: NetworkX graph to be lesioned.
num_lesions: Number of top degree nodes to remove.
Returns:
G: NetworkX graph
A: Adjacency matrix for graph
"""
# Error checking
G = deepcopy(graph)
if num_lesions == 0:
return G, nx.adjacency_matrix(G)
assert num_lesions >= 0 and num_lesions < graph.order, 'Attempting to\
remove too many/few nodes'
for l in range(num_lesions):
# Identify node to cut
node_i, node_d = max(G.degree().items(),
key=lambda degree: degree[1])
G.remove_node(node_i)
#print (node_i, node_d)
if G.order() > 0:
return G, nx.adjacency_matrix(G)
else:
print 'Graph completely lesioned.'
return None, None
示例8: update_nl
def update_nl(self, dist):
self.G.remove_edges_from(self.G.edges())
print "dr:"
print self.dr()
for row in list(enumerate(self.dr())):
for col in list(enumerate(row[1])):
if col[1] > dist:
self.G.add_edge(col[0], row[0], x=self.x[col[0]]-self.x[row[0]], y=self.y[col[0]]-self.y[row[0]], z=0., r=col[1])
print nx.adjacency_matrix(self.G)
示例9: createMultiplex
def createMultiplex(self):
print self.politicsGraph.nodes().__len__()
sortedPoliticalComentators = sorted(self.politicsGraph.nodes())
politicalComentatorsAdjMat = nx.adjacency_matrix(self.politicsGraph, sortedPoliticalComentators)
sortedChurchComentators = sorted(self.churchGraph.nodes())
churchComentatorsAdjMat = nx.adjacency_matrix(self.churchGraph, sortedChurchComentators)
otherComentators = sorted(self.othersGraph.nodes())
otherAdjMat = nx.adjacency_matrix(self.othersGraph, otherComentators)
self.addLayerToGraph(politicalComentatorsAdjMat, sortedPoliticalComentators, 'L1', 1)
self.addLayerToGraph(churchComentatorsAdjMat, sortedChurchComentators, 'L2', 2)
self.addLayerToGraph(otherAdjMat, otherComentators, 'L3', 3)
示例10: show_graph_features
def show_graph_features(G,circular=False):
for node,adj_list in G.adjacency_iter():
print node, ': ',adj_list
print nx.adjacency_matrix(G)
#N\u00f3s:
print 'N\u00famero de n\u00f3s: ',G.number_of_nodes()
print 'N\u00f3s: \\n','\\t',G.nodes()
#Arestas:
print 'N\u00famero de arestas: ',G.number_of_edges()
print 'Arestas: \\n','\\t',G.edges(data=True)
示例11: graph_diff
def graph_diff(g0, g1):
m0 = nx.adjacency_matrix(g0)
m1 = nx.adjacency_matrix(g1)
delta = 0
for i in range(0, m0.shape[0]):
for j in range(0, m0.shape[1]):
if i > j:
# print m0[(i,j)],int(m1[(i,j)]>0)
# if(m0[(i,j)]==1 and int(m1[(i,j)]>0)!=1):
if m0[(i, j)] != int(m1[(i, j)] > 0):
delta += 1
return delta
示例12: cal_exact_Nd_simple
def cal_exact_Nd_simple(H, random_weight=False):
"""return (Nd, N-Rank) """
G = H.copy()
N = H.number_of_nodes()
try:
G2 = nx.adjacency_matrix(G, weight = 'weight')
#~ print 'weight'
except:
G2 = nx.adjacency_matrix(G)
if random_weight:
G2 = np.array(G2)*np.random.random((N, N))
rank_G = mranksvd(G2)
return max(1, N-rank_G), N-rank_G
示例13: GTrieInsert
def GTrieInsert(self, graph, label=None, states=False):
if not self.root.isLeaf() and self.null_graph:
self.insertRecursive(networkx.Graph(), [], networkx.adjacency_matrix(networkx.Graph()).todense(),
self.root, 0, label, states)
components = networkx.connected_components(graph.to_undirected()) \
if networkx.is_directed(graph) else networkx.connected_components(graph)
component_len = [1 for x in components if len(x) > 1]
if len(list(components)) > 1 and sum(component_len) > 1:
print "Illegal Graph Insert: Graph has more than one connnected component."
return
cannonGraph = self.GTCannon(graph.copy())
matrix = networkx.adjacency_matrix(cannonGraph).todense()
conditions = self.utility.symmetryConditions(cannonGraph)
self.insertRecursive(cannonGraph, conditions, matrix, self.root, 0, label, states)
示例14: init
def init():
global op1, op2, grouping, network, adj_mat
op1 = [(-1 + 2 * random.random()) for agents in range(no_of_agents)]
op2 = [(-1 + 2 * random.random()) for agents in range(no_of_agents)]
grouping = [random.randint(1,m) for agents in range(no_of_agents)]
network = nx.erdos_renyi_graph(no_of_agents,p)
adj_mat = nx.adjacency_matrix(network)
示例15: test_eigenvector_v_katz_random
def test_eigenvector_v_katz_random(self):
G = nx.gnp_random_graph(10,0.5, seed=1234)
l = float(max(eigvals(nx.adjacency_matrix(G).todense())))
e = nx.eigenvector_centrality_numpy(G)
k = nx.katz_centrality_numpy(G, 1.0/l)
for n in G:
assert_almost_equal(e[n], k[n])