示例#1
0
 def test_that_specified_temp_performs_same_as_constant_temperature(self):
     temperatures = np.ones(len(self.times)) * self.temperature
     outputs_specs = simulation.run_simulation(
         self.solution,
         self.times,
         condition_type='specified-temperature-constant-volume',
         output_species=False,
         output_reactions=False,
         output_directional_reactions=False,
         output_rop_roc=False,
         temperature_values=temperatures)
     self.solution.TPX = self.temperature, self.pressure, self.mole_fractions
     outputs_const = simulation.run_simulation(
         self.solution,
         self.times,
         condition_type='constant-temperature-and-volume',
         output_species=False,
         output_reactions=False,
         output_directional_reactions=False,
         output_rop_roc=False)
     print(outputs_specs)
     print(outputs_const)
     # make sure all are within 1000
     self.compare_data_frames(outputs_const['conditions'],
                              outputs_specs['conditions'])
示例#2
0
 def test_specified_temp_over_different_time_steps(self):
     """compare the first iteration of one simulation with the last iteration
     of one taking smaller steps"""
     temperatures = np.ones(len(self.times)) * self.temperature
     outputs1 = simulation.run_simulation(
         self.solution,
         self.times,
         condition_type='specified-temperature-constant-volume',
         output_species=False,
         output_reactions=False,
         output_directional_reactions=False,
         output_rop_roc=False,
         temperature_values=temperatures)
     times2 = np.linspace(0, self.times[1])
     temperatures2 = np.ones(len(times2)) * temperatures[0]
     self.solution.TPX = self.temperature, self.pressure, self.mole_fractions
     outputs2 = simulation.run_simulation(
         self.solution,
         times2,
         condition_type='specified-temperature-constant-volume',
         output_species=False,
         output_reactions=False,
         output_directional_reactions=False,
         output_rop_roc=False,
         temperature_values=temperatures2)
     self.compare_data_frames(outputs1['conditions'].iloc[1, :],
                              outputs2['conditions'].iloc[-1, :])
示例#3
0
def table_2(plot=False, verbose=False):
    print '%table 2'
    print '%', dt.datetime.now()
    import os
    os.system('git rev-parse HEAD')
    for load in ['day', 'night', 'continuous', 'lighting', 'freezer']:
        for battery in [lead_dict]:
            sim.run_simulation(battery, inverter_type='typical', load_type=load, plot=plot, verbose=verbose)
示例#4
0
def test_run_simulation():
    """Test that all particles are updated the correct amount of times."""
    graph = network.new_network(100, 50)
    simulation.init_network(graph, 0.5)

    def update_particle(graph, node, timestep):
        if "updates" not in graph.node[node]:
            graph.node[node]["updates"] = -1
        graph.node[node]["updates"] += 1
        assert timestep == graph.node[node]["updates"]

    simulation.run_simulation(graph, update_particle, 10, print_=False)
示例#5
0
def get_data(args):
    """ Read in a dataset and make sure it has fields
            text, T_true, T_proxy, C_true, Y_sim
    """
    if args.simulate:
        # Add columns T_true T_proxy C_true Y_sim to the data
        df = pd.read_csv(args.data, sep='\t', error_bad_lines=False)
        df['text'] = df['text'].map(lambda x: x.lower()
                                    if isinstance(x, str) else x)
        df = simulation.run_simulation(
            df,
            propensities=[args.p1, args.p2] if args.p1 > 0 else None,
            precision=args.pre,
            recall=args.rec,
            b0=args.b0,
            b1=args.b1,
            offset=args.off,
            gamma=args.gamma,
            accuracy=args.acc,
            proxy_type=args.ptype,
            size=args.size)

        # df2 = df[['text', 'Y_sim', 'C_true', 'T_proxy']]
        # df2.to_csv('music_complete.tsv', sep='\t'); quit()

    else:
        # use what's given without any changes
        # (T_true, T_proxy, C_true, and Y should already be in there)
        df = pd.read_csv(args.data, sep='\t', error_bad_lines=False)
        df['text'] = df['text'].map(lambda x: x.lower()
                                    if isinstance(x, str) else x)
        df['Y_sim'] = df['Y']
        df['C_true'] = df['C']

    return df
示例#6
0
def param_test(env, episodes, agent, params, verbose=False):
    """
    Runs simulation under given conditions and tests specified range of
    hyperparameters, tracks total reward from each episode and returns
    list of those values.
    """
    feat_count = env.env.observation_space.shape[0]
    act_count = env.env.action_space.n

    # track each params rewards and process a new learner per param
    param_rewards = []
    for param_value in params:

        if verbose:
            print('Processing param: ' + str(param_value))

        # build the learner to utilize in the simulation, update the param value
        # being adjust in the simulation here
        learner = agent(num_feat=feat_count,
                        num_acts=act_count,
                        alpha=param_value,
                        gamma=0.99,
                        epsilon=0.99,
                        epsilon_decay=0.99)

        # run simulation and track the returned rewards
        rewards = run_simulation(env, episodes, learner, verbose=verbose)

        # only track every 10th reward for cleaner plots
        param_rewards.append(rewards[::10] + [rewards[-1]])

    return param_rewards
示例#7
0
def run_model(file_or_directory, param_map={}):

    # Determine if input is single or multi run.
    if os.path.isfile(file_or_directory):
        # Single run mode, open file and run.
        logger.debug("Importing file: {}".format(file_or_directory))
        input_file = open(file_or_directory, "r")

        # Parse into dataset.
        dataset = parse(input_file)
        logger.debug("Built dataset: {}".format(dataset.get("name")))
        for attribute in sorted(dataset.to_dict().keys()):
            logger.debug("    {} = {}".format(attribute, dataset.get(attribute)))

        # Parse model parameters and call model.
        result = None
        if param_map:
            logger.debug("Running model with custom parameters: {}".format(param_map))
            result = run_simulation(dataset, **param_map)
        else:
            logger.debug("Running model with default parameters.")
            result = run_simulation(dataset)

        # Run complete, return results.
        logger.info("Completed simulation run: {} ({} - {})".format(dataset.get("name"),
            dataset.get("start_year"), dataset.get("end_year")))
        return result

    elif os.path.isdir(file_or_directory):
        # Gather files an directories, and perform a recursive descent
        # into the contents, collecting results from runs.
        root_path = os.path.abspath(file_or_directory)
        dir_files = os.listdir(file_or_directory)
        dir_results = []

        for dir_file in dir_files:
            # Merge results, which may be lists of results, into a single list.
            abs_path = "{}/{}".format(root_path, dir_file)
            dir_results += [run_model(abs_path, param_map)]

        logger.info("Processed {} dataset runs.".format(len(dir_results)))
        return dir_results
    else:
        # Not a file or directory, exit.
        raise Exception("Not a file or directory: {}".format(file_or_directory))
