Пример #1
0
def main(argv, current_directory):
    options = parse_command_line(argv)
    size = options['size']
    createModel(options)
    coef = getCoef(size)
    g = createGraph(size)
    #mu is the thresold
    mu = options['value_max']
    regret_min = mu
    (borne_sup, borne_inf) = (mu, 0)
    count = 0
    iteration_number = 2 * log2(size * size) + 1
    while count < iteration_number:
        regret_min = mu
        #print("regret_min :", mu)
        caps = getCapacity(size, coef, mu)
        (flow, cut) = maximum_flow(g, "s", "t", caps)
        if isValid(size, flow):
            borne_sup = mu
            mu = (borne_sup + borne_inf) / 2.
        else:
            borne_inf = mu
            mu = (borne_sup + borne_inf) / 2.
        count += 1

    print(regret_min)
def main(argv, current_directory):
    options=parse_command_line(argv)
    size=options['size']
    createModel(options)
    coef=getCoef(size)
    g=createGraph(size)
    #mu is the thresold
    mu=0
    sat_max=0
    (borne_inf,borne_sup)=(0,options['value_max'])
    count=0
    iteration_number=2*log2(size*size)+1
    while count<iteration_number:
        sat_max=mu
        #print("satisfaction_max", mu)
        caps=getCapacity(size,coef,mu)
        (flow,cut)=maximum_flow(g,"s","t",caps)
        if isValid(size,flow):
            borne_inf=mu
            mu=(borne_sup+borne_inf)/2.
        else:
            borne_sup=mu
            mu=(borne_sup+borne_inf)/2.
        count+=1
    print(sat_max)
Пример #3
0
    def strength_of_vote_management(self, voter_profile):

        # Initialize the graph weights
        for pattern in self.pattern_nodes:
            self.vote_management_graph.set_edge_weight(("source", pattern),
                                                       voter_profile[pattern])
            for i in range(self.required_winners):
                if pattern[i] == 1:
                    self.vote_management_graph.set_edge_weight(
                        (pattern, i), voter_profile[pattern])

        # Iterate towards the limit
        r = [(float(sum(voter_profile.values())) -
              voter_profile[tuple([PREFERRED_MORE] * self.required_winners)]) /
             self.required_winners]
        while len(r) < 2 or r[-2] - r[-1] > STRENGTH_TOLERANCE:
            for i in range(self.required_winners):
                self.vote_management_graph.set_edge_weight((i, "sink"), r[-1])
            max_flow = maximum_flow(self.vote_management_graph, "source",
                                    "sink")
            sink_sum = sum(v for k, v in max_flow[0].iteritems()
                           if k[1] == "sink")
            r.append(sink_sum / self.required_winners)

            # We expect strengths to be above a specified threshold
            if sink_sum < STRENGTH_THRESHOLD:
                return 0

        # Return the final max flow
        return round(r[-1], 9)
Пример #4
0
 def perform_min_cut(self):
     ''' Remove the source and sink from their current location
     in the graph.
     '''
     self.add_source_and_sink(((0,0),(0,100)), Compass.EAST)
     o = minmax.maximum_flow(self.graph, self.source, self.sink)
     self.remove_source_and_sink()
     return o;
Пример #5
0
 def test_trivial_maxflow(self):
     gr = digraph()
     gr.add_nodes([0, 1, 2, 3])
     gr.add_edge((0, 1), wt=5)
     gr.add_edge((1, 2), wt=3)
     gr.add_edge((2, 3), wt=7)
     flows, cuts = maximum_flow(gr, 0, 3)
     assert flows[(0, 1)] == 3
     assert flows[(1, 2)] == 3
     assert flows[(2, 3)] == 3
Пример #6
0
 def test_trivial_maxflow(self):
      gr = digraph()
      gr.add_nodes([0,1,2,3])
      gr.add_edge((0,1), wt=5)
      gr.add_edge((1,2), wt=3)
      gr.add_edge((2,3), wt=7)
      flows, cuts = maximum_flow(gr, 0, 3)
      assert flows[(0,1)] == 3
      assert flows[(1,2)] == 3
      assert flows[(2,3)] == 3
