我写了一些代码,试图使用本文中提到的一系列启发式和算法来近似最小化反馈弧集/最大化有向图的最大非循环子图(最多n=100个节点)的顶点的排序Franz J.Brandenburg和Kathrin Hanauer的《设置问题》,德国帕索大学。
被读入的数据是一个邻接矩阵,它被转换为igraph。图形实例。
我正在记忆成本函数和筛选函数。这两个函数的参数都是rank(包含顶点排序的元组)和edgeList(包含表示边的元组的元组)。
由于我一次处理多个实例,并且顶点由整数表示,因此我需要确保在处理一个实例(图)后,两个函数的缓存都被清除,我不完全确定这是否会发生。我发现了一些memize定时缓存实现和memize with _remove方法,尽管我一直得到相同的结果。
这是为今天早些时候(2015年6月12日下午5:00)到期的一个项目准备的,但由于我很固执,我一直在努力,并希望确保我正确使用了记忆方法。
我附上我使用过的相关代码:
@memoize
def cost(rank, edgeList):
rankMap = {}
for i in range(len(rank)):
rankMap[rank[i]] = i
cost = 0
for edge in edgeList:
u, v = edge[0], edge[1]
if rankMap[u] < rankMap[v]:
cost += 1
return cost
class memoize:
"""Gives the class it's core functionality."""
def __call__(self, *args):
if args not in self._memos:
self._memos[args] = self._function(*args)
return self._memos[args]
def __init__(self, function):
self._memos = {}
self._function = function
"""Removes all memos. This is particularly useful if something that affects the output has changed."""
def remove_memos(self):
self._memos = {}
def alg_star(algorithm, costFunc, graph, rank):
edgeList = tuple([i.tuple for i in graph.es()])
while True:
rankPrime = rank
rank = algorithm(tuple(rank), edgeList)
if costFunc(tuple(rank), edgeList) <= costFunc(tuple(rankPrime), edgeList):
break
return rankPrime
@memoize
def sifting(rank, edgeList):
copyRank = list(rank)
rankValues = {}
for node in rank:
rankValues[tuple(copyRank)] = cost(tuple(copyRank), edgeList)
for i in range(1,len(copyRank)):
copyRank[i-1], copyRank[i] = copyRank[i], copyRank[i-1]
rankValues[tuple(copyRank)] = cost(tuple(copyRank), edgeList)
copyRank = list(argMax(rankValues))
return copyRank
# def evaluateFAS(fileNameList):
rankings = []
for fileName in fileList:
print fileName
adjMatrix, incoming, outgoing = fasGraph(fileName)
instance = igraph.Graph.Adjacency(adjMatrix.tolist())
pre_process(instance)
# rank = kss200(instance)
rank = fasAlg(adjMatrix, incoming, outgoing)
rank = alg_star(sifting, cost, instance, rank)
rank = np.array(rank) + 1
rankings.append(rank)
cost.remove_memos() #not sure if working properly
sifting.remove_memos() # not sure if working properly
# return rankings
如有任何帮助和指导,我们将不胜感激。
我觉得还可以。让我们试一下
class memoize:
"""Gives the class it's core functionality."""
def __call__(self, *args):
if args not in self._memos:
self._memos[args] = self._function(*args)
return self._memos[args]
def __init__(self, function):
self._memos = {}
self._function = function
"""Removes all memos. This is particularly useful if something that affects the output has changed."""
def remove_memos(self):
self._memos = {}
@memoize
def f(x, y):
print('f')
return x + y
@memoize
def g(x, y):
print('g')
return x * y
print(f(2,3))
print(f(2,3))
print(g(2,3))
print(g(2,3))
print(f._memos)
print(g._memos)
f.remove_memos()
g.remove_memos()
print(f._memos)
print(g._memos)
输出
f
5
5
g
6
6
{(2, 3): 5}
{(2, 3): 6}
{}
{}
你为什么认为它不能正常工作?