Пример #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
@author: ViniciusJokubauskas
"""


import numpy as np
import pymprog as pp
from variables import *

rNumberClients = range(numberClients)
rNumberChannels = range(numberChannels)
rNumberProducts = range(numberProducts)

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

x = pp.var('choice', 
        t, bool) #create 3 variables
        
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:
Пример #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
np.set_printoptions(precision = 2, linewidth = 200)
from random import Random

rand = Random()
roads = 10
time = 10
M = [(i,t) for i in range(roads) for t in range(time+1)]
        
age_i_0 = [rand.randint(1,10) for i in range(roads)]

import pymprog as PYM
PYM.begin('test run') # begin modeling        
age = PYM.var('age_i_o',M, bounds = (0,10))


PYM.verbose(True) # be verbose
xs = PYM.var('xs', M, kind=bool) # create 100 variables #try one variable with bounds=(0,numb_activities..)
xl = PYM.var('xl', M, kind=bool) # create 100 variables
minimize(sum(50*xs + 120*xl), 'cost over 10 years')

cons_dict = {}
for i,j in xl:
    xl[i,j] + xs[i,j] <=1
    R.name = 'Only one type of activity per asset per step_' + str(i)
    cons_dict.update(str(R))
    print("R.name = ",R.name,"\n R = ",R)
for iii in range(len(age_i_0)):
    age[iii,0] == age_i_0[iii]

for i,j in M:
    # xl[i,j] + xs[i,j] <=1
Пример #5
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) )