Esempio n. 1
0
def get_fitness(start_pos, start_a, brain, iterations, light, test_data=None):
    """
    Returns the fitness of a vehicle using real-world simulation
    :param start_pos: vehicle starting position
    :param start_a: vehicle starting angle
    :param brain: vehicle brain
    :param iterations: number of iterations to run simulation for
    :param light: the light of the simulation
    :return: fitness of vehicle
    """
    # create sprites
    vehicle = BrainVehicle(start_pos, start_a, light)
    vehicle.set_values(brain)
    # create Simulation
    vehicle = Simulator(light).run_simulation(iterations, False, vehicle)
    fitness = np.mean(vehicle.sensor_left) + np.mean(vehicle.sensor_right)

    # check for other initial conditions
    if test_data is not None:
        for test in test_data:
            vehicle = BrainVehicle(test[0], test[1], light)
            vehicle.set_values(brain)
            vehicle = Simulator(light).run_simulation(iterations, False,
                                                      vehicle)
            fitness += np.mean(vehicle.sensor_left) + np.mean(
                vehicle.sensor_right)
        fitness /= len(test_data) + 1
    return fitness
Esempio n. 2
0
def oneRoundDelay(step=10000):
    injectRate = 0.9
    factory = GridNetworkFactory(makeSimpleNode(), Queues)
    factory.constructNetwork(6,6)\
        .setFlow(Flow((0,0),(0,5),injectRate))\
        .setFlow(Flow((5,0),(5,5),injectRate))\
        .setFlow(Flow((2,0),(3,5),injectRate))

    network = factory.getNetwork()

    packetFactory = PacketFactory()
    simulator = \
        Simulator(network,step,ConstLinkRateGenerator(1),packetFactory)
    simulator.run()
    #simulator.printNetwork()
    stat = simulator.getStaticsInfo()
    print stat['aveDelay']
    packetPool = sorted(stat['packetPool'], key=lambda p: p.getID)

    py.subplot(211)
    py.vlines([p.getCreateTime() for p in packetPool], [1],
              [p.getDelay() for p in packetPool], 'r')
    py.xlabel('Packet create time(bp with $\lambda$ = 0.9)')
    py.ylabel('delay')
    py.grid(True)

    injectRate = 0.9
    factory = GridNetworkFactory(makeMNode(2), Queues)
    factory.constructNetwork(6,6)\
        .setFlow(Flow((0,0),(0,5),injectRate))\
        .setFlow(Flow((5,0),(5,5),injectRate))\
        .setFlow(Flow((2,0),(3,5),injectRate))

    network = factory.getNetwork()

    packetFactory = PacketFactory()
    simulator = \
        Simulator(network,step,ConstLinkRateGenerator(1),packetFactory)
    simulator.run()
    #simulator.printNetwork()

    stat = simulator.getStaticsInfo()
    print stat['aveDelay']
    packetPool = sorted(stat['packetPool'], key=lambda p: p.getID)

    py.subplot(212)
    py.vlines([p.getCreateTime() for p in packetPool], [1],
              [p.getDelay() for p in packetPool], 'b')
    py.xlabel('Packet create time (m=2 with $\lambda$ = 0.9)')
    py.ylabel('delay')
    py.grid(True)
    py.savefig('packetDelayInOneRound_09')
    py.show()
Esempio n. 3
0
def main():
    #make sure the user specifies the correct number of arguments
    if (len(sys.argv) < 3):
        exitError(
            "ERROR: Invalid arguments\nUSAGE: /usr/bin/python3.5 project1.py p1-input01.txt simout01.txt"
        )
    #extract our processes from the input file, then begin the simulation
    processes = readInput(sys.argv[1])
    Simulator(Algorithm.FCFS, processes)
    print("\n")
    Simulator(Algorithm.SRT, processes)
    print("\n")
    Simulator(Algorithm.RR, processes)