Пример #7
0
def cut_graph(gr,imsize):
    """ Solve max flow of graph gr and return binary
    labels of the resulting segmentation."""
    m,n = imsize
    source = m*n # second to last is source
    sink = m*n+1 # last is sink
    # cut the graph
    flows,cuts = maximum_flow(gr,source,sink)
    # convert graph to image with labels
    res = zeros(m*n)
    for pos,label in cuts.items()[:-2]: #don"t add source/sink
        print label
        res[pos] = label
    return res.reshape((m,n))
Пример #8
0
def cut_graph(gr, imsize):
    ###""" 用最大流对图 gr 进行分割,并返回分割结果的二值标记 """
    m, n = imsize
    source = m * n  # 倒数第二个节点是源点
    sink = m * n + 1  # 倒数第一个是汇点

    # 对图进行分割
    flows, cuts = maximum_flow(gr, source, sink)

    # 将图转为带有标记的图像
    res = zeros(m * n)
    for pos, label in list(cuts.items())[:-2]:  # 不要添加源点 / 汇点
        res[pos] = label

    return res.reshape((m, n))
Пример #9
0
def const_graph(text):
    nVertices = 1
    #print text
    for sent in splitSentences(text):
        #print sent
        score = class_1(sent)
        alltext[nVertices] = (score, sent)
        allscores[nVertices] = score
        nVertices = nVertices + 1
    src = 0
    dst = nVertices

    gr.add_nodes(xrange(0, nVertices + 1))

    for i in xrange(1, nVertices):
        #print i
        w = alltext[i][0]
        gr.add_edge((0, i), wt=w)
        gr.add_edge((i, nVertices), wt=1 - w)

    for i in xrange(1, nVertices):
        for j in xrange(i, nVertices):
            if (i == j):
                continue
            s = 1.0 / abs(j - i)
            s = s * s
            gr.add_edge((i, j), wt=s)

    #print gr
    #print alltext
    flows, cuts = maximum_flow(gr, 0, nVertices)
    #	print flows
    #print cuts
    subjsents = [x for x in xrange(1, nVertices) if cuts[x] is 0]
    subjsents.sort(key=allscores.get, reverse=True)

    budget = 200
    avail = 200
    summary = ''
    for x in subjsents:
        sent = alltext[x][1]
        wc = len(sent.split())
        wc = len(nltk.word_tokenize(sent.strip()))
        if (wc <= avail):
            summary = summary + sent + '.'
            avail = avail - wc
    #print subjsents
    return summary
Пример #10
0
def const_graph(text):
	nVertices=1;
	#print text
	for sent in splitSentences(text):
		#print sent
		score=class_1(sent)
		alltext[nVertices]=(score, sent)
		allscores[nVertices]=score
		nVertices=nVertices+1;
	src=0;
	dst=nVertices;
	
        gr.add_nodes(xrange(0,nVertices+1))
        
	for i in xrange(1,nVertices):
	  #print i
	  w=alltext[i][0]
          gr.add_edge((0, i), wt=w )          
          gr.add_edge((i, nVertices), wt=1-w)          

	for i in xrange(1,nVertices):
		for j in xrange(i,nVertices):
			if(i==j):
				continue;
			s = 1.0/abs(j-i)
			s = s*s
          		gr.add_edge((i, j), wt=s)
          
	#print gr
	#print alltext
	flows, cuts = maximum_flow(gr, 0, nVertices)
#	print flows
	#print cuts
	subjsents=[x for x in xrange(1,nVertices) if cuts[x] is 0 ]
	subjsents.sort(key=allscores.get, reverse=True)
	
	budget=200;
	avail= 200;
	summary='';
	for x in subjsents:
		sent=alltext[x][1]
		wc=len(sent.split());
		wc=len(nltk.word_tokenize(sent.strip()))
		if(wc <= avail):
			summary = summary + sent + '.'
			avail = avail - wc;
	#print subjsents
	return summary
Пример #11
0
def cut_graph(gr, imsize):
    """Solve for max flow of graph gr and return binary
       labels of resulting segmentation.
    """
    m, n = imsize
    source = m * n
    sink = m * n + 1

    # cut graph
    flows, cuts = maximum_flow(gr, source, sink)

    # convert graph to image with labels
    res = np.zeros(m * n)
    for pos, labels in np.cuts.items()[:-2]:
        res[pos] = label
    return res.reshape((m, n))
