def exploreNeighborhood(ini_N, ini_S, ini_G):
    N = copy.deepcopy(ini_N)
    S = copy.deepcopy(ini_S)
    G = copy.deepcopy(ini_G)
    bestNg = S
    besta = alpha(N, S)
    if besta <= 0.000001 and besta >= -0.000001:
        return bestNg
    for i in range(len(N)):
        relaxS = relax(
            S,
            i)  # relax the variables one by one, each time only one is relaxed
        bestNgtmp, bestatmp = exploreNeighborhoodAux(N, G, relaxS, bestNg,
                                                     besta)
        if bestNgtmp is not None and bestatmp is not None:

            bestNg = bestNgtmp
            besta = bestatmp
            if besta <= 0.000001 and besta >= -0.000001:
                return bestNg

    return bestNg
示例#2
0
def EAMQ(operator, N, G, cardp, cardBest, divT, loopsInfo_dir, f, consC):

    print("Enter the main algorithm EAMQ")
    startT = time.time()

    # Initialization Step
    SP = []
    SBest = []
    nbloops = 0
    timeoutL = globs["timeout"]
    setGlobals("cross_total", 0.0)
    setGlobals("cross_num", 0)
    setGlobals("explore_aftcross_total", 0.0)
    setGlobals("explore_aftcross_num", 0)
    setGlobals("nbloops", 0)
    setGlobals("passT", 0.0)

    for i in range(cardp):
        S0 = randomScenario(G)
        while S0 is None:
            S0 = randomScenario(G)
            print("random scenario none")
        S = exploreNeighborhood(N, S0, G)
        while S is None:
            S = exploreNeighborhood(N, S0, G)
            print("explore neighbor none")
        SP.append(S)

    print("After initialization")
    passT = time.time() - startT
    globs["initial_time"] += passT

    ite_passT = 0

    # Main Loop
    while passT < timeoutL:

        # Selection Step
        select_startT = time.time()
        SBest = selectBestScenarios(N, SP, cardBest)
        setGlobals("best_scenario", SBest[0])
        select_passT = time.time() - select_startT
        globs["select_time"] += select_passT

        a = alpha(N, SBest[0])
        setGlobals("best_a", a)

        passT = time.time() - startT
        globs["passT"] = passT

        globs["nbloops"] = nbloops

        if nbloops > 0:
            ite_passT = time.time() - ite_startT

        if nbloops == 1:
            globs["first_ite"] += ite_passT
            globs["ite_select_time"] += ite_select_passT
        print("Loop %d, elapsed time is %f, timeout is %d, a is %f." %
              (nbloops, passT, timeoutL, a))
        print("Loop %d, elapsed time is %f, timeout is %d, a is %f." %
              (nbloops, passT, timeoutL, a),
              file=f)

        if a < 0.00001 and a > -0.00001:
            setGlobals("best_scenario", SBest[0])
            setGlobals("best_a", a)
            globs["last_ite"] += ite_passT
            return 0

        ite_startT = time.time()
        nbloops += 1
        print("nbloops: %d" % nbloops)

        # New Generation Step
        if nbloops % divT != 0:
            # Crossover Step
            SG = []
            for i in range(cardp - cardBest):

                ran_best1 = random.randint(0,
                                           len(SBest) -
                                           1)  # randomly select a scenario
                ran_best2 = random.randint(0,
                                           len(SBest) -
                                           1)  # randomly select a scenario

                while ran_best1 == ran_best2:
                    ran_best2 = random.randint(
                        0,
                        len(SBest) - 1)  # randomly select a base relation
                    if ran_best2 != ran_best1:  # need two different random number
                        break
                    print("reselect best scenario randomly")

                S1 = SBest[ran_best1]
                S2 = SBest[ran_best2]
                ite_select_passT = time.time() - startT

                if operator == "crossConsA":
                    S = crossConsA(N, G, S1, S2)
                elif operator == "crossConsB":
                    S = crossConsB(N, G, S1, S2)
                elif operator == "crossVarsA":
                    S = crossVarsA(N, G, S1, S2)
                elif operator == "crossVarsB":
                    S = crossVarsB(N, G, S1, S2)
                elif operator == "crossVarsC":
                    S = crossVarsC(N, G, S1, S2)
                elif operator == "crossConsC":
                    S = crossConsC(N, G, S1, S2, consC)
                elif operator == "crossConsD":
                    S = crossConsD(N, G, S1, S2)
                else:
                    print("Invalid operator %s" % operator)
                    sys.exit()

                explore_startT = time.time()
                S = exploreNeighborhood(N, S, G)
                explore_passT = time.time() - explore_startT

                globs["explore_aftcross_total"] += explore_passT
                globs["explore_aftcross_num"] += 1

                SG.append(S)
            SP = SBest + SG
        else:
            # Diversification Step
            print("Diversification Step")
            print("Diversification Step", file=f)
            SBest1 = selectBestScenarios(N, SBest, 1)
            SP = SBest1
            for i in range(cardp - 1):
                S = randomScenario(G)
                S = exploreNeighborhood(N, S, G)
                SP.append(S)

    return 0
