Exemple #1
0
def uploadData(setData):
    try:
        mySimulation = Simulation()
        mySimulation.setUp(dataUploadStorage[session["user_id"]]["data"])
        mySimulation.runNewSim()
    except:
        #print("Simulation failed.")
        pass
    thesePaths = mySimulation.getAllPaths()
    theseHeatMaps = mySimulation.getAllHeatData()
    thisFileName = str(setData[0])
    rows = str(setData[1])
    cols = str(setData[2])
    getLocations = parseLocations(rows, cols, setData[3])
    getSubjectMap = parseSubjectMap(setData[4])
    db = connectToDB()
    cur = db.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute(
        "INSERT INTO datasets (datasetname, userid, heatdata, vectordata, locationmap, subjectmap) VALUES (%s, %s, %s, %s, %s, %s)",
        (thisFileName, 1, json.dumps(theseHeatMaps), json.dumps(thesePaths),
         json.dumps(getLocations), json.dumps(getSubjectMap)))
    db.commit()
    cur.close()
    db.close()
    session["currentlyUploading"] = False
    del dataUploadStorage[session["user_id"]]
    session["uploadingFileName"] = ""
    emit('finishedUploading')
Exemple #2
0
def main():
    filename = './data/hashcode.in'
    print('Reading simulation...')

    sim = Simulation(filename)

    street_ids_with_cars = set()
    for car in sim.cars:
        street_ids_with_cars.update([s.id for s in car.path[:-1]])

    for isect in sim.intersections:
        isect.set_schedule(
            [(s, 1) for s in isect.queues.keys() if s in street_ids_with_cars],
            sim.duration)

    time_beg = datetime.now()

    score, arrivals = sim.simulate()

    time_end = datetime.now()
    print(time_end - time_beg)

    print(f'score: {score}')

    sim.write_schedule('./data/submission.csv')
Exemple #3
0
def run(probability, samples=1, turning=False, fname=None):
    # Run simulation for each radius
    average_collisions = []
    for i, sample in enumerate(range(samples)):
        print '\tSim {} of {}'.format(i + 1, samples)
        sim = Simulation(probability, turning=turning)
        sim.run(animate=False, fname=fname)
        average_collisions.append(sim.average_collisions())
    return float(sum(average_collisions)) / len(average_collisions)
Exemple #4
0
def main():
    # Read arguments
    args = parser().parse_args()
    seed(args.seed)
    # Run once
    if not args.run_all:
        sim = Simulation(args.probability, turning=args.turning)
        sim.run(animate=args.animate, fname=args.output_file)
        print 'collisions = {}'.format(sim.average_collisions())
    # Run all
    else:
        probabilities = np.linspace(0.04, 0.2, 17)
        run_all(probabilities, turning=args.turning, fname=args.output_file)
Exemple #5
0
def init(screen_size):
    screen = init_screen(screen_size)

    images = {}
    images['star0'] = pygame.image.load('img/star0.png')
    images['star0'].set_colorkey((0, 0, 0))
    images['star1'] = pygame.image.load('img/star0.png')
    images['star1'].set_colorkey((0, 0, 0))

    images['star0yellow'] = colored_copy(images['star0'], (0, 255, 255, 0))

    sim = Simulation()
    sim.draw_stars(images, screen)

    return screen, images, sim
Exemple #6
0
def run_ratio(ratio, radii, tracking, coverage=0.1, T=120, dt=1, fname=None):
    '''Runs the specified target-robot ratio for the specified environment radii'''
    # Run simulation for each radius
    observations = []
    for i, R in enumerate(radii):
        m_max, n_max = 10, 20
        if ratio <= 1:
            m = m_max
            n = int(ratio * m_max)
        else:
            n = n_max
            m = int(n_max / ratio)
        print '\tSim {} of {}: n = {}, m = {}'.format(i + 1, len(radii), n, m)
        sim = Simulation(m, n, T, dt, R, tracking=tracking)
        sim.run(vis='', fname=fname)
        observations.append(sim.average_observations(normalize=True))
    return radii, observations
Exemple #7
0
def main():
    # Read arguments
    args = parser().parse_args()
    seed(args.seed)
    # Run once
    if not args.run_all:
        sim = Simulation(args.m,
                         args.n,
                         args.t,
                         args.dt,
                         args.r,
                         tracking=args.tracking)
        sim.run(vis=args.visualization, fname=args.output_file)
        print 'observations = {}'.format(
            sim.average_observations(normalize=True))
    # Run ratios
    else:
        ratios = [1 / 5., 1 / 2., 1, 4, 10]
        run_ratios(ratios, tracking=args.tracking, fname=args.output_file)
