Exemple #1
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('-p', '--peng', type=int, 
                    help='initial penguin population size')
  parser.add_argument('-b', '--bear', type=int, 
                    help='initial bear population size')
  parser.add_argument('-d', '--dim', type=int, 
                    help='dimension of square world')
  parser.add_argument('-g', '--gen', type=int,
                    help='number of generations')
  parser.add_argument('-o', '--out', type=str,
                    help='frame output file')
  args = parser.parse_args()
  #Default simulation parameters
  num_peng = 50
  num_bear = 10
  dim = 10
  gen = 100
  outfile = "lattice.frames"
  if(args.peng):
    num_peng = args.peng
  if(args.bear):
    num_bear = args.bear
  if(args.dim):
    dim = args.dim
  if(args.gen):
    gen = args.gen
  if(args.out):
    outfile = args.out

  sim.run_simulation(num_peng, num_bear, dim, gen, outfile)
  vis.run_visualizer(outfile)
Exemple #2
0
def main():
    welcome()
    coins = fetch_coins()
    currency, quantity = input_buy()
    try:
        price = coins[currency]['price']
    except Exception as e:
        dramatic_typing("Invalid currency entered, please try again \n")
        input_buy()
    run_simulation(coins[currency]['price'], quantity, currency)
    quitMenu()
Exemple #3
0
def agregate_methods_case1(lamb_array):
    mu_case1 = 1
    results = []
    for lamb in lamb_array:
        results.append(
            s.run_simulation(lamb / 2, lamb / 2, mu_case1, mu_case1, 'exp'))
        print(f'Simulação {lamb}')
        print(results)
    return results
    def simulate_earn_rate(self, df_historical_price, strategy):
        history = run_simulation(crypto_amount=self.init_crypto_amount,
                                 assets_jpy=self.initial_currency,
                                 strategy=strategy,
                                 df_historical_price=df_historical_price)
        final_state = history[-1]
        final_total_asset = final_state["total"]
        earn_rate = calc_earn_rate(final_total_asset, self.initial_currency)

        return earn_rate
def run():
    logger.info("/run")
    try:
        for res in run_simulation(step_by_step=False):
            logger.info(res)
        json_dump = json.dumps({"result": "success", "message": "OK"})
        return Response(response=json_dump, status=200)
    except Exception as e:
        json_dump = json.dumps({"result": "error", "message": str(e)})
        return Response(response=json_dump, status=200)
Exemple #6
0
def run_ga(df_historical_price, coef):
    initial_jpy_asset = 200000
    crypto_amount = 0

    history = run_simulation(crypto_amount=crypto_amount, assets_jpy=initial_jpy_asset, coef=coef,
                             df_historical_price=df_historical_price)
    final_state = history[-1]
    final_total_asset = final_state["total"]
    earn_rate = (final_total_asset - initial_jpy_asset) / initial_jpy_asset * 100

    return earn_rate
def home():
    form = InputForm()
    if form.validate_on_submit():
        prediction = simulator.run_simulation([
            form.num_col.data, form.num_brit.data, form.general.data,
            form.offensive.data, form.allies.data
        ])
        print(prediction)
        flash(f'It looks like the {prediction} win this one!', 'info')
        # return redirect(url_for('home'))

    return render_template('index.html', form=form)
