def sim_Annealing(T, OBJs, execTime, *args):
    temp = args[0]
    alpha = args[1]
    niter = args[2]
    s = [0] * len(OBJs)
    bs = s  # best state found
    start = time()
    while temp > 1:
        if time() - start > execTime:
            break
        si = neightborhood(s, T, OBJs)
        for _ in range(niter):
            sn = take_Random(si)
            oValue = bp.state_Value(sn, OBJs)
            if oValue > bp.state_Value(s, OBJs):
                s = sn
                si = neightborhood(s, T, OBJs)  # updating neightborhood
                if oValue > bp.state_Value(bs, OBJs):
                    bs = sn
            else:
                p = math.exp((oValue - bp.state_Value(s, OBJs)) / temp)
                if random.random() < p:
                    s = sn
                    si = neightborhood(s, T, OBJs)  # updating neightborhood
        temp *= alpha
    return bs
Пример #2
0
def grasp(iter):
    bs = [0]*len(bp.OBJs)
    for _ in range(iter):
        s = greedy_Random_Construct()
        s = local_Search(s)
        if bp.state_Verify(s) and bp.state_Value(s) > bp.state_Value(bs):
            bs = s
    return bs
Пример #3
0
def genetic(popMaxSize, iter, crossoverRate, mutationRate):
    si = init_Population(popMaxSize)
    bs = [0]*len(bp.OBJs)
    for _ in range(iter):
        si = generate_New_Pop(si, crossoverRate, mutationRate)
        s = best_in_Pop(si)
        if bp.state_Verify(s) and bp.state_Value(s) > bp.state_Value(bs):
            bs = s
    return bs
Пример #4
0
def deepest_Descent(s):
    bs = s  # best state found
    si = neightborhood(s)
    c = True  # continue flag
    while c:
        c, sn = select_Best(si)
        if bp.state_Value(sn) > bp.state_Value(bs):
            bs = sn
            si = neightborhood(sn)
        else:
            break
    return bs
Пример #5
0
def multistart_Descend(iter, use_Deepest=False):
    if use_Deepest:
        func = dd.deepest_Descent
    else:
        func = sd.simple_Descent
    bs = [0] * len(bp.OBJs)  # best state found
    for _ in range(iter):
        s = random_Start_State()
        sn = func(s)
        if bp.state_Verify(sn) and bp.state_Value(sn) > bp.state_Value(bs):
            bs = sn
    return bs
Пример #6
0
def beam_Search(m):
    f = queue.Queue(m)
    f.put([0]*len(bp.OBJs)) # starting queue with the initial state
    bs = [0]*len(bp.OBJs)   # starting best state as initial state
    while f.qsize() > 0:
        st = f.get()
        if bp.state_Value(st) > bp.state_Value(bs):
            bs = st
        si = select_Best_States(m-f.qsize(), st)
        for i in si:
            f.put(i)
    return bs
Пример #7
0
def simple_Descent(s):
    bs = s # best state found
    si = neightborhood(s)
    while len(si) > 0:
        for _ in range(len(si)):
            sn = take_Random(si)
            if bp.state_Value(sn) > bp.state_Value(bs):
                bs = sn
                si = neightborhood(sn)
                break
        else:
            break # exiting if no better state is found
    return bs
Пример #8
0
def deepest_Descent(T, OBJs, s, startTime, execTime):
    bs = s  # best state found
    si = neightborhood(s, T, OBJs)
    c = True  # continue flag
    while c:
        if time() - startTime > execTime:
            break
        c, sn = select_Best(si, T, OBJs)
        if bp.state_Value(sn, OBJs) > bp.state_Value(bs, OBJs):
            bs = sn
            si = neightborhood(sn, T, OBJs)
        else:
            break
    return bs
Пример #9
0
def grasp(T, OBJs, execTime, *args):
    niter = args[0]
    numBest = args[1]
    s = [0] * len(OBJs)
    bs = s  # best state found
    start = time()
    for _ in range(niter):
        if time() - start > execTime:
            break
        s = greedy_Random_Construct(s, numBest, T, OBJs, start, execTime)
        sl = local_Search(T, OBJs, s, start, execTime)  # local state found
        if bp.state_Verify(
                sl, T,
                OBJs) and bp.state_Value(sl, OBJs) > bp.state_Value(bs, OBJs):
            bs = sl
    return bs
