def getname_clicked(self):
     number = self.n_field.text()
     name = main.get_name(number=number)
     if name:
         self.name.setText(name)
     else:
         self.name.setText('Invalid digit')
     self.name.resize(self.n_field.sizeHint())
Ejemplo n.º 2
0
def dummy_phase_estimation(phase,
                           n=3,
                           ancilla=0,
                           precision=None,
                           config=None,
                           backend="local_qiskit_simulator",
                           skip=[],
                           coupling_map=None,
                           basis_gates=None):
    from main import setup, execute, get_name, plot_circuit
    if precision:
        ancilla = int(np.ceil(np.log2(2 + 1 / 2 / precision)))
    if ancilla:
        qp, qc, qrs, cr = setup(
            n,
            additional_registers={"qr": {
                "ur": 1,
                "ar": ancilla
            }},
            login=backend == "ibmqx5")
        qr, ur, ar = qrs
        creg = [qr[i] for i in range(len(qr))]
        creg += [ar[i] for i in range(len(ar))]
    else:
        qp, qc, qrs, cr = setup(n,
                                additional_registers={"qr": {
                                    "ur": 1
                                }},
                                login=backend == "ibmqx5")
        qr, ur = qrs
        creg = [qr[i] for i in range(len(qr))]
    qc.x(ur[0])

    def cu(qc, ctl, ur, n):
        # if abs(n*phase-1) > 1e-3 and n*phase > 1e-3:
        qc.cu1(n * 2 * np.pi * phase, ctl, ur[0])
        # if n == 1:
        # qc.cz(ctl, ur[0])

    phase_estimation(qc, creg, ur, cu)
    # qc.optimize_gates()
    qc.barrier(qr)
    qc.barrier(ur)
    qc.measure(qr, cr)

    res = execute(qp,
                  meta="QPE(%d+%d)-1 U1(%f)" % (n, ancilla, phase),
                  config=config,
                  backend=backend,
                  coupling_map=coupling_map,
                  basis_gates=basis_gates)
    # print(res.get_ran_qasm(get_name()))
    # print(res.get_counts(get_name()))
    print("N: %d\tAncilla: %d" % (n, ancilla))
    hc = handle_counts(res.get_counts(get_name()), n, skip=skip)
    print_handled_counts(hc)
    return hc
Ejemplo n.º 3
0
def main(
    fitness,
    prob_gru: float,
    prob_gru_nr: float,
    prob_gru_nu: float,
    prob_simple_rnn: float,
    train_iterations=0,
    version=0,
    unused_cpu=1,
):
    """
    Run a population's configuration.

    :param fitness: Fitness function used to evaluate the population
    :param prob_gru: Probability of mutating towards a GRU-node
    :param prob_gru_nr: Probability of mutating towards a GRU-NR-node
    :param prob_gru_nu: Probability of mutating towards a GRU-NU-node
    :param prob_simple_rnn: Probability of mutating towards a SimpleRNN-node
    :param train_iterations: Number of training generations
    :param version: Version of the model
    :param unused_cpu: Number of CPUs not used during training
    """
    # Re-configure the config-file
    cfg = Config()
    cfg.bot.angular_dir = []
    cfg.bot.delta_dist_enabled = False
    cfg.bot.dist_enabled = True
    cfg.game.duration = 60  # 60 seconds should be enough to reach the target from each starting orientation
    cfg.genome.node_add_prob = 0  # Do not change number of hidden nodes
    cfg.genome.node_disable_prob = 0  # Do not change number of hidden nodes
    cfg.population.pop_size = 512
    cfg.population.compatibility_thr = 1.  # Very small since all architectures have strictly one hidden node

    # Let inputs apply to configuration
    cfg.genome.rnn_prob_gru = prob_gru
    cfg.genome.rnn_prob_gru_nr = prob_gru_nr
    cfg.genome.rnn_prob_gru_nu = prob_gru_nu
    cfg.genome.rnn_prob_simple_rnn = prob_simple_rnn
    cfg.evaluation.fitness = fitness
    cfg.update()

    # Create the population
    folder = get_folder(experiment_id=4)
    name = get_name(cfg=cfg, version=version)
    pop = Population(
        name=name,
        config=cfg,
        folder_name=folder,
        use_backup=False,
    )

    # Make sure that all of the genomes in the initial population have exactly one hidden node
    if pop.generation == 0:
        for g in pop.population.values():
            g.mutate_add_node(pop.config.genome)

    # Give overview of population
    gru = cfg.genome.rnn_prob_gru
    gru_nr = cfg.genome.rnn_prob_gru_nr
    gru_nu = cfg.genome.rnn_prob_gru_nu
    rnn = cfg.genome.rnn_prob_simple_rnn
    msg = f"\n\n\n\n\n===> RUNNING EXPERIMENT 4 FOR THE FOLLOWING CONFIGURATION: <===" \
          f"\n\t> fitness:             {cfg.evaluation.fitness}" \
          f"\n\t> GRU enabled:         {gru > 0}  (probability={round(gru, 2)})" \
          f"\n\t> GRU-NR enabled:      {gru_nr > 0}  (probability={round(gru_nr, 2)})" \
          f"\n\t> GRU-NU enabled:      {gru_nu > 0}  (probability={round(gru_nu, 2)})" \
          f"\n\t> SRU enabled:         {rnn > 0}  (probability={round(rnn, 2)})" \
          f"\n\t> Saving under folder: {folder}" \
          f"\n\t> Training iterations: {train_iterations}\n"
    pop.log(msg)

    # Set games used for evaluation
    games_train, games_eval = get_game_ids(experiment_id=4)

    # Execute the requested segments
    try:
        train(
            game_config=cfg,
            games=games_train,
            iterations=train_iterations,
            population=pop,
            unused_cpu=unused_cpu,
        )

        # Evaluate the trained population
        evaluate(
            games=games_eval,
            population=pop,
            unused_cpu=unused_cpu,
        )
        training_overview(population=pop, )
        visualize_genome(
            genome=pop.best_genome,
            population=pop,
        )

        # Perform GRU-analysis if population is NEAT-GRU
        if gru > 0:
            gru_analysis(
                population=pop,
                unused_cpu=unused_cpu,
                experiment_id=4,
            )
            monitor(
                game_id=games_eval[0],
                population=pop,
                genome=pop.best_genome,
            )
    except Exception as e:
        pop.log(traceback.format_exc(), print_result=False)
        raise e
    finally:
        process_killer('run_population.py')  # Close all the terminated files
