Ejemplo n.º 1
0
def controller(x: simulator.State, dt: float, time: float):
    global active_parking_spot, recalculate
    running = True
    for event in pygame.event.get():
        if event.type == pygame.QUIT: running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_0:
                active_parking_spot = 0
            elif event.key == pygame.K_1:
                active_parking_spot = 1
            elif event.key == pygame.K_2:
                active_parking_spot = 2
            elif event.key == pygame.K_3:
                active_parking_spot = 3
            elif event.key == pygame.K_q:
                running = False
            recalculate = True
    print(f"time: {time:.1f}")

    if car_is_in_box(x, p_list[active_parking_spot]):
        if simulator.is_zero(x.speed):
            active_parking_spot += 1
            if active_parking_spot == len(p_list): active_parking_spot = 0
    visualizer.update(x.position.x, x.position.y, x.orientation, active_parking_spot)
    recalculate = True if ((not recalculate and simulator.is_zero(x.speed)) or time % 10 < 0.1) else False

    cs = mpc.get_control_signals(x, p_list[active_parking_spot], 0.3, recalculate=recalculate)

    if simulation_time < time or not running:
        x.position.x, x.position.y, x.orientation = 0, 0, 0
        simulator.run(replay)

    cs_s.append(cs)
    return cs
Ejemplo n.º 2
0
#Output file name
OUTFILENAME = 'results_example.data'

#number of trials to run
TRIALS = 100

#attempts to generate a predicate structure the first time, to see if it is possible at all in the current dimension
ATTEMPTS = 10

#dimensions over which to test as (name,levels) tuples
D = [
   ('predicates',[5,6,7,8,9,10]), #total number of predicates (expressions+functions+relations)
   ('types',[10,]), # total number of possible predicate types (with the same amount of arity-1 as arity-2 types)
   ('objects',[1,2,3,4]), #total number of objects
   ('height',[2,3,4]), #longest path to an object
   ('chance_function',[1.0,]), #probability of arity-1 predicates being functions
   ('preservation',[0.5]), #closeness of the graphs
   ('typeshape',['random']) #shape of predicate type distribution
   ('heightshape',['square']) #shape of height distribution
   ('max_arity',[2]) #max arity of predicates
   ('preservationdecay',[0]) #decay of preservation parameter per layer
   ('scaling',[1.0]) #size of the target graph compared to base
]


#
# END CONFIGURATION SECTION
#

simulator.run(A,D,TRIALS,ATTEMPTS,OUTFILENAME)
Ejemplo n.º 3
0
def main():
    #env = gym.make(ENV_NAME)
    agent = Agent(5)

    if TRAIN:  # Train mode
        for _ in range(NUM_EPISODES):
            terminal = False

            time = 0
            point_list = np.zeros(18)
            reward_circle_list = np.zeros((8,3))
            rx = 226
            ry = 226
            r_theta = 1
            ex = 23
            ey = 23
            e_theta = 2

            e_action = 0
            
            #observation = env.reset()
            observation = lim.learn_image_init()

            """
            for _ in xrange(random.randint(1, NO_OP_STEPS)):
                last_observation = observation
                observation, _, _, _ = env.step(0)  # Do nothing
            state = agent.get_initial_state(observation, last_observation)
            """

            last_observation = observation
            is_init_state_random = random.randint(1,10)
            if  is_init_state_random <=6:
                rx = random.randint(20,230)
                ry = random.randint(20,230)
                while(simulator.collision_check(rx,ry,ex,ey)):
                    rx = random.randint(20,230)
                    ry = random.randint(20,230)
                observation = lim.learn_image_maker(rx,ry,r_theta,ex,ey,point_list[0],point_list[1],point_list[2],point_list[3],point_list[4],point_list[5],point_list[6],point_list[7],point_list[8],point_list[9],point_list[10],point_list[11],point_list[12],point_list[13],point_list[14],point_list[15],point_list[16],point_list[17])

            state = agent.get_initial_state(observation, last_observation)
            state = state.transpose(1,2,0)
            while not terminal:
                last_observation = observation
                action = agent.get_action(state)+1
                #observation, reward, terminal, _ = env.step(action)
                reward,terminal,point_list,time,rx,ry,r_theta,ex,ey,e_theta,point_list,reward_circle_list=simulator.run(time,action,e_action,rx,ry,r_theta,ex,ey,e_theta,point_list,reward_circle)
                observation = lim.learn_image_maker(rx,ry,r_theta,ex,ey,point_list[0],point_list[1],point_list[2],point_list[3],point_list[4],point_list[5],point_list[6],point_list[7],point_list[8],point_list[9],point_list[10],point_list[11],point_list[12],point_list[13],point_list[14],point_list[15],point_list[16],point_list[17])
                # env.render()
                #processed_observation = preprocess(observation, last_observation)
                state = agent.run(state, action, reward, terminal, observation)
                print((rx,ry,r_theta))
                print(('reward:'+str(reward)))
    else:  # Test mode
        # env.monitor.start(ENV_NAME + '-test')
        for _ in range(NUM_EPISODES_AT_TEST):
            terminal = False
            observation = env.reset()
            for _ in range(random.randint(1, NO_OP_STEPS)):
                last_observation = observation
                observation, _, _, _ = env.step(0)  # Do nothing
            state = agent.get_initial_state(observation, last_observation)
            while not terminal:
                last_observation = observation
                action = agent.get_action_at_test(state)
                observation, _, terminal, _ = env.step(action)
                env.render()
                processed_observation = preprocess(observation, last_observation)
                state = np.append(state[1:, :, :], processed_observation, axis=0)