Exemple #8
0
    def _set_optimization_variables_initials(self, qinit, x0, uinit):

        self.simulation = Simulation(self._discretization.system, \
            self._pdata, qinit)
        self.simulation.run_system_simulation(x0, \
            self._discretization.time_points, uinit, print_status = False)
        xinit = self.simulation.simulation_results

        repretitions_xinit = \
            self._discretization.optimization_variables["X"][:,:-1].shape[1] / \
                self._discretization.number_of_intervals
        
        Xinit = ci.repmat(xinit[:, :-1], repretitions_xinit, 1)

        Xinit = ci.horzcat([ \

            Xinit.reshape((self._discretization.system.nx, \
                Xinit.numel() / self._discretization.system.nx)),
            xinit[:, -1],

            ])

        uinit = inputchecks.check_controls_data(uinit, \
            self._discretization.system.nu, \
            self._discretization.number_of_intervals)
        Uinit = uinit

        qinit = inputchecks.check_constant_controls_data(qinit, \
            self._discretization.system.nq)
        Qinit = qinit

        self._optimization_variables_initials = ci.veccat([ \

                Uinit,
                Qinit,
                Xinit,

            ])
Exemple #9
0
def sim_process(sim_queue, client_queue):
    sim = Simulation('../model/Cirship.fmu')
    print('Simulation ready')
    id = 0

    watches = {
        'real': set(),
        'bool': set(),
    }

    while True:
        while not client_queue.empty():
            msg = client_queue.get_nowait()
            if msg['type'] == 'set':
                ref = msg['ref']
                value = msg['value']

                if isinstance(value, bool):
                    sim.set_bool(ref, value)
                else:
                    sim.set_real(ref, value)
            elif msg['type'] == 'watch':
                for ref in msg.get('real', []):
                    watches['real'].add(ref)
                for ref in msg.get('bool', []):
                    watches['bool'].add(ref)

        t = sim.update()
        id += 1

        reals = {ref: sim.get_real(ref) for ref in watches['real']}
        bools = {ref: sim.get_bool(ref) for ref in watches['bool']}

        refs = {'id': id, 'time': t, **reals, **bools}

        sim_queue.put(refs)
        time.sleep(0.05)
Exemple #10
0
def simulate(ind):
    return Simulation().simulate(ind)
def run_sim(model):
    odefunction = lambda t, x: model.ode(t, x)
    sim_params = get_sim_parameters()
    sim = Simulation(sim_params)
    return sim.simulate(odefunction)
 def startSim(self):
     self.sim[0] = Simulation(self.population, self.screen, self.clock)
Exemple #13
0
#! /usr/bin/env python3

from sim import Simulation

if __name__ == "__main__":

    sim = Simulation(ants=5, x=100, y=100, num_rivers=20)

    sim.run()
Exemple #14
0
def sim(nt, dri):
    ip = InputParameters(nt, dri)
    s = Simulation(ip)
    s.run()
Exemple #15
0
     '--motion-noise',
     dest='m_noise',
     required=False,
     type=float,
     help='The amount of motion noise to add to the particle filter.')
 parser.add_argument(
     '--ignore-regions',
     dest='ignore_regions',
     action='store_true',
     help='Set this flag to disable using the region probabilities.')
 args = parser.parse_args()
 config = get_pf_config(args.config_file)
 building_map = BuildingMap(args.map_data)
 # If this is a feed generator run, start the user simulator.
 if args.make_feed:
     simulation = Simulation(building_map, args.feed)
     w = DisplayWindow(building_map, args.map_image, sim=simulation)
     w.start_make_feed()
 # Otherwise, run the particle filter on an existing feed.
 else:
     display_on = False if args.no_disp else True
     c_noise = args.c_noise if args.c_noise else 0
     m_noise = args.m_noise if args.m_noise else 0
     feed_processor = FeedProcessor(args.feed,
                                    args.loop_feed,
                                    c_noise,
                                    m_noise,
                                    ignore_regions=args.ignore_regions)
     pf = ParticleFilter(config, building_map, feed_processor)
     w = DisplayWindow(building_map, args.map_image, pf, display=display_on)
     w.start_particle_filter()
Exemple #16
0
number_of_calculated_models = 0
total_number_of_models = total_number_of_models * 60

for n in number_of_samples:
    number_of_samples_text = str(n)
    for seed in seeds:
        seed_text = str(seed)
        for length in sample_length_values:
            sample_length_text = str(length)
            rand = random.Random()
            for wd, mc in window_device.items():
                w = wd[0]
                d = wd[1]
                sample_gen = SampleGen(mc, rand)
                simulator = Simulation(sample_gen)
                # time used to generate all samples
                rand.seed(seed)
                sample_generation_time = 0
                for i in range(n):
                    start = time.time()
                    sample_gen.sample(length)
                    end = time.time()
                    sample_generation_time += end - start
                rand.seed(seed)
                # evaluate the MC given the current combination of parameters
                start = time.time()
                # performance indicator 1 - prediction accuracy
                accuracy = simulator.runSimulation(mc, n, length, is_dpm)
                end = time.time()
                # performance indicator 2 - execution time