示例#3
0
def crossVarsB(N, neighbors, S1, S2):
    startT = time.time()
    V1 = [i for i in range(len(N))]
    V2 = []
    while len(V1) > len(V2):
        ran_v = random.randint(0, len(V1)-1) 
        V2.append(V1[ran_v])
        V1.remove(V1[ran_v])

    n = globs["size"]
    Id = 0
    from helpfuncs import B_dict
    with open("allen.identity") as f:
        Id = B_dict[f.readline().strip()]
    if n <= 8:
        N1 = tuple([array('B',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
        N2 = tuple([array('B',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
    elif n <= 16:
        N1 = tuple([array('H',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
        N2 = tuple([array('H',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
    else:
        N1 = tuple([array('I',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
        N2 = tuple([array('I',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
        
    for i in range(len(N1)):
        for j in range(i+1, len(N1)):
            if i in V1 and j in V1:
                N1[i][j] = S1[i][j]
                N1[j][i] = S1[j][i]
                N2[i][j] = S2[i][j]
                N2[j][i] = S2[j][i]
            elif i in V2 and j in V2:
                N1[i][j] = S2[i][j]
                N1[j][i] = S2[j][i]
                N2[i][j] = S1[i][j]
                N2[j][i] = S1[j][i]

    a1 = alpha(N, N1)
    a2 = alpha(N, N2)
    if a1 <= a2:
        S = N1
    else:
        S = N2

    unsele_edges = []
    for i in range(len(neighbors)):
        for j in neighbors[i]:
            baselist = bitdecoding(S[i][j])
            if j > i and len(baselist) > 1:
                unsele_edges.append((i, j))

    while unsele_edges:  # if there exist some edges need to be handled
        ran_e = random.randint(0, len(unsele_edges)-1) 
        u, v = unsele_edges[ran_e]

        if S[u][v] & N[u][v] != 0:
            rel = S[u][v] & N[u][v]
        else:
            rel = S[u][v]

        rellist = bitdecoding(rel)
        ran_b = random.randint(0, len(rellist)-1)
        S[u][v] = rellist[ran_b] 
        S[v][u] = inv[rellist[ran_b]-1]

        unsele_edges.remove(unsele_edges[ran_e])
                
        # G-consistent
        ppc(S, neighbors) #path consistency on the initial graph (partial)
        
    return S
示例#4
0
def crossConsC(N, neighbors, S1, S2, d):
    startT = time.time()
    n = globs["size"]
    Id = 0
    from helpfuncs import B_dict
    with open("allen.identity") as f:
        Id = B_dict[f.readline().strip()]
    if n <= 8:
        S = tuple([array('B',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
    elif n <= 16:
        S = tuple([array('H',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])
    else:
        S = tuple([array('I',[B_dict['DALL'] if i != j else Id for i in range(len(neighbors))]) for j in range(len(neighbors))])

    # constraint of each edge is set as a random base relation

    nbloops = 0

    a1 = alpha(N, S1)
    a2 = alpha(N, S2)

    if a1 <= a2:
        S_fst = S1
        S_scd = S2
    else:
        S_fst = S2
        S_scd = S1

    unsele = []
    unsele_not0 = []
    unsele_0 = []
    
    for i in range(len(neighbors)):
        for j in neighbors[i]: 
            baselist = bitdecoding(S[i][j])
            if j > i and len(baselist) > 1:
                unsele.append((i, j))

    for (i, j) in unsele:
        if N[i][j] & S[i][j] == 0:
            unsele_0.append((i, j))
        else:
            unsele_not0.append((i, j))

    while unsele:  # while there exist unhandled edges

        if unsele_not0:  # if there exist some edges need to be handled which has common relation with the target QCN
            print("unsele_not0")
            ran_e = random.randint(0, len(unsele_not0)-1)
            u, v = unsele_not0[ran_e]

            nbloops += 1

            if nbloops % d == 0:
                S_1 = S_scd
                S_2 = S_fst
            else:
                S_1 = S_fst
                S_2 = S_scd
            
            if S[u][v] & N[u][v] != 0:
                rel = S[u][v] & N[u][v]
            else:
                rel = S[u][v]

            if S_1[u][v] & rel != 0:
                rel = S_1[u][v] & rel
            elif S_2[u][v] & rel != 0:
                rel = S_2[u][v] & rel

            baselist = bitdecoding(rel)
            if len(baselist) > 1:
                ran_b = random.randint(0, len(baselist)-1) 
            elif len(baselist) > 0:
                ran_b = 0
            else:
                print(rel)
                print(baselist)
                print("crossover baselist 0 elements in unsele_not0")
                return None
            b = baselist[ran_b]
            S[u][v] =  b 
            S[v][u] = inv[b-1]

            unsele.remove(unsele[ran_e]) 
            unsele_not0.remove(unsele_not0[ran_e]) 
                    
            # G-consistent
            if not ppc(S, neighbors): 
                print("Inconsistency occurs in crossConsC")
                return None
            
            for (i, j) in unsele_not0:
                if N[i][j] & S[i][j] == 0:
                    unsele_0.append((i, j))
                    unsele_not0.remove((i, j))
    
        elif unsele_0:  # if there exist some edges need to be handled which has no common relation with the target QCN
            print("unsele_0")
            ran_e = random.randint(0, len(unsele_0)-1) 
            u, v = unsele_0[ran_e]

            nbloops += 1

            if nbloops % d == 0:
                S_1 = S_scd
                S_2 = S_fst
            else:
                S_1 = S_fst
                S_2 = S_scd
            
            if S[u][v] & N[u][v] != 0:
                rel = S[u][v] & N[u][v]
            else:
                rel = S[u][v]

            if S_1[u][v] & rel != 0:
                rel = S_1[u][v] & rel
            elif S_2[u][v] & rel != 0:
                rel = S_2[u][v] & rel

            baselist = bitdecoding(rel)
            if len(baselist) > 1:
                ran_b = random.randint(0, len(baselist)-1) 
            elif len(baselist) > 0:
                ran_b = 0
            else:
                print("crossover baselist 0 elements")
                return None
            b = baselist[ran_b]
            S[u][v] =  b 
            S[v][u] = inv[b-1]

            unsele.remove(unsele[ran_e])
            unsele_0.remove(unsele_0[ran_e])
                    
            # G-consistent
            if not ppc(S, neighbors): #path consistency on the initial graph (partial)
                print("Inconsistency occurs in crossConsC")
                return None

    print("----------------------after while----------------------")
    passT = time.time() - startT
    globs["cross_total"] = globs["cross_total"] + passT
    globs["cross_num"] += 1

    return S
def exploreNeighborhoodAux(ini_N, ini_neighbors, ini_N_, ini_bestNg, besta):

    N = copy.deepcopy(ini_N)
    neighbors = copy.deepcopy(ini_neighbors)
    N_ = copy.deepcopy(ini_N_)
    bestNg = copy.deepcopy(ini_bestNg)

    # G-consistent
    from ppc import pPC as ppc
    if ppc(N_, neighbors):  #path consistency on the initial graph (partial)

        a = alpha(N, N_)
        if a >= besta:
            return bestNg, besta

        unsele_edges = []
        for i in range(len(neighbors)):
            for j in neighbors[i]:  # traverse each edge
                baselist = bitdecoding(N_[i][j])
                if j > i and len(baselist) > 1:
                    unsele_edges.append((i, j))

        if len(unsele_edges) > 0:  # if there exist unhandled edges
            ran_e = random.randint(0,
                                   len(unsele_edges) -
                                   1)  # randomly choose one
            u, v = unsele_edges[ran_e]
            baselist = bitdecoding(N_[u][v])
            ran_b = random.randint(0,
                                   len(baselist) - 1)  # random base relation

            removeblist = copy.deepcopy(baselist)
            r1 = baselist[ran_b]  # substitute to b
            removeblist.remove(removeblist[ran_b])  # remove b
            r2 = 0
            for k in removeblist:
                r2 = r2 | k
            N1 = copy.deepcopy(N_)
            N2 = copy.deepcopy(N_)
            N1[u][v] = r1
            N1[v][u] = inv[r1 - 1]
            N2[u][v] = r2
            N2[v][u] = inv[r2 - 1]

            bestNgtmp, bestatmp = exploreNeighborhoodAux(
                N, neighbors, N1, bestNg, besta)  # recursion
            if bestNgtmp is not None and bestatmp is not None:
                bestNg = bestNgtmp
                besta = bestatmp
                if besta <= 0.000001 and besta >= -0.000001:
                    return bestNg, besta

            bestNgtmp, bestatmp = exploreNeighborhoodAux(
                N, neighbors, N2, bestNg, besta)  # recursion
            if bestNgtmp is not None and bestatmp is not None:
                bestNg = bestNgtmp
                besta = bestatmp

        else:  # if there is no unhandled edge
            bestNg = N_
            besta = a
        return bestNg, besta

    else:
        return None, None