Beispiel #1
0
def update(f,cf, frontier, curr_candidate_sol,baseline_min,baseline_max,total=0.0, n=0):

  global eraDict, eraCount , eraTracker, crr_era, prev_era, terminateCount, terminator, eraList, a12Factor, eraDictCount

  # print "FROM UPDATE -->", curr_candidate_sol
  for x in frontier:
    s = x.score
    curr_candidate_sol.decisionVec = x.have
    new = extrapolate(frontier,x,f,cf,curr_candidate_sol,baseline_min,baseline_max)
    # new_normalized_score = (new.score - BaseLine.baseline_min) / ( BaseLine.baseline_max - BaseLine.baseline_min + 0.001)
    new_normalized_score = (new.score - BaseLine.baseline_min) / ( BaseLine.baseline_max - BaseLine.baseline_min)

    obj_list = []
    for objective in new.objectives:
      obj_list.append(objective)

    eraList.append(obj_list)

    if eraCount ==19:
      ## comparing prev and current
      crr_era = sorted(eraList, reverse=True)
      #print("Current era: ", crr_era)

      eraDict[eraDictCount] = crr_era
      eraDictCount = eraDictCount + 1
      a12Output =  utilities.a12(crr_era, prev_era)

      if a12Output <= a12Factor:
         terminateCount = terminateCount + 1

      eraList = []
      eraCount = 0
      prev_era = crr_era
    else:
      # print "eraDictCount: %s" %(eraDictCount)
      # print "eraCount: %s" %(eraCount)
      eraCount +=  1
    if terminateCount >= terminator:
       break  

    # print "new_score:", new.score
    # print "extrapolated vector:", new.have
    # print "parent :", s
    if new.score < s:
      # print "+++++++++++++++++++++++++++++++++++++++"
      # print "new.have=", new.have
      # print "x.have=", x.have
      # print "new.score=", new.score
      # print "s=", s
      x.score = new.score
      x.have = new.have

    total +=x.score
    # print "x.score:", x.score
    # print "total:", total
    # print "n:", n
    total +=x.score
    n += 1
  return total,n
