예제 #1
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
예제 #2
0
파일: solver.py 프로젝트: viniciusjk/Tcc
    <=channelCap[j]
    
#maxOfferProductConstraint:    
for k in rNumberProducts:
    sum(x[i,j,k] for i in rNumberClients for j in rNumberChannels)\
    <=maxOfferProduct[k]

#minOfferProductConstraint:  

#for k in rNumberProducts:
#    sum(x[i,j,k] for i in rNumberClients for j in rNumberChannels)\
#    >=minOfferProduct[k]
    
#budgetConstraint:

pp.st(sum(x[i,j,k]*cost[j] for i in rNumberClients for j in rNumberChannels\
    for k in rNumberProducts)<=budget, "Budget Constr")
    
#clientLimitConstraint:

for i in rNumberClients:
   pp.st( sum(x[i,j,k] for j in rNumberChannels for k in rNumberProducts)<=1,
         "client "+str(i)+" Limit")

#rurdleRateConstraint:

pp.st(sum(x[i,j,k]*expectedReturn[i][j][k] for i in rNumberClients for j in\
    rNumberChannels for k in rNumberProducts)>= (1+rurdleRate)*sum(x[i,j,k]\
    *cost[j] for i in rNumberClients for j in rNumberChannels\
    for k in rNumberProducts),"rurdleRate Cons")
    
pp.solve() # solve the model
예제 #3
0
def ppSolver(expectedReturn, numberClients, numberChannels, numberProducts,
             cost, budget, channelCap, minOfferProduct, maxOfferProduct,
             rurdleRate):

    startTime = timeit.default_timer()
    rNumberClients = range(numberClients)
    rNumberChannels = range(numberChannels)
    rNumberProducts = range(numberProducts)

    t = pp.iprod(rNumberClients, rNumberChannels, rNumberProducts)
    pp.begin('basic')  # begin modelling
    pp.verbose(False)  # be verbose

    x = pp.var('choice', t, bool)

    pp.maximize(sum(x[i,j,k]*expectedReturn[i][j][k] for i in rNumberClients\
                 for j in rNumberChannels for k in rNumberProducts))

    #channelLimitConstraint:
    for j in rNumberChannels:
        sum(x[i,j,k] for i in rNumberClients for k in rNumberProducts)\
        <=channelCap[j]

    #maxOfferProductConstraint:
    for k in rNumberProducts:
        sum(x[i,j,k] for i in rNumberClients for j in rNumberChannels)\
        <=maxOfferProduct[k]

    #minOfferProductConstraint:


#    for k in rNumberProducts:
#        sum(x[i,j,k] for i in rNumberClients for j in rNumberChannels)\
#        >=minOfferProduct[k]

#budgetConstraint:

    pp.st(sum(x[i,j,k]*cost[j] for i in rNumberClients for j in\
        rNumberChannels for k in rNumberProducts)<=budget,"Budget Constr.")

    #clientLimitConstraint:

    for i in rNumberClients:
        pp.st(sum(x[i,j,k] for j in rNumberChannels for k in rNumberProducts)\
              <=1,"Client "+str(i)+" limit")

    #rurdleRateConstraint:

    pp.st(sum(x[i,j,k]*expectedReturn[i][j][k] for i in rNumberClients for j \
          in rNumberChannels for k in rNumberProducts)>= (1+rurdleRate)\
            *sum(x[i,j,k]*cost[j] for i in rNumberClients for j in\
                rNumberChannels for k in rNumberProducts),"Rurdle Rate Constr")

    pp.solve()  # solve the model

    #    pp.sensitivity() # sensitivity report
    endTime = timeit.default_timer() - startTime
    print("Objetivo encontrado: ", round(pp.vobj(), 2), " em ",
          round(endTime, 3), " segundos")

    print("\n\n\n")
    appendCsv(numberClients, "Solver method", endTime, True,
              round(pp.vobj(), 2))
    pp.end()  #Good habit: do away with the model
예제 #4
0
파일: merge.py 프로젝트: saintfrank/Opti
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