我需要在networkx 2.1中生成一个随机的全连接有向图,以评估非对称旅行商问题的算法的性能。例如,生成具有100个节点的图,它们是完全连接的,边缘权重是随机分配的。该图是有向的(从节点i到节点j的边缘权重不一定等于从节点j到节点i的边缘权重)
想知道是否有一个networkx函数来生成这种有向图或一些示例代码以供参考。
我检查了networkx 2.1(https://networkx.github.io/documentation/networkx-2.1/reference/generators.html?highlight=generator#module-networkx.generators.directed)文档中的“定向生成器”部分,但是这些生成器似乎不符合我的要求。
答案 0 :(得分:2)
Networkx并不完全具有这种生成器,因为它是非常特定的任务。因此,您应该手动构造该图。您可以创建完整的有向图:
export class RegistercustomerPage implements OnInit {
category= "product";
constructor(private geolocation: Geolocation){}
ngOnInit() {
this.loadMap();
}
loadMap(){
this.geolocation.getCurrentPosition().then((resp) => {
console.log(this.category);
this.disaplyCategory();
});
}
disaplyCategory(){
alert(this.category)
}
}
,然后为每个图形边缘分配随机权重:
........................
for book_data in data['items']:
volume_info = book_data['volumeInfo']
title = volume_info['title']
genres = volume_info.get('categories')
authors = volume_info.get('authors')
description = volume_info.get('description')
if not Books.objects.filter(title=title).exists():
book = Books.objects.create(title=title, description=description)
# Does authors exists in database?
existing_authors = Authors.objects.filter(author_name__in=authors)
existing_authors_names = {authors.author_name for authors in existing_authors}
# Create a list of missing authors
missing_authors = [
Authors(author_name=author_name)
for author_name in authors
if author_name not in existing_authors_names
]
# Creating author before adding it to relation
if missing_authors:
missing_authors = Authors.objects.bulk_create(missing_authors)
print(missing_authors)
for m in missing_authors:
m.save()
# Adding to relation
book.authors.add(*existing_authors, *missing_authors)
..........................
因此您将准确获得所需的图形:
class Authors(models.Model):
author_name = models.CharField(max_length=200)
def __str__(self):
return self.author_name
class Books(models.Model):
title = models.CharField(max_length=300)
description = models.TextField(blank=True, null=True)
authors = models.ManyToManyField(Authors, blank=True)
genres = models.ManyToManyField(Genres, blank=True)
def __str__(self):
return self.title
import networkx as nx
import random
N = 7
G = nx.complete_graph(N, nx.DiGraph())
答案 1 :(得分:2)
有关如何执行此操作的几种选择。在这里,我仅使用itertools
列出具有随机权重的所有加权边的列表。然后,我使用add_weighted_edges_from
创建有向图。这样就不会太长,我只使用3个节点。
import networkx as nx
import itertools
import random
G = nx.DiGraph()
weighted_edge_list = [(u,v,random.random()) for u,v in itertools.permutations(range(3),2)]
G.add_weighted_edges_from(weighted_edge_list)
G.edges(data=True)
> OutEdgeDataView([(0, 1, {'weight': 0.025851202944826346}), (0, 2, {'weight': 0.8067025754602839}), (1, 0, {'weight': 0.7729736390607577}), (1, 2, {'weight': 0.8724493159416196}), (2, 0, {'weight': 0.9049870220916731}), (2, 1, {'weight': 0.9636865700934618})])