Beispiel #2
0
def SimulatedAnnealing(modelParam):
    ###print purpose
    output = ""
    cntForQ=0
    cntForExcl=0
    cntForPlus=0
    cntForDot=0

    printCounter =  0

    eMaxVal = 0
    curr_sol=modelParam()
    best_sol =modelParam()
    best_sol.copy(curr_sol)
    #print("Before ... ", curr_sol.getCurrentBaseline())

    #print("isBaseLineSet:", BaseLine.is_baseline_set)

    if BaseLine.is_baseline_set == False:
        #curr_sol.updateBaseline(BaseLine.getInitialBaseline(modelParam))
        initialBaseline = BaseLine.getInitialBaseline(modelParam)
        #print("Output of initial baseline ", initialBaseline)
        BaseLine.baseline_min = initialBaseline[0]
        BaseLine.baseline_max = initialBaseline[1]
        newBaseLine = [BaseLine.baseline_min, BaseLine.baseline_max]
        curr_sol.updateBaseline(newBaseLine)        
    else:
        #print("HO GAYA TRUE")
        newBaseLine = [BaseLine.baseline_min, BaseLine.baseline_max]
        curr_sol.updateBaseline(newBaseLine)
        #print("newBaseLine:", newBaseLine)
    #print("BaseLine Min:", BaseLine.baseline_min)
    #print("BaseLine Max:", BaseLine.baseline_max)
    #print( "After ... ",    curr_sol.getCurrentBaseline())
    #exit
    ## kMaxVal is always fixed to 1000 !
    kMaxVal=1000
    #counter = 0
    counter = 1000
    ## to keep track of eras
    eraDict = {}
    eraCount  = 0
    eraTracker = 50
    crr_era, prev_era = [], [0 for _ in range(curr_sol.numOfDec)]
    terminateCount = 0
    terminator = 10
    eraList = []
    a12Factor = 0.56
    eraDictCount  = 0

    while (counter > 0) and (curr_sol.sumOfObjs() > eMaxVal):

        printCounter = printCounter + 1

        neighbor_sol=generateNeighbor(curr_sol, randint(0, curr_sol.numOfDec-1), modelParam)


        if neighbor_sol.sumOfObjs() < best_sol.sumOfObjs():
            best_sol.copy(neighbor_sol)
            curr_sol.copy(neighbor_sol)
            cntForExcl = cntForExcl + 1
            output = output + "!"
        elif neighbor_sol.sumOfObjs() < curr_sol.sumOfObjs():
            curr_sol.copy(neighbor_sol)
            cntForPlus = cntForPlus + 1
            output = output + "+"
        elif fetchProbOfAcceptance(neighbor_sol.sumOfObjs(), curr_sol.sumOfObjs(), float(counter)/float(kMaxVal)) > random():
            curr_sol.copy(neighbor_sol)
            cntForQ = cntForQ + 1
            output = output + "?"
        else:
           output = output + "."
           cntForDot = cntForDot  + 1
        if printCounter % eraTracker == 0:
           #print("\ncounter={}, best energy seen so far={}, '?'={}, '!'={}, '+'={}, '.'={}, output={}".format(printCounter, best_sol.sumOfObjs(), cntForQ, cntForExcl, cntForPlus, cntForDot, output))
           cntForQ = 0
           cntForExcl = 0
           cntForPlus = 0
           cntForDot = 0
           output = ""
           ## era purpose
        if BaseLine.baseline_min > best_sol.sumOfObjs():
           BaseLine.baseline_min = best_sol.sumOfObjs()    
        if BaseLine.baseline_max < best_sol.sumOfObjs():
           BaseLine.baseline_max = best_sol.sumOfObjs()   
        newBaseLine = [BaseLine.baseline_min, BaseLine.baseline_max]
        curr_sol.updateBaseline(newBaseLine)                   
        if eraCount ==19:
          ## comparing prev and current
          crr_era = sorted(eraList, reverse=True)
          #print("Current era: ", crr_era)

          eraDict[eraDictCount] = crr_era
          #print ("Contents of the dictionary ", eraDict[eraDictCount])          
          eraDictCount = eraDictCount + 1
          #print ("era dict count ", eraDictCount)
          
          a12Output =  utilities.a12(crr_era, prev_era)

          if a12Output <= a12Factor:
             terminateCount = terminateCount + 1
          eraList = []
          eraCount = 0
          prev_era = crr_era
          #print("era count ={}, era dict= {}, a12={}, terminator={}".format(eraCount, prev_era, crr_era, a12Output, terminateCount))
        else:
          eraList.append(best_sol.getobj())
          eraCount +=  1
          #print("era count ... ", eraCount)
        if terminateCount >= terminator:
             break
#        if curr_sol.sumOfObjs() < curr_sol.getCurrentBaseline()[0]:
#          curr_sol.updateBaseline( [curr_sol.sumOfObjs(), curr_sol.getCurrentBaseline()[1]])
#          # print("+++++^^BASELINE UPDATED")
#        if curr_sol.sumOfObjs() > curr_sol.getCurrentBaseline()[1]:
#          curr_sol.updateBaseline([curr_sol.getCurrentBaseline()[0], curr_sol.sumOfObjs()])
          #print("+++++^^BASELINE UPDATED MILA MAX")
          #exit()

