Exemplo n.º 1
0
def Build_Proximity_Graph_Uniform(x, cutoff, y=None):
    H = Hypergraph(0)
    if y is not None:
        cflib.Build_Proximity_Graph_2Sets_Uniform(H.hg, x, y, cutoff)
    else:
        cflib.Build_Proximity_Graph_Uniform(H.hg, x, cutoff)
    return H
Exemplo n.º 2
0
def Build_Pair_Graph(x, cutoff, y=None):
    H = Hypergraph(0)
    if y is not None:
        cflib.Build_Pair_Graph_2Sets(H.hg, x, y, cutoff)
    else:
        cflib.Build_Pair_Graph(H.hg, x, cutoff)
    return H
Exemplo n.º 3
0
def Build_Proximity_Graph_Variable(x, r, y=None):
    H = Hypergraph(0)
    if y is not None:
        cflib.Build_Proximity_Graph_2Sets_Variable_np(H.hg, x, y, r)
    else:
        cflib.Build_Proximity_Graph_Variable_np(H.hg, x, r)
    return H
def solve_roth(n):
    graph = Hypergraph.roth(n)
    print('n =', n, ':')
    print(graph.incidence)
    start = tm.time()
    coloring, num_steps = solve(graph, print_per_time=100)
    elapsed_time = tm.time() - start
    return coloring, num_steps, elapsed_time
def solve_roth_bf(n):
    # brute force
    graph = Hypergraph.roth(n)
    print('n =', n, ':')
    print(graph.incidence)
    start = tm.time()
    coloring = graph.find_optimal_coloring()
    elapsed_time = tm.time() - start
    return coloring, elapsed_time
Exemplo n.º 6
0
def Build_Proximity_Graph_Given_Length(x, N_desired, cutoff, y=None):
    H = Hypergraph(0)
    if y is not None:
        r = np.empty((y.shape[0], ), dtype=x.dtype)
        cflib.Build_Proximity_Graph_2Sets_Given_Length_np(
            H.hg, x, y, N_desired, cutoff, r)
    else:
        r = np.empty((x.shape[0], ), dtype=x.dtype)
        cflib.Build_Proximity_Graph_Given_Length_np(H.hg, x, N_desired, cutoff,
                                                    r)
    return H, r
Exemplo n.º 7
0
def random_graph_generator():
    """
    Fonction qui génère aléatoirement un hypergraphe de taille
    raisonnable (maximum 15 sommets et hyper-arêtes) .
    """
    n = randint(1, 16)
    # Nombre du sommets
    V = set("v" + str(i) for i in range(1, n + 1))

    max_hyperedge = 2**n - 1
    # Maximum d'hyper-arêtes qu'on peut obtenir avec n sommets

    x = min(16, max_hyperedge + 1)
    # Maximum d'hyper-arêtes
    m = randint(1, x)
    # Nombre d'hyper-arêtes

    MatrixTranspose = []
    i = 0
    while i < m:
        row = [0 if random() < 0.5 else 1 for j in range(n)]
        # Génère une hyper-arête
        if row not in MatrixTranspose:
            # Vérifier qu'il n'existe pas la même hyper-arête deux fois
            MatrixTranspose.append(row)
            i += 1

    n = len(MatrixTranspose[0])

    incidenceMatrix = [[row[i] for row in MatrixTranspose] for i in range(n)]

    E = {
        "E" + str(j + 1):
        ["v" + str(i + 1) for i in range(n) if incidenceMatrix[i][j]]
        for j in range(m)
    }

    return Hypergraph(V, E, incidenceMatrix)
Exemplo n.º 8
0
        super(BeckFialaProblem, self).__init__(state)

    def move(self):
        """Inverses a color"""
        idx = np.random.randint(0, len(self.state) - 1)
        self.state[idx] = -self.state[idx]

    def energy(self):
        """Calculates the discrepancy of the coloring."""
        return self.graph.calc_discrepancy(self.state)