示例#8
0
 def evaluate_controller(self, controller, sleep_seconds=0, graphics=True, debug=False, print_results=False, _chromosome_controller=False):
     """ Changes the state of the scenario.
         To use the same scenario for several controllers, make deepcopies of it.
     """
     recorder = run_simulation(controller, self.floors, _sleep_seconds=sleep_seconds,
                    number_of_steps=self.number_of_steps, visualization=graphics, print_results=print_results, debug=debug,
                    _chromosome_controller=_chromosome_controller)
     fitness = get_recorder_fitness(recorder)
     return fitness
示例#9
0
def test_detour_at_obstacle():
    """Test that the DO particle update is applied correctly."""
    graph = nx.Graph()
    graph.add_nodes_from([1, 2, 3, 4, 5, 6])
    graph.add_edges_from([(1, 5), (1, 2), (1, 3), (1, 4), (4, 3), (3, 2),
                          (2, 6)])
    simulation.init_network(graph, f=0)
    graph.node[1]["particles"] = [simulation.Particle(1, 0, 6)]
    graph.node[2]["particles"] = [simulation.Particle(2, 0, 5)]
    graph.node[3]["particles"] = [simulation.Particle(3, 0, 5)]
    expected_id = graph.node[1]["particles"][0].id
    # Run the simulation on predictable order of nodes.
    simulation.run_simulation(graph,
                              simulation.detour_at_obstacle,
                              1,
                              order=simulation.SimOrder.Increasing)
    # We expect the particle at either node 4 or 5.
    expected_at = list(
        map(lambda p: p[0].id
            if p else None, [graph.node[n]["particles"] for n in [4, 5]]))
    assert expected_id in expected_at
示例#10
0
 def test_simulations(self):
     try:
         run_simulation(self.parameters, self.outfolder, solver="trajectory_recovery")
         run_simulation(self.parameters, self.outfolder, solver="weighted_trajectory_recovery")
         run_simulation(self.parameters, self.outfolder, solver="semidef_relaxation_noiseless")
     except RuntimeError as e:
         self.fail("run_simulation raised exception: " + str(e))
示例#11
0
 def test_constant_temperature_and_volume(self):
     outputs = simulation.run_simulation(
         self.solution,
         self.times,
         condition_type='constant-temperature-and-volume',
         output_species=False,
         output_reactions=False,
         output_directional_reactions=False,
         output_rop_roc=False)
     conditions = outputs['conditions']
     temperatures = conditions['temperature (K)'].values
     pressures = conditions['pressure (Pa)'].values
     volumes = conditions['volume (m3)'].values
     int_energies = conditions['internal energy (J/kg)']
     print(conditions)
     self.assertNotAlmostEqual(min(pressures) / max(pressures), 1)
     self.assertNotAlmostEqual(min(int_energies) / max(int_energies), 1)
     self.assertAlmostEqual(min(volumes) / max(volumes), 1)
     self.assertAlmostEqual(min(temperatures) / max(temperatures), 1)
     self.assertAlmostEqual(temperatures[0], self.temperature)
示例#12
0
def index(request):
    form = CalculatorForm()
    output = None
    cycles = None
    if request.method == 'POST':
        submitted = True
        form = CalculatorForm(request.POST)
        print "posted"
        print form.__dict__
        if form.is_valid():
            output = run_simulation(form)
            cycles = len(output)
    else:
        submitted = False
    return render(request, 'calculator.html', {
        'output': output,
        'cycles': cycles,
        'form': form,
        'submitted': submitted
    })
def test_simulation():
    stages = [
        Stage("Build & Unit Test",
              duration=timedelta(minutes=10),
              failure_rate=0.02),
        Stage("System Test", duration=timedelta(minutes=20), failure_rate=0.2),
        Stage("Performance Test",
              duration=timedelta(minutes=120),
              failure_rate=0.1,
              single_threaded=True),
    ]

    start_time = datetime(year=2017, month=12, day=11, hour=8)
    commits = generate_commits(100, start_time, offset=2000, max_interval=100)
    deployer = Deployer(duration=timedelta(minutes=2),
                        deploy_policy=DeployPolicy.EveryPassing)
    runs = run_simulation(start_time,
                          stages,
                          commits=commits,
                          deployer=deployer)
    assert len(runs) <= 100
示例#14
0
def table_5(plot=False, verbose=False):
    print '% table 5'
    print '%', dt.datetime.now()
    import os
    os.system('git rev-parse HEAD')
    output = []
    both_index = []
    load_index = []
    battery_index = []
    for load in ['day', 'night', 'continuous', 'lighting', 'freezer']:
        for battery in [lead_dict, lith_dict, pbc_dict]:
            d = sim.run_simulation(battery, inverter_type='typical', load_type=load, plot=plot, verbose=verbose)
            d['battery_type'] = battery['type']
            d['load_type'] = load
            output.append(d)

            both_index.append(load + ' ' + battery['type'])
            load_index.append(load)
            battery_index.append(battery['type'])
        print
    df = p.DataFrame(output)
    return df
示例#15
0
def gossip_convergence(simParams):
    """Plot the convergence of gossip over different simulation parameters."""
    results = {}  # <nodes: (expected_result, result_per_timestep)>

    # For each given simulation parameters run the simulation.
    for simParam in simParams:

        # Setup the initial graph.
        G = graph.new_network(simParam.network_size, simParam.avg_degree)
        simulation.init_graph(
            G,
            max_node_particles=simParam.max_node_particles,
            initial_data_f=lambda: random.uniform(1, sys.maxsize))

        # Calculate expected result from initial graph state.
        expected_result = simParam.expected_result_f(
            [node_data["data"] for _, node_data in G.nodes(data=True)])

        # Run the simulation and save collected data.
        collected_data = simulation.run_simulation(
            G,
            update_f=lambda g, n, t: particle_dynamics.gossip(
                g,
                n,
                t,
                k_neighbors=simParam.gossip_k,
                state_update=simParam.state_update_f),
            timesteps=simParam.max_timesteps,
            collect=collect.avg_node_data)
        results[simParam.label] = (expected_result, collected_data)

    # Finally plot the results for each simulation parameter.
    for label, (expected_result, result_per_timestep) in results.items():
        error_at_timestep = np.abs(expected_result - list(
            result_per_timestep.values())) / expected_result
        plt.semilogy(error_at_timestep, label=label)
    plt.legend()
    plt.show()
