Exemplo n.º 1
0
def opt_modularity_wrapper(graph_generator_name, left, right, seed=None):
    """
    This function takes the same parameters as get_obj_val and can be imported anywhere and 
    used to get optimal modularity for a graph.
    """
    graph, _ = generate_graph(graph_generator_name, left, right, seed=seed)
    print('%i nodes, %i edges' %
          (nx.number_of_nodes(graph), nx.number_of_edges(graph)))
    print('creating dat file...')
    graph2dat(graph)
    print('creating dat file...DONE')
    return get_modularity(graph)
Exemplo n.º 2
0
def get_obj_val(graph_generator_name,
                left,
                right,
                seed=None,
                obj_params='ndarray',
                sign=1,
                backend='IBMQX',
                backend_params={'depth': 3},
                return_x=False):
    # Generate the graph
    G, _ = generate_graph(graph_generator_name, left, right, seed=seed)
    B = nx.modularity_matrix(G).A
    return get_obj(G.number_of_nodes(),
                   B,
                   obj_params=obj_params,
                   sign=sign,
                   backend=backend,
                   backend_params=backend_params,
                   return_x=return_x)
Exemplo n.º 3
0
def test_angles(graph_generator_name,
                left,
                right,
                angles,
                seed=None,
                verbose=0,
                compute_optimal=False,
                backend='IBMQX',
                backend_params={
                    'backend_device': None,
                    'depth': 3
                }):
    # note that compute optimal uses brute force! Not recommended for medium and large problem
    # angles should be a dictionary with fields 'beta' and 'gamma', e.g. {'beta': 2.0541782343349086, 'gamma': 0.34703642333837853}

    rand_seed = seed

    # Generate the graph
    G, _ = generate_graph(graph_generator_name, left, right, seed=seed)
    # Use angles

    # Using NetworkX modularity matrix
    B = nx.modularity_matrix(G).A

    # Compute ideal cost
    if compute_optimal:
        optimal_modularity = gm.compute_modularity(G, B, solution_bitstring)
        print("Optimal solution energy: ", optimal_modularity)
    else:
        optimal_modularity = None

    if backend == 'IBMQX':
        if not isinstance(angles, (np.ndarray, np.generic, list)):
            raise ValueError(
                "Incorrect angles received: {} for backend {}".format(
                    angles, backend))
        var_form = IBMQXVarForm(num_qubits=G.number_of_nodes(),
                                depth=backend_params['depth'])
        resstrs = var_form.run(angles)
    else:
        raise ValueError("Unsupported backend: {}".format(backend))

    if verbose > 1:
        # print distribution
        allstrs = list(product([0, 1], repeat=len(qubits)))
        freq = {}
        for bitstr in allstrs:
            freq[str(list(bitstr))] = 0
        for resstr in resstrs:
            resstr = str(list(resstr))  # for it to be hashable
            if resstr in freq.keys():
                freq[resstr] += 1
            else:
                raise ValueError(
                    "received incorrect string: {}".format(resstr))
        for k, v in freq.items():
            print("{} : {}".format(k, v))

    # Raw results
    modularities = [gm.compute_modularity(G, B, x) for x in resstrs]
    mod_max = max(modularities)
    # Probability of getting best modularity
    if compute_optimal:
        mod_pmax = float(np.sum(np.isclose(
            modularities, optimal_modularity))) / float(len(modularities))
    else:
        mod_pmax = None
    mod_mean = np.mean(modularities)
    if verbose:
        print("Best modularity found:", mod_max)
        print("pmax: ", mod_pmax)
        print("mean: ", mod_mean)
    return {
        'max': mod_max,
        'mean': mod_mean,
        'pmax': mod_pmax,
        'optimal': optimal_modularity,
        'x': angles
    }