Пример #12
0
def cut_graph(gr,imsize):
    """   グラフgrの最大フローを求め、領域分割結果の2値ラベルを返す   """
    
    m,n = imsize
    source = m*n # 最後から2つ目がソース
    sink = m*n+1 # 最後がシンク
    
    # グラフをカットする
    flows,cuts = maximum_flow(gr,source,sink)
    
    # グラフをラベル画像に変換する
    res = np.zeros(m*n)
    for pos,label in cuts.items()[:-2]: # ソースとシンクを除く
        res[pos] = label

    return res.reshape((m,n))
def cut_graph(gr,imsize):
    """    Solve max flow of graph gr and return binary 
        labels of the resulting segmentation."""
    
    m,n = imsize
    source = m*n # second to last is source
    sink = m*n+1 # last is sink
    
    # cut the graph
    flows,cuts = maximum_flow(gr,source,sink)
    
    # convert graph to image with labels
    res = zeros(m*n)
    for pos,label in cuts.items()[:-2]: #don't add source/sink
        res[pos] = label

    return res.reshape((m,n))
Пример #14
0
def cut_graph(gr, imsize):
    """ グラフgrの最大フローを求め、
    領域分割結果の2値ラベルを返す """

    m, n = imsize
    source = m * n  # 最後から2つ目がソース
    sink = m * n + 1  # 最後がシンク

    # グラフをカットする
    flows, cuts = maximum_flow(gr, source, sink)

    # グラフをラベル画像に変換する
    res = zeros(m * n)
    for pos, label in cuts.items()[:-2]:  # ソースとシンクを除く
        res[pos] = label

    return res.reshape((m, n))
Пример #15
0
def classify(gr,numSource,numSink):
    """Classify using the built graph by the max_flow algorithm

    Parameters
    ----------
    
    gr: 
        The graph model
    numSource: integer
        The number of positive data points
    numSink: integer
        The number of negative data points
    """
    
    flows, cuts = maximum_flow(gr, 0, numSource)

    return cuts
Пример #16
0
def cuts(adj, source, sink, k, prettyprint=False):
    """
    cuts returns an oracle that terminates at all cuts between source and sink
    with capacity less than or equal to k.
    """
    # Convert adj to a cut-able pygraph.
    graph = digraph()
    for nid in adj:
        graph.add_node(nid)
    for cid in adj:
        for pid in adj[cid]:
            graph.add_edge((cid, pid))

    ret = set()
    while True:
        (flow, asgn) = maximum_flow(graph, source, sink)

        # Find the minimum cut.
        mincut = set()
        for (u, v) in flow:
            if flow[(u, v)] > 0 and asgn[u] != asgn[v]:
                mincut.add((u, v))

        # If it's too large, we're done; break.
        maxflow = 0
        for edge in mincut:
            maxflow += flow[edge]
        if 0 < maxflow and maxflow <= k:
            ret.update(mincut)
        else:
            break

        # Reweight one edge in the cut so that it will no longer be min.
        edge = max([(int(u), int(v)) for (u, v) in mincut])
        edge = (str(edge[0]), str(edge[1]))
        graph.del_edge(edge)
        graph.add_edge(edge, wt=len(adj))

    if not prettyprint:
        return lambda query, cid, nid: (cid, nid) in ret
    else:
        return set([nid for (cid, nid) in ret])