Esempio n. 4
0
def run_and_plot_endtoend(overlap=0.):
    """ Runs and plots the end-to-end learning process """

    #np.random.seed(0)
    N_pl = 104
    N_ep = 104
    K_pl = K_ep = 0.6  #0.5 TODO
    network = LearningNetwork(N_pl=N_pl,
                              N_ep=N_ep,
                              K_pl=K_pl,
                              K_ep=K_ep,
                              overlap=overlap,
                              num_wta_modules=8,
                              start_random=False,
                              start_wta=True)
    inputgen = NavigationInput(T=22000)  # 18000 TODO
    sim1 = Simulator(network, inputgen)
    pm.plot_J(sim1)
    m, f = sim1.simulate()
    sim1.m = m
    sim1.f = f
    pm.plot_main(sim1, f)
    pm.plot_J(sim1)

    inputgen = OneCacheInput(K_ep=K_ep)
    sim2 = Simulator(network, inputgen)
    m, f = sim2.simulate()
    sim2.m = m
    sim2.f = f
    pm.plot_main(sim2, f)
    pm.plot_J(sim2)

    inputgen = PresentationInput(pre_seed_locs=[pi / 4, 3 * pi / 2],
                                 K_pl=K_pl,
                                 K_ep=K_ep)
    sim3 = Simulator(network, inputgen)
    m, f = sim3.simulate()
    pm.plot_main(sim3, f)
    pm.plot_J(sim3)
    with open("learnednet.p", "wb") as p:
        pickle.dump({
            "sim1": sim1,
            "sim2": sim2,
            "sim3": sim3,
            "m": m,
            "f": f
        }, p)
    import pdb
    pdb.set_trace()
Esempio n. 5
0
def simulate():
    '''
    strategy_params=dict(top=60,btm=40,rsi=14,average=111,duration=5))
    +--------+-----+-------+------+---------+---------+---------+---------+
    | _score | cnt | w_pct |  pr  |   pnl   | mtm_pnl | max_equ |  max_dd |
    +--------+-----+-------+------+---------+---------+---------+---------+
    |  5.70  |  97 |  0.61 | 1.25 | 7163.57 | 7163.57 | 7608.81 | 1129.33 |
    +--------+-----+-------+------+---------+---------+---------+---------+
    equity curve = 570x.png

    strategy_params=dict(top=60,btm=40,rsi=12,average=180,duration=7))
    +--------+-----+-------+------+----------+----------+----------+---------+
    | _score | cnt | w_pct |  pr  |   pnl    | mtm_pnl  | max_equ  |  max_dd |
    +--------+-----+-------+------+----------+----------+----------+---------+
    |  7.56  | 106 |  0.67 | 1.22 | 11139.79 | 11139.79 | 11158.79 | 1330.16 |
    +--------+-----+-------+------+----------+----------+----------+---------+
    equity curve = 756x.png
    '''

    m = RSIStrategy(name='rsi2_spy',
                    strategy_params=dict(top=60,
                                         btm=40,
                                         rsi=12,
                                         average=180,
                                         duration=7))

    s = Simulator()
    s.add_strategy(m)
    s.run(DataFeedList(['SPY.csv'], data_type='D'))

    s.write('rsi2_SPY_%s' % datetime.now().strftime("%Y%m%d"))
Esempio n. 6
0
def main():
    cfg.load()
    cfg.print_all()

    hexes = [
        Person(i=0, j=0),
        Person(i=0, j=-5),
        Person(i=5, j=-5),
        Person(i=-4, j=5)
    ]

    # person = Person(i=0, j=0)
    # for i in range(10):
    #     print(person.go_brr(hexes).name)

    # pop = Population()
    # pop.get_by_id(4).state = State.Deceased
    # pop.get_by_id(5).state = State.Recovered
    # print(pop)

    sim = Simulator()
    # print(sim.population)
    # d = Drawer.Drawer()
    # d.draw_hexes(sim.plane.hexagons, hexes)
    # print(util.get_surrounding(hexes[1].coordinates, sim.plane.hexagons))
    # sim.tick()
    # sim.tick()
    for i in range(10):
        sim.tick()
