Example #1
0
def run_random_agents():
    genotype_structure=gen_structure.DEFAULT_GEN_STRUCTURE(2)
    gen_size = gen_structure.get_genotype_size(genotype_structure)
    random_genotype = Evolution.get_random_genotype(RandomState(None), gen_size*2) # pairs of agents in a single genotype

    sim = Simulation(
        genotype_structure=genotype_structure,
        agent_body_radius=4,
        agents_pair_initial_distance=20,
        agent_sensors_divergence_angle=np.radians(45),  # angle between sensors and axes of symmetry
        brain_step_size=0.1,
        trial_duration=200,  # the brain would iterate trial_duration/brain_step_size number of time
        num_cores=1
    )

    trial_index = 0
    data_record_list = []
    random_seed = utils.random_int()

    perf = sim.run_simulation([random_genotype],0, random_seed, data_record_list=data_record_list)
    print("random perf: {}".format(perf))


    data_record = data_record_list[0]
    vis = Visualization(sim)
    vis.start_simulation_from_data(trial_index, data_record)
def get_spinning_agents_data():
    genotype_structure = gen_structure.DEFAULT_GEN_STRUCTURE(2)

    sim = Simulation(
        entropy_type='shannon',
        genotype_structure=genotype_structure,
        trial_duration=
        200,  # the brain would iterate trial_duration/brain_step_size number of time
    )

    # set network manually
    for a in range(2):
        agent_net = sim.agents_pair_net[a]

        # set agent network manually
        agent_net.sensor_gains = np.zeros((2))
        agent_net.sensor_biases = np.zeros((2))
        agent_net.sensor_weights = np.zeros((2, 2))
        agent_net.motor_gains = np.ones((3))
        agent_net.motor_biases = np.zeros((3))
        agent_net.motor_weights = \
            np.full((3,2),-np.inf) if a==0 \
            else np.array([
                [0.4, 0.4],
                [-np.inf, -np.inf], # set emitter weights to zero so that output is zero 
                [1., 1.]
            ])
        agent_net.brain.taus = np.ones((2))
        agent_net.brain.gains = np.ones((2))
        agent_net.brain.biases = np.ones((2))
        agent_net.brain.weights = np.ones((2, 2))

    data_record_list = []

    random_seed = utils.random_int()

    perf = sim.run_simulation(rnd_seed=random_seed,
                              data_record_list=data_record_list)
    print("random perf: {}".format(perf))

    # from dyadic_interaction.visual import Visualization
    # vis = Visualization(sim)
    # vis.start_simulation_from_data(trial_index=0, data_record=data_record)

    data_record = data_record_list[0]
    from dyadic_interaction import plot_results
    plot_results.plot_behavior(data_record)
    plot_results.plot_neural_activity_scatter(data_record)
    plot_results.plot_inputs(data_record)
    plot_results.plot_wheels(data_record)
    plot_results.plot_emitters(data_record)

    return data_record
def test_plot(entropy_type):
    from dyadic_interaction import plot_results

    sim = Simulation(entropy_type=entropy_type,
                     genotype_structure=GEORGINA_GEN_STRUCTURE,
                     num_cores=1)

    data_record_list = []
    perf = sim.run_simulation(agent_pair_genome,
                              data_record_list=data_record_list)
    print('Performance: {}'.format(perf))

    data_record = data_record_list[0]
    plot_results.plot_behavior(data_record)
Example #4
0
def random_pairs():
    dir = "data/2n_rp-3_shannon-dd_neural_social_coll-edge/seed_001"
    evo_file = os.path.join(dir, "evo_2000.json")
    sim_file = os.path.join(dir, "simulation.json")
    output_file = os.path.join(dir, "perf_dist.json")
    evo = Evolution.load_from_file(evo_file, folder_path=dir)
    sim = Simulation.load_from_file(sim_file)
    sim.num_random_pairings = 0  # we build the pairs dynamically
    pop_size = len(evo.population)
    best_agent = evo.population[0]
    if os.path.exists(output_file):
        perfomances, distances = read_data_from_file(output_file)
    else:
        new_population_pairs = []
        perfomances = []
        distances = []
        for j in range(1, pop_size):
            b = evo.population[j]
            pair = np.concatenate([best_agent, b])
            new_population_pairs.append(pair)
            distances.append(euclidean_distance(best_agent, b))
        for i in tqdm(range(pop_size - 1)):
            perf = sim.run_simulation(new_population_pairs, i)
            perfomances.append(perf)
        write_data_to_file(perfomances, distances, output_file)
    plt.scatter(distances, perfomances)
    plt.show()