示例#16
0
 def test_specified_temperature_constant_volume_changing_T(self):
     temperatures = np.linspace(900, 1000, len(self.times))
     print temperatures
     outputs = simulation.run_simulation(
         self.solution,
         self.times,
         condition_type='specified-temperature-constant-volume',
         output_species=False,
         output_reactions=False,
         output_directional_reactions=False,
         output_rop_roc=False,
         temperature_values=temperatures)
     conditions = outputs['conditions']
     temperatures = conditions['temperature (K)'].values
     pressures = conditions['pressure (Pa)'].values
     volumes = conditions['volume (m3)'].values
     int_energies = conditions['internal energy (J/kg)']
     print(conditions)
     self.assertNotAlmostEqual(min(int_energies) / max(int_energies), 1)
     self.assertNotAlmostEqual(min(temperatures) / max(temperatures), 1)
     self.assertAlmostEqual(min(temperatures), 900)
     self.assertAlmostEqual(max(temperatures), 1000)
     self.assertAlmostEqual(min(volumes) / max(volumes), 1)
示例#17
0
    #agent_setup = [{"selfish":0.8, "ratio":0.6}]
    agent_setup = []

    trust_used = False
    inbox_trust_sorted = False
    trust_filter_on = False

    # for (trust_used, trust_filter_on, inbox_trust_sorted) in \
    #     [(False,False,False), (True, True, False), (True, True, True)]:
    #for (trust_used, trust_filter_on, inbox_trust_sorted) in \
    #    [(False,False,False)]:
    for spamminess in [0]:
        results = sim.run_simulation(NUM_FACTS=num_facts, \
                                     NUM_NOISE=num_noise, \
                                     NUM_AGENTS=num_agents, \
                                     AGENT_PER_FACT=agent_per_fact, \
                                     CONNECTION_PROBABILITY=connection_probability, \
                                     NUM_STEPS=num_steps, \
                                     WILLINGNESS=willingness, \
                                     COMPETENCE=competence, \
                                     NUM_TRIAL=num_trial,\
                                     GRAPH_TYPE=graph_type, \
                                     AGENT_SETUP=agent_setup, \
                                     SPAMMINESS=spamminess, \
                                     SELFISHNESS=selfishness, \
                                     TRUST_USED=trust_used, \
                                     INBOX_TRUST_SORTED=inbox_trust_sorted,\
                                     TRUST_FILTER_ON=trust_filter_on)
        print results
        print_results(results)
示例#18
0
prep_time is exp(40)
rec_time exp(40)

number of preparation rooms is either 4
number of recovery rooms is either 5

"""
firstExperiment = []
print("\n\nSimulation #1: \n")
for k in range(1, 11):

    interarrival_time = randomize.exponential(25)
    prep_time = randomize.exponential(40)
    rec_time = randomize.exponential(40)
    results = simulation.run_simulation(4, 5, interarrival_time, prep_time,
                                        rec_time, simulation_length, k, False)
    firstExperiment = firstExperiment + [results[0]]
    #avg = stats.mean(results[0])
    #conf = stats.confidence95(results[0])
    #lower_bound = conf[0]
    #upper_bound = conf[1]

    #print("The average preparation queue length is %.2f with a 95%% confidence interval of [%.2f , %.2f]." % (avg, lower_bound, upper_bound))
"""
Simulation #2 - interarrival time exponentially distributed, others uniformly

interarrival_time is exp(25)

prep_time is unif(30,50)
rec_time unif(30,50)
top_node_percent = 0.01

# In[6]:


# prevent pickling error in multiprocessing
def defaultdict_using_list_func():
    return defaultdict(list)


def earlist_date_func():
    return datetime(1970, 1, 1)


# In[13]:

from simulation import run_simulation
# some test
result = run_simulation(retweets,
                        T_window=T_window,
                        top_node_percent=top_node_percent,
                        update_interval=update_interval,
                        incremental=True,
                        top_k=10,
                        top_k_computation_interval=timedelta(minutes=60),
                        min_rwc_score=0.85,
                        head_n=12 * 1e5,
                        return_graph=True)

pickle.dump(result, open('output/simulation_result.pkl', 'wb'))
示例#20
0
def simulate():
    try:
        run_simulation(False)
    except Exception as e:
        print('oops ', e)
示例#21
0
def f(params):
    outfolder = 'results/{}/'.format(params['key'])
    run_simulation(params, outfolder, solver=params['solver'], verbose=True)
示例#22
0
for i in range(2):
    office_2.add_worker(Worker('A'))
    office_2.add_worker(Worker('B'))
    office_2.add_worker(Worker('C'))
    office_2.add_worker(Worker('E'))


queue_1 = SinglyLinkedList()
queue_2 = SinglyLinkedList()

for i in range(30):
    queue_1.add(Client())
    queue_2.add(Client())


simulation.run_simulation(office_1, queue_1)
simulation.run_simulation(office_2, queue_2)


office_1.print_summary()
office_2.print_summary()

del office_1
del office_2
del queue_1
del queue_2

# Część 2ga
# Narysować histogram dla 100 kolejek

office_1_times = []
示例#23
0
PATH = sys.argv[1] if len(sys.argv) == 2 else str(Path(__file__).parent.absolute())[:-3]+'imgs/'
NAME = 'huge'

fst = Param(
    CLUSTERS = 12**2,
    CLUST_SIDE_LEN = 7,
    DAYS = 100,

    INFECTION_TIME = 20,
    DEATH_RATE = 0.4,
    INFECT_RATE = 0.3,
    MIGRATIONS_PER_DAY = 100,
    FEAR_RATE = 0.4,
    HEALTHCARE_CAPACITY = 2500
)


start = time()
cumulative, active, healed, dead, migrations, real_mig = run_simulation(fst, PATH)