Esempio n. 7
0
    def wake_learning(self, random_movements, veh_pos=None, graphics=True):
        """ Create a vehicle and run for some time-steps """
        self.random_movements = random_movements
        # Create vehicle in simulation
        self.sim = Simulator(self.light)

        if veh_pos is None:
            vehicle_pos, vehicle_angle = find_random_pos(self.light)
        else:
            vehicle_pos, vehicle_angle = veh_pos, random.randint(0, 360)

        self.random_vehicle = self.sim.init_simulation(random_movements,
                                                       graphics=graphics,
                                                       cycle='wake (training)',
                                                       veh_pos=vehicle_pos,
                                                       veh_angle=vehicle_angle)
        vehicle_move = [[
            self.random_vehicle.motor_left[0],
            self.random_vehicle.motor_right[0],
            self.random_vehicle.sensor_left[0],
            self.random_vehicle.sensor_right[0]
        ]]
        for t in range(1, random_movements):
            vehicle_move.append([
                self.random_vehicle.motor_left[t],
                self.random_vehicle.motor_right[t],
                self.random_vehicle.sensor_left[t],
                self.random_vehicle.sensor_right[t]
            ])
        vehicle_first_move = []
        for t in range(0, len(vehicle_move)):
            vehicle_first_move.append(np.transpose(np.array(vehicle_move[t])))
        self.vehicle_first_move = np.transpose(np.array(vehicle_first_move))
Esempio n. 8
0
def runRateApproxProtocolTest():
    experimentSpec = {
        'packetGen': {'type': 'random',
                      'length': 24},
        'code': {'type': 'spinal',
                 'puncturing': {'type': '8-way-v2',
                                'numLastCodeStep': 2},
                 'hash': 'one-at-a-time',
                 'bitsPerSymbol': 10,
                 'k': 4},
        'map': {'type': 'linear',
                'bitsPerSymbol': 10,
                'precisionBits': 14},
        'channel': {'type': 'AWGN',
                    'SNR_dB': 10},
        'demap': {'type': 'null'},
        'decoder': {'type': 'regular',
                   'beamWidth': 16,
                   'maxPasses': 48*8},
        'detector': {'type': 'oracle'},
        'protocol': {'type': 'rate-approx',
                     'maxSymbols': 48*7,
                     'delta': 0.99},
        'statistics': {'type': 'errors'}
        }
    if 1==0:
        experimentSpec['protocol'] = {'type': 'sequential', 'maxPasses':48*8}
    runner = Simulator(1)
    res = runner.runExperiment(experimentSpec, 
                               numpy.random.RandomState().tomaxint(4) % 4294967295,
                               500)
    print str(res)
Esempio n. 9
0
def runRaptorTest():
    experimentSpec = {
            'packetGen': {'type': 'random',
                          'length': 9500},
            'code': {'type': 'raptor'},
            'map': {'type': 'QAM',
                    'bitsPerSymbol': 6},
            'channel': {'type': 'AWGN_c',
                        'SNR_dB': 20},
            'demap': {'type': 'QAM',
                      'useApprox': True},
            'decoder': {'type': 'raptor',
                        'numIter': 40},
            'detector': {'type': 'oracle'},
            'protocol': {'type': 'rate-approx',
                         'maxSymbols': 11500,
                         'delta': 0.97,
                         'minSymbols':1280},
            'statistics': {'type': 'errors'}
            }
    runner = Simulator(2)
    res = runner.runExperiment(experimentSpec, 
                               numpy.random.RandomState().tomaxint(4) % 4294967295,
                               3)
    print str(res)
Esempio n. 10
0
def main():
    root = tkinter.Tk()
    root.title('Brownian Motion Simulation')
    simulator = Simulator(root)
    numSapienses = input("Please input numSapienses:")
    simulator.simulate(int(numSapienses), 0.01)
    root.mainloop()
Esempio n. 11
0
def main():
    import this
    root = tkinter.Tk()
    root.title('Brownian Motion Simulation')
    simulator = Simulator(root, 50)
    simulator.simulate(300, 0.3)
    root.mainloop()