#        #DOUBT
#        if curr_sol.sumOfObjs() > 12.7814799596:
#            print("GREATER THAN 13")
#            #exit()
        #print("current energy ", curr_sol.sumOfObjs())
        counter = counter - 1
        #counter= counter + 1

    #Update Global Baseline :
    #print(curr_sol.getCurrentBaseline());

    BaseLine.baseline_min = curr_sol.getCurrentBaseline()[0]
    BaseLine.baseline_max = curr_sol.getCurrentBaseline()[1]
    BaseLine.is_baseline_set = True


    #print("BaseLine Min:", BaseLine.baseline_min)
    #print("BaseLine Max:", BaseLine.baseline_max)
    #print("Era Dict Count :", eraDictCount)
    #print("Era Dictionary First:", eraDict[1])
    #print("-------------------------------------------------------------------------------------")
    #print("Era Dictionary Last:", eraDict[eraDictCount])
    #print("-------------------------------------------------------------------------------------")

    _printSolution(best_sol.decisionVec, best_sol.sumOfObjs(), best_sol.getobj(), printCounter)
    _printEndMsg(SimulatedAnnealing.__name__)
    # print("------------------------------------------------------------------------------------------------")
    # print("Era dictionary First:=", eraDict[1])
    # print("Era dictionary Last:=", eraDict[eraDictCount])
    # print("------------------------------------------------------------------------------------------------")
    #print("era dict ", len(eraDict[1]))
    #exit()    
    return eraDict
Beispiel #3
0
def MaxWalkSat(model, maxTries=100, maxChanges=10, threshold=0, p=0.5, step=10):
    printCounter = 0
    ####
    #print purpose
    output = ""
    printCounter = 0
    cnt_Exc = 0
    cnt_Que = 0
    cnt_Dot = 0
    cnt_Pls = 0
    ## to keep track of eras
    eraDict = {}
    eraCount = 0
    eraTracker = 50
    temporary_sol= model()   # Just for getting the object
    crr_era, prev_era = [], [0 for _ in xrange(temporary_sol.numOfDec)]
    terminateCount = 0
    terminator = 10
    eraList = []
    a12Factor = 0.56
    eraDictCount = 0

    #print("isBaseLineSet:", BaseLine.is_baseline_set)

    for cntTry in range(maxTries):

        curr_solve_for_model = model()

        if BaseLine.is_baseline_set == False:
          #curr_sol.updateBaseline(BaseLine.getInitialBaseline(modelParam))
          initialBaseline = BaseLine.getInitialBaseline(model)
          #print("Output of initial baseline ", initialBaseline)
          BaseLine.baseline_min = initialBaseline[0]
          BaseLine.baseline_max = initialBaseline[1]
          newBaseLine = [BaseLine.baseline_min, BaseLine.baseline_max]
          curr_solve_for_model.updateBaseline(newBaseLine)        
        else:
          #print("HO GAYA TRUE")
          newBaseLine = [BaseLine.baseline_min, BaseLine.baseline_max]
          curr_solve_for_model.updateBaseline(newBaseLine)
          # print("newBaseLine:", newBaseLine)

        if cntTry==0:
            sbest=model()
            sbest.copy(curr_solve_for_model)
        for cng in range(maxChanges):
            printCounter = printCounter + 1

            if curr_solve_for_model.sumOfObjs() < threshold:
                print("\n Got lucky !. \n Found the solution early for {} by MaxWlakSat at step {} \n".format(model.__name__, printCounter))
                sbest.copy(curr_solve_for_model)
                _printSolution(curr_solve_for_model.decisionVec, curr_solve_for_model.sumOfObjs(), curr_solve_for_model.getobj(), printCounter)
                _printEndMsg(MaxWalkSat.__name__)
                return sbest.decisionVec

            decToMutate=randint(0, curr_solve_for_model.numOfDec-1)
            ## keeping tack of values before mutating annd labeling them as old
            score_old = curr_solve_for_model.sumOfObjs()
            oldModel = model()
            oldModel.copy(curr_solve_for_model)

            if p < random():
                curr_solve_for_model=generateNeighbor(curr_solve_for_model, decToMutate, model)
            else:
                #curr_solve_for_model=_mutateSelectivelyWithModifiedRange(model, curr_solve_for_model, decToMutate, step)
                curr_solve_for_model=_mutateSelectively(model, curr_solve_for_model, decToMutate, step)
            ## lets heck teh ebhavior !
                
            if curr_solve_for_model.sumOfObjs() < sbest.sumOfObjs():
                sbest.copy(curr_solve_for_model)
                    
                #'?' means muatted solution  is better than best soultuion
                # btw, we are only interested in the best and we keep that
                output = output + "?"
                cnt_Que = cnt_Que + 1
            elif curr_solve_for_model.sumOfObjs() < score_old:
                #'!' means muatted solution  is better than old soultuion

                output = output + "!"
                cnt_Exc = cnt_Exc + 1
            elif curr_solve_for_model.sumOfObjs() >= score_old:
                ## '+' means old solution is better than mutated solution
                output = output + "+"
                cnt_Pls = cnt_Pls + 1
            else:
                output = output + "."
                cnt_Dot = cnt_Dot + 1
            # if printCounter % 40 == 0:
            if printCounter % eraTracker == 0:
                #print("itrations so far={} '?'={}, '!'={}, '+'={}, '.'={}, output={} ".format(printCounter, cnt_Que, cnt_Exc, cnt_Pls, cnt_Dot,output))
                #print(output + '\n')
                output = ""

                cnt_Que = 0
                cnt_Exc = 0
                cnt_Pls = 0
                cnt_Dot = 0

            ## era purpose
            if BaseLine.baseline_min > sbest.sumOfObjs():
                  BaseLine.baseline_min = sbest.sumOfObjs()    
            if BaseLine.baseline_max < sbest.sumOfObjs():
                  BaseLine.baseline_max = sbest.sumOfObjs() 
            newBaseLine = [BaseLine.baseline_min, BaseLine.baseline_max]
            curr_solve_for_model.updateBaseline(newBaseLine)                          
            if eraCount ==19:
                ## comparing prev and current
                crr_era = sorted(eraList, reverse=True)
                #print("Current era:", curr_era)

                eraDict[eraDictCount] = crr_era
                eraDictCount = eraDictCount + 1
                a12Output = utilities.a12(crr_era, prev_era)

                if a12Output <= a12Factor:
                    terminateCount = terminateCount + 1
                eraList = []
                eraCount = 0
                prev_era = crr_era
                #print("era count ={}, era dict= {}, a12={}, terminator={}".format(eraCount, prev_era, crr_era, a12Output, terminateCount))
            else:
                eraList.append(sbest.getobj())
                eraCount += 1

            if terminateCount >= terminator:
                break            

            