Ejemplo n.º 4
0
 def funcBtnUpload(self):
     self.path = filedialog.askopenfile()
     self.final_name = main.get_name(self.path.name)
     tkinter.messagebox.showinfo('Know your position',
                                 message='You are in--' +
                                 str(self.final_name))
Ejemplo n.º 5
0
    qp, qc, qrs, cr = setup(n,
                            additional_registers={"qr": {
                                "ur": 1
                            }},
                            login=backend == "ibmqx5")
    qr, ur = qrs
    creg = [qr[i] for i in range(len(qr))]

    qc.x(ur[0])

    def cu(qc, ctl, ur, n):
        p = (n * phase) % 1
        if not (p < 1e-4 or 1 - p < 1e-4):
            qc.cu1(p * 2 * np.pi, ctl, ur[0])

    phase_estimation(qc, creg, ur, cu)

    qc.barrier(qr)
    qc.measure(qr, cr)

    meta = "QPE(%d+%d)-1 U1(%f)" % (n, ancilla, phase)
    meta = "Test_only"

    res = execute(qp, meta=meta, config=None, backend=backend)

    print("N: %d\tAncilla: %d" % (n, ancilla))
    counts = res.get_counts(get_name())

    print(counts)
Ejemplo n.º 6
0
def main(
    fitness,
    prob_gru: float,
    prob_sru: float,
    prob_lstm: float,
    version=0,
    unused_cpu=1,
):
    """
    Run a population's configuration.

    :param fitness: Fitness function used to evaluate the population
    :param prob_gru: Probability of mutating towards a GRU-node
    :param prob_sru: Probability of mutating towards a SRU-node
    :param prob_lstm: Probability of mutating towards a LSTM-node
    :param version: Version of the model
    :param unused_cpu: Number of CPUs not used during training
    """
    # Re-configure the config-file
    cfg = Config()
    cfg.bot.angular_dir = []
    cfg.bot.delta_dist_enabled = False
    cfg.bot.dist_enabled = True
    cfg.game.duration = 60  # 60 seconds should be enough to reach the target from each starting orientation
    cfg.population.pop_size = 512

    # Let inputs apply to configuration
    cfg.genome.rnn_prob_gru = prob_gru
    cfg.genome.rnn_prob_simple_rnn = prob_sru
    cfg.genome.rnn_prob_lstm = prob_lstm
    cfg.evaluation.fitness = fitness
    cfg.update()

    # Copy population over from experiment1
    name = get_name(cfg=cfg, version=version)
    path_exp1 = f'population/storage/experiment1/{name}/'
    if not os.path.exists(path_exp1):
        raise Exception(
            f"Experiment 1 must be executed first for population {name}, terminating experiment 2..."
        )

    # Population exists in experiment1, copy over to experiment2 (change experiment1 population's folder and save)
    pop = Population(name=name,
                     config=cfg,
                     folder_name=get_folder(experiment_id=1),
                     use_backup=False)
    assert pop.generation > 0  # Population is not new (redundant check)
    folder = get_folder(experiment_id=2)
    pop.folder_name = folder
    pop.save()  # Overrides pre-existing populations!

    # Copy over all generations as well, since these are used during population evaluation
    path = f"population{'_backup' if pop.use_backup else ''}/storage/{pop.folder_name}/{pop}/"
    copy_tree(f"{path_exp1}generations", f"{path}generations")

    # Give overview of population
    gru = cfg.genome.rnn_prob_gru
    sru = cfg.genome.rnn_prob_simple_rnn
    lstm = cfg.genome.rnn_prob_lstm
    msg = f"\n\n\n\n\n===> RUNNING EXPERIMENT 2 FOR THE FOLLOWING CONFIGURATION: <===" \
          f"\n\t> fitness:             {cfg.evaluation.fitness}" \
          f"\n\t> GRU enabled:         {gru > 0}  (probability={round(gru, 2)})" \
          f"\n\t> SRU enabled:         {sru > 0}  (probability={round(sru, 2)})" \
          f"\n\t> LSTM enabled:        {lstm > 0}  (probability={round(lstm, 2)})" \
          f"\n\t> Saving under folder: {folder}\n"
    pop.log(msg)

    # Set games used for evaluation
    _, games_eval = get_game_ids(experiment_id=2)

    # Execute the requested segments
    try:
        # Evaluate the trained population
        evaluate(
            games=games_eval,
            population=pop,
            unused_cpu=unused_cpu,
        )
    except Exception as e:
        pop.log(traceback.format_exc(), print_result=False)
        raise e
    finally:
        process_killer('run_population.py')  # Close all the terminated files