Esempio n. 12
0
def main():
    """
    Relaxed Checkpoint Simulator simulates the execution of an application given the job parameters required
    """
    MAX_JOBS = 10
    RUNTIME = 50 * HOUR
    OCI_LIST = [
        1.2 * HOUR, 1.7 * HOUR, 2.1 * HOUR, 2.8 * HOUR, 3.3 * HOUR, 4.7 * HOUR
    ]
    BETA_LIST = [
        0.1 * HOUR, 0.2 * HOUR, 0.25 * HOUR, 0.3 * HOUR, 0.35 * HOUR,
        0.4 * HOUR
    ]

    # Ask for Input
    print("Relaxed Checkpointing Simulator")
    print("Configurations. \n 1) Maximum number of jobs:", MAX_JOBS,
          "\n 2) Total compute time    :", RUNTIME, "seconds\n")

    system = Machine()
    simulator_properties = SimulatorProperties(RUNTIME)
    simulator = Simulator(system, simulator_properties)

    initialize_jobs(system, OCI_LIST, BETA_LIST, MAX_JOBS)
    simulator.__do_simulation__()
Esempio n. 13
0
    def run(self):

        sim = Simulator(self.location, self.year_choice, Windturbine(5), terrain_factor = self.terrain_factor )
        sim.latitude = self.latitude
        sim.longitude = self.longitude

        if self.store_wt_out:
            P_wt,_ = sim.calc_wind(self.windfeatures)
        else:
            P_wt = 0
        if self.store_sp_out:
            P_sp,_ = sim.calc_solar(Az=self.solarfeatures[2::3], Inc=self.solarfeatures[1::3],sp_area=self.solarfeatures[0::3], sp_eff=self.sp_eff)
        else:
            P_sp = 0
        if self.store_total_out:
            P_tot,_ = sim.calc_total_power(self.solarfeatures, self.windfeatures, self.sp_eff)
        else:
            P_tot = 0

        data = {'Pwt':P_wt,'Psp': P_sp,'Ptot': P_tot}

        self.write_data(data, self.filename)

        evt = SimDoneEvent(myEVT_SIMDONE, -1, filename=self.filename)
        wx.PostEvent(self.parent, evt)
Esempio n. 14
0
def main(i, is_worst_case):
    sim = Simulator(n, f, GoodPlayer, BadPlayer, is_worst_case=is_worst_case)
    res_lst = sim.simulate(i)
    plt.xlabel("Number of turns")
    plt.ylabel("Percentage of good policies")
    plt.plot(range(1, i+1), res_lst, 'o')
    plt.show()
    def doT1nT2n(self, Community_Coordinate):
        nPnt = 10  #1000
        nLink = 11  #40

        tests = ""
        s = Simulator(nPnt)
        s.genPoints(Community_Coordinate)
        #s.genRandomLinks(nLink*nPnt)

        return s.pAll

        ##        f2=    open('doT1nT2n2.txt', 'w')
        ##        for i in range(0,100):
        ##            for j in range(0,i+1):
        ##                nSteps=self.MutiTimesNoGen(s,1,i,j,0.5,0.2)
        ##                print str(i)+"\t"+ str(j) +"\t"+str(nSteps)
        ##                f2.write(str(i)+"\t"+ str(j) +"\t"+str(nSteps)+"\n")
        ##                tests=tests+str(nSteps)+"\t"
        ##            for j in range(i,101):
        ##                tests=tests+"0\t"
        ##            tests=tests+("\n")
        ##        f = open('doT1nT2n.txt', 'w')
        ##        f.write(tests)

        return
Esempio n. 16
0
def main():
    # define a controller, which moves the robot and provides the control commands to the localizer
    landmarks_x = [0.0, 100.0, 100.0, 0.0, 75.0]
    landmarks_y = [0.0, 0.0, 100.0, 100.0, 50.0]

    motion_cmd = [
        MotionCommand(20, 0.25 * pi),
        MotionCommand(20, 0.25 * pi),
        MotionCommand(20, 0.25 * pi),
        MotionCommand(20, 0.25 * pi),
        MotionCommand(20, 0.25 * pi),
        MotionCommand(20, 0.25 * pi),
        MotionCommand(20, 0.25 * pi)
    ]

    lm_map = LandmarkMap(landmarks_x, landmarks_y)
    simulator = Simulator(landmark_map=lm_map)

    localizer = Localizer()

    for cmd in motion_cmd:
        simulator.move(cmd.v, cmd.omega)
        localizer.odometry_callback(cmd.v, cmd.omega)

        r, phi = simulator.get_measurements()
        localizer.measurement_callback(r, phi)

    simulator.plot()
    localizer.plot()

    plt.show(block=True)