Пример #17
0
def cuts(adj, source, sink, k, prettyprint=False):
    """
    cuts returns an oracle that terminates at all cuts between source and sink
    with capacity less than or equal to k.
    """
    # Convert adj to a cut-able pygraph.
    graph = digraph()
    for nid in adj:
        graph.add_node(nid)
    for cid in adj:
        for pid in adj[cid]:
            graph.add_edge((cid, pid))

    ret = set()
    while True:
        (flow, asgn) = maximum_flow(graph, source, sink)

        # Find the minimum cut.
        mincut = set()
        for (u, v) in flow:
            if flow[(u, v)] > 0 and asgn[u] != asgn[v]:
                mincut.add((u, v))

        # If it's too large, we're done; break.
        maxflow = 0
        for edge in mincut:
            maxflow += flow[edge]
        if 0 < maxflow and maxflow <= k:
            ret.update(mincut)
        else:
            break

        # Reweight one edge in the cut so that it will no longer be min.
        edge = max([(int(u), int(v)) for (u,v) in mincut])
        edge = (str(edge[0]), str(edge[1]))
        graph.del_edge(edge)
        graph.add_edge(edge, wt=len(adj))

    if not prettyprint:
        return lambda query, cid, nid: (cid, nid) in ret
    else:
        return set([nid for (cid, nid) in ret])
    def strength_of_vote_management(self, voter_profile):
        """
        This method converts the voter profile into a capacity graph and
        iterates on the maximum flow using the Edmonds Karp algorithm. The end
        result is the limit of the strength of the voter management as per
        Markus Schulze's Calcul02.pdf (draft, 28 March 2008, abstract: "In this
        paper we illustrate the calculation of the strengths of the vote
        managements.").
        """

        # Initialize the graph weights
        for pattern in self.pattern_nodes:
            self.vote_management_graph.set_edge_weight(("source", pattern),
                                                       voter_profile[pattern])
            for i in range(self.required_winners):
                if pattern[i] == 1:
                    self.vote_management_graph.set_edge_weight(
                        (pattern, i), voter_profile[pattern]
                    )

        # Iterate towards the limit
        r = [(
            float(sum(voter_profile.values())) -
            voter_profile[tuple([PREFERRED_MORE] * self.required_winners)]
        ) / self.required_winners]
        while len(r) < 2 or r[-2] - r[-1] > STRENGTH_TOLERANCE:
            for i in range(self.required_winners):
                self.vote_management_graph.set_edge_weight((i, "sink"), r[-1])
            max_flow = maximum_flow(self.vote_management_graph, "source",
                                    "sink")
            sink_sum = sum(v for k, v in six.iteritems(max_flow[0])
                           if k[1] == "sink")
            r.append(sink_sum / self.required_winners)

            # We expect strengths to be above a specified threshold
            if sink_sum < STRENGTH_THRESHOLD:
                return 0

        # Return the final max flow
        return round(r[-1], 9)
Пример #19
0
 def solveMaxFlow(self):
     instance = self.instance
     flow, _ = maximum_flow(self.graph, sourceID, sinkID, self.capacities)
     # form the reduced network in which only arcs with flow are present
     reducedNetwork = digraph()
     reducedNetwork.add_graph(self.graph) # does not add node attributes
     for arc in self.graph.edges():
         if flow[arc] == 0:
             reducedNetwork.del_edge(arc)
     for node in self.graph.nodes():
         if reducedNetwork.neighbors(node) == []:
             reducedNetwork.del_node(node)
     
     # form paths for agents
     solution = []
     for i in range(instance.nAgents):
         nodeID = self._getNetworkID(instance.agents[i], time = 0, stage = 1)
         layoutNode = self.nodeToLayout[nodeID]
         stage = 1   
         solution.append([])
         while (True):
             if (stage == 1):
                 solution[i].append(layoutNode)
                 if layoutNode in instance.exits:
                     break
             try:
                 neighbors = reducedNetwork.neighbors(nodeID)
             except:
                 break # nodeID is not in the network: the agent is too far from exit
             if (neighbors == []):
                 break
             if (len(neighbors) > 1):
                 print("More than one possibility in the solution!")
                 exit()
             nodeID = neighbors[0]
             layoutNode = self.nodeToLayout[nodeID]
             stage = self.nodeToStage[nodeID]
     return solution
