def method_1(self):
		#creates a distance matrix that essentially is a list containing lists with the property where matrix[i][j] is the distance between point i and point j
		t0 = dt.time()#starts to time the method until its completion
		matrix = []
		meth1sol = []
		for i in li:
			r = []
			for j in li:
				r.append(i.distance(j))
			matrix.append(r)
		n = len(matrix)
		V = range(n)
		E = [(i,j) for i in V for j in V if i!=j]
		#the algorithm that eliminates invalid subtours
		pm.begin('subtour elimination')
		x = pm.var('x', E, bool)
		#minimizes the sum of the distances found in the matrix
		pm.minimize(sum(matrix[i][j]*x[i,j] for i,j in E), 'dist')
		for k in V:
			sum( x[k,j] for j in V if j!=k ) == 1
			sum( x[i,k] for i in V if i!=k ) == 1
			#calls the solver method and deactivates the result message 
			pm.solver(float, msg_lev = pm.glpk.GLP_MSG_OFF)
			pm.solver(int, msg_lev= pm.glpk.GLP_MSG_OFF)
			pm.solve()
		global subtourg
		#the function that creates subtours
		def subtourl(x):
			succ = 0
			subt = [succ] #start from node 0
			while True:
				succ=sum(x[succ,j].primal*j for j in V if j!=succ)
				if succ == 0: break #tour found
				subt.append(int(succ+0.5))
			return subt
		subtourg = subtourl
		while True:
			#a loop that creates subtours and keeps them if they are valid, terminating the programme in the process, or discards them if they are not
		   subt = subtourg(x)
		   if len(subt) == n:
		      #print("Optimal tour length: %g"%pm.vobj())
		      #print("Optimal tour:"); print(subt)
		      break
		   print("New subtour: %r"% subt)
		   if len(subt) == 1: break #something wrong
		   #now add a subtour elimination constraint:
		   nots = [j for j in V if j not in subt]
		   sum(x[i,j] for i in subt for j in nots) >= 1
		   pm.solve() #solve the IP problem again
		pm.end()
		#print(subt)
		#now the solution is added to a list that can be interpreted by the connect method
		for i in subt:
			meth1sol.append(li[i])
		print(len(meth1sol))
		self.connect(meth1sol, method1_colour, 1)
		t1 = dt.time()
		t = t1 - t0
		t = round(t, 2)#the required time is calculated and rounded for conviniency
		self.t1.set("time:\n{}s".format(t))
Exemplo n.º 2
0
	def predict(self, c, unknown):
		if c.size < 2:
			return []
		
		addedElems = 0
		if c.shape[1]-c.shape[0]>1:
			added = numpy.zeros((c.shape[1]-c.shape[0], c.shape[1]))
			addedElems = added.shape[0] * added.shape[1]
			c = numpy.vstack((c, added))

		detected = c.shape[0]
		recognizers = c.shape[1]
		size = c.size
		
		mp.beginModel('basic')
		mp.verbose(False)
		x = mp.var(range(size), 'X', kind=bool)
		

		# One label per detected object
		for i in range(0, detected):
			tmp = numpy.zeros((detected, recognizers))
			tmp[i, :] = 1
			tmp = tmp.reshape((1, size))[0]
			mp.st(sum(x[j]*int(tmp[j]) for j in range(size))==1)

		if self.constraints == True:
			# Use recognizer up to once
			if unknown==True:
				lim = recognizers-1
			else:
				lim = recognizers
			for i in range(0, recognizers):
				tmp = numpy.zeros((detected, recognizers))
				tmp[:, i] = 1
				tmp = tmp.reshape((1, size))[0]
				mp.st(sum(x[j]*int(tmp[j]) for j in range(size))<=1)
			
		c = c.reshape((1, size)).tolist()[0]
			
		mp.minimize(sum(c[i]*x[i] for i in range(size)), 'myobj')
		mp.solve(int)
		
		X = numpy.zeros((1, size))
		for i in range(size):
			X[0, i] = x[i].primal
		X = X[0,0:size-addedElems]

		labels = X.reshape(((size-addedElems)/(recognizers), recognizers))
		predicted = []
		for i in range(0, labels.shape[0]):
			l = numpy.argmax(labels[i,:])
			if l==recognizers-1 and unknown==True:
				l = -1
			predicted.append(l)
			
		return predicted