Esempio n. 17
0
def runBscLDPCTest():
    experimentSpec = {
           'packetGen': {'type': 'random',
                          'length': 648*2/3},
            'code': {'type': 'ldpc',
                     'n': 648,
                     'rate': (2,3),
                     'bitsPerSymbol': 1},
            'map': {'type': 'linear',
                    'bitsPerSymbol': 1,
                    'precisionBits': 1},
            'channel': {'type': 'BSC',
                        'flipProb': 0.04},
            'demap': {'type': 'BSC',
                      'flipProb': 0.04},
            'decoder': {'type': 'ldpc-float-bp',
                        'numIter': 40},
            'detector': {'type': 'oracle'},
            'protocol': {'type': 'one-try',
                         'numSymbols': 648},
            'statistics': {'type': 'errors'}
             }
    runner = Simulator(0)
    res = runner.runExperiment(experimentSpec, 
                               numpy.random.RandomState().tomaxint(4) % 4294967295,
                               100)
    print str(res)
Esempio n. 18
0
def runItppQamLDPCTest():
    experimentSpec = {
            'packetGen': {'type': 'random',
                          'length': 648*5/6},
            'code': {'type': 'ldpc',
                     'n': 648,
                     'rate': (5,6),
                     'bitsPerSymbol': 1},
            'map': {'type': 'QAM',
                    'bitsPerSymbol': 6},
            'channel': {'type': 'AWGN_c',
                        'SNR_dB': 17.8},
            'demap': {'type': 'QAM'},
            'decoder': {'type': 'ldpc-float-bp',
                        'numIter': 40},
            'detector': {'type': 'oracle'},
            'protocol': {'type': 'one-try',
                         'numSymbols': 648/6},
            'statistics': {'type': 'errors'}
            }
    runner = Simulator(0)
    res = runner.runExperiment(experimentSpec, 
                               numpy.random.RandomState().tomaxint(4) % 4294967295,
                               100)
    print str(res)
Esempio n. 19
0
File: Console.py Progetto: ecell/ode
def main():
    an_ess_file = None

    # -------------------------------------
    # when ecell3-session [essfile] check file exist
    # and set anESSfile 
    # -------------------------------------

    for i in range(len(sys.argv) - 1):
        i = i + 1
        if not sys.argv[i][0] == "-":
            if os.path.isfile(sys.argv[i]):
                if sys.argv[i - 1] != "-e" and sys.argv[i - 1] != "-f":
                    an_ess_file = sys.argv[i]
            else:
                sys.stderr.write("Error: %s does not exist.\n" % sys.argv[i])
                sys.exit(1) 

    a_simulator = Simulator()
    a_console = Console(a_simulator, '')

    if an_ess_file:
        a_console.load_script(an_ess_file)
    else:
        a_console.interact()
Esempio n. 20
0
def runParallelKTest():
    experimentSpec = {
        'packetGen': {'type': 'random',
                      'length': 300},
        'code': {'type': 'spinal',
                 'puncturing': {'type': '8-way-v2',
                                'numLastCodeStep': 2},
                 'hash': 'one-at-a-time',
                 'bitsPerSymbol': 10,
                 'k': 3},
        'map': {'type': 'linear',
                'bitsPerSymbol': 10,
                'precisionBits': 14},
        'channel': {'type': 'AWGN',
                    'SNR_dB': 10},
        'demap': {'type': 'null'},
        'decoder': {'type': 'parallel',
                    'alpha': 4,
                    'beta': 64,
                   'maxPasses': 48*8},
        'detector': {'type': 'oracle'},
        'protocol': {'type': 'sequential',
                     'maxPasses': 48*8},
        'statistics': {'type': 'errors'}
        }
    runner = Simulator(1)
    res = runner.runExperiment(experimentSpec, 
                               numpy.random.RandomState().tomaxint(4) % 4294967295,
                               10)
    print str(res)