Ejemplo n.º 4
0
        try:
            start_address = compiler.parse_program(stream, load_address)
        except SyntaxError as exception:
            if name.endswith("fail.txt"):
                print "failed as expected"
                continue
            else:
                print "failed", str(exception)
                sys.exit(1)
        else:
            print "passed"
        
        if name in compile_only:
            print "Not running", name
            continue
        
        reload(simulator)
        
        simulator.load(generator.code, load_address)
        
        result = simulator.run(start_address, step = False, verbose = False)
        try:
            expected = expected_results[name]
        except KeyError:
            print "Obtained:", result
            raise
        
        if result != expected:
            print "Expected:", expected
            print "Obtained:", result
Ejemplo n.º 5
0
ATTEMPTS = 10

#dimensions over which to test as (name,levels) tuples
D = [
    ('predicates',
     [5, 6, 7, 8, 9,
      10]),  #total number of predicates (expressions+functions+relations)
    (
        'types', [
            10,
        ]
    ),  # total number of possible predicate types (with the same amount of arity-1 as arity-2 types)
    ('objects', [1, 2, 3, 4]),  #total number of objects
    ('height', [2, 3, 4]),  #longest path to an object
    ('chance_function', [
        1.0,
    ]),  #probability of arity-1 predicates being functions
    ('preservation', [0.5]),  #closeness of the graphs
    ('typeshape', ['random'])  #shape of predicate type distribution
    ('heightshape', ['square'])  #shape of height distribution
    ('max_arity', [2])  #max arity of predicates
    ('preservationdecay', [0])  #decay of preservation parameter per layer
    ('scaling', [1.0])  #size of the target graph compared to base
]

#
# END CONFIGURATION SECTION
#

simulator.run(A, D, TRIALS, ATTEMPTS, OUTFILENAME)
import simulator
from conf import init_conf, Conf
if __name__ == '__main__':

    for i in range(1000, 2000, 50):
        Conf.CLIENT_NO = i
        init_conf('conf')
        _, accuracy = simulator.run()
        if accuracy < 0.05:
            result = "sufficient number of patients for 95% accuracy: {}".format(
                i)
            file = open('accuracy_result.txt', 'w')
            file.write(result)
            file.close()
            break
Ejemplo n.º 7
0
import simulator
from utils import plot_history


init = {'victim': 0, 'predator': 2}
value_range = 3


def vp(config):
    impacts = dict(victim=0, predator=0)
    if config['victim'] < config['predator']:
        impacts['victim'] = -1
        impacts['predator'] = -1
    elif config['victim'] > config['predator']:
        impacts['victim'] = 1
        impacts['predator'] = 1
    else:
        impacts['victim'] = 1
        impacts['predator'] = -1
    return impacts


response = simulator.run("report", value_range, init, vp, nsteps=150)
print(response)
response = plot_history("report")
print(response)

Ejemplo n.º 8
0
        sys.stderr.write(str(exception) + "\n")
        sys.exit(1)

    print "Functions:"
    pprint.pprint(compiler.functions)

    print "Main variables:"
    pprint.pprint(compiler.local_variables)

    print "Main code:"
    addr = program_address
    for v in generator.code:
        print "%04x: %03i (%02x)" % (addr, v, v)
        addr += 1

    print "Opcode usage:"
    d = compiler.get_opcodes_used()
    freq = map(lambda (k, v): (v, k), d.items())
    freq.sort()
    for v, k in freq:
        print simulator.lookup[k], v

    if run:
        print "Loading"
        simulator.load(generator.code, program_address)
        print "Running"
        print simulator.run(start_address)

    if output:
        compiler.save_opcodes(file_name)