Example #5
0
    def __init__(self, simulation=None, video_path=None):

        self.simulation = simulation or Simulation()

        self.agents_pair_body = self.simulation.agents_pair_body
        self.agents_pair_net = self.simulation.agents_pair_net

        # self.agent_body_radius = simulation.agent_body_radius
        # self.agent_sensors_divergence_angle = simulation.agent_sensors_divergence_angle
        # self.agent_position = None
        # self.agent_angle = None
        # self.emitter_position = None

        # self.agent = AgentBody(
        #     agent_body_radius=self.agent_body_radius,
        #     agent_sensors_divergence_angle=self.agent_sensors_divergence_angle
        # )

        self.video_path = video_path
        self.video_mode = self.video_path is not None        

        pygame.init()

        if self.video_mode:
            self.video_tmp_dir = tempfile.mkdtemp(dir=os.path.dirname(self.video_path))
            self.main_surface = pygame.Surface((MAX_CANVAS_SIZE, MAX_CANVAS_SIZE))
        else:
            self.main_surface = pygame.display.set_mode((MAX_CANVAS_SIZE, MAX_CANVAS_SIZE))
def test_visual(entropy_type):
    from dyadic_interaction.visual import Visualization

    sim = Simulation(entropy_type=entropy_type,
                     genotype_structure=GEORGINA_GEN_STRUCTURE,
                     num_cores=1)

    data_record_list = []
    perf = sim.run_simulation(agent_pair_genome,
                              data_record_list=data_record_list)
    print('Performance: {}'.format(perf))

    data_record = data_record_list[0]
    vis = Visualization(sim)
    trial_index = 1
    vis.start_simulation_from_data(trial_index, data_record)
def test_data(entropy_type):

    sim = Simulation(entropy_type=entropy_type,
                     entropy_target_value='neural',
                     concatenate=True,
                     genotype_structure=GEORGINA_GEN_STRUCTURE,
                     num_cores=1)

    utils.make_dir_if_not_exists('data/master/')

    data_record_list = []
    perf = sim.run_simulation([agent_pair_genome],
                              0,
                              data_record_list=data_record_list)
    print('Performance: {}'.format(perf))

    data_record = data_record_list[0]
    for t in range(sim.num_trials):
        # t = 0
        for k, v in data_record.items():
            for a in range(2):
                utils.save_json_numpy_data(
                    v[t][a],
                    'data/master/{}_{}_{}.json'.format(k, t + 1, a + 1))
Example #8
0
def same_pairs():
    dir = "data/2n_shannon-dd_neural_social_coll-edge/seed_001"
    evo_file = os.path.join(dir, "evo_2000.json")
    sim_file = os.path.join(dir, "simulation.json")
    output_file = os.path.join(dir, "perf_dist.json")
    if os.path.exists(output_file):
        perfomances, distances = read_data_from_file(output_file)
    else:
        evo = Evolution.load_from_file(evo_file, folder_path=dir)
        sim = Simulation.load_from_file(sim_file)
        assert sim.num_random_pairings == 0
        pop_size = len(evo.population)
        perfomances = []
        distances = []
        for i in tqdm(range(pop_size)):
            perf = sim.run_simulation(evo.population, i)
            a, b = np.array_split(evo.population[i], 2)
            perfomances.append(perf)
            distances.append(euclidean_distance(a, b))
        write_data_to_file(perfomances, distances, output_file)
    plt.scatter(distances, perfomances)
    plt.show()