print('time elapsed:', time() - start, flush=True) 
make_gif(PATH, NAME)

# plt.plot(range(len(migrations)), migrations, label='migrations', color='blue')
plt.plot(range(len(real_mig)), real_mig, label='migrations', color='blue', ls=':')
make_plot(fst, cumulative, active, healed, dead, label='', color='red')

plt.savefig(PATH+NAME+'.png')
print("The visualization of the simulation is available at './imgs/'", flush=True)

示例#24
0
    #agent_setup = [{"selfish":0.8, "ratio":0.6}]
    agent_setup = []

    trust_used = False
    inbox_trust_sorted = False
    trust_filter_on = False

    # for (trust_used, trust_filter_on, inbox_trust_sorted) in \
    #     [(False,False,False), (True, True, False), (True, True, True)]:
    #for (trust_used, trust_filter_on, inbox_trust_sorted) in \
    #    [(False,False,False)]:
    for spamminess in [0]:
        results = sim.run_simulation(NUM_FACTS=num_facts, \
                                     NUM_NOISE=num_noise, \
                                     NUM_AGENTS=num_agents, \
                                     AGENT_PER_FACT=agent_per_fact, \
                                     CONNECTION_PROBABILITY=connection_probability, \
                                     NUM_STEPS=num_steps, \
                                     WILLINGNESS=willingness, \
                                     COMPETENCE=competence, \
                                     NUM_TRIAL=num_trial,\
                                     GRAPH_TYPE=graph_type, \
                                     AGENT_SETUP=agent_setup, \
                                     SPAMMINESS=spamminess, \
                                     SELFISHNESS=selfishness, \
                                     TRUST_USED=trust_used, \
                                     INBOX_TRUST_SORTED=inbox_trust_sorted,\
                                     TRUST_FILTER_ON=trust_filter_on)
        print results
        print_results(results)
stages = [
    Stage("Commit Stage", duration=timedelta(minutes=3), failure_rate=0.005),
    Stage("Automated Acceptance Test",
          duration=timedelta(minutes=20),
          failure_rate=0.01),
    Stage("Performance Test",
          duration=timedelta(minutes=20),
          failure_rate=0.01),
    Stage("Internal Release",
          duration=timedelta(minutes=4),
          failure_rate=0.01,
          single_threaded=True),
]

start_time = datetime(year=2017, month=12, day=11, hour=8)

commits = generate_commits(100, start_time, offset=2000, max_interval=100)

deployer = Deployer(duration=timedelta(minutes=4),
                    deploy_policy=DeployPolicy.OnceADay,
                    deploy_hour=17,
                    deploy_day=6)

runs = run_simulation(start_time, stages, commits=commits, deployer=deployer)
print_runs("simulation_farley", stages, runs)

metrics_calc = MetricsCalculator(runs)
metrics = metrics_calc.metrics()
print_metrics("simulation_farley", metrics)
print(metrics.pretty_print())
def f(params):
    if params["outfolder"] != '':
        outfolder = f'{params["outfolder"]}/{params["key"]}/'
    else:
        outfolder = None
    run_simulation(params, outfolder, solver=params['solver'], verbose=True)
    ]

    # Iterate over random seed
    for i in range(5):
        # bootstrap
        np.random.seed(seed)

        # Set a particular evaluation for the seed
        seed_evaluation = evaluations[seed - seed_add]

        # Iterate over trajectories of the given number to run simulation
        for trajectory_index in range(
                num_trajectories_list[num_trajectories_index - 1],
                num_trajectories_list[num_trajectories_index]):
            print(
                f"seed:{seed - seed_add} / trajectory: {seed_evaluation.num_trajectories}",
                end='\r')

            # Run simulation and get trace & true performances of every target policy
            total_latency_for_each_policy, trace = \
                run_simulation(policies=policies, num_requests=num_requests, servers=servers)

            # Get the estimate of every target policy on the trajectory.

    # After finishing iterating over every random seed,
    # display the estimate of each target policy for the given number of trajectories
    for seed_evaluation in evaluations:
        """
                Implement
                """
示例#28
0
# ma być: 3xA, 3xB, 3xC, 1xE

for i in range(3):
    office.add_worker(Worker('A'))
    office.add_worker(Worker('B'))
    office.add_worker(Worker('C'))

office.add_worker(Worker('E'))

for i in range(30):
    c = Client()
    print(c, 'lines up')
    queue.add(c)

simulation.run_simulation(office, queue)