Exemple #8
0
def run_test(user_polarization, film_polarization, model, always_watch,
             rewatch_rec_mult, rewatch_view_mult, anti_bubble_sys,
             recommender_randomness, user_discovery_factor):
    """
    Runs a test with the provided simulator parameters.
    """
    test_name = "test-up%1.1f-fp%1.1f-%s-%s-%s-rrm%1.1f-rvm%1.1f-rr%1.1f-udf%1.1f" % (
        user_polarization, film_polarization, model, anti_bubble_sys,
        str(always_watch).lower(), rewatch_rec_mult, rewatch_view_mult,
        recommender_randomness, user_discovery_factor)
    print("Running %s..." % test_name, file=master_log)
    print("Running (%d of %d) %s... " % (test_idx, NUM_TESTS, test_name),
          end="")
    master_log.flush()
    sys.stdout.flush()

    reload(simulator)
    simulator.TEST_NAME = test_name
    simulator.MAX_STEPS = 100
    simulator.USER_POLARIZATION_STRENGTH = user_polarization
    simulator.FILM_POLARIZATION_STRENGTH = film_polarization
    simulator.RECOMMENDER_MODEL = model
    simulator.ALWAYS_WATCH = always_watch
    simulator.REWATCH_RECOMMENDATION_MULTIPLIER = rewatch_rec_mult
    simulator.REWARCH_VIEW_MULTIPLIER = rewatch_view_mult
    simulator.ANTI_BUBBLE_SYSTEM = anti_bubble_sys
    simulator.RECOMMENDER_RANDOMNESS = recommender_randomness
    simulator.USER_DISCOVERY_FACTOR = user_discovery_factor
    simulator.K_VAL = 200

    try:
        simulator.run_simulation()
        print("Succeeded")
    except simulator.TestAlreadyCompletedException as e:
        print("Previously Completed", file=master_log)
        print("Previously Completed")
    except Exception as e:
        print("FAILED: %s" % str(e), file=master_log)
        print("FAILED!\n%s" % str(e))
Exemple #9
0
def main():

    robot_params = {"ROBOT_SIZE": ROOMBA_SIZE, "HEAD_SIZE": 1.9, "SPEED": 3}
    room_params = {"ROOM_POLYGON": ROOM_POLYGON, "OBSTECLES": OBSTECLES}
    stop_conditions = {
        "MIN_COVERAGE_TO_EXIT": MIN_COVERAGE_TO_EXIT,
        "MAX_NO_GAIN_STEPS": MAX_NO_GAIN_STEPS,
        "MAX_TIME": 9000
    }

    stats = run_simulation(robot_params,
                           room_params,
                           stop_conditions,
                           visual_feedback=True)

    matplotlib.pyplot.plot(stats)
    matplotlib.pyplot.show()
 def generator():
     for res in run_simulation(step_by_step=True):
         yield json.dumps(res) + "\n"
Exemple #11
0
import random
import matplotlib.pyplot as plt
import numpy as np
import custom_math as cm
from simulator import run_simulation
import parameters as p

market_prices = []
complete_infos = []
tracker = []

for i in range(p.N_AGENTS * 2 + 1):
    print(i, "/", p.N_AGENTS * 2 + 1)
    signal_diff = p.N_AGENTS - i
    true_state = "A" if random.uniform(0, 1) > 0.5 else "B"
    result = run_simulation(true_state, signal_diff, verbose=False)
    market_prices.append(result[1])
    complete_infos.append(result[2])
    tracker.append(result[2] * (1 - p.ERROR_AVERAGE) + (1 - result[2]) *
                   (p.ERROR_AVERAGE))

#what percentage of the total bits are retained by each aggregation method in our simulations?
#price_retention = []
#average_retention = []
#for i in range(len(complete_infos)):
#    if abs(complete_infos[i]) > 0.1:
#        price_retention.append(market_prices[i] / complete_infos[i])
#        average_retention.append(average_beliefs[i] / complete_infos[i])
#
#print("Averaging: ", np.mean(average_retention), "(", np.std(average_retention), ")")
#print("Mkt_price: ", np.mean(price_retention), "(", np.std(price_retention), ")")
Exemple #12
0
from reconfig import dynamic_reconfigurator
from cost import cost_calculator

import simulator
import simpy
import cPickle

sim_context = context.SimulationContext(simpy.Environment(), 86400, "../data/vm_configuration.csv")
simulator = simulator.Simulator(sim_context)

workload_file = open("../data/sess.dat",'r')
workload = cPickle.load(workload_file)
workload_file.close()
workload = workload[0,86400*52:86400*53]
workload_generator = workload_generator.WorkloadGenerator(workload, sim_context)
simulator.add_workload_generator(workload_generator)

stat_collector = statistics_collector.StatisticsCollector(sim_context)
simulator.add_statistics_collector(stat_collector)

perf_calculator = perf_calculator.PerformanceCalculator(sim_context)
simulator.add_performance_calculator(perf_calculator)

vm_reconfigurator = dynamic_reconfigurator.DynamicReconfigurator(sim_context)
simulator.add_vm_reconfigurator(vm_reconfigurator)