Exemplo n.º 3
0
def merge ( Y, W ):
        
    import operator
    import sys
    
    N = 4
    M = 4
    
    # index and data
    patternid, yid, wid, rid = range(N*M), range(N*M), range(N*M), range(2)
    
    #problem definition
    pymprog.beginModel('basic')
    pymprog.verbose(True)
    
    # Stiamo facendo uno split, il pattern precedente e' P, e noi vogliamo creare due pattern figli Y e W
    # P, Y, e W sono delle matrici NxM, rappresentate come vettori, di bit. 
    # N sono i layer, mentre M sono le hit in quel layer 
    P = pymprog.var(patternid, 'P', bool)       # Parent Pattern
    Y = pymprog.var(range(3), 'Y', bool)        # First sub-pattern
    W = pymprog.var(range(3), 'W', bool)        # Second sub-pattenr
    
    
    # Queste tre relazioni logiche impongono che per ogni traccia k, questa venga riconosciuta da almeno un sub-pattern 
    # e traducono la relazione 
    #   covered[k] = coveredY[k] V coveredW[k]      |  k = {1,2,3} 
    # con
    #   covered[k] = 1                              |  k = {1,2,3} 
    covered = pymprog.var(range(3), 'covSubTot', bool)
    
    r  = pymprog.st( covered[k] >= Y[k]  for k in range(3) )
    r += pymprog.st( covered[k] >= W[k]  for k in range(3) )
    r += pymprog.st( covered[k] <= Y[k] + W[k]  for k in range(3) )
    r += pymprog.st( covered[k] == 1  for k in range(3) )
    #
    # # # # # # #
    
    totY = pymprog.var( range(1), 'totY', bounds=(1, 3) )
    totW = pymprog.var( range(1), 'totW', bounds=(1, 3) )
    
    r += pymprog.st( sum ( Y[k] for k in range(3) ) == totY[i] for i in range(1) )
    r += pymprog.st( sum ( W[k] for k in range(3) ) == totW[i] for i in range(1) )
    
    
    
    AY = pymprog.var(range(N*M), 'AY', int) 
    AW = pymprog.var(range(N*M), 'AW', int)
    
    ## Ora voglio fare che *per ogni punto* nella griglia 2D,                                       
    r += pymprog.st	(  AY[ i ] >= Y[k] * myTracks[k][ i ] for i in range(N*M)  for k in range(3) )
    r += pymprog.st	(  AY[ i ] <= sum( Y[k] * myTracks[k][ i ]  for k in range(3)  )  for i in range(N*M)  )
    
    r += pymprog.st	(  AW[ i ] >= W[k] * myTracks[k][ i ] for i in range(N*M)  for k in range(3) )
    r += pymprog.st	(  AW[ i ] <= sum( W[k] * myTracks[k][ i ]  for k in range(3)  )  for i in range(N*M)  )
    
    # Le ampiezze nei vari layer ... poi si potra' semplificare
    AmpY = pymprog.var(range(N), 'AmpY', int)
    AmpW = pymprog.var(range(N), 'AmpW', int)
    
    
    r += pymprog.st	(   sum(  AY[i*N+j] for j in mRange ) == AmpY[i] for i in nRange )
    r += pymprog.st	(   sum(  AW[i*N+j] for j in mRange ) == AmpW[i] for i in nRange )
    
    
    VolTotY = pymprog.var(range(1), 'VolTotY', int)        # Second sub-pattenr
    VolTotW = pymprog.var(range(1), 'VolTotW', int)        # Second sub-pattenr
    
    
    #r += st	(   sum(  AY[i*N+j] for j in mRange ) == AmpY[i] for i in nRange )
    r += pymprog.st	(   sum(  AmpY[j] for j in nRange ) == VolTotY[i] for i in range(1) )
    r += pymprog.st	(   sum(  AmpW[j] for j in nRange ) == VolTotW[i] for i in range(1) )
    
    
    pymprog.minimize( VolTotY[0] + VolTotW[0]  , 'Total Volume')
    
    
    sys.stdout.write("\nSolving ...")
    pymprog.solve()
    sys.stdout.write(" done.\n\n")
    
    
    print("Total Volume = %g"% pymprog.vobj())
   
    print 'Y'
    print Y 
    print 'W'
    print W
    
    print AmpY
    print AmpW
    
    print 'AY'
    print_variables_matrix_primal(AY)
    print 'AW'
    print_variables_matrix_primal(AW)
 
    print 'Y'
    print_variables_matrix_cross(AY)
    print 'W'
    print_variables_matrix_cross(AW)

    print 'Volume Y : ' 
    print VolTotY[0].primal
    print 'Volume W : ' 
    print VolTotW[0].primal
    print 'Volume Tot : ' 
    print sum( tracks[i] for i in range(N*M) )
    def solve_offline(self, w):
        ''' pre-compute offline solution '''
        T = range(self.T)
        self.w = dict.fromkeys(T, 0)  # vector of charges and discharges

        # making some shortcuts so the LP is more readable and similar to
        # the model in our paper
        b0 = self.level
        # we use a positive Bm in this problem (like d)
        Bp = Bm = self.max_rate
        B = self.capacity
        CC = self.street.C
        alpha = self.efficiency
        p = self.exp_prices
        ka = self.kwh_adj

        # magnitudes without me involved
        fp0 = [self.street.f(t, 0, p[t])[0] for t in T]
        fm0 = [self.street.f(t, 0, p[t])[1] for t in T]
        # maximal limit for magnitude we expect
        maxx = 100
        # maximal number of consecutive critical steps considered
        K = range(self.max_k)
        e = [math.pow(self.c_h, k + 1) for k in K]
        TK  = [(t,k) for t in T for k in K if k <= t]

        pymprog.beginModel('offline')
        #pymprog.verbose(True)
        pymprog.solvopt(tm_lim=1000*60*self.max_runtime)
        #print "Options:", pymprog.solvopt()

        # create variables
        c = pymprog.var(T, 'C')  # charges
        d = pymprog.var(T, 'D')  # discharges
        x = pymprog.var(T, 'X')  # max mag on cable
        # True if there have been at least k-1 consecutive
        # critical steps before t
        v = pymprog.var(T, 'V')  # cost
        co = pymprog.var(TK, 'CO', bool) # consecutive overload

        # set objective
        pymprog.minimize(
            w * sum(v[t] for t in T) - sum(p[t] * (d[t] - c[t]) for t in T),
            'wC-R'
        # we use a positive d in this problem
        )

        # set constraints
        # ... battery contraints
        pymprog.st(0 <= c[t] <= Bp for t in T)
        pymprog.st(0 <= d[t] <= Bm for t in T)
        # we use a positive d in this problem
        for t in T:
            pymprog.st(b0 + sum(ka * (alpha * c[j]) - ka * d[j] for j in range(t + 1)) <= B)
            pymprog.st(b0 + sum(ka * (alpha * c[j]) - ka * d[j] for j in range(t + 1)) >= 0)
        # ... cable constraints
        pymprog.st(x[t] >= 0 for t in T)
        pymprog.st(x[t] >= fp0[t] + c[t] - d[t] for t in T)
        pymprog.st(x[t] >= -fm0[t] - c[t] + d[t] for t in T)
        pymprog.st(x[t] >= -fp0[t] - c[t] + d[t] for t in T)
        pymprog.st(x[t] >= fm0[t] + c[t] - d[t] for t in T)

        # ... cons. overloading constraints
        pymprog.st(v[t] >= e[k] * co[t, k] for t, k in TK)
        pymprog.st(co[t, 0] >= (x[t]-CC)/(maxx - CC) for t in T)
        pymprog.st(co[t, k] >= co[t-1, k-1] + co[t, k-1] - 1.5 for t, k in TK if ((t, k-1) in TK and (t-1, k-1) in TK))

        pymprog.solve()
        # status can be in (opt, feas, undef)
        assert(pymprog.status() in ('opt', 'feas'))
        # value of objective (this should meet the actual outcome!)
        #print 'Objective = {}'.format(pymprog.vobj())
        # use sthg like this to inspect variables
        #print ';\n'.join('%s = %g {dual: %g}' % (
        #            x[t].name, x[t].primal, x[t].dual)
        #                    for t in T)

        for t in T:
            self.w[t] = c[t].primal - d[t].primal