def compute_std_from_random_runs(num_cores, num_good_runs,
                                 entropy_target_value):

    from dyadic_interaction.simulation import Simulation

    assert entropy_target_value in ['neural', 'distance', 'angle']

    genotype_structure = gen_structure.DEFAULT_GEN_STRUCTURE(num_neurons)
    gen_size = gen_structure.get_genotype_size(genotype_structure)

    num_data_points_per_agent_pair = sim_duration * num_trials
    num_data_points = num_data_points_per_agent_pair * num_good_runs  # 8 million!
    if entropy_target_value == 'distance':
        num_all_runs = num_good_runs * MULTIPLY_FACTOR
    else:
        num_all_runs = num_good_runs

    all_distances = np.zeros(num_data_points)
    rs = RandomState(seed)

    sim_array = [
        Simulation(
            entropy_type='shannon-dd',
            genotype_structure=genotype_structure,
        ) for _ in range(num_cores)
    ]

    random_genotypes = [
        Evolution.get_random_genotype(rs, gen_size * 2)
        for _ in range(num_all_runs)
    ]

    def run_one_core(r):
        data_record_list = []
        sim_array[r % num_cores].run_simulation(
            random_genotypes, r, data_record_list=data_record_list)
        data_record = data_record_list[0]
        if entropy_target_value == 'neural':
            concat_outputs = np.concatenate([
                data_record['brain_output'][t][a] for t in range(4)
                for a in range(2)
            ])
            concat_outputs = np.concatenate(
                [concat_outputs[:, c] for c in range(num_neurons)])
            return concat_outputs
        elif entropy_target_value == 'distance':
            concat_distances = np.concatenate(data_record['distance'])
            if any(concat_distances > MAX_DISTANCE):
                return None
            return concat_distances
        else:
            assert entropy_target_value == 'angle'
            concat_angles = np.concatenate([
                data_record['angle'][t][a] for t in range(4) for a in range(2)
            ])
            return concat_angles

    run_distances = Parallel(
        n_jobs=num_cores)(  # prefer="threads" does not work
            delayed(run_one_core)(r) for r in tqdm(range(num_all_runs)))
    good_run_distances = [run for run in run_distances if run is not None]
    print("Number of good runs: {}".format(len(good_run_distances)))
    assert len(good_run_distances) >= num_good_runs
    all_distances = np.concatenate(good_run_distances[:num_good_runs]
                                   )  # take only the first 1000 good runs

    # json.dump(
    #     all_distances,
    #     open('data/tmp_distances.json', 'w'),
    #     indent=3,
    #     cls=NumpyListJsonEncoder
    # )

    std = all_distances.std()
    print(std)
Example #10
0
        else:
            # use the specified dir if it doesn't exist
            outdir = args.dir
        utils.make_dir_if_not_exists(outdir)

    else:
        outdir = None

    sim = Simulation(
        num_random_pairings=args.num_random_pairings,
        entropy_type=args.entropy_type,
        entropy_target_value=args.entropy_target_value,
        concatenate=args.concatenate == 'on',
        isolation=args.isolation == 'on',
        collision_type=args.collision_type,
        genotype_structure=genotype_structure,
        agent_body_radius=4,
        agents_pair_initial_distance=20,
        agent_sensors_divergence_angle=np.radians(
            45),  # angle between sensors and axes of symmetry
        brain_step_size=0.1,
        trial_duration=args.
        trial_duration,  # the brain would iterate trial_duration/brain_step_size number of time
        num_cores=args.cores)

    if args.dir is not None:
        sim_config_json = os.path.join(outdir, 'simulation.json')
        sim.save_to_file(sim_config_json)

    if args.num_random_pairings == 0:
        genotype_size *= 2  # two agents per genotype