if __name__ == '__main__':
    # check for 2 rooms with 2 and 3 doctors
    visit_rate = [1, 1, 1, 1, 1]
    content = None
    plot_array = []

    while (True):
        content = "2, 6, 20, 5\n{}, {}\n{}, {}, {}\n".format(
            visit_rate[0], visit_rate[1], visit_rate[2], visit_rate[3],
            visit_rate[3])
        file = open("conf", "w")
        file.write(content)
        file.close()
        init_conf('conf')
        r, _ = simulator.run()
        plot_array.append(sum(r[0]) + sum(r[1]))
        if (sum(r[0]) + sum(r[1])) == 0:
            break
        else:
            for i in range(len(visit_rate)):
                visit_rate[i] += 1
    print("ideal doctors visit rate:")
    print(visit_rate)

    labels = range(len(plot_array))
    fig, ax = plt.subplots()
    ax.plot(labels, plot_array)
    ax.set(xlabel="doctors service rate",
           ylabel='number of patients in rooms  queue',
           title='Check if queues are empty in rooms')
Ejemplo n.º 10
0
    delta_y = state.position.y - ref[1]
    if delta_x < 0.5 and delta_y < 0.5:
        delta_fi = ref[2] - state.orientation
        delta_fi = atan2(sin(delta_fi), cos(delta_fi))

        hl_1 = half_length * cos(delta_fi) + half_width * sin(delta_fi)
        hw_1 = half_width * cos(delta_fi) + half_length * sin(delta_fi)

        R = np.array(((cos(-ref[2]), -sin(-ref[2])),
                      (sin(-ref[2]),  cos(-ref[2]))))
        delta_1 = R.dot([delta_x, delta_y])
        if abs(delta_1[0]) < 0.9 - hw_1 and abs(delta_1[1]) < 1.175 - hl_1 and delta_fi < 0.411:
            return True
    return False


def list_from_file(file_in):
    output_list = []
    with open(file_in) as file:
        for line in file:
            p = line.split(':')
            p_ = [float(i) for i in p]
            output_list.append(p_)
    return output_list


p_list = list_from_file("parking_spots.txt")
mpc = mpc2.ModelPredictiveControl()
visualizer.visualize(p_list)
simulator.run(controller)
Ejemplo n.º 11
0
## Experiment data -------------------------

initialBacklogSize = 15
initialCodedSize = 0
maxTime = 30.0 # days
meanDevTime = 10.5 # mean, days
varDevTime = 0.1 # variation (the less the better process)
quality = 1 # probability of reopen
meanTestTime = 6.0 # mean, days
meanUsArrival = 2.0 # mean, days
developerCount = 5
qaCount = 2

from simulator import run

data = run({"theseed": 99999, "initialBacklogSize": initialBacklogSize, "maxTime": maxTime, "meanDevTime": meanDevTime,
          "varDevTime": varDevTime, "meanTestTime": meanTestTime, "meanUsArrival": meanUsArrival,
          "developerCount": developerCount, "qaCount": qaCount, "initialCodedSize": initialCodedSize,
          "quality": quality})
print data
input('press a key')
Ejemplo n.º 12
0
from request_stream import RequestStream
import simulator

import request_handler_fifo

req_stream = RequestStream("write")
simulator.run(100000)

#print simulator.time
#print simulator.required_request_count

print "#######################\n"
print "Done with insertions. Now will perform required operations"
print "#######################\n"

req_stream.update_type("mixed")
simulator.run(100000)
Ejemplo n.º 13
0
import simulator as sim
import numpy as np
import csv

num_simulations = 500
M = range(1, 31)

# Distance between Rx and Tx
# D = [5, 10, 20]
D = [5, 10, 20]
writer = csv.writer(open('geraf.csv', 'w'), delimiter=',')
writer.writerow(D)
writer.writerow(M)

for d in D:
    n_hops = []
    std_dev_on_hops = []

    for m in M:
        n_hops_m = []
        for _ in range(num_simulations):
            n_hops_m.append(sim.run(d, m))

        n_hops.append(np.mean(n_hops_m))
        std_dev_on_hops.append(np.std(n_hops_m))

    writer.writerow(n_hops)
    writer.writerow(std_dev_on_hops)
Ejemplo n.º 14
0

template_triangles = renderer.render_template_triangles()

# Generate or load agents
failed_to_load_agents = False
flocks = None
if cfg.reuse_agents:
    flocks = agents.load_from_pickle(amaze)
    if flocks is None:
        failed_to_load_agents = True
if not cfg.reuse_agents or failed_to_load_agents:
    flocks = agents.generate_first_flock(amaze)

global_map, buffers, completion_time, solver =\
    simulator.run(context, device, queue, amaze, flocks, template_triangles)

t2 = time()
print("Calculations [s]:", t2 - t1)

if cfg.render_display_on:
    animation = renderer.render_animation(amaze, flocks, template_triangles, global_map)

    if cfg.output_video:
        displayer.savevideo(animation)
    if cfg.output_images:
        displayer.saveimages(animation)

t3 = time()
print("Rendering [s]:", t3 - t2)
print("Total [s]:", t3 - t1)