office.print_summary()
'''
# Propozycja usprawnienia:

Wykorzystanie stringów określających typ pracownika
i porównywanie tych stringów z typem zadania nie jest
wydajne, porównania łańcuchów znaków są z natury powolne,
nawet jesli mówimy o łańcuchach jednoznakowych

Szybszą metodą byłoby wykorzystanie zestawu flag bitowych
określających typ zadania: na przykład

```
A = 0b001
示例#29
0
def main():
    # Points for graphing data
    points_g2_a = []
    points_g2_b = []
    points_g3 = [(0, 0)]

    # Run independent matching trial
    print('\nMATCHING WITHOUT PARTNER DEPENDENCE')
    player1, player2, num_turns, debug = setup(0)
    m0_p1_a, m0_p1_b, m0_p2_a, m0_p2_b = run_simulation(player1, player2, num_turns, debug,
                                                        points_g2_a, points_g2_b, 0)
    show_info(player1, player2, num_turns)

    ''' GRAPH SETUP '''

    # Set up graph 1a
    plt.figure(1)
    plt.title('Probability of choosing A as a function\nPlayer 1 (0.6, 0.6)')
    plt.xlabel('Fractional income of A')
    plt.ylabel('Ratio for A choices')
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    t1_patch = mpatches.Patch(color='red', label='Independent')
    t2_patch = mpatches.Patch(color='blue', label=str(player2.weight) + ' Weighting')
    t3_patch = mpatches.Patch(color='green', label='Joint')
    plt.legend(handles=[t1_patch, t2_patch, t3_patch])

    # Set up graph 1b
    plt.figure(2)
    plt.title('Probability of choosing A as a function\nPlayer 1 (0.2, 0.8)')
    plt.xlabel('Fractional income of A')
    plt.ylabel('Ratio for A choices')
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    t1_patch = mpatches.Patch(color='red', label='Independent')
    t2_patch = mpatches.Patch(color='blue', label=str(player2.weight) + ' Weighting')
    t3_patch = mpatches.Patch(color='green', label='Joint')
    plt.legend(handles=[t1_patch, t2_patch, t3_patch])

    # Set up graph 2a
    plt.figure(3)
    plt.title('Change in Income over time for Player 2, A' +
              '\nPlayer 1 (' + str(player1.prob_a) + ', ' + str(player1.prob_b) + '); ' +
              'Player 2 (' + str(player2.prob_a) + ', ' + str(player2.prob_b) + ')')
    plt.xlabel('Time')
    plt.ylabel('Income')
    plt.xlim(0, num_turns)
    plt.ylim(0, 1)
    t1_patch = mpatches.Patch(color='red', label='Independent')
    t2_patch = mpatches.Patch(color='blue', label=str(player2.weight) + ' Weighting')
    t3_patch = mpatches.Patch(color='green', label='Joint Decision History')
    true_patch = mpatches.Patch(color='black', label='P(A)/[P(A) + P(B)]: '
                                                     + str(player2.prob_a / (player2.prob_a + player2.prob_b)))
    plt.legend(handles=[t1_patch, t2_patch, t3_patch, true_patch])

    # Set up graph 2b
    plt.figure(4)
    plt.title('Change in income over time for Player 2, B' +
              '\nPlayer 1 (' + str(player1.prob_a) + ', ' + str(player1.prob_b) + '); ' +
              'Player 2 (' + str(player2.prob_a) + ', ' + str(player2.prob_b) + ')')
    plt.xlabel('Time')
    plt.ylabel('Income')
    plt.xlim(0, num_turns)
    plt.ylim(0, 1)
    t1_patch = mpatches.Patch(color='red', label='Independent')
    t2_patch = mpatches.Patch(color='blue', label=str(player2.weight) + ' Weighting')
    t3_patch = mpatches.Patch(color='green', label='Joint')
    true_patch = mpatches.Patch(color='black', label='P(B)/[P(A) + P(B)]: ' +
                                                     str(player2.prob_b / (player2.prob_a + player2.prob_b)))
    plt.legend(handles=[t1_patch, t2_patch, t3_patch, true_patch])

    # Set up graph 3
    plt.figure(5)
    plt.title('Cumulative choices' +
              '\nPlayer 1 (' + str(player1.prob_a) + ', ' + str(player1.prob_b) + '); ' +
              'Player 2 (' + str(player2.prob_a) + ', ' + str(player2.prob_b) + ')')
    plt.xlabel('Cumulative A choices')
    plt.ylabel('Cumulative B choices')
    t1_patch = mpatches.Patch(color='red', label='Independent')
    t2_patch = mpatches.Patch(color='blue', label=str(player2.weight) + ' Weighting')
    t3_patch = mpatches.Patch(color='green', label='Joint')
    slope_patch = mpatches.Patch(color='black', label='y = x')
    plt.legend(handles=[t1_patch, t2_patch, t3_patch, slope_patch])
    plt.plot(range(0, num_turns), range(0, num_turns), color='black', linewidth=3)

    ''' FEED DATA INTO GRAPHS '''

    # 2a
    plt.figure(3)
    plt.plot([point[1] for point in points_g2_a], [point[0] for point in points_g2_a], color='red', linewidth=2)
    plt.hlines(player2.prob_a / (player2.prob_a + player2.prob_b), 0, num_turns, colors='black', linewidth=4)
    points_g2_a = []    # Reset

    # 2b
    plt.figure(4)
    plt.plot([point[1] for point in points_g2_b], [point[0] for point in points_g2_b], color='red', linewidth=2)
    plt.hlines(player2.prob_b / (player2.prob_a + player2.prob_b), 0, num_turns, colors='black', linewidth=4)
    points_g2_b = []  # Reset

    # Get choices for 3
    for i in range(2, len(player2.history)):
        if player2.history[i][0] == 'A':
            points_g3.append((points_g3[-1][0] + 1, points_g3[-1][1]))
        else:
            points_g3.append((points_g3[-1][0], points_g3[-1][1] + 1))

    # 3
    plt.figure(5)
    graph3_max_x = max(point[0] for point in points_g3)
    graph3_max_y = max(point[1] for point in points_g3)
    plt.plot([point[0] for point in points_g3], [point[1] for point in points_g3], color='red')
    points_g3 = [(0, 0)]

    # 1a
    graph1_points = []
    iterations = np.linspace(0.0, 1.0, num=21)
    plt.figure(1)
    # Trial 1
    for step in iterations:
        player1 = Player(1, 0, 0, 0.6, 0.6)
        player2 = Player(2, 0, 0.25, step, 1.0 - step)
        player1.other_player = player2
        player2.other_player = player1
        run_simulation(player1, player2, num_turns, debug, [], [], 1)
        fractional_income = player2.prob_a / (player2.prob_a + player2.prob_b)
        prob_choice = player2.times_picked_a / (player2.times_picked_a + player2.times_picked_b)
        graph1_points.append((fractional_income, prob_choice))
    plt.plot([point[0] for point in graph1_points], [point[1] for point in graph1_points], color='red')
    # Trial 2
    graph1_points = []
    for step in iterations:
        player1 = Player(1, 0, 0, 0.6, 0.6)
        player2 = Player(2, 1, 0.25, step, 1.0 - step)
        player1.other_player = player2
        player2.other_player = player1
        run_simulation(player1, player2, num_turns, debug, [], [], 1)
        fractional_income = player2.prob_a / (player2.prob_a + player2.prob_b)
        prob_choice = player2.times_picked_a / (player2.times_picked_a + player2.times_picked_b)
        graph1_points.append((fractional_income, prob_choice))
    plt.plot([point[0] for point in graph1_points], [point[1] for point in graph1_points], color='blue')
    # Trial 3
    graph1_points = []
    for step in iterations:
        player1 = Player(1, 0, 0, 0.6, 0.6)
        player2 = Player(2, 2, 0.25, step, 1.0 - step)
        player1.other_player = player2
        player2.other_player = player1
        run_simulation(player1, player2, num_turns, debug, [], [], 1)
        fractional_income = player2.prob_a / (player2.prob_a + player2.prob_b)
        prob_choice = player2.times_picked_a / (player2.times_picked_a + player2.times_picked_b)
        graph1_points.append((fractional_income, prob_choice))
    plt.plot([point[0] for point in graph1_points], [point[1] for point in graph1_points], color='green')

    # 1b
    graph1_points = []
    plt.figure(2)
    # Trial 1
    for step in iterations:
        player1 = Player(1, 0, 0, 0.2, 0.8)
        player2 = Player(2, 0, 0.25, step, 1.0 - step)
        player1.other_player = player2
        player2.other_player = player1
        run_simulation(player1, player2, num_turns, debug, [], [], 1)
        fractional_income = player2.prob_a / (player2.prob_a + player2.prob_b)
        prob_choice = player2.times_picked_a / (player2.times_picked_a + player2.times_picked_b)
        graph1_points.append((fractional_income, prob_choice))
    plt.plot([point[0] for point in graph1_points], [point[1] for point in graph1_points], color='red')
    # Trial 2
    graph1_points = []
    for step in iterations:
        player1 = Player(1, 0, 0, 0.2, 0.8)
        player2 = Player(2, 1, 0.25, step, 1.0 - step)
        player1.other_player = player2
        player2.other_player = player1
        run_simulation(player1, player2, num_turns, debug, [], [], 1)
        fractional_income = player2.prob_a / (player2.prob_a + player2.prob_b)
        prob_choice = player2.times_picked_a / (player2.times_picked_a + player2.times_picked_b)
        graph1_points.append((fractional_income, prob_choice))
    plt.plot([point[0] for point in graph1_points], [point[1] for point in graph1_points], color='blue')
    # Trial 3
    graph1_points = []
    for step in iterations:
        player1 = Player(1, 0, 0, 0.2, 0.8)
        player2 = Player(2, 2, 0.25, step, 1.0 - step)
        player1.other_player = player2
        player2.other_player = player1
        run_simulation(player1, player2, num_turns, debug, [], [], 1)
        fractional_income = player2.prob_a / (player2.prob_a + player2.prob_b)
        prob_choice = player2.times_picked_a / (player2.times_picked_a + player2.times_picked_b)
        graph1_points.append((fractional_income, prob_choice))
    plt.plot([point[0] for point in graph1_points], [point[1] for point in graph1_points], color='green')

    # Run weighted matching trial
    print('\nPLAYER 2 TAKES PLAYER 1\'S DECISIONS INTO ACCOUNT. WEIGHS OWN DECISIONS MORE')
    print(str(player2.weight))
    player1, player2, num_turns, debug = setup(1)
    m1_p1_a, m1_p1_b, m1_p2_a, m1_p2_b = run_simulation(player1, player2, num_turns, debug, points_g2_a, points_g2_b, 0)
    show_info(player1, player2, num_turns)

    ''' FEED DATA INTO GRAPHS '''

    # 2a
    plt.figure(3)
    plt.plot([point[1] for point in points_g2_a], [point[0] for point in points_g2_a], color='blue', linewidth=2)
    points_g2_a = []

    # 2b
    plt.figure(4)
    plt.plot([point[1] for point in points_g2_b], [point[0] for point in points_g2_b], color='blue', linewidth=2)
    points_g2_b = []

    # Get choices for 3
    for i in range(2, len(player2.history)):
        if player2.history[i][0] == 'A':
            points_g3.append((points_g3[-1][0] + 1, points_g3[-1][1]))
        else:
            points_g3.append((points_g3[-1][0], points_g3[-1][1] + 1))

    # 3
    plt.figure(5)
    graph3_max_x_2 = max(point[0] for point in points_g3)
    graph3_max_x = max(graph3_max_x_2, graph3_max_x)
    graph3_max_y_2 = max(point[1] for point in points_g3)
    graph3_max_y = max(graph3_max_y_2, graph3_max_y)
    plt.plot([point[0] for point in points_g3], [point[1] for point in points_g3], color='blue')
    points_g3 = [(0, 0)]

    # Run unweighted matching trial
    print('\nPLAYER 2 JOINTLY TAKES PLAYER 1\'S DECISIONS INTO ACCOUNT.')
    player1, player2, num_turns, debug = setup(2)
    m2_p1_a, m2_p1_b, m2_p2_a, m2_p2_b = run_simulation(player1, player2, num_turns, debug, points_g2_a, points_g2_b, 0)
    show_info(player1, player2, num_turns)

    ''' FEED DATA INTO GRAPHS '''

    # 2a
    plt.figure(3)
    plt.plot([point[1] for point in points_g2_a], [point[0] for point in points_g2_a], color='green', linewidth=2)

    # 2b
    plt.figure(4)
    plt.plot([point[1] for point in points_g2_b], [point[0] for point in points_g2_b], color='green', linewidth=2)

    # Get choices for 3
    for i in range(2, len(player2.history)):
        if player2.history[i][0] == 'A':
            points_g3.append((points_g3[-1][0] + 1, points_g3[-1][1]))
        else:
            points_g3.append((points_g3[-1][0], points_g3[-1][1] + 1))

    # 3
    plt.figure(5)
    graph3_max_x_2 = max(point[0] for point in points_g3)
    graph3_max_x = max(graph3_max_x_2, graph3_max_x)
    graph3_max_y_2 = max(point[1] for point in points_g3)
    graph3_max_y = max(graph3_max_y_2, graph3_max_y)
    plt.plot([point[0] for point in points_g3], [point[1] for point in points_g3], color='green')
    plt.xlim(0, graph3_max_x)
    plt.ylim(0, graph3_max_y)

    # Prints out summary of income values
    print('\n\n***** SUMMARY (' + str(num_turns) + ' RUNS) *****')
    print('\t\tP2 true values:')
    print('\t\t\t' + 'a: ' + str(player2.prob_a / (player2.prob_a + player2.prob_b)))
    print('\t\t\t' + 'b: ' + str(player2.prob_b / (player2.prob_a + player2.prob_b)))
    print('\nTRIAL 1: Player 2 ignores Player 1\'s actions:')
    print('\tP2\'s Button A Income Rate: ' + str(round(m0_p2_a, 2)))
    print('\tP2\'s Button B Income Rate: ' + str(round(m0_p2_b, 2)))
    if player2.weight < 0.5:
        keyword = 'less'
    else:
        keyword = 'more'
    print('TRIAL 2: Player 2 weighs (' + str(player2.weight) + ') Player 1\'s actions ' + keyword)
    print('\tP2\'s Button A Income Rate: ' + str(round(m1_p2_a, 2)))
    print('\tP2\'s Button B Income Rate: ' + str(round(m1_p2_b, 2)))
    print('TRIAL 3: Player 2 jointly uses Player 1\'s actions:')
    print('\tP2\'s Button A Income Rate: ' + str(round(m2_p2_a, 2)))
    print('\tP2\'s Button B Income Rate: ' + str(round(m2_p2_b, 2)))

    # Show plots
    plt.show(1)
    plt.show(2)
    plt.show(3)
    plt.show(4)
    plt.show(5)

    return
d = -10.0

# probability that game repeats
w = .895

# population size
pop = 100

# probability that any one player will be mutated each generation
# or, the expected percentage of the population that will be mutated each generation
mutate_prob = .05


generations = 10000
milestone = 10
silent = True

selection_strength = .4

# options: dwol, dwl, cwl, cwol, onlyl
player1_seed = 'dwol'

# options: alle, allc, only_cwol
player2_seed = 'alle'

# where to store trial data
# if set to None, it will store in ./trials/trial{x}/ where {x} is the next available number
file_prefix = './demo/'

simulation.run_simulation(p=p, a=a, c_l=c_l, c_h=c_h, b=b, d=d, w=w, pop=pop, selection_strength=selection_strength, mutate_prob=mutate_prob, generations=generations, milestone=milestone, file_prefix=file_prefix, silent=False, player1_seed=player1_seed, player2_seed=player2_seed)
示例#31
0
def run(config_file, output_loc, is_slave, identity):
    random.seed(10)

    ## Read input configuration
    f = open(config_file)
    config = sj.loads(f.read())
    f.close()

    ## Set output configuration
    output(output_loc, is_slave, identity, sj.dumps(config) + '\n')

    num_steps = config['num_steps']
    num_trials = config['num_trials']
    trust_used = config['trust_used']
    inbox_trust_sorted = config['inbox_trust_sorted']
    if 'trust_filter_on' in config.keys():
        trust_filter_on = config['trust_filter_on']
    else:
        trust_filter_on = True

    i = 1

    for num_fact in config['num_facts']:
        for num_noise in config['num_noise']:
            for num_agents in config['num_agents']:
                for agent_per_fact in config['agent_per_fact']:
                    for graph in config['graph_description']:
                        graph_type = graph['type']
                        radius = graph['radius']
                        for agent_setup in config['agent_setup']:
                            for w in config['willingness']:
                                for c in config['competence']:
                                    for spam in config['spamminess']:
                                        for selfish in config['selfishness']:
    
                                            print "Case", i, "being executed"
                                            print "running for %d/%d facts %d agents"\
                                                %(num_fact, num_noise, num_agents)
                                            print "\t%d facts per agent "\
                                                %agent_per_fact
                                            print "\t%s/%.1f graph for %s steps" \
                                                %(graph_type, radius, num_steps)
                                            print "\tw:%.1f/c:%.1f for %d trials"\
                                                %(w,c,num_trials)
                                            print "\tagent setup", agent_setup
                                            i += 1
                                            results = sim.run_simulation(num_fact, \
                                                                         num_noise,\
                                                                         num_agents, \
                                                                         agent_per_fact,\
                                                                         radius, \
                                                                         num_steps, \
                                                                         w, c, \
                                                                         num_trials, \
                                                                         graph_type,\
                                                                         agent_setup,\
                                                                         spam, selfish,\
                                                                         trust_used,\
                                                                         inbox_trust_sorted, \
                                                                         trust_filter_on)
                                            output(output_loc, is_slave, identity, sj.dumps(results) + '\n' )
示例#32
0
# This is a sample Python script.
from simulation import Simulation, run_simulation

simulation = Simulation()
run_simulation()
示例#33
0
def run(config_file, output_loc, is_slave, identity):
    random.seed(10)

    ## Read input configuration
    f = open(config_file)
    config = sj.loads(f.read())
    f.close()

    ## Set output configuration
    output(output_loc, is_slave, identity, sj.dumps(config) + "\n")

    num_steps = config["num_steps"]
    num_trials = config["num_trials"]
    trust_used = config["trust_used"]
    inbox_trust_sorted = config["inbox_trust_sorted"]
    if "trust_filter_on" in config.keys():
        trust_filter_on = config["trust_filter_on"]
    else:
        trust_filter_on = True

    i = 1

    for num_fpro in config["num_fpro"]:
        for num_fcon in config["num_fcon"]:
            for num_npro in config["num_npro"]:
                for num_ncon in config["num_ncon"]:
                    for num_groups in config["num_groups"]:
                        for num_agents in config["num_agents"]:
                            for agent_per_fact in config["agent_per_fact"]:
                                for graph in config["graph_description"]:
                                    graph_type = graph["type"]
                                    radius = graph["radius"]
                                    for agent_setup in config["agent_setup"]:
                                        for w in config["willingness"]:
                                            for c in config["competence"]:
                                                for spam in config["spamminess"]:
                                                    for selfish in config["selfishness"]:
                                                        for e in config["engagement"]:
                                                            for u in config["uncertainty_handling"]:

                                                                print "Case", i, "being executed"
                                                                print "running for %d/%d facts per group %d groups %d agents" % (
                                                                    num_fpro + num_fcon,
                                                                    num_npro + num_ncon,
                                                                    num_groups,
                                                                    num_agents,
                                                                )
                                                                print "\t%d agents per fact " % agent_per_fact
                                                                print "\t%s/%.1f graph for %s steps" % (
                                                                    graph_type,
                                                                    radius,
                                                                    num_steps,
                                                                )
                                                                print "\tw:%.1f/c:%.1f/e:%.1f/u:%.1f for %d trials" % (
                                                                    w,
                                                                    c,
                                                                    e,
                                                                    u,
                                                                    num_trials,
                                                                )
                                                                print "\tagent setup", agent_setup
                                                                i += 1
                                                                results = sim.run_simulation(
                                                                    num_fpro,
                                                                    num_fcon,
                                                                    num_npro,
                                                                    num_ncon,
                                                                    num_groups,
                                                                    num_agents,
                                                                    agent_per_fact,
                                                                    radius,
                                                                    num_steps,
                                                                    w,
                                                                    c,
                                                                    e,
                                                                    u,
                                                                    num_trials,
                                                                    graph_type,
                                                                    agent_setup,
                                                                    spam,
                                                                    selfish,
                                                                    trust_used,
                                                                    inbox_trust_sorted,
                                                                    trust_filter_on,
                                                                )
                                                                output(
                                                                    output_loc,
                                                                    is_slave,
                                                                    identity,
                                                                    sj.dumps(results) + "\n",
                                                                )
示例#34
0
              stiffness=STIFFNESS,
              unstretched_length=UNSTRETCHED_LENGTH,
              viscosity=VISCOSITY)

robot = TensegrityRobot()
robot.add_rods([rod1, rod2, rod3, rod4, rod5, rod6, rod7, rod8, rod9])
robot.add_cables([cab1, cab3, cab4, cab5, cab7, cab8, cab9, cab10])
robot.add_cables([cab13, cab14, cab15, cab16, cab21, cab22, cab23, cab24])
robot.add_cables([
    cab25, cab26, cab27, cab28, cab29, cab30, cab31, cab32, cab33, cab34,
    cab35, cab36
])
robot.add_cables([cab37, cab38, cab39, cab40])
rob_vis.plot_cur_state(robot)

hist_states = run_simulation(robot, time=10, dt=0.01)
rob_vis.animate_historical_states(robot=robot,
                                  states=hist_states,
                                  interval=0.01)
'''
pos0 = robot.get_rods()[4].get_endpoint_a().get_position()
K = []
for i in robot.get_cables():
    print("1", i.get_unstretched_length())
    len = i.get_unstretched_length()
    i.set_unstretched_length(len /2)
    hist_states = run_simulation( robot, time=2, dt=0.01 )
    rob_vis.animate_historical_states( robot=robot, states=hist_states, interval=0.01 )
    print("2", i.get_unstretched_length() )
    print(robot.get_rods()[4].get_endpoint_a().get_position() - pos0)
    i.set_unstretched_length(len)