Esempio n. 21
0
    def doT1pT2p(self):
        nPnt = 1000
        nLink = 40
        nT1 = 40
        nT2 = 20
        tests = ""
        s = Simulator(nPnt)
        s.genPoints()
        s.genRandomLinks(nLink * nPnt)

        f2 = open('doT1pT2p2.txt', 'w')
        for i in range(0, 101):
            for j in range(0, i + 1):
                nSteps = self.MutiTimesNoGen(s, 1, nT1, nT2, 0.01 * i,
                                             0.01 * j)
                print str(i) + "\t" + str(j) + "\t" + str(nSteps)
                f2.write(str(i) + "\t" + str(j) + "\t" + str(nSteps) + "\n")
                tests = tests + str(nSteps) + "\t"
            for j in range(i, 101):
                tests = tests + "0\t"
            tests = tests + ("\n")
        f = open('doT1pT2p.txt', 'w')
        f.write(tests)

        return
 def __init__(self, flightParamsTemplate, submissionFile, testFlightsFile):
     self.submissionFile = submissionFile
     self.flightParamsTemplate = flightParamsTemplate
     self.testFlightsFile = testFlightsFile
     print "Starting simulator using:", testFlightsFile
     self.simulator = Simulator()
     print "Simulator started."
Esempio n. 23
0
def runCoherenceFadingTest():
    experimentSpec = {
        'packetGen': {'type': 'random',
                      'length': 300},
        'code': {'type': 'spinal',
                 'puncturing': {'type': '8-way-v2',
                                'numLastCodeStep': 2},
                 'hash': 'one-at-a-time',
                 'bitsPerSymbol': 10,
                 'k': 3},
        'map': {'type': 'soft',
                'bitsPerSymbol': 10},
        'channel': {'type': 'coherence-fading',
                    'interval': 10,
                    'SNR_dB': 10},
        'demap': {'type': 'null'},
        'decoder': {'type': 'regular',
                   'beamWidth': 16,
                   'maxPasses': 48*8},
        'detector': {'type': 'oracle'},
        'protocol': {'type': 'sequential',
                     'maxPasses': 48*8},
        'statistics': {'type': 'errors'}
        }
    runner = Simulator(1)
    res = runner.runExperiment(experimentSpec, 
                               numpy.random.RandomState().tomaxint(4) % 4294967295,
                               100)
    print str(res)
Esempio n. 24
0
def runFirstErrorStatisticsTest():
    experimentSpec = {
        'packetGen': {'type': 'random',
                      'length': 256},
        'code': {'type': 'spinal',
                 'puncturing': {'type': '8-way-v2',
                                'numLastCodeStep': 2},
                 'hash': 'one-at-a-time',
                 'bitsPerSymbol': 10,
                 'k': 4},
        'map': {'type': 'linear',
                'bitsPerSymbol': 10,
                'precisionBits': 14},
        'channel': {'type': 'AWGN',
                    'SNR_dB': -2},
        'demap': {'type': 'null'},
        'decoder': {'type': 'regular',
                   'beamWidth': 100,
                   'maxPasses': 48*8},
        'detector': {'type': 'oracle'},
        'protocol': {'type': 'one-try',
                     'numSymbols': 256*2},
        'statistics': {'type': 'first-error'}
        }
    runner = Simulator(1)
    for i in xrange(10):
        res = runner.runExperiment(experimentSpec, 
                                   numpy.random.RandomState().tomaxint(4) % 4294967295,
                                   1)
        print str(res),
    print 