if __name__ == '__main__':

    n = int(sys.argv[1])
    graph = Hypergraph.roth(n)
    init_coloring = np.asarray(
        [np.random.randint(0, 2) * 2 - 1 for i in range(n)])
    print("init. coloring:", init_coloring)

    bfp = BeckFialaProblem(init_coloring, graph)

    bfp.Tmin = 0.2
    bfp.steps = 50000
    bfp.copy_strategy = "slice"
    start_time = time.time()
    state, disc = bfp.anneal()
    elapsed_time = time.time() - start_time

    print("n =", graph.n, ", m =", graph.m)
    print("Incidence matrix:\n", graph.incidence)
Exemplo n.º 9
0
    def run_least_squares(self):
        logger.info('===== Mode: ' + self.mode + ' =====')
        N = self.graph.number_of_nodes()

        if self.mode == 'C-CADMM':
            C = np.ones((self.graph.number_of_nodes(), 1))
        elif self.mode == 'D-CADMM':
            C = nx.incidence_matrix(self.graph)
            logger.debug("Hybrid C = \n" + str(C.todense()))
        elif self.mode == 'H-CADMM':
            # ===========================================
            # if random select
            if 'random_hyperedge' in self.setting.keys():
                r = self.setting['random_hyperedge']
                n_sample = int(N * r)
                hyperedge = np.random.choice(np.arange(N), (n_sample, ),
                                             replace=False)
                hyperedge = list(hyperedge)
            else:
                hyperedge = []
            # ============================================
            # check if n_FC is set
            if 'n_FC' in self.setting.keys():
                n_FC = self.setting['n_FC']
            else:
                n_FC = -1
            # =================================================
            # normal process, check if hyperedge is set or not
            C = np.asarray(nx.incidence_matrix(self.graph).todense())
            H = Hypergraph(C, hyperedge=hyperedge, num=n_FC)
            C = H.incidence_matrix()
            logger.debug("Hybrid C = \n" + str(C))
        else:
            raise ValueError("mode must be set")
        # check to see if penalty need to be set
        if self.setting['penalty'] <= 0:
            # get L and l
            L, l = cond_num(C)
            self.setting['penalty'] = np.sqrt(2 / (L * l * (1 + 2 * L / l)))
            logger.debug('penalty = ' + str(self.setting['penalty']))
            print('auto penalty used')

        # convert C to A, B to compute residual
        A, B = self.incidence_to_ab(C)

        # reshape them as (-1, 1), which is a 2D vector
        node_degree, edge_degree = (np.squeeze(np.asarray(C.sum(axis=1))),
                                    np.squeeze(np.asarray(C.sum(axis=0))))

        # extract simulation settings
        setting = self.setting
        rho, v, x0, max_iter = (setting['penalty'], setting['objective'],
                                setting['initial'], setting['max_iter'])
        x_opt = v.mean(axis=0)

        # initial value
        z0 = C.T.dot(x0) / edge_degree.reshape(-1, 1)
        alpha0 = np.zeros_like(x0)
        primal_gap, primal_residual, dual_residual = [], [], []

        logger.info('Mode: %s, starting for-loop', self.mode)
        x, z, alpha = x0, z0, alpha0
        for i in range(max_iter):
            z_prev = z  # save for computing dual residual
            x = (v - alpha +
                 rho * C.dot(z)) / (1 + rho * node_degree.reshape(-1, 1))
            z = C.T.dot(x) / edge_degree.reshape(-1, 1)
            alpha += rho * (node_degree.reshape(-1, 1) * x - C.dot(z))

            primal_gap.append(LA.norm(x - x_opt) / LA.norm(x_opt))
            primal_residual.append(LA.norm(A.dot(x) - B.dot(z)))
            dual_residual.append(LA.norm(rho * C.dot(z - z_prev)))

            # stop if accuracy is reached
            if primal_gap[-1] < self.setting['epsilon']:
                break

            # debug printing
            step = max_iter // 10
            if i % step == step - 1:
                logger.info('Progress %.1f', 100 * (i + 1) / max_iter)

        logger.info('Mode: %s, ending for loop', self.mode)
        edges = C.sum()
        return primal_gap, primal_residual, dual_residual, edges