示例#35
0
文件: backtest.py 项目: necuk/CS-GO
def test_all_system():
    money = 0
    betcount = 0
    won = 0
    count = 0
    allodds = pinnacle.execute("SELECT * FROM csgo").fetchall()
    for i in allodds:
        if (float(i[4]) - 1) * (float(i[5]) - 1) > 1:
            continue
        i = list(i)
        if i[2] == 'Virtus Pro':
            i[2] = 'Virtus.Pro'
        elif i[3] == 'Virtus Pro':
            i[3] = 'Virtus.Pro'

        times = [(datetime.strptime(i[1], '%Y-%m-%d') -
                  timedelta(days=1)).isoformat()[:10],
                 (datetime.strptime(i[1], '%Y-%m-%d') +
                  timedelta(days=1)).isoformat()[:10]]
        matches = statsdb.execute("SELECT * FROM Match WHERE date = '%s'" %
                                  (i[1]))
        for match in matches:
            team1 = statsdb.execute(
                "SELECT hltv_alias FROM Team WHERE team_id = %s" %
                (str(match[2]))).fetchone()[0]
            team2 = statsdb.execute(
                "SELECT hltv_alias FROM Team WHERE team_id = %s" %
                (str(match[3]))).fetchone()[0]
            if set([team1.lower(),
                    team2.lower()]) == set([i[2].lower(), i[3].lower()]):
                if team1.lower() == i[2].lower():
                    team1 = match[6:11]
                    team2 = match[11:16]
                else:
                    team1 = match[11:16]
                    team2 = match[6:11]

                winner = get_winner(match[0])
                if winner:
                    try:
                        winrate = run_simulation('all', team1, team2, True,
                                                 i[1])
                    except Exception:
                        traceback.print_exc()
                        continue

                    if winrate[0] != 0:
                        try:
                            print i[2], get_players(team1), winrate[0], i[4]
                            print i[3], get_players(team2), winrate[1], i[5]
                        except:
                            pass

                    if profit(winrate[0], i[4]):
                        betcount += 1
                        money -= 200
                        if winner == match[2]:
                            won += 1
                            money += 200 * float(i[4])
                    elif profit(winrate[1], i[5]):
                        betcount += 1
                        money -= 200
                        if winner == match[3]:
                            won += 1
                            money += 200 * float(i[5])

                break

        print betcount, money
    print float(money) / (betcount * 200)