Esempio n. 25
0
def penaltyFunction(lamb, mu, numServers, simTime, numReps, maxMIPS, aggressivness):
    mySim = Simulator(lam, mu, numServers, simTime, numRepsSim, maxMIPS, aggressivness)
    mySim.runSimulation()
    totalPenalty = 0

    maxTemps                = mySim.getMaxTemps()
    responseTimes           = mySim.getAvgResponseTime()
    avgjobsinsys            = mySim.getAvgJobsInSimulation()
    avgUtilizations         = mySim.getAvgServerUtils()
    powerConsumedByServers  = mySim.getPowerConsumptions()

    for rep in powerConsumedByServers:
        repIndex = powerConsumedByServers.index(rep)

        print '*****************************************************'
        print 'Log dump for rep', repIndex+1
        print 'Avg avg utils: ', sum(avgUtilizations[repIndex]) / len(avgUtilizations[repIndex])
        print 'Avg power consumed', sum(powerConsumedByServers[repIndex]) / len(powerConsumedByServers[repIndex])
        print 'Avg Response Time', sum(responseTimes[repIndex]) / len(responseTimes[repIndex])
        for i in range(0, len(rep)):
            print 'Server', i, '\tUtil:', avgUtilizations[repIndex][i], '\tMax temp:', maxTemps[repIndex][i],  '\t\tConsumed:', powerConsumedByServers[repIndex][i], '\tRT:', responseTimes[repIndex][i]

        maxTempForRep      = max(maxTemps[repIndex])
        maxPowerConsForRep = max(powerConsumedByServers[repIndex])
        maxUtilForRep      = max(avgUtilizations[repIndex])
        maxRTForRep        = max(responseTimes[repIndex])

        # Huge penalties for infeasible solutions
        if maxTempForRep > maxTemperature:
            totalPenalty += maxTempForRep
        if maxUtilForRep > maxUtilization:
            totalPenalty += maxUtilForRep
        if maxRTForRep > maxResponseTime:
            totalPenalty += maxRTForRep

        # Calculate norms against the maximums for each list
        # No actual use for this, penalties wouldn't make sense since the normalized scores can only be compared relative to the max...
        # normMaxTemps        = [float(i)/maxTempForRep for i in maxTemps[repIndex]].sort(reverse=True)
        # normPowerConsumed   = [float(i)/maxPowerConsForRep for i in powerConsumedByServers[repIndex]].sort(reverse=True)
        # normAvgUtils        = [float(i)/maxUtilForRep for i in avgUtilizations[repIndex]].sort(reverse=True)
        # normResponseTimes   = [float(i)/maxRTForRep for i in responseTimes[repIndex]].sort(reverse=True)

        avgMaxTempForRep    = sum(maxTemps[repIndex]) / len(maxTemps[repIndex])
        avgPowerConsForRep  = sum(powerConsumedByServers[repIndex]) / len(powerConsumedByServers[repIndex])
        avgUtilForRep       = sum(avgUtilizations[repIndex]) / len(avgUtilizations[repIndex])
        avgRTForRep         = sum(responseTimes[repIndex]) / len(responseTimes[repIndex])

        for item in rep:
            itemIndex = rep.index(item)
            if maxTemps[repIndex][itemIndex] > avgMaxTempForRep:
                totalPenalty += maxTemps[repIndex][itemIndex] - avgMaxTempForRep
            if powerConsumedByServers[repIndex][itemIndex] > avgPowerConsForRep:
                totalPenalty += powerConsumedByServers[repIndex][itemIndex] - avgPowerConsForRep
            if avgUtilizations[repIndex][itemIndex] > avgUtilForRep:
                totalPenalty += avgUtilizations[repIndex][itemIndex] - avgUtilForRep
            if responseTimes[repIndex][itemIndex] > avgRTForRep:
                totalPenalty += responseTimes[repIndex][itemIndex] - avgRTForRep
        # ENDFOR
    return totalPenalty