#            if curr_solve_for_model.sumOfObjs() < curr_solve_for_model.getCurrentBaseline()[0]:
#                curr_solve_for_model.updateBaseline( [curr_solve_for_model.sumOfObjs(), curr_solve_for_model.getCurrentBaseline()[1]])
#                # print("+++++^^BASELINE UPDATED")
#            if curr_solve_for_model.sumOfObjs() > curr_solve_for_model.getCurrentBaseline()[1]:
#                curr_solve_for_model.updateBaseline([curr_solve_for_model.getCurrentBaseline()[0], curr_solve_for_model.sumOfObjs()])
                #print("+++++^^BASELINE UPDATED MILA MAX")
                #exit()

        #Update Global Baseline :
        #print(curr_solve_for_model.getCurrentBaseline());

        BaseLine.baseline_min = curr_solve_for_model.getCurrentBaseline()[0]
        BaseLine.baseline_max = curr_solve_for_model.getCurrentBaseline()[1]
        BaseLine.is_baseline_set = True

    #print("BaseLine Min:", BaseLine.baseline_min)
    #print("BaseLine Max:", BaseLine.baseline_max)
    #print("Era Dict Count :", eraDictCount)
    #print("Era Dictionary First:", eraDict[1])
    #print("-------------------------------------------------------------------------------------")
    #print("Era Dictionary Last:", eraDict[eraDictCount])
    #print("-------------------------------------------------------------------------------------")

    _printSolution(sbest.decisionVec, sbest.sumOfObjs() , sbest.getobj(), printCounter)
    _printEndMsg(MaxWalkSat.__name__)

    return  eraDict