Ejemplo n.º 7
0
def test_get_with_no_id():
    path = pathlib.Path("./nbs/other/Assessment.ipynb")
    assert main.get_name(path) == "Assessment"
Ejemplo n.º 8
0
def test_get_name():
    path = pathlib.Path("./nbs/chapters/00-Introduction-to-the-course.ipynb")
    assert main.get_name(path) == "Introduction to the course"
 def test_outofrange_number(self):
     assert main.get_name(-1) == False
 def test_correct_number(self):
     assert main.get_name(1) == 'one'
 def test_outofrange_number_2(self):
     assert main.get_name(10) == False
Ejemplo n.º 12
0
def main(
    fitness,
    prob_gru: float,
    prob_sru: float,
    prob_lstm: float,
    train_iterations=0,
    version=0,
    unused_cpu=1,
):
    """
    Run a population's configuration.

    :param fitness: Fitness function used to evaluate the population
    :param prob_gru: Probability of mutating towards a GRU-node
    :param prob_sru: Probability of mutating towards a SRU-node
    :param prob_lstm: Probability of mutating towards a LSTM-node
    :param train_iterations: Number of training generations
    :param version: Version of the model
    :param unused_cpu: Number of CPUs not used during training
    """
    # Re-configure the config-file
    cfg = Config()
    cfg.bot.angular_dir = []
    cfg.bot.delta_dist_enabled = False
    cfg.bot.dist_enabled = True
    cfg.game.duration = 60  # 60 seconds should be enough to reach the target from each starting orientation
    cfg.population.pop_size = 512

    # Let inputs apply to configuration
    cfg.genome.rnn_prob_gru = prob_gru
    cfg.genome.rnn_prob_simple_rnn = prob_sru
    cfg.genome.rnn_prob_lstm = prob_lstm
    cfg.evaluation.fitness = fitness
    cfg.update()

    # Create the population
    folder = get_folder(experiment_id=1)
    name = get_name(cfg=cfg, version=version)
    pop = Population(
        name=name,
        config=cfg,
        folder_name=folder,
        use_backup=False,
    )

    # Give overview of population
    gru = cfg.genome.rnn_prob_gru
    sru = cfg.genome.rnn_prob_simple_rnn
    lstm = cfg.genome.rnn_prob_lstm
    msg = f"\n\n\n\n\n===> RUNNING EXPERIMENT 1 FOR THE FOLLOWING CONFIGURATION: <===" \
          f"\n\t> fitness:             {cfg.evaluation.fitness}" \
          f"\n\t> GRU enabled:         {gru > 0}  (probability={round(gru, 2)})" \
          f"\n\t> SRU enabled:         {sru > 0}  (probability={round(sru, 2)})" \
          f"\n\t> LSTM enabled:        {lstm > 0}  (probability={round(lstm, 2)})" \
          f"\n\t> Saving under folder: {folder}" \
          f"\n\t> Training iterations: {train_iterations}\n"
    pop.log(msg)

    # Set games used for evaluation
    games_train, games_eval = get_game_ids(experiment_id=1)

    # Execute the requested segments
    try:
        train(
            debug=False,
            games=games_train,
            iterations=train_iterations,
            population=pop,
            unused_cpu=unused_cpu,
        )

        # Evaluate the trained population
        evaluate(
            games=games_eval,
            population=pop,
            unused_cpu=unused_cpu,
        )
        training_overview(population=pop, )
        visualize_genome(
            genome=pop.best_genome,
            population=pop,
        )
    except Exception as e:
        pop.log(traceback.format_exc(), print_result=False)
        raise e
    finally:
        process_killer('run_population.py')  # Close all the terminated files