Пример #10
0
def beam_Search(T, OBJs, execTime, *args):
    m = args[0]
    f = queue.Queue(m)
    f.put([0] * len(OBJs))  # starting queue with the initial state
    bs = [0] * len(OBJs)  # starting best state as initial state
    start = time()
    while f.qsize() > 0:
        if time() - start > execTime:
            break
        st = f.get()
        if bp.state_Value(st, OBJs) > bp.state_Value(bs, OBJs):
            bs = st
        si = select_Best_States(m - f.qsize(), st, T, OBJs)
        for i in si:
            f.put(i)
    return bs
Пример #11
0
def select_Best_States(n, st):
    si = bp.state_Expansion(st)
    si = [[bp.state_Value(s),s] for s in si]
    si.sort(reverse=True)
    si = [i[1] for i in si]
    bss = []
    for i in filter(bp.state_Verify, si):
        bss.append(i)
    return bss[:n]
Пример #12
0
def genetic(T, OBJs, execTime, *args):
    popMaxSize = args[0]
    niter = 500
    crossoverRate = args[1]
    mutationRate = args[2]
    si = init_Population(popMaxSize, OBJs)
    bs = [0] * len(OBJs)
    start = time()
    for _ in range(niter):
        if time() - start > execTime:
            break
        si = generate_New_Pop(si, crossoverRate, mutationRate, T, OBJs)
        s = best_in_Pop(si, T, OBJs)
        if bp.state_Verify(
                s, T,
                OBJs) and bp.state_Value(s, OBJs) > bp.state_Value(bs, OBJs):
            bs = s
    return bs
Пример #13
0
def select_Best_States(n, st, T, OBJs):
    si = bp.state_Expansion(st)
    si = [[bp.state_Value(s, OBJs), s] for s in si]
    si.sort(reverse=True)
    si = [i[1] for i in si]
    bss = []
    for i in si:
        if bp.state_Verify(i, T, OBJs):
            bss.append(i)
    return bss[:n]
Пример #14
0
def branch_n_bound(use_opt_estimate=True):
    bs = triv_solution()  # best state found
    sv = bp.state_Value(bs)  # value of best bs
    pq.insert(0, [0] * len(bp.OBJs))  # pushing initial state in queue
    while not pq.isEmpty():
        cs = pq.remove()  # current state
        si = bp.state_Expansion(cs)  # expansion of current state
        for s in si:
            if bp.state_Verify(s):
                if use_opt_estimate:  # selecting estimate method
                    est = opt_Estimate(s)
                else:
                    est = n_Opt_Estimate(s)
                if bp.state_Value(est) > sv:
                    if bp.state_Value(s) > sv:
                        bs = s  # updating best bs
                        sv = bp.state_Value(s)  # updating best value
                    pq.insert(bp.state_Value(s), s)
    return bs
Пример #15
0
def init_Population(popMaxSize, OBJs):
    pop = [[0] * len(OBJs)]  # insert initial state
    for _ in range(popMaxSize):
        s = pop[len(pop) - 1].copy()  # get last added state
        s = mutation(s)
        if bp.state_Value(s,
                          OBJs) == 0:  # for safity, empty states are not added
            p = random.randint(0, len(s) - 1)
            s[p] += 1
        pop.append(s)
    return pop
Пример #16
0
def select_Best(si):
    sn = -1  # best state position
    sv = 0  # state value
    for i in range(len(si)):
        v = bp.state_Value(si[i])  # current value
        if bp.state_Verify(si[i]) and v > sv:
            sv = v
            sn = i
    if sn == -1:
        return False, []
    return True, si[sn]
Пример #17
0
def test():
    results = []  # heuristics results
    normResults = []  # heuristics normalized results
    execTimes = []  # heuristics execution times
    avr = []  # heuristics avarages
    sdv = []  # heuristics standard deviations
    normAvr = []  # normalized heuristics avarages
    normSdv = []  # normalized heuristics standard deviations
    timeAvr = []  # heuristics execution times avarages
    timeSdv = []  # heuristics execution times standard deviations
    for h in HEURISTICS:  # for each metaheuristic
        funcName = h[0]
        func = h[1]
        par = h[3]
        r = []  # problens results
        t = []  # problens execution time
        for p in TEST:  # for each test problem
            T = p[0]
            OBJs = p[1]
            start = time()
            ans = func(T, OBJs, 300, *par)
            end = time()
            r.append(bp.state_Value(ans, OBJs))
            t.append(end - start)
        results.append(r.copy())
        execTimes.append(t.copy())
        avr.append(mean(r))
        sdv.append(stdev(r))
        timeAvr.append(mean(t))
        timeSdv.append(stdev(t))
    names = [x[0] for x in HEURISTICS]
    normResults = crossNormalize(results)  # normalizing problens results
    normAvr = [mean(x) for x in normResults]
    normSdv = [stdev(x) for x in normResults]
    # saving boxplots:
    genarate_Boxplot(' Teste - Valores', normResults, names, 'Valor',
                     'Meta-Heurística')
    genarate_Boxplot(' Teste - Tempo de Execução', execTimes, names,
                     'Tempo (segundos)', 'Meta-Heurística')
    headers = [
        'Meta-heurística', 'Média Absoluta', 'Desvio Padrão Absoluto',
        'Média Normalizada', 'Desvio Padrão Normalizado',
        'Média do Tempo de Execução', 'Desvio Padrão do Tempo de Execução'
    ]
    # saving table:
    generateLatexTable([names, avr, sdv, normAvr, normSdv, timeAvr, timeSdv],
                       headers, 'Tabela')
    # making and saving ranks:
    avgRank(results)
    normRank(normAvr)