示例#36
0
import scraper
import myconstants
import forecast
import squad_selection
import simulation

# Scrape data
# players = scraper.scrape_player_data(1)

# Populate database
# myconstants.PLAYER_COLLECTION.remove()
# new_players = scraper.populate_collection(myconstants.PLAYER_COLLECTION, players)

# Run forecasts
# myconstants.FORECASTS_COLLECTION.remove()
# forecast.run_forecasts()

# # Run simulation of season
myconstants.SQUADS_COLLECTION.remove()
simulation.run_simulation()
示例#37
0
             unstretched_length=UNSTRETCHED_LENGTH_h,
             viscosity=VISCOSITY)

# Side cables
cab7 = Cable(end_point1=rod1.get_endpoint_a(),
             end_point2=rod2.get_endpoint_b(),
             stiffness=STIFFNESS,
             unstretched_length=UNSTRETCHED_LENGTH_v,
             viscosity=VISCOSITY)
cab8 = Cable(end_point1=rod2.get_endpoint_a(),
             end_point2=rod3.get_endpoint_b(),
             stiffness=STIFFNESS,
             unstretched_length=UNSTRETCHED_LENGTH_v,
             viscosity=VISCOSITY)
cab9 = Cable(end_point1=rod3.get_endpoint_a(),
             end_point2=rod1.get_endpoint_b(),
             stiffness=STIFFNESS,
             unstretched_length=UNSTRETCHED_LENGTH_v,
             viscosity=VISCOSITY)

robot = TensegrityRobot()
robot.add_rods([rod1, rod2, rod3])
robot.add_cables([cab1, cab2, cab3, cab4, cab5, cab6, cab7, cab8, cab9])

rob_vis.plot_cur_state(robot)
hist_states = run_simulation(robot, time=3, dt=0.005)
rob_vis.plot_cur_state(robot)

rob_vis.plot_com_graphs(hist_states)
#rob_vis.animate_historical_states(robot=robot, states=hist_states, interval=0.01)