Exemple #17
0
def my_calculation(arguments):
    """
    This function returns the assets after death for the given arguments.
    """
    args, rate_of_return, years_to_wait = arguments

    #
    # Calculate the most efficient Roth conversion amount.
    #
    most_assets = 0
    roth_conversion_amount = 0
    best_roth_conversion_amount = 0

    while True:
        simulation = Simulation(
            args.starting_balance_hsa,
            args.starting_balance_taxable,
            args.starting_balance_trad_401k,
            args.starting_balance_trad_ira,
            args.starting_balance_roth_401k,
            args.starting_balance_roth_ira,
            rate_of_return,
            years_to_wait,
            args.current_age,
            args.age_of_retirement,
            args.age_to_start_rmds,
            args.age_of_death,
            roth_conversion_amount,  # this is our variable
            args.income,
            args.yearly_income_raise,
            args.max_income,
            args.age_of_marriage,
            args.spending,
            args.contribution_limit_hsa,
            args.contribution_catch_up_amount_hsa,
            args.contribution_catch_up_age_hsa,
            args.contribution_limit_401k,
            args.contribution_limit_401k_total,
            args.contribution_catch_up_amount_401k,
            args.contribution_catch_up_age_401k,
            args.contribution_limit_ira,
            args.contribution_catch_up_amount_ira,
            args.contribution_catch_up_age_ira,
            args.do_mega_backdoor_roth,
            args.work_state,
            args.retirement_state,
            args.add_dependent,
            args.public_safety_employee,
            args.employer_match_401k,
            args.max_contribution_percentage_401k,
            args.employer_contribution_hsa)
        simulation.simulate()

        if round(simulation.get_total_assets_after_death(), 2) >= round(
                most_assets, 2):
            best_roth_conversion_amount = roth_conversion_amount
            most_assets = simulation.get_total_assets_after_death()

        traditional_money = (simulation.accounts.trad_401k.get_value() +
                             simulation.accounts.trad_ira.get_value())
        if round(traditional_money, 2) == 0:
            break
        roth_conversion_amount += args.roth_conversion_unit

    simulation = Simulation(
        args.starting_balance_hsa, args.starting_balance_taxable,
        args.starting_balance_trad_401k, args.starting_balance_trad_ira,
        args.starting_balance_roth_401k, args.starting_balance_roth_ira,
        rate_of_return, years_to_wait, args.current_age,
        args.age_of_retirement, args.age_to_start_rmds, args.age_of_death,
        best_roth_conversion_amount, args.income, args.yearly_income_raise,
        args.max_income, args.age_of_marriage, args.spending,
        args.contribution_limit_hsa, args.contribution_catch_up_amount_hsa,
        args.contribution_catch_up_age_hsa, args.contribution_limit_401k,
        args.contribution_limit_401k_total,
        args.contribution_catch_up_amount_401k,
        args.contribution_catch_up_age_401k, args.contribution_limit_ira,
        args.contribution_catch_up_amount_ira,
        args.contribution_catch_up_age_ira, args.do_mega_backdoor_roth,
        args.work_state, args.retirement_state, args.add_dependent,
        args.public_safety_employee, args.employer_match_401k,
        args.max_contribution_percentage_401k, args.employer_contribution_hsa)
    simulation.simulate()
    return simulation.get_total_assets_after_death()
Exemple #18
0
#!/usr/bin/env python

from parse import Parser
from sim import Simulation

#----- Main

parser = Parser("sampledata.csv")
simulation = Simulation()
simulation.setUp(parser.getData())
print("Running ...")
simulation.runFullSim()
print(simulation.getAllPaths())
print(simulation.getAllHeatData())
'''
print('This is a test!')
parser = Parser("sampledata.csv")
simulation = Simulation()
simulation.setUp(parser.getData())
done = False
while not done:
    print("(25) to see all paths thus far. (35) to see all heat data. (99) to quit.")
    print("-xx to completely run sim, in increments of xx.")
    print("Total time so far: " + str(simulation.getTotalTime()))
    inputStr = str(input("How long to move? "))
    if(inputStr[0] == '-'):
        simulation.oneStep(int(inputStr[1:]))

    if (int(inputStr) == 99):
        done = True
    elif (int(inputStr) == 25):