Esempio n. 26
0
    def getScore(self, pos, it):
        '''Determines how close a particle is to the optima - lower is better
		'''
        uavPoly = pos[:len(pos) // 2]
        targetPoly = pos[len(pos) // 2:]
        sim = Simulator(uavPoly, targetPoly, f"test{it}")
        score = sim.runTest()
        return score
Esempio n. 27
0
    def __init__(self, light_pos, type=None, net_filename=None):

        self.net = None  # NARX network
        self.net_filename = net_filename

        # network training
        self.training_runs, self.training_time = None, None
        self.random_movements, self.after_ga_movements = None, None

        if type == 'skmlp':
            self.net = narx.load_narx_mlp(net_filename)
        if net_filename is not None:
            start_time = time.time()
            saved_net = narx.load_pyrenn(net_filename)
            self.net = PyrennNarx()
            self.net.set_net(saved_net)
            self.training_runs = int(
                re.search('\d+',
                          re.search('r\d+', net_filename).group(0)).group(0))
            self.training_time = int(
                re.search('\d+',
                          re.search('t\d+', net_filename).group(0)).group(0))
            self.network_delay = int(
                re.search('\d+',
                          re.search('d\d+', net_filename).group(0)).group(0))
            print 'Loaded NARX from file "%s" in %ds' % (
                net_filename, time.time() - start_time)

        self.vehicle_training_data = None  # this data will hold all the vehicles that the network will train with
        self.ga_test_data = None  # this data will hold all the vehicles that the GA will test the fitness from
        self.pos_before_collect = None  # first position of vehicle before random collection
        self.ang_before_collect = None  # first angle of vehicle before random collection
        self.collection_vehicle_pos = [
        ]  # all pos of collection vehicle to pass to wakeTest vehicle to show on Sim
        self.pos_after_collect = None  # last position of vehicle after collection (passed to GA)
        self.ang_after_collect = None  # last angle of vehicle after collection (passed to GA)

        self.random_vehicle = None
        self.brain = None  # Vehicle brain assigned after GA, 6 weights
        self.vehicle_first_move = None
        self.predicted_pos = None

        self.ga_individuals = None
        self.ga_generations = None

        if light_pos is None:
            light_pos = [1100, 600]
        self.light = Light(light_pos)
        self.sim = Simulator(self.light)

        self.actual_vehicle = None

        self.count_cycles = 0

        # vars for test_2_1
        self.error_sensor_log = None  # predicted sensor log
        self.real_sensor_log = None  # actual sensor log
Esempio n. 28
0
    def __connect(self):
        # 初回起動チェック
        try:
            if Lora.__isConnect:
                return
        except AttributeError:
            Lora.__isConnect = True
            Lora.__isStart = False
            Lora.__isLock = False

        # Connect device
        mode = self.__config.getSimulator().strip().lower()
        devicename = self.__config.getDevicename()
        baudrate = self.__config.getBaudrate()
        if mode in "true":
            Lora.device = Simulator(devicename, int(baudrate))
        else:
            try:
                Lora.device = Serial(devicename, int(baudrate))
            except Exception as e:
                print(e)
                return

        # ES920 Welcomeメッセージ待機
        sleep(3.0)

        # Set Send/Recv variables
        Lora.sendMessages = deque()
        Lora.recvListeners = []

        # 各種設定
        self.send(["2", "a 2"])
        self.send("b %s" % self.__config.getBandwidth())
        self.send("c %s" % self.__config.getSpreadingfactor())
        self.send("d %s" % self.__config.getChannel())
        self.send("e %s" % self.__config.getPanid())
        self.send("f %s" % self.__config.getOwnid())
        self.send(["l 2", "n 2", "o 1", "p 1", "q 1", "s 1"])
        self.send("u %s" % self.__config.getPower())
        self.send(["w", "z"])

        # Send thread
        self.__thSend = Thread(
            target=self.__sendThread,
            args=(None, Lora.device, Lora.sendMessages)
        )
        self.__thSend.setDaemon(True)
        self.__thSend.start()

        # Receive thread
        self.__thRecv = Thread(
            target=self.__recvThread,
            args=(None, Lora.device, Lora.recvListeners)
        )
        self.__thRecv.setDaemon(True)
        self.__thRecv.start()
        return
    def setUp(self):
        """ Setup function TestTypes for class Simulator """

        self.SimulatorObj = Simulator(netlist)

        self.simul_timeout = self.SimulatorObj.simul_timeout
        self.netlist = self.SimulatorObj.netlist

        pass
Esempio n. 30
0
 def __init__(self, test_flights_info, zoneOptions, npts_per_leg, flightParamsTemplate, submission_file):
     self.test_flights_info  = test_flights_info
     self.zoneOptions        = zoneOptions
     self.npts_per_leg       = npts_per_leg
     self.submission_file    = submission_file
     self.flightParamsTemplate = flightParamsTemplate
     print "Starting simulator..."
     self.simulator = Simulator()
     print "Simulator started."