Пример #18
0
def roulette(si, OBJs):
    probRatio = []  # roulette
    # Adding all states's values to probRatio:
    for s in si:
        probRatio.append(bp.state_Value(s, OBJs))
    # Normalizing the values:
    ratioSum = sum(probRatio)
    probRatio = [(i / ratioSum) for i in probRatio]
    # Building the "partitions" of the roulette:
    for i in range(len(probRatio)):
        probRatio[i] = sum(probRatio[i:])
    # Selecting a random element:
    selector = random.random()
    for i in range(len(probRatio)):
        if selector >= probRatio[i]:
            s = si[i]
            break
    return s
Пример #19
0
def roulette(si, OBJs):
    probRatio = []  # roulette
    c = []
    # Adding values to probRatio:
    for s in si:
        probRatio.append(bp.state_Value(s, OBJs))
    # Normalizing the values:
    ratioSum = sum(probRatio)
    probRatio = [(i / ratioSum) for i in probRatio]
    # Building the "partitions" of the roulette:
    probRatio = list(accumulate(probRatio))
    # Selecting a random element:
    ratioSum = sum(probRatio)
    selector = random.random()
    for i in range(len(probRatio)):
        if selector <= probRatio[i]:
            c = si[i]
            break
    return c
Пример #20
0
def train():
    testParameters = []
    for h in HEURISTICS:  # for each metaheuristic
        funcName = h[0]
        func = h[1]
        parList = h[2]
        parameters = build_Parameters(parList)
        results = []  # heuristics results
        normResults = []  # heuristics normalized results
        execTimes = []  # heuristics execution times
        for p in TRAIN:  # for each train problem
            T = p[0]
            OBJs = p[1]
            r = []  # problem results
            n = []  # problem normalized results
            t = []  # problem execution time
            for c in parameters:  # for each configuration of hiperparameters
                start = time()
                ans = func(T, OBJs, 120, *c)
                end = time()
                r.append(bp.state_Value(ans, OBJs))  # saving result
                t.append(end - start)  # saving execution time
            n = normalize(r)  # normalizing results
            results.append(r.copy())  # saving problem results
            normResults.append(n.copy())  # saving problem normalized results
            execTimes.append(t.copy())  # saving problem execution time
        testPar, bestResults, bestTimes, xTickLabels = take_Best_Configurations(
            parameters, results, normResults, execTimes)
        testParameters.append(testPar.copy())
        # saving best parameter in a file:
        with open('Results.txt', 'a') as file:
            file.write(funcName + ': ' + str(testPar) + '\n')
        # printing boxplots:
        genarate_Boxplot(funcName + '_-_Valores', bestResults, xTickLabels,
                         'Valor Normalizado', 'Melhores Hiperparâmetros')
        genarate_Boxplot(funcName + '_-_Tempo_de_Execução', bestTimes,
                         xTickLabels, 'Tempo (segundos)',
                         'Melhores Hiperparâmetros')
    return testParameters
Пример #21
0
def sim_Annealing(s,temp,iter):
    bs = s # best state found
    alpha = random.random() # random value in [0,1]
    while temp > 1:
        si = neightborhood(s)
        for _ in range(iter):
            sn = take_Random(si)
            if bp.state_Value(sn) > bp.state_Value(s):
                s = sn
                si = neightborhood(s) # updating neightborhood
                if bp.state_Value(sn) > bp.state_Value(bs):
                    bs = sn
            else:
                p = math.exp((bp.state_Value(sn) - bp.state_Value(s))/temp)
                if random.random() < p:
                    s = sn
                    si = neightborhood(s) # updating neightborhood
        temp *= alpha
    return bs
Пример #22
0
def fitness(s, T, OBJs):
    if bp.state_Verify(s, T, OBJs):
        return bp.state_Value(s, OBJs)
    return 0