Пример #20
0
    def strength_of_vote_management(self, voter_profile):

        # Initialize the graph weights
        for pattern in self.pattern_nodes:
            self.vote_management_graph.set_edge_weight(("source", pattern), voter_profile[pattern])
            for i in range(self.required_winners):
                if pattern[i] == 1:
                    self.vote_management_graph.set_edge_weight((pattern, i), voter_profile[pattern])

        # Iterate towards the limit
        r = [(float(sum(voter_profile.values())) - voter_profile[tuple([PREFERRED_MORE] * self.required_winners)]) / self.required_winners]
        while len(r) < 2 or r[-2] - r[-1] > STRENGTH_TOLERANCE:
            for i in range(self.required_winners):
                self.vote_management_graph.set_edge_weight((i, "sink"), r[-1])
            max_flow = maximum_flow(self.vote_management_graph, "source", "sink")
            sink_sum = sum(v for k, v in max_flow[0].iteritems() if k[1] == "sink")
            r.append(sink_sum / self.required_winners)

            # We expect strengths to be above a specified threshold
            if sink_sum < STRENGTH_THRESHOLD:
                return 0

        # Return the final max flow
        return round(r[-1], 9)
Пример #21
0
Created on Fri May 16 09:22:20 2014

@author: admin
"""
from pygraph.classes.digraph import digraph
from pygraph.algorithms.minmax import maximum_flow

gr=digraph()
gr.add_nodes([0,1,2,3])

gr.add_edge((0,1), wt=4)
gr.add_edge((1,2), wt=3)
gr.add_edge((2,3), wt=5)
gr.add_edge((0,2), wt=3)
gr.add_edge((1,3), wt=4)
flows,cuts=maximum_flow(gr,0,3)
print 'flowis:',flows
print 'cutis:',cuts

print
from scipy.misc import imresize
import graphcut
from pylab import *
from PIL import Image

im=array(Image.open('empire.jpg'))
im=imresize(im,0.07,interp='bilinear')
size=im.shape[:2]
#addtworectangulartrainingregions
labels=zeros(size)
labels[3:18,3:18]=-1
Пример #22
0
 def test_random_maxflow(self):
      gr = testlib.new_digraph(wt_range=(1,20))
      flows, cuts = maximum_flow(gr, 0, 1)
      # Sanity test
      for each in flows:
          assert gr.edge_weight(each) >= flows[each]
Пример #23
0
 def test_random_maxflow(self):
     gr = testlib.new_digraph(wt_range=(1, 20))
     flows, cuts = maximum_flow(gr, 0, 1)
     # Sanity test
     for each in flows:
         assert gr.edge_weight(each) >= flows[each]
Пример #24
0
from pygraph.classes.digraph import digraph
from pygraph.algorithms.minmax import maximum_flow

gr = digraph()
gr.add_nodes([0, 1, 2, 3])

gr.add_edge((0, 1), wt=4)
gr.add_edge((1, 2), wt=3)
gr.add_edge((2, 3), wt=5)
gr.add_edge((0, 2), wt=3)
gr.add_edge((1, 3), wt=4)

flows, cuts = maximum_flow(gr, 0, 3)  # 0为源点,3为汇点
print("flow is:", flows)
print("cuts is:", cuts)
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 18 20:52:07 2016

@author: user
"""

from pygraph.classes.digraph import digraph
from pygraph.algorithms.minmax import maximum_flow

gr = digraph()
gr.add_nodes([0,1,2,3])

gr.add_edge((0,1), wt=4)
gr.add_edge((1,2), wt=3)
gr.add_edge((2,3), wt=5)
gr.add_edge((0,2), wt=3)
gr.add_edge((1,3), wt=4)

flows,cuts = maximum_flow(gr,0,3)
print 'flow is:', flows
print 'cut is:', cuts
Пример #26
0
    for i in range(N):
        gr.add_nodes([i+1])
        gr.add_edge((0,i+1), wt=1)
        
    for i in range(M):
        gr.add_nodes([N+i+1])   
        gr.add_edge((N+i+1,N+M+1), wt=1)
        
    for i in range(N):
        for j in range(M):
            if(u[i][j]>=lmb):
                gr.add_edge((i+1,N+j+1), wt=1)
            else:
                gr.add_edge((i+1,N+j+1), wt=0)
    
    flows, cuts = maximum_flow(gr, 0, N+M+1)
    

    
    for i in range(N):
        k=0
        for j in range(M):
            if(flows[(i+1,N+j+1)]==0):
                k+=1
        if(k==N):
            sortie = 0
            
    if(sortie == 1):
        oldflow = flows
    lmb += 1