Example #11
0
def run_simulation_from_dir(dir, generation=None, genotype_idx=0, **kwargs):
    ''' 
    utitity function to get data from a simulation
    '''

    random_pos_angle = kwargs.get('random_pos_angle', None)
    entropy_type = kwargs.get('entropy_type', None)
    entropy_target_value = kwargs.get('entropy_target_value', None)
    concatenate = kwargs.get('concatenate', None)
    collision_type = kwargs.get('collision_type', None)
    ghost_index = kwargs.get('ghost_index', None)
    initial_distance = kwargs.get('initial_distance', None)
    isolation = kwargs.get('isolation', None)
    write_data = kwargs.get('write_data', None)

    func_arguments = locals()
    from pyevolver.evolution import Evolution
    evo_files = [f for f in os.listdir(dir) if f.startswith('evo_')]
    assert len(evo_files) > 0, "Can't find evo files in dir {}".format(dir)
    file_num_zfill = len(evo_files[0].split('_')[1].split('.')[0])
    if generation is None:
        # assumes last generation
        evo_files = sorted([f for f in os.listdir(dir) if f.startswith('evo')])
        evo_json_filepath = os.path.join(dir, evo_files[-1])
    else:
        generation = str(generation).zfill(file_num_zfill)
        evo_json_filepath = os.path.join(dir, 'evo_{}.json'.format(generation))
    sim_json_filepath = os.path.join(dir, 'simulation.json')
    sim = Simulation.load_from_file(sim_json_filepath)
    evo = Evolution.load_from_file(evo_json_filepath, folder_path=dir)

    if initial_distance is not None:
        print("Forcing initial distance to: {}".format(initial_distance))
        sim.agents_pair_initial_distance = initial_distance
        sim.set_initial_positions_angles()

    if random_pos_angle:
        print("Randomizing positions and angles")
        random_state = RandomState()
        sim.set_initial_positions_angles(random_state)

    if entropy_type is not None:
        sim.entropy_type = entropy_type
        print("Forcing entropy type: {}".format(sim.entropy_type))

    if entropy_target_value is not None:
        sim.entropy_target_value = entropy_target_value
        print("Forcing entropy target value: {}".format(
            sim.entropy_target_value))

    if concatenate is not None:
        sim.concatenate = concatenate == 'on'
        print("Forcing concatenation: {}".format(sim.concatenate))

    if collision_type is not None:
        sim.collision_type = collision_type
        sim.init_agents_pair()
        print("Forcing collision_type: {}".format(sim.collision_type))

    if isolation is not None:
        sim.isolation = isolation
        print("Forcing isolation to: {}".format(isolation))

    data_record_list = []
    genotype_idx_unsorted = evo.population_sorted_indexes[genotype_idx]
    random_seed = evo.pop_eval_random_seeds[genotype_idx_unsorted]

    if ghost_index is not None:
        assert ghost_index in [0, 1], 'ghost_index must be 0 or 1'
        # get original results without ghost condition and no random
        func_arguments['ghost_index'] = None
        func_arguments['random_pos_angle'] = False
        func_arguments['initial_distance'] = None
        func_arguments['write_data'] = None
        _, _, original_data_record_list = run_simulation_from_dir(
            **func_arguments)
        perf = sim.run_simulation(
            evo.population_unsorted,
            genotype_idx_unsorted,
            random_seed,
            data_record_list,
            ghost_index=ghost_index,
            original_data_record_list=original_data_record_list)
        print(
            "Overall Performance recomputed (non-ghost agent only): {}".format(
                perf))
    else:
        perf = sim.run_simulation(evo.population_unsorted,
                                  genotype_idx_unsorted, random_seed,
                                  data_record_list)
        if genotype_idx == 0:
            original_perfomance = evo.best_performances[-1]
            print("Original Performance: {}".format(original_perfomance))
        print("Overall Performance recomputed: {}".format(perf))

    if write_data:
        for s, data_record in enumerate(data_record_list, 1):
            if len(data_record_list) > 1:
                outdir = os.path.join(dir, 'data', 'sim_{}'.format(s))
            else:
                outdir = os.path.join(dir, 'data')
            utils.make_dir_if_not_exists(outdir)
            for t in range(sim.num_trials):
                for k, v in data_record.items():
                    if v is dict:
                        # summary
                        if t == 0:  # only once
                            outfile = os.path.join(outdir, '{}.json'.format(k))
                            utils.save_json_numpy_data(v, outfile)
                    elif len(v) != sim.num_trials:
                        # genotype/phenotype
                        outfile = os.path.join(outdir, '{}.json'.format(k))
                        utils.save_json_numpy_data(v, outfile)
                    elif len(v[0]) == 2:
                        # data for each agent
                        for a in range(2):
                            outfile = os.path.join(
                                outdir,
                                '{}_{}_{}.json'.format(k, t + 1, a + 1))
                            utils.save_json_numpy_data(v[t][a], outfile)
                    else:
                        # single data for both agent (e.g., distance)
                        outfile = os.path.join(outdir,
                                               '{}_{}.json'.format(k, t + 1))
                        utils.save_json_numpy_data(v[t], outfile)

    return evo, sim, data_record_list