Exemplo n.º 10
0
def get_H_incidence(G):
    Cd = nx.incidence_matrix(G)
    H = Hypergraph(Cd)
    return H.incidence_matrix()
                coloring[idx] += gamma * np.dot(r, u[short_idx])
                short_idx += 1
        for (idx, flag) in enumerate(alive_points):
            if flag:
                if (not (inf_alive <= coloring[idx]
                         and coloring[idx] <= sup_alive)):
                    alive_points[idx] = False
                    num_alive_points -= 1
        if time_with_mod == print_per_time:
            print("t =", time, ", alive points =", num_alive_points, ",",
                  coloring)
            time_with_mod = 0
        time_with_mod += 1

    final_coloring = np.round(coloring)
    for idx in range(n):
        if final_coloring[idx] == 0:
            final_coloring[idx] = np.random.randint(0, 2) * 2 - 1
    print("Final coloring (float): ", coloring)
    print("Final coloring (int): ", final_coloring)


if __name__ == '__main__':
    graph = Hypergraph.random(2, 4)

    print("n =", graph.n, ", m =", graph.m)
    print("Incidence matrix:\n", graph.incidence)
    print("degree=", graph.degree)

    solve_beck_fiala(graph, print_per_time=100)
Exemplo n.º 12
0
    x = np.zeros(n)  # fractional
    l = math.ceil(math.log2(math.log2(m)))
    print("l =", l)
    alive_points = np.full(n, True)
    for i in range(0, l):
        x = sub_routine(graph, x, alive_points)

    x_int = np.copy(x)
    for i in range(0, n):
        if alive_points[i]:
            if random.random() <= (1 - x[i]) * 0.5:
                x_int[i] = -1
            else:
                x_int[i] = 1
    return x, x_int


if __name__ == '__main__':
    # For test
    np.random.seed(0)
    graph = Hypergraph.random(6, 6)
    np.random.seed()

    print("n =", graph.n, ", m =", graph.m)
    print("Incidence matrix:\n", graph.incidence)
    print("degree=", graph.degree)

    coloring, fractional = main_routine(graph)
    print("coloring =", coloring)
    print("fractional =", fractional)
Exemplo n.º 13
0
def Filter(ke, H, dofmaps, data):
    htrue = Hypergraph()
    hfalse = Hypergraph()
    cflib.filter_np(ke, H.hg, dofmaps, data, htrue.hg, hfalse.hg)
    return htrue, hfalse
Exemplo n.º 14
0
def Load_gmsh(fname,gdim=3):
    H = Hypergraph()
    cflib.Hypergraph_Destroy(H.hg)
    X = cflib.load_gmsh_np(gdim, H.hg, fname)
    return X,H
# -*- encoding: utf-8 -*-

"""
Basic test of Bansal's algorithm for Roth's problem
Usage: 
$ python bdg_on_roth_problem.py [n]
"""

import sys
from Hypergraph import Hypergraph
from bansal_dadusch_garg import *

n = int(sys.argv[1])
graph = Hypergraph.roth(n)

print("n =", graph.n, ", m =", graph.m)
print("Incidence matrix:\n", graph.incidence)
print("degree =", graph.degree, ":")
for i in range(n):
    print("\tdegree of point", i, "=", Hypergraph.get_roth_degree(n, i))

# coloring, time = solve(graph, print_per_time = 100)
# print("final discrepancy =", graph.calc_discrepancy(coloring))

opt_coloring, disc = graph.find_optimal_coloring()
print('optimal coloring =', opt_coloring)
print('optimal discrepancy = ', disc)