cost_calculator = cost_calculator.CostCalculator(sim_context)
simulator.add_cost_calculator(cost_calculator)

simulator.run_simulation()
import matplotlib.pyplot as plt
from simulator import run_simulation

p, b = run_simulation(n_agents=100,
                      n_time_steps=100,
                      time_per_evidence=100,
                      n_evidence=1,
                      starting_cash=1000,
                      update_when_receiving=False)

plt.figure(figsize=(12, 4))
plt.plot(p)
plt.plot(b)
plt.legend(['Price', 'Total evidence as belief'])
plt.xlabel("Time (market cycles)")
plt.grid()
plt.show()
Exemple #14
0
import random
import matplotlib.pyplot as plt
import numpy as np
import custom_math as cm
from simulator import run_simulation
import parameters as p

true_state = "A"  #if random.uniform(0,1) > 0.5 else "B"
result = run_simulation(true_state, signal_diff=1)
print(result[1], result[2])
Exemple #15
0
import simulator

tax_rate = .3
simulation_length_in_months = 48

simulator.run_simulation(simulation_length_in_months, tax_rate)
Exemple #16
0
    if constants.PROCESS_DIVIDEND_ANNOUNCEMENTS:
        dividend_data = dividend_declaration_data_loader.get_data()
        x_table, y_table = dividend_declaration_data_loader.process_dividend_announcements(historical_prices,
                                                                                           dividend_data,
                                                                                           constants.STORE_DATA)

    if constants.PROCESS_EARNING_ANNOUNCEMENTS:
        earning_announcement_data = earning_announcement_data_loader.get_data()
        # x_table, y_table = earning_announcement_data_loader.process_earning_announcements(historical_prices,
        #                                                                                  earning_announcement_data,
        #                                                                                  company_sentiment,
        #                                                                                  trends,
        #                                                                                  constants.STORE_DATA)

    if constants.RUN_SIMULATION:
        simulator.run_simulation(historical_prices, earning_announcement_data, company_sentiment, trends)

    if constants.RUN_MACHINE_LEARNING:
        if constants.USE_CACHED_MACHINE_LEARNING_DATA:
            encoded_x, x_table, y_table, trades = machine_learning.get_cached_data()
        else:
            encoded_x, x_table, y_table, trades = machine_learning.get_data(historical_prices,
                                                                            earning_announcement_data,
                                                                            company_sentiment,
                                                                            trends,
                                                                            constants.STORE_DATA)
        final = list()
        for i in range(2014, 2019):
            res = machine_learning.run_machine_learning(encoded_x, x_table, y_table, trades, i)
            final.append(res)
        print(final)
Exemple #17
0
# Announce the start of the simulation
test_name = "test-up%1.1f-fp%1.1f-%s-%s-%s-rrm%1.1f-rvm%1.1f-rr%1.1f-udf%1.1f" % (
    user_polarization, film_polarization, model, anti_bubble_sys,
    str(always_watch).lower(), rewatch_rec_mult, rewatch_view_mult,
    recommender_randomness, user_discovery_factor)
print("Running %s... " % test_name, end="")
sys.stdout.flush()

# Actually set the simulator module's parameters
simulator.TEST_NAME = test_name
simulator.MAX_STEPS = 100
simulator.USER_POLARIZATION_STRENGTH = user_polarization
simulator.FILM_POLARIZATION_STRENGTH = film_polarization
simulator.RECOMMENDER_MODEL = model
simulator.ALWAYS_WATCH = always_watch
simulator.REWATCH_RECOMMENDATION_MULTIPLIER = rewatch_rec_mult
simulator.REWARCH_VIEW_MULTIPLIER = rewatch_view_mult
simulator.ANTI_BUBBLE_SYSTEM = anti_bubble_sys
simulator.RECOMMENDER_RANDOMNESS = recommender_randomness
simulator.USER_DISCOVERY_FACTOR = user_discovery_factor

# Run the simulation and print the result
try:
    simulator.run_simulation()
    print("Succeeded")
except simulator.TestAlreadyCompletedException as e:
    print("Previously Completed")
except Exception as e:
    print("FAILED!\n%s" % str(e))