Exemplo n.º 4
0
    parser.add_argument(
        "--remove-edge",
        help="remove random edge from the graph",
        action="store",
        const=-1,  # hack! '-1' means remove random edge
        default=None,
        nargs='?',
        type=int)
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO)

    test_all = True

    G_original, _ = generate_graph(args.graph_generator,
                                   args.l,
                                   args.r,
                                   seed=args.graph_generator_seed,
                                   weight=args.weighted,
                                   remove_edge=None)
    spectrum_original = nx.linalg.spectrum.laplacian_spectrum(G_original)
    print(spectrum_original)

    if test_all:
        max_norm = -1
        max_edge_ind = -1
        for edge_ind in range(G_original.number_of_edges()):
            G, _ = generate_graph(args.graph_generator,
                                  args.l,
                                  args.r,
                                  seed=args.graph_generator_seed,
                                  weight=args.weighted,
                                  remove_edge=edge_ind)
Exemplo n.º 5
0
        # load from edgelist
        G = import_konect(args.graph)
        solution_bitstring = None
        graph_name = os.path.basename(args.graph)
    elif args.pajek:
        G = import_pajek(args.pajek)
        solution_bitstring = None
        graph_name = os.path.basename(args.pajek)
    elif args.edgelist:
        G = import_edgelist(args.edgelist)
        solution_bitstring = None
        graph_name = os.path.basename(args.edgelist)
    else:
        # generate
        G, solution_bitstring = generate_graph(args.graph_generator,
                                               args.l,
                                               args.r,
                                               seed=args.seed)
        graph_name = None

    if args.label:
        label = args.label
    else:
        import time
        label = time.strftime("%Y%m%d-%H%M%S")

    if args.graph or args.pajek or args.edgelist:
        outname = "data/out/{}_{}_seed_{}_method_{}_iter_size_{}_backend_{}_pyomo_timelimit_{}".format(
            label, graph_name, args.seed, args.method, args.iter_size,
            args.backend, args.pyomo_timelimit)
    else:
        outname = "data/out/{}_{}_left_{}_right_{}_seed_{}_method_{}_iter_size_{}_backend_{}_pyomo_timelimit_{}".format(
Exemplo n.º 6
0
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-g",
                        "--graph-generator",
                        type=str,
                        default="get_random_partition_graph",
                        help="graph generator function")
    parser.add_argument("-l",
                        type=int,
                        default=15,
                        help="number of vtx in the left (first) community")
    parser.add_argument("-r",
                        type=int,
                        default=17,
                        help="number of vtx in the right (second) community")
    parser.add_argument("--graph",
                        type=str,
                        help="path to KONECT edgelist (out.graphname file)")
    parser.add_argument("--seed", type=int, default=None, help="random seed")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)
    if args.graph:
        G = import_konect(args.graph)
    else:
        G, _ = generate_graph(args.graph_generator,
                              args.l,
                              args.r,
                              seed=args.seed)
    cluster(G)
Exemplo n.º 7
0
parser = argparse.ArgumentParser()
parser.add_argument("-q", type=int, default=5, help="number of qubits / 2 (total number of qubits is 2*q)")
parser.add_argument("-threads", type=int, default=1, help="number of threads qiskit aer is using")
parser.add_argument(
    "--save",
    help="saves summarized results as a csv, with name as parameter. If csv exists, it appends to the end",
    type=str)
args = parser.parse_args()

logging.basicConfig(level=logging.INFO)

p = 2
backend = Aer.get_backend("qasm_simulator")

G, _ = generate_graph("get_connected_caveman_graph", 2, args.q)
B = nx.modularity_matrix(G, weight='weight').A
qubitOp = get_modularity_qubitops(B)
var_form = QAOAVarForm(qubitOp, p)
parameters = np.random.uniform(-np.pi, np.pi, 2*p)
qc = var_form.construct_circuit(parameters)
qc.measure(qc.qregs[0], qc.cregs[0])
start_time = timeit.default_timer()
qobj = execute(qc, backend=backend, backend_options = {"max_parallel_threads" : args.threads})
res = qobj.result()
runtime = timeit.default_timer() - start_time
print("Finished in: {:.2f} sec on {} threads".format(runtime, args.threads))
header = ['nqubits', 'nthreads', 'runtime (sec)']
results = [args.q, args.threads, runtime]
if args.save:
    if Path(args.save).exists():