Beispiel #1
0
class CommandsListener(threading.Thread):
    def __init__(self, thymioController, mainLogger):
        threading.Thread.__init__(self)
        # Create socket for listening to simulation commands
        self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.__sock.bind((cl.COMMANDS_LISTENER_HOST, cl.COMMANDS_LISTENER_PORT))
        self.__sock.listen(5)
        self.__thymioController = thymioController
        self.__mainLogger = mainLogger
        self.__simulation = None
        self.__counter = pr.starter_number

    def run(self):
        while 1:
            try:
                # Waiting for client...
                self.__mainLogger.debug("CommandListener - Waiting on accept...")
                conn, (addr, port) = self.__sock.accept()
                self.__mainLogger.debug('CommandListener - Received command from (' + addr + ', ' + str(port) + ')')
                if addr not in cl.TRUSTED_CLIENTS:
                    self.__mainLogger.error(
                        'CommandListener - Received connection request from untrusted client (' + addr + ', ' + str(
                            port) + ')')
                    continue

                # Receive one message
                self.__mainLogger.debug('CommandListener - Receiving command...')
                recvOptions = recvOneMessage(conn)
                self.__mainLogger.debug('CommandListener - Received ' + str(recvOptions))

                if recvOptions.kill:
                    # Received killing command -> Stop everything
                    self.__thymioController.killRequest()
                    if self.__simulation:
                        self.__simulation.stop()
                    break
                elif recvOptions.start and (not self.__simulation or self.__simulation.isStopped()):
                    # Adding experiment number to pr.EXPERIMENT_NAME
                    experiment_name = pr.EXPERIMENT_NAME + "_" + str(self.__counter)
                    self.__counter += 1
                    # Received start request AND simulation is not running -> Start a new simulation
                    self.__mainLogger.debug("CommandListener - Starting simulation...")
                    self.__simulation = Simulation(self.__thymioController, recvOptions.debug, experiment_name)
                    self.__thymioController.setSimulation(self.__simulation)
                    self.__simulation.start()
                elif recvOptions.stop and self.__simulation and not self.__simulation.isStopped():  # TODO: Stop properly
                    # Received stop request AND simulation is up and running -> Stop the simulation
                    self.__mainLogger.debug("CommandListener - Stopping simulation...")
                    self.__simulation.stop()
                    self.__simulation = None
                elif recvOptions.stopthymio:
                    self.__mainLogger.debug("CommandListener - Stopping Thymio...")
                    self.__thymioController.stopThymio()

            except:
                self.__mainLogger.critical(
                    'Error in CommandsListener: ' + str(sys.exc_info()[0]) + ' - ' + traceback.format_exc())

        self.__mainLogger.debug('CommandListener - KILLED -> Exiting...')
def main():
    coffee = Body.ThermalBody(500)
    solver = Solver.Euler(0.5)

    def stop_condition(coffee):
        return coffee.temperature > sim.Ta * 1.1

    sim = Simulation.CoolingSim(stop_condition, solver, 293, 0.05, coffee)
    t, T = sim.get_results()
    plt.plot(t, T)

    coffee = Body.ThermalBody(500)
    solver = Solver.RK2(0.5)

    def stop_condition(coffee):
        return coffee.temperature > sim.Ta * 1.1

    sim = Simulation.CoolingSim(stop_condition, solver, 293, 0.05, coffee)
    t, T = sim.get_results()
    plt.plot(t, T)

    plt.title("OOP Cooling Curves")
    plt.xlabel("Time [s]")
    plt.ylabel("Temperature[K]")
    plt.legend(["Euler Curve", "RK2 Cooling Curve"])
Beispiel #3
0
def main():

    for device in ConfigureWin.config["devices"]:
        for city in ConfigureWin.config["citys"]:
            print(city + " device: " + device)
            simulation = Simulation(city, device)
            simulation.start()
def handlePerformedActionShow(words, writeFile):
    global opponentName
    global numBoardCards
    global preflopBets
    global postflopBets
    global turnBets
    global riverBets
    global boardCards
    global d

    if(words[5] == opponentName):
        opponentHand = []
        for card in words[1:5]:
            opponentHand.append(parseCard(card))
        preflopRating = Pokerini.pokeriniLookup(opponentHand, d)
        writeFile.write(str(preflopRating)+","+','.join(preflopBets))
        writeFile.write('\n')
        if(numBoardCards >= 3):
            postflopRanking = Simulation.simulateOld(opponentHand, boardCards[0:3], 3, 100)
            writeFile.write(str(postflopRanking)+","+','.join(postflopBets))
            writeFile.write('\n')
        if(numBoardCards >= 4):
            turnRanking = Simulation.simulateOld(opponentHand, boardCards[0:4], 4, 100)
            writeFile.write(str(turnRanking)+","+','.join(turnBets))
            writeFile.write('\n')
        if(numBoardCards == 5):
            riverRanking = Simulation.simulateOld(opponentHand, boardCards[0:5], 5, 100)
            writeFile.write(str(riverRanking)+","+','.join(riverBets))
            writeFile.write('\n')
def main():

    skull = Body.GravBody(5, 6.371 * 10**6, 8000.)
    solver = Solver.RK2(0.001)

    def stop_condition(skull):
        return skull.velocity > 0

    sim1 = Simulation.TrajectorySim(stop_condition, solver, skull)
    x, y = sim1.get_results()
    skull2 = Body.GravBody(5, 6.371 * 10**6, 8000.)
    sim2 = Simulation.InverseTrajectorySim(stop_condition, solver, skull2)
    a, b = sim2.get_results()

    plt.plot(x, y)
    plt.plot(a, b)
    plt.title("Skull Tosses")
    plt.xlabel("Time [s]")
    plt.ylabel("Height [m]")
    plt.legend(["Uniform Gravity", "Inverse Square Gravity"])

    plt.figure()
    varray = np.arange(0, 100, 0.5)
    harray = []
    for v in varray:
        skull3 = Body.GravBody(5, 6.371 * 10**6, v)
        sim3 = Simulation.InverseTrajectorySim(stop_condition, solver, skull3)
        result = sim3.get_results()
        harray.append(skull3.position)

    plt.plot(varray, harray)
    plt.title("Maximum Height vs. Initial Velocity")
    plt.xlabel("Initial Velocity [m/s]")
    plt.ylabel("Maximum Height [m]")
    def ranCoor(self, p_mu, p_numu):
#.. Rotation angles
        phi = Simu.getRandom() * 2.*mth.pi
        cPhi = mth.cos(phi)
        sPhi = mth.sin(phi)

        cTheta = -1. + 2.*Simu.getRandom()
        sTheta = mth.sqrt(1. - cTheta**2)
        theta = mth.acos(cTheta)

#.. Rotation angles
        Ra = np.array([          \
             [cPhi   , -sPhi,    0.      ], \
             [sPhi   ,  cPhi,    0.      ], \
             [0.     , 0.,       1.      ] \
                                ])
#        print("Ra:", Ra)
        Rb = np.array([          \
             [cTheta    , 0.,    -sTheta     ], \
             [0.        , 1.,    0.          ], \
             [sTheta    , 0.,    cTheta      ] \
                                   ])
#        print("Rb:", Rb)

        Rr = np.dot(Ra, Rb)
#        print("Rr:", Rr)
        
#.. Do rotation:
        p_mu1  = np.dot(Rr, p_mu)
        p_numu1 = np.dot(Rr, p_numu)

        return  p_mu1, p_numu1, cTheta, phi
Beispiel #7
0
    def __init__(self, master=None):
        super().__init__(master=master)
        self.title("Choice Selection")
        self.geometry("350x125")
        choiceLabel = Label(self, text="Please select which you will use")
        choiceLabel.grid(row=0, column=1)

        global rockImage
        global paperImage
        global scissorsImage

        rockImage = ImagesHelper.GetImage("Rock")
        paperImage = ImagesHelper.GetImage("Paper")
        scissorsImage = ImagesHelper.GetImage("Scissors")

        rockButton = Button(self, text="Rock", image=rockImage)
        rockButton.bind("<Button>",
                        lambda e: Simulation.RockSimulationForm(self))
        rockButton.grid(row=1, column=0)

        paperButton = Button(self, image=paperImage)
        paperButton.bind("<Button>",
                         lambda e: Simulation.PaperSimulationForm(self))
        paperButton.grid(row=1, column=1)

        scissorsButton = Button(self, image=scissorsImage)
        scissorsButton.bind("<Button>",
                            lambda e: Simulation.ScissorsSimulationForm(self))
        scissorsButton.grid(row=1, column=2)
Beispiel #8
0
def handlePerformedActionShow(words, writeFile):
    global myName
    global numBoardCards
    global preflopBets
    global postflopBets
    global turnBets
    global riverBets
    global boardCards
    global d

    if (words[5] == myName):
        myHand = []
        for card in words[1:5]:
            myHand.append(parseCard(card))
        preflopRating = Pokerini.pokeriniLookup(myHand, d)
        writeFile.write(str(preflopRating) + "," + ','.join(preflopBets))
        writeFile.write('\n')
        if (numBoardCards >= 3):
            postflopRanking = Simulation.simulateOld(myHand, boardCards[0:3],
                                                     3, 100)
            writeFile.write(
                str(postflopRanking) + "," + ','.join(postflopBets))
            writeFile.write('\n')
        if (numBoardCards >= 4):
            turnRanking = Simulation.simulateOld(myHand, boardCards[0:4], 4,
                                                 100)
            writeFile.write(str(turnRanking) + "," + ','.join(turnBets))
            writeFile.write('\n')
        if (numBoardCards == 5):
            riverRanking = Simulation.simulateOld(myHand, boardCards[0:5], 5,
                                                  100)
            writeFile.write(str(riverRanking) + "," + ','.join(riverBets))
            writeFile.write('\n')
Beispiel #9
0
 def CalPerformance(self, model):
     testTimes = 100
     testHorizon = 500
     successTimes = 0
     for i in range(testTimes):
         # initialize variable
         preO = 0
         histO = np.tile([[1, 0, 0]], (1, self.L))
         Q_tm1 = 0
         for t in range(testHorizon):
             # decide which action to take
             if preO == 2:
                 a_t = 0
             else:
                 probA = model.predict(histO, batch_size=1)
                 if np.random.uniform() < probA[0, 0]:
                     a_t = 0
                 else:
                     a_t = 1
             # run simulation once
             simObj = Simulation(self.systemParaDict, a_t, Q_tm1)
             simObj.Main()
             curO = simObj.o_t
             # add o_t-1 into history
             newHistO = np.array([[0, 0, 0]])
             newHistO[0, curO] = 1
             histO = np.hstack((histO[:, 3:], newHistO))
             # count successful times
             if a_t == 1 and simObj.f_t == 'S':
                 successTimes += 1
             # update temporary variables
             preO = curO
             Q_tm1 = simObj.Q_t
     # calculate throughput of the secondary user
     return successTimes / (testTimes * testHorizon)
Beispiel #10
0
 def set_variables_panel(self):
     self.simulation = Simulation(self)
     font_ctrl = wx.Font(11, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)
     font_var = wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)
     font = wx.Font(15, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)
     font_exec = wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)
     self.parameters_text = wx.StaticText(self.panel, label='Parametry Symulacji:', pos=(0.01*self.screen_size[0], 0.36*self.screen_size[1]))
     self.parameters_text.SetFont(font_var)
     self.parameters_text.Hide()
     y = 0.36 * self.screen_size[1]
     for i in range(6):
         self.var_start.append(wx.StaticText(self.panel, label='', pos=(0.01*self.screen_size[0], y + 0.04*(i+1)*self.screen_size[1])))
         self.var_start[i].Hide()
         self.var_start[i].SetFont(font_var)
         self.Ctrls.append(wx.SpinCtrlDouble(self.panel, value='0', pos=(0.12*self.screen_size[0], y + 0.04*(i+1)*self.screen_size[1]), size=(0.09*self.screen_size[0], -1)))
         self.Ctrls[i].Hide()
         self.Ctrls[i].SetFont(font_ctrl)
         self.var_exec.append(wx.StaticText(self.panel, label='', pos=((0.86-i*0.15)*self.screen_size[0], 0.87*self.screen_size[1])))
         self.var_exec[i].Hide()
         self.var_exec[i].SetFont(font_exec)
         self.legend.append(wx.StaticText(self.panel, label='', pos=(0.01*self.screen_size[0],0.6*self.screen_size[1] + 0.04*(i+1)*self.screen_size[1])))
         self.legend[i].SetFont(font)
     self.language = wx.StaticText(self.panel, label=u'Język', pos=(0.01*self.screen_size[0], 0.01 * self.screen_size[1]))
     self.language.SetFont(font)
     png1 = wx.Image('variants.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
     self.variants = []
     variants = wx.StaticBitmap(self.panel, -1, png1, (0.35 * self.screen_size[0], 0.3 * self.screen_size[1]),
                                     (png1.GetWidth(), png1.GetHeight()))
     self.variants.append(variants)
     font = wx.Font(18, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.NORMAL)
     variants2 = wx.StaticText(self.panel,label='\n1\n\n\n\n\n2\n\n\n\n3\n\n\n\n4',pos=(0.3 * self.screen_size[0],0.3 * self.screen_size[1]))
     variants2.SetFont(font)
     self.variants.append(variants2)
     for i in self.variants:
         i.Hide()
Beispiel #11
0
def main():

    city = "Shenzhen"
    device = "5100"

    simulation = Simulation(city, device)
    simulation.start()
Beispiel #12
0
def evolve_dag(population_size=10, number_of_offsprings=10, n=22, edge_mutation_probability=0.2,
        weight_mutation_probability=1., iters=10, tracks=[], frames_limit=25):

    population = initial_population(population_size, n)
    objective_values = evaluate_population(population, tracks, frames_limit)


    matrix = population[0].edges
    results = np.zeros(iters)
    last_saved_value = 0.


    for t in range(iters):
        print t
        children = []
        parent_indices = parent_selection(objective_values, population_size, number_of_offsprings)
        print parent_indices
        ### crossover
        for i in range(len(parent_indices)/2):
            c1, c2 = dag.crossover(population[parent_indices[2*i]], population[parent_indices[2*i+1]], -const.network_weights_limit, const.network_weights_limit)
            children.append(c1)
            children.append(c2)

        ### mutation
        for child in children:
            if np.random.random() < edge_mutation_probability:
                child.edge_mutation()
            if np.random.random() < weight_mutation_probability:
                child.weight_mutation(-const.network_weights_limit, const.network_weights_limit)

        ### children evaluation and replacement
        children_objective_values = evaluate_population(children, tracks, frames_limit)

        objective_values = np.hstack((objective_values, children_objective_values))
        tmp_population = population + children
        I = np.argsort(objective_values)[::-1]
        population = []
        for i in range(population_size):
            population.append(tmp_population[I[i]])
        objective_values = objective_values[I[:population_size]]


        ### statistics
        if (population[0].edges == matrix ).sum() != population[0].n ** 2 or t == iters-1:
            matrix = population[0].edges
            population[0].draw(save=True, nr=t)
        results[t] = objective_values.max()

        print t, results[t]

        if objective_values.max() - last_saved_value > 0.07 or t == iters-1:
            last_saved_value = objective_values.max()
            dag.save_population(population)
            np.savetxt(path_root + 'results.txt', results)
            for i in range(len(tracks)):
                title = path_root + "track_" + str(i+1) + "_gen_" + str(t)
                sim.simulation_movie(tracks[i], create_cars(population[:5]), title=title, frames_limit=frames_limit, show_demo=False, save=True)

    return results, population
 def GenerateTrans(self, s):
     r = np.sqrt(self._epsilon * self._beta) / 1000.
     rp = np.sqrt(self._epsilon / self._beta)
     x = Simu.getParabolic(r)
     y = Simu.getParabolic(r)
     xp = Simu.getParabolic(rp)
     yp = Simu.getParabolic(rp)
     return x, y, xp, yp
 def Simulation_launch(self):
     if self.busy > 0:
         return False
     # A new simulation thread is created
     if self.Simulation_stop():
         self.simulation = Simulation(self.OneStep)
         self.simulation.start()
     return True
Beispiel #15
0
def main():
	battlesimulator = Master()
	battlesimulator.introMessage()
	setupPlayers = SetupPlayers()
	setupPlayers.askPlayer()
	battlesimulator.displayStats(Warrior(1, 2, 3), Warrior(4, 5, 6))
	warriorSet = WarriorSet(Warrior(1, 2, 3), Warrior(4, 5, 6))
	warriorSet.printWarriors()
	simulation = Simulation()
	simulation.setWarriors(Warrior(1, 2, 3), Warrior(4, 5, 6))
	simulation.run()
Beispiel #16
0
def evaluate_action_with_robots(results, state):
    pf_normal_value = evaluate_action(results, state)

    sum_potential = 0.0
    number_of_actions = 0.0
    for p in results.positions():
        if p.cat() == Category.INFIELD or p.cat() == Category.OPPGOAL:
            sum_potential += evaluate_single_pos_with_robots(
                state.pose * p.pos(), state.opp_robots, state.own_robots)
            number_of_actions += 1

    assert number_of_actions > 0
    sum_potential /= number_of_actions

    squared_difference = np.abs(
        pf_normal_value - sum_potential
    )  # decide whether considering other robots is appropriate
    if squared_difference < 0.05:  # upper bound - how to choose?
        return pf_normal_value

    # ab hier experimental
    # new Ball pos with passing

    new_ball_pos = results.expected_ball_pos_mean

    #update state
    new_state = copy.copy(state)
    new_state.ball_position = m2d.Vector2(0.0, 0.0)  # Ball = Robot
    new_state.translation = new_ball_pos
    #new_state.rotation = pass # maybe rotation as needed for direkt / shortest path to the ball
    new_state.potential_field_function = "normal"

    # Simulation as in Simulation.py (decide_smart)

    actions_consequences = []
    # Simulate Consequences
    for action in new_state.actions:  #new_state.actions includes the possible kicks
        single_consequence = a.ActionResults([])
        actions_consequences.append(
            Sim.simulate_consequences(action, single_consequence, new_state,
                                      30))

    best_action_with_team = Sim.decide_smart(actions_consequences, state)

    # compare new best action
    # TODO: Add simulation of a second kick without other robots to have better comparison
    # needed: action which would have been done without other robots
    # what should get returned?? to compare with other actions
    """
    if best_value > pf_normal_value:
        return sum_potential
    """

    return sum_potential
Beispiel #17
0
 def execute(self, simulation: Simulation):
     """
     Runs a simulation using the using the neural network as the agent
     :param simulation: The simulation to run, and get the score from
     :return: The score from the simulation
     """
     while simulation.get_state(
             batch_id=self.batch_id) != Simulation.SimulationState.FINISHED:
         input_data = simulation.get_data(batch_id=self.batch_id)
         processed_data = self.run(input_data)
         simulation.apply_controls(processed_data, batch_id=self.batch_id)
     return simulation.get_score(batch_id=self.batch_id)
Beispiel #18
0
def init_multi_params():
    global FULL_SCREEN
    global FRAME_SIZE
    global CROP_SIZE
    global SCREEN_SIZE
    global ACC
    Sim.init_multi()
    Ac.init_multi_arduino_communication()
    CROP_SIZE = (106, 360)
    SCREEN_SIZE = (8.0, 12.0)
    FULL_SCREEN = (8.0, 12.0)
    ACC = RELATIVE_ACC * SCREEN_SIZE[0]
Beispiel #19
0
 def setUp(self):
     Simulation.setupJobEffMC()
     cores = 3000
     bandwidth = 3000
     self.system = Site.Batch( cores, bandwidth )
     file1 = "/store/data/1"
     file2 = "/store/data/2"
     theStore = Data.EventStore()
     theStore.addFile( file1, 10000 )
     theStore.addFile( file2, 20000 )
     inputData = { file1, file2 }
     aJob = Job.Job( "T2_CH_CERN", inputData, 0.1, 220, 200, theStore )
     self.system.addJob( aJob )
     self.system.runJob( aJob, 0 )
Beispiel #20
0
 def GenerateSamples(self, model):
     # initialize variables
     fullX = np.zeros((self.T, 3 * self.L))
     fullY = np.zeros((self.T, 2))
     indexU = np.zeros((self.T, 1))
     sampleA, sampleR = [], []
     preO = 0
     histO = np.tile([[1, 0, 0]], (1, self.L))
     Q_tm1 = 0
     # generate trainX
     for t in range(self.T):
         # decide which action to take
         if preO == 0:
             a_t = 1
         elif preO == 1:
             probA = model.predict(histO, batch_size=1)
             if np.random.uniform() < probA[0, 0]:
                 a_t = 0
             else:
                 a_t = 1
         else:
             a_t = 0
         # run simulation once
         simObj = Simulation(self.systemParaDict, a_t, Q_tm1)
         simObj.Main()
         curO = simObj.o_t
         # add o_t-1 into history
         newHistO = np.array([[0, 0, 0]])
         newHistO[0, preO] = 1
         histO = np.hstack((histO[:, 3:], newHistO))
         # collect data
         fullX[t, :] = histO
         sampleA.append(a_t)
         sampleR.append(simObj.r_t)
         if curO == 1:
             indexU[t, 0] = 1
         # update temporary variables
         preO = curO
         Q_tm1 = simObj.Q_t
     # calculate reward-to-go
     rSum = 0
     for t in reversed(range(self.T - 1)):
         fullY[t, 0] = sampleA[t + 1]
         rSum = self.beta * rSum + sampleR[t + 1]
         fullY[t, 1] = rSum
     # extract train data
     trainX = fullX[np.nonzero(indexU > 0)[0], :]
     trainY = fullY[np.nonzero(indexU > 0)[0], :]
     # return results
     return trainX, trainY
Beispiel #21
0
    def GenerateSamples(self, model):
        # initialize variables
        fullX = np.zeros((self.T, 3 * self.L))
        fullY = np.zeros((self.T, 2))
        sampleA, sampleR = [], []
        histO = np.tile([[1, 0, 0]], (1, self.L))
        Q_tm1 = 0
        # generate trainX
        for t in range(self.T):
            # decide which action to take
            probA = model.predict(histO, batch_size=1)
            if np.random.uniform() < probA[0, 0]:
                a_t = 0
            else:
                a_t = 1
            # run simulation once
            simObj = Simulation(self.systemParaDict, a_t, Q_tm1)
            simObj.Main()
            curO = simObj.o_t
            # add o_t into history
            newHistO = np.array([[0, 0, 0]])
            newHistO[0, curO] = 1
            histO = np.hstack((histO[:, 3:], newHistO))
            # collect data
            fullX[t, :] = histO
            sampleA.append(a_t)
            sampleR.append(simObj.r_t)
            # update temporary variables
            Q_tm1 = simObj.Q_t

            # print('===== t =', t, '=====')
            # print('input = ' + str(histO))
            # print('p_N = ' + str(probA[0, 0]))
            # print('a_t = ' + str(a_t))
            # print('r_t = ' + str(simObj.r_t))
        # calculate reward-to-go
        rSum = 0
        for t in reversed(range(self.T)):
            fullY[t, 0] = sampleA[t]
            rSum = self.beta * rSum + sampleR[t]
            fullY[t, 1] = rSum
        # extract train data
        trainX = fullX
        trainY = fullY

        # print(trainY)

        # return results
        return trainX, trainY
Beispiel #22
0
def set_a_trader_simulation(path_trader_folder):
    path_RAS, path_Trades, path_Pnls = [""] * 3
    if os.path.isfile(os.path.join(path_trader_folder, 'RawArbSignals.csv')):
        path_RAS = os.path.join(path_trader_folder, 'RawArbSignals.csv')
    if os.path.isfile(os.path.join(path_trader_folder, 'Trades.csv')):
        path_Trades = os.path.join(path_trader_folder, 'Trades.csv')
    if os.path.isfile(os.path.join(path_trader_folder, 'TraderPnls.csv')):
        path_Pnls = os.path.join(path_trader_folder, 'TraderPnls.csv')

    trader_name = ' - '.join(str(path_trader_folder).split('\\')[-2:])
    trader_simulation_obj = Simulation(name=trader_name)
    trader_simulation_obj.files_set_data(file_RAS=path_RAS,
                                         file_Trades=path_Trades,
                                         file_Pnl=path_Pnls)
    return trader_simulation_obj
 def __OnScriptNew(self, event):
     name = wx.GetTextFromUser("Enter Script Name:", "Script Name")
     if (name is None) or (len(name) < 0):
         return
     newScript = Simulation.SimScript(name)
     self.sim.savedPresets.startScripts.append(newScript)
     self.RefreshBox()
Beispiel #24
0
def EvaluationNN3(env, action_space, size_input, labels, TrainingSet, nSamples,
                  max_epochs):

    average_NN = np.empty((0))
    success_percentageNN = np.empty((0))

    for i in range(len(nSamples)):
        model = NN3(action_space, size_input)
        encoded = tf.keras.utils.to_categorical(labels)
        model.fit(TrainingSet[0:nSamples[i], :],
                  encoded[0:nSamples[i], :],
                  epochs=50)
        T = 100
        [trajNN, controlNN,
         flagNN] = sim.FlatPolicySim(env, model, max_epochs, T, size_input)
        length_trajNN = np.empty((0))
        for j in range(len(trajNN)):
            length_trajNN = np.append(length_trajNN, len(trajNN[j][:]))
        average_NN = np.append(
            average_NN, np.divide(np.sum(length_trajNN), len(length_trajNN)))
        success_percentageNN = np.append(
            success_percentageNN, np.divide(np.sum(flagNN),
                                            len(length_trajNN)))

    return average_NN, success_percentageNN
Beispiel #25
0
def test_computational_time():
    """This test ensures that the time required for the Adiabatic Quantum
       Computation is properly calculated.

       Asserts:
           That the function results_of_simulation(100,2,H0,H1) returns the
           expected value of the time, in a simulation with 100 steps, 2
           particles and certain hi and Jij coefficients.
    """
    hi = numpy.array((1, 2))
    Jij = numpy.array(((0, 1), (1, 0)))
    H0 = Simulation.Hamiltonian_0(2)
    H1 = Simulation.Hamiltonian_1(2, hi, Jij)
    expected_result = 0.6571
    actual_result = Simulation.results_of_simulation(100, 2, H0, H1)
    assert actual_result == expected_result
Beispiel #26
0
def ethz_config_pim( test_sys, options ):
    (TestCPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)

    # JIWON: existing code created only one PIM system, modified to create multiple as necessary
    test_sys.pim_sys = [build_pim_system(options, test_mem_mode, TestCPUClass, pim_id=i) for i in xrange(options.num_pim_sys)]
    for i in xrange(options.num_pim_sys):
        pim_device_range = AddrRange(PIM_ADDRESS_BASE + i * PIM_ADDRESS_SIZE_INT, size = PIM_ADDRESS_SIZE) # added by JIWON
        test_sys.pim_sys[i].p2s = Bridge(ranges=test_sys.mem_ranges, delay='0.01ns', req_size=32, resp_size=32)
        test_sys.pim_sys[i].s2p = Bridge(ranges=pim_device_range, delay='0.01ns', req_size=32, resp_size=32)

        if ( GEM5_ENABLE_COMM_MONITORS == "TRUE" ):
            test_sys.pim_sys[i].Smon = CommMonitor()

            if ( SMON_DUMP_ADDRESS == "TRUE" ):
                test_sys.pim_sys[i].Smon.dump_addresses=True
                test_sys.pim_sys[i].Smon.dump_file="m5out/smon_addr_dump.txt"

            test_sys.pim_sys[i].pimbus.master = test_sys.pim_sys[i].Smon.slave
            test_sys.pim_sys[i].Smon.master = test_sys.pim_sys[i].p2s.slave
        else:
            test_sys.pim_sys[i].pimbus.master = test_sys.pim_sys[i].p2s.slave

        test_sys.pim_sys[i].s2p.master = test_sys.pim_sys[i].pimbus.slave
        if ( MOVE_PIM_TO_HOST == "FALSE" ):
            test_sys.pim_sys[i].p2s.master = test_sys.smcxbar.slave
            test_sys.smcxbar.master = test_sys.pim_sys[i].s2p.slave;
        else:
            test_sys.pim_sys[i].p2s.master = test_sys.membus.slave
            test_sys.membus.master = test_sys.pim_sys[i].s2p.slave;
Beispiel #27
0
def average_over_seeds(model_type_list,
                       model_parameters_list,
                       n=N,
                       k=K,
                       t=T,
                       possible_rewards=POSSIBLE_REWARDS,
                       get_reward_probabilities=get_reward_probabilities,
                       min_seed=MIN_SEED,
                       max_seed=MAX_SEED):
    """
    run simulation for many models, with different seeds and return the required arrays for Visualization.py
    plot functions with vis.DATA list_type argument
    :param model_type_list: list of ModelType enums, containing the models to run
    :param model_parameters_list: list of dictionaries containing parameters for the models in model_type_list
    :param n: number of machines
    :param k: number of machines to choose each round
    :param t: number of trials
    :param possible_rewards: list of possible machine rewards
    :param get_reward_probabilities: function that returns a list of reward probabilities
    :param min_seed: lowest seed to run
    :param max_seed: highest seed to run
    :return: convergence, reward_sum, distance_from_real_distributions - arrays of tuples, first argument in tuple
    is the sim.type and the second is the actual data
    """
    convergence_list = np.zeros((len(model_type_list), t - 1))
    reward_sums = np.zeros((len(model_type_list), t))
    regrets = np.zeros((len(model_type_list), t))
    distances = [[] for _ in range(len(model_type_list))]
    sim_titles = []
    for seed in tqdm(range(min_seed, max_seed + 1)):
        optimal_reward = None
        cur_rewards = np.zeros_like(reward_sums)
        for i, model_type, model_parameters in tqdm(
                zip(np.arange(len(model_type_list)), model_type_list,
                    model_parameters_list)):
            np.random.seed(seed)
            sim = s.Simulation(n, k, t, possible_rewards,
                               get_reward_probabilities, model_type,
                               **model_parameters)
            if seed == min_seed:
                sim_titles.append(sim.type)
            sim.run_simulation()
            convergence_list[i, :] += sim.get_convergence_rate()
            if sim.type == "Optimal Model":
                optimal_reward = sim.get_reward_sum()
            cur_rewards[i, :] += sim.get_reward_sum()
            reward_sums[i, :] += cur_rewards[i, :]
            for j, machine in enumerate(sim.machine_list):
                distances[i].append(
                    vis.fr_metric(
                        machine.reward_probabilities,
                        sim.model.estimated_machine_reward_distribution[j, :]))
        regrets[...] += optimal_reward - cur_rewards
    convergence_list /= (max_seed - min_seed + 1)
    reward_sums /= (max_seed - min_seed + 1)
    regrets /= (max_seed - min_seed + 1)
    return [(sim_titles[i], convergence_list[i, :]) for i in range(len(model_type_list))], \
           [(sim_titles[i], reward_sums[i, :]) for i in range(len(model_type_list))], \
           [(sim_titles[i], distances[i]) for i in range(len(model_type_list))], \
           [(sim_titles[i], regrets[i]) for i in range(len(model_type_list))]
Beispiel #28
0
def EvaluationNN1(map, stateSpace, P, traj, control, ntraj):
    average_NN = np.empty((0))
    success_percentageNN = np.empty((0))
    average_expert = np.empty((0))

    for i in range(len(ntraj)):
        action_space = 5
        labels, TrainingSet = ProcessData(traj[0:ntraj[i]][:],
                                          control[0:ntraj[i]][:], stateSpace)
        model = NN1(action_space)
        model.fit(TrainingSet, labels, epochs=50)
        predictions, deterministic_policy = MakePredictions(model, stateSpace)
        T = 100
        base = ss.BaseStateIndex(stateSpace, map)
        TERMINAL_STATE_INDEX = ss.TerminalStateIndex(stateSpace, map)
        [trajNN, controlNN,
         flagNN] = sim.StochasticSampleTrajMDP(P, predictions, 1000, T, base,
                                               TERMINAL_STATE_INDEX)
        length_trajNN = np.empty((0))
        for j in range(len(trajNN)):
            length_trajNN = np.append(length_trajNN, len(trajNN[j][:]))
        average_NN = np.append(
            average_NN, np.divide(np.sum(length_trajNN), len(length_trajNN)))
        success_percentageNN = np.append(
            success_percentageNN, np.divide(np.sum(flagNN),
                                            len(length_trajNN)))

        length_traj = np.empty((0))
        for k in range(ntraj[i]):
            length_traj = np.append(length_traj, len(traj[k][:]))

        average_expert = np.append(
            average_expert, np.divide(np.sum(length_traj), len(length_traj)))

    return average_NN, success_percentageNN, average_expert
Beispiel #29
0
 def start_times(self):
     Mp = 1.0
     Ms = 1. * 10.**(-6)
     ap = 2.0
     e = 0.5
     As = 1.0
     Ap = 0.25
     omega = 0.
     i = 0.
     sim = Simulation.ExoSim(Mp, Ms, ap, e, As, Ap, omega, i, apnd=True)
     sim.advance()
     time, bodies = sim.get_results()
     t = np.array(time)
     v = np.array([b[1].velocity.x for b in bodies])
     test = v[1:] * v[:-1]
     vt = v[:-1]
     tt = t[:-1]
     times = tt[test < 0]
     if len(times) == 1.:
         times = np.append(times, sim.period / 2. + times[0])
     test2 = vt[test < 0]
     if test2[0] < 0:
         return times
     elif test2[0] > 0:
         return np.array([times[1], times[0] + sim.period])
Beispiel #30
0
def e_8_f():
    bnb = Sim.BallAndBeam()
    max_force = 15
    rise_time_theta = 1

    beam_mass = bnb.dynamics.beam_mass
    ball_mass = bnb.dynamics.ball_mass
    beam_length = bnb.dynamics.beam_length
    gravity = bnb.dynamics.gravity

    c_theta = 1 / (beam_length * (ball_mass / 4 + beam_mass / 3))
    natural_frequency_theta = np.pi / (2 * rise_time_theta * (1 - damping_ratio**2)**(1/2))
    proportional_gain_theta = natural_frequency_theta**2 / c_theta
    derivative_gain_theta = 2 * damping_ratio * natural_frequency_theta / c_theta

    rise_time_z = 10 * rise_time_theta
    natural_frequency_z = np.pi / (2 * rise_time_z * (1 - damping_ratio**2)**(1/2))
    proportional_gain_z = natural_frequency_z**2 / -gravity
    derivative_gain_z = 2 * damping_ratio * natural_frequency_z / -gravity

    bnb.add_controller(PD.BallAndBeam,
                       proportional_gain_z, derivative_gain_z,
                       proportional_gain_theta, derivative_gain_theta, max_force)
    # a square wave with magnitude 0.25±0.15 meters and frequency 0.01 Hz
    requests = sg.generator(sg.constant, amplitude=0.0, t_step=bnb.seconds_per_sim_step, t_final=10)
    handle = bnb.view_animation(requests)
    Sim.Animations.plt.waitforbuttonpress()
    Sim.Animations.plt.close()
    return handle
 def load_default(self):
     self.params = np.array([
         51.9957, 81, 3.7998e-7, -0.204599, 0, 328.93, 88.8624, 11.7176,
         1182.19, 2026.27, 7.14503, 0, 0, 89.1588, 87.5647, 0.278594
     ])
     energy = self.params[0]
     etalimit = self.params[1] / 180.0 * np.pi
     pos = self.params[2:5]
     orien = R.EulerZXZ2Mat(self.params[5:8] / 180.0 * np.pi)
     #        strain=np.array([ 0.00228725, -0.00046991, -0.00013953, -0.0001595 ,  0.00143135,
     #                    0.00070123,  0.00089509,  0.00438468,  0.0014488 ])+np.array([ -1.66347153e-03,   9.19749189e-04,   8.19250063e-05,
     #                                -1.33069566e-04,  -1.18838324e-03,  -2.40553445e-04,
     #                                         1.67946465e-03,  -8.97547675e-03,  -8.87805809e-04])
     strain = np.zeros(9)
     strain = strain.reshape((3, 3)) + np.eye(3)
     orien = strain.dot(orien)
     Det = G.Detector()
     Det.Move(self.params[8], self.params[9], self.params[10:13],
              R.EulerZXZ2Mat(self.params[13:16] / 180.0 * np.pi))
     self._xrd.Setup(energy, etalimit, pos, orien, Det)
     self._xrd.Simulate()
     self.choosePeakID.setMinimum(0)
     self.choosePeakID.setMaximum(len(self._xrd.Peaks) - 1)
     try:
         self.res = pickle.load(open('tmp_res.pickle', 'r'))
     except:
         self.res = [None] * len(self._xrd.Peaks)
     self.l0.setText('Setup finished')
Beispiel #32
0
 def __init__(self):
     self._sample = G.CrystalStr('Ti7')
     self._sample.getRecipVec()
     self._sample.getGs(11)
     self._Peaks = None
     self._Gs = None
     self._PeaksInfo = None
Beispiel #33
0
def pull_data(run, test_x, test_y, num_round):
    yhats = []
    yhhats = []
    MSEs = []
    xhats = []
    for i in range(0, len(run)):
        method = run[i]
        print(run[i])
        res_file = os.path.join(data_dir, method + "_results.dat")
        DR_model = Dim_Red.load_DR(method, data_dir)
        X_0 = DR_model.Encode_X(test_x)
        #add predicted y (yhat) to list of yhats
        yhats = [*yhats, DR_model.Pred_Y(X_0)[:, 0:1]]
        #convert DR to x for xhat
        xhat = DR_model.Decode_X(X_0)
        xhats = [*xhats, xhat]
        #add simulated y from xhat to list of yhhats
        yhhats = [*yhhats, Simulation.Evaluate_yhhat(test_x, xhat)]
        #add MSE stats for PLS
        MSEs = [
            *MSEs,
            generate_stats(test_y, yhats[-1], yhhats[-1][0], yhhats[-1][1],
                           test_x, xhats[-1], num_round)
        ]
    print(MSEs)
    return yhats, xhats, yhhats, MSEs
Beispiel #34
0
def get_sample(traj_dist,experiment_id):
    #Start a simulation and do the stuff
    functions = {}
    args = {}
    real_fun(functions)

    states = np.genfromtxt('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj'+str(experiment_id+1)+'state.txt', delimiter=',',dtype=np.float32)
    actions = np.genfromtxt('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj'+str(experiment_id+1)+'action.txt' ,dtype=np.float32)
    T,d = states.shape

    #Create simulation
    Sim = Simulation(function=functions["Traj{}".format(str(experiment_id+1))], args=[[0,0,3],0])
    Sim.restart()

    f = open('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj{}pred.txt'.format(experiment_id+1),'w+')
    r = open('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj{}residuals.txt'.format(experiment_id+1),'w+')

    for timestep in range(T):
        states[timestep,:] = normalize(state_norms[experiment_id],controller.getDif(Sim.cid,Sim.copter,Sim.target))
        old = actions[timestep,:].copy()
        actions[timestep,:] = denormalize(action_norms[experiment_id], get_action(traj_dist,states[timestep,:],timestep)[0])
        Sim.forward(actions[timestep,:].tolist())
        f.write(str(actions[timestep,:])+'\n')
        r.write(str(old-actions[timestep,:])+'\n')
        #Sim.forward()
        Sim.sync()
    print(vrep.simxStopSimulation(Sim.cid,vrep.simx_opmode_oneshot_wait))
    f.close()
    r.close()
    return states,actions
Beispiel #35
0
 def updateHandRanking(self):
     if(self.cardsChanged == True):
         if(self.numBoardCards == 0): #preflop
             self.pokeriniRank = Pokerini.pokeriniLookup(self.myHand, pokeriniDict)
             self.calculatePreflopBetLimit()
         if(self.numBoardCards >= 3):#postflop
             #self.simulationWinChance = Simulation.simulate(self.myHand, self.boardCards, self.numBoardCards, 200, handEvalDict, translationDict)
             self.simulationWinChance = Simulation.simulateOld(self.myHand, self.boardCards, self.numBoardCards, self.numSimulations)
     self.cardsChanged = False
class Simulation_Control(object):
    """ Controls the simulation, either step by step, or in
        a continuous mode.
    """

    def __init__(self, SimulationStep):

        self.OneStep = SimulationStep   # function that launches one step of the simulation

        ## Status of the simulation programme
        self.simulation = None  # name of the simulation thread
        self.busy = 0   # busy meter to avoid fatal parallelism between simulation and display

        #self.previous_Disp_period = self.Disp_period = 1    # display period

    def RunButtonClick(self, event=None):
        self.simulation_steady_mode = True     # Continuous functioning
        self.Simulation_resume()   

    def PauseButtonClick(self,event=None):
        self.Simulation_stop()
        
    def Simulation_stop(self):
        if self.simulation is not None:
            self.simulation.stop()
            if self.simulation.isAlive():
                #print 'strange...'
                #sleep(2)
                self.simulation = None  # well...
                return False
            self.simulation = None
        return True
        
    def Simulation_launch(self):
        if self.busy > 0:
            return False
        # A new simulation thread is created
        if self.Simulation_stop():
            self.simulation = Simulation(self.OneStep)
            self.simulation.start()
        return True
        
    def Simulation_resume(self):
        return self.Simulation_launch()
Beispiel #37
0
def startStandalone():
    import Simulation
    print('MagneticPendulum  -Standalone')
    print('--------------------------------------------')
    print('Image resolution: {0}x{0} Output: {1}'.format(Parameter.RESOLUTION, Parameter.IMG_NAME))
    print('Working with {0} sub-processes in total.'.format(Parameter.MAX_PROCESSES))
    print('============================================')
    start = time.time()
    im= Image.new('RGB', (Parameter.RESOLUTION, Parameter.RESOLUTION))
    data = []
    pixel = [] + [0]*(Parameter.RESOLUTION**2)
    manager = Manager()
    coordinates = manager.Queue()
    values = manager.Queue()
    workerRunning = manager.Value('i', 0)
    Simulation.createAllCoordinates(coordinates, data) 
    while workerRunning.get() < Parameter.MAX_PROCESSES:
        Process(target=Simulation.workerThread,args=(coordinates, workerRunning, values)).start()
        time.sleep(1)
    while workerRunning.value > 0:
        Simulation.drawImage(im, data, pixel, values)
        time.sleep(Parameter.REPAINT)
    Simulation.drawImage(im, data, pixel, values)
    print('Image succeeded. Time consumed: {0:.2f}s'.format((time.time() - start)))
    print('Exiting...')
    sys.exit(0)     
def startServer():
    freeze_support()
    print('MagneticPendulum  -Cluster/Server')
    print('--------------------------------------------')
    print('Image resolution: {0}x{0} Output: {1}'.format(Parameter.RESOLUTION, Parameter.IMG_NAME))
    print('============================================')
    print('Now waiting to have some working clients.')
    import Simulation
    manager = ClusterQueueManager()
    data = []
    coordinates = manager.getCoordinates()
    values = manager.getValues()
    im= Image.new('RGB', (Parameter.RESOLUTION, Parameter.RESOLUTION))
    pixel = [] + [0]*(Parameter.RESOLUTION**2)
    Simulation.createAllCoordinates(coordinates, data)
    start = time.time()
    manager.start()
    while not coordinates.empty():
        while manager.getRunningClients() > 0:
            if not values.empty():
                Simulation.drawImage(im, data, pixel, values)
            time.sleep(Parameter.REPAINT)
        time.sleep(.5)
    print("Coordinates are now completely distributed.")
    
    while manager.getRunningClients() > 0:
        time.sleep(Parameter.REPAINT)
        print('Waiting for {0} clients to be done'.format(manager.getRunningClients()))
    Simulation.drawImage(im, data, pixel, values)
    print('Image succeeded. Time consumed: {0:.2f}s'.format((time.time() - start)))
    print('Exiting...')
    sys.exit(0)
    def run(self):
        while 1:
            try:
                # Waiting for client...
                self.__mainLogger.debug("CommandListener - Waiting on accept...")
                conn, (addr, port) = self.__sock.accept()
                self.__mainLogger.debug('CommandListener - Received command from (' + addr + ', ' + str(port) + ')')
                if addr not in cl.TRUSTED_CLIENTS:
                    self.__mainLogger.error(
                        'CommandListener - Received connection request from untrusted client (' + addr + ', ' + str(
                            port) + ')')
                    continue

                # Receive one message
                self.__mainLogger.debug('CommandListener - Receiving command...')
                recvOptions = recvOneMessage(conn)
                self.__mainLogger.debug('CommandListener - Received ' + str(recvOptions))

                if recvOptions.kill:
                    # Received killing command -> Stop everything
                    self.__thymioController.killRequest()
                    if self.__simulation:
                        self.__simulation.stop()
                    break
                elif recvOptions.start and (not self.__simulation or self.__simulation.isStopped()):
                    # Adding experiment number to pr.EXPERIMENT_NAME
                    experiment_name = pr.EXPERIMENT_NAME + "_" + str(self.__counter)
                    self.__counter += 1
                    # Received start request AND simulation is not running -> Start a new simulation
                    self.__mainLogger.debug("CommandListener - Starting simulation...")
                    self.__simulation = Simulation(self.__thymioController, recvOptions.debug, experiment_name)
                    self.__thymioController.setSimulation(self.__simulation)
                    self.__simulation.start()
                elif recvOptions.stop and self.__simulation and not self.__simulation.isStopped():  # TODO: Stop properly
                    # Received stop request AND simulation is up and running -> Stop the simulation
                    self.__mainLogger.debug("CommandListener - Stopping simulation...")
                    self.__simulation.stop()
                    self.__simulation = None
                elif recvOptions.stopthymio:
                    self.__mainLogger.debug("CommandListener - Stopping Thymio...")
                    self.__thymioController.stopThymio()

            except:
                self.__mainLogger.critical(
                    'Error in CommandsListener: ' + str(sys.exc_info()[0]) + ' - ' + traceback.format_exc())

        self.__mainLogger.debug('CommandListener - KILLED -> Exiting...')
def setup_cpus(options):
    # By default, set workload to path of user-specified binary
    workloads = options.cmd
    numThreads = 1

    if options.cpu_type == "detailed" or options.cpu_type == "inorder":
        # check for SMT workload
        workloads = options.cmd.split(";")
        if len(workloads) > 1:
            process = []
            smt_idx = 0
            inputs = []
            outputs = []
            errouts = []

            if options.input != "":
                inputs = options.input.split(";")
            if options.output != "":
                outputs = options.output.split(";")
            if options.errout != "":
                errouts = options.errout.split(";")

            for wrkld in workloads:
                smt_process = LiveProcess()
                smt_process.executable = wrkld
                smt_process.cmd = wrkld + " " + options.options
                if inputs and inputs[smt_idx]:
                    smt_process.input = inputs[smt_idx]
                if outputs and outputs[smt_idx]:
                    smt_process.output = outputs[smt_idx]
                if errouts and errouts[smt_idx]:
                    smt_process.errout = errouts[smt_idx]
                process += [smt_process]
                smt_idx += 1
        numThreads = len(workloads)

    (CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
    CPUClass.clock = options.clock
    CPUClass.numThreads = numThreads

    return (CPUClass, test_mem_mode, FutureClass)
##    p3 = 10
##    p4 = .1
##    p5 = 1000.
####    p1 = .001
##    p1 = 0.000
####    p2 = .007
####    p2 = 0.007
##    p2 = 0.0075
##    p3 = 10
##    p4 = 5E-4
##    p5 = 10.0

    #Now make a new simulation
    sim = Simulation(sim_id,
                     sim_base_path,
                     ts,
                     te,
                     dt)
    #add some gradients
##    #from Van Winkle et al 2012 for 02
##    D = 1.7e-9 / (1e-12) #um^2/sec
##    consump_rate = (4.0e-17)#*(10**6) mols/cell/sec #umols/cell/sec
##    #This value later gets normalized using the 
##    #set the outside concentration
##     outside_c = 1.04e-4*10**6 #(umol/L) or uM
    #from War-tenberg et al., 2001

    D = 10.0 # um^2/sec
    consump_rate = 2.0e-20 #mol/cell/sec
    production_rate = 2.0e-20
##    outside_c = .1 #umol/L or uM
Beispiel #42
0
Datei: fs.py Projekt: abusse/gem5
parser = optparse.OptionParser()
Options.addCommonOptions(parser)
Options.addFSOptions(parser)

# Add the ruby specific and protocol specific options
if '--ruby' in sys.argv:
    Ruby.define_options(parser)

(options, args) = parser.parse_args()

if args:
    print "Error: script doesn't take any positional arguments"
    sys.exit(1)

# system under test can be any CPU
(TestCPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)

# Match the memories with the CPUs, based on the options for the test system
TestMemClass = Simulation.setMemClass(options)

if options.benchmark:
    try:
        bm = Benchmarks[options.benchmark]
    except KeyError:
        print "Error benchmark %s has not been defined." % options.benchmark
        print "Valid benchmarks are: %s" % DefinedBenchmarks
        sys.exit(1)
else:
    if options.dual:
        bm = [SysConfig(disk=options.disk_image, rootdev=options.root_device,
                        mem=options.mem_size, os_type=options.os_type),
Beispiel #43
0
    # instantiate an EtherSwitch
    switch = EtherSwitch()
    # instantiate distEtherLinks to connect switch ports
    # to other gem5 instances
    switch.portlink = [DistEtherLink(speed = options.ethernet_linkspeed,
                                      delay = options.ethernet_linkdelay,
                                      dist_rank = options.dist_rank,
                                      dist_size = options.dist_size,
                                      server_name = options.dist_server_name,
                                      server_port = options.dist_server_port,
                                      sync_start = options.dist_sync_start,
                                      sync_repeat = options.dist_sync_repeat,
                                      is_switch = True,
                                      num_nodes = options.dist_size)
                       for i in xrange(options.dist_size)]

    for (i, link) in enumerate(switch.portlink):
        link.int0 = switch.interface[i]

    return switch
# Add options
parser = optparse.OptionParser()
Options.addCommonOptions(parser)
Options.addFSOptions(parser)
(options, args) = parser.parse_args()

system = build_switch(options)
root = Root(full_system = True, system = system)
Simulation.run(options, root, None, None)

Beispiel #44
0
  # Copyright © 2016 Jalel Benerrami. All rights reserved.
 
# from /Users/jalelbenerrami/Desktop/project_Python/Point2D import*
# from /Users/jalelbenerrami/Desktop/project_Python/Simulation import*

from Point2D import *
from Simulation import *

  #
  # Run programm by choosing parameters into the terminal
  #

# Number of random points
n = input("\nEnter the number of points you want to generate : ")
n = int(n)
print(n, "\n")    
    
# Choose a strategy
s = input("Choose a strategy : " )
s = int(s)
print(s, "\n")

# Create a simulation with given number of points
Sim = Simulation(n)
    
# Execute the created simulation
Sim.execute(s)
    
# Display the information about executed simulation
print(Sim, "\n")
    
Beispiel #45
0
if buildEnv['TARGET_ISA'] == "alpha":
    system = makeLinuxAlphaRubySystem(test_mem_mode, bm[0])
elif buildEnv['TARGET_ISA'] == "x86":
    system = makeLinuxX86System(test_mem_mode, options.num_cpus, bm[0], True)
    setWorkCountOptions(system, options)
else:
    fatal("incapable of building non-alpha or non-x86 full system!")

system.ruby = Ruby.create_system(options,
                                 system,
                                 system.piobus,
                                 system._dma_devices)

system.cpu = [CPUClass(cpu_id=i) for i in xrange(options.num_cpus)]

for (i, cpu) in enumerate(system.cpu):
    #
    # Tie the cpu ports to the correct ruby system ports
    #
    cpu.icache_port = system.ruby._cpu_ruby_ports[i].port
    cpu.dcache_port = system.ruby._cpu_ruby_ports[i].port
    if buildEnv['TARGET_ISA'] == "x86":
        cpu.itb.walker.port = system.ruby._cpu_ruby_ports[i].port
        cpu.dtb.walker.port = system.ruby._cpu_ruby_ports[i].port
        cpu.interrupts.pio = system.piobus.port
        cpu.interrupts.int_port = system.piobus.port

root = Root(system = system)

Simulation.run(options, root, system, FutureClass)
from Simulation import *
default = raw_input("Welcome. \n To use default settings, press y, else, press any other key" )
if default == 'y':
    print "Running simulator with default settings"
    run = Simulation(500,500,400,400,2)
else:
    x = raw_input("Enter quadcopter start x coordinate: ")
    y = raw_input("Enter quadcopter start y coordinate: ")
    tx = raw_input("Enter target x coordinate: ")
    ty = raw_input("Enter target y coordinate: ")
    difficulty = raw_input("Enter number of obstacles: ")
    run = Simulation(int(x),int(y),int(tx),int(ty),int(difficulty))

run.render()


# diffusion testing
IM = InternalModel()
IM.add_node('a') # no degradation

IM2 = InternalModel()
IM2.add_node('a','linear',params=[0.5])
IM2.add_node('b','linear',params=[1])
eid = IM2.add_edge('b','b','hill_activ',params=[1,1,2])
IM2.add_edge('a',eid,'lin_activ',is_mod=True,mod_type='mult',params=[5])

cell1 = Cell([0])
cell2 = Cell([1])
cell3 = Cell([3])

sim = Simulation()
sim.add_cell(cell1)
sim.add_cell(cell2)
sim.add_cell(cell3)

im_id = sim.add_internal_model(IM)
im_id2 = sim.add_internal_model(IM2)

connections = np.array([[True,True,False],[True,True,True],[False,True,True]])

sim.set_internal_model([0,1],im_id)
sim.set_internal_model([2],im_id2)
sim.add_interaction('a','a','diffusion',connections,params=[1])

sim.set_initial_conditions([0],{'a':0})
sim.set_initial_conditions([1],{'a':6})
Beispiel #48
0
                        app, options.spec_input))
            multiprocesses.append(workload.makeLiveProcess())
        except:
            print >>sys.stderr, "Unable to find workload for %s: %s" % (
                    buildEnv['TARGET_ISA'], app)
            sys.exit(1)
elif options.cmd:
    multiprocesses, numThreads = get_processes(options)
else:
    print >> sys.stderr, "No workload specified. Exiting!\n"
    sys.exit(1)

#JON_print_members(options, "OPTIONS", 156)


(CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
CPUClass.numThreads = numThreads

# Check -- do not allow SMT with multiple CPUs
if options.smt and options.num_cpus > 1:
    fatal("You cannot use SMT with multiple CPUs!")

np = options.num_cpus
system = System(cpu = [CPUClass(cpu_id=i) for i in xrange(np)],
                mem_mode = test_mem_mode,
                mem_ranges = [AddrRange(options.mem_size)],
                cache_line_size = options.cacheline_size)

# Create a top-level voltage domain
system.voltage_domain = VoltageDomain(voltage = options.sys_voltage)
IM.add_edge('sp',uy_edge,'hill_inactiv',is_mod=True,mod_type='mult',params=[1.0,1.0,0.145,20])

# mystery species m things
# u -> m
IM.add_edge('u','m','hill_activ',params=[1.0/Tm,4e-6,6])
# m -| yan
IM.add_edge('m',uy_edge,'hill_inactiv',is_mod=True,mod_type='mult',params=[1.0,1.0,0.7,3])

# need to make some cells 
# the 1d case is easy:
# in our 'lattice', all the cells are distance 1 apart
NCells = 60
cells = [Cell([x]) for x in np.linspace(1,NCells,NCells)]

# add these cells to the simulation
sim = Simulation()
for i in xrange(NCells):
    sim.add_cell(cells[i])

im_id = sim.add_internal_model(IM)

# set all cells to have the same internal model
sim.set_internal_model(range(NCells),im_id)

# set boundary conditions before setting intercellular interactions
sim.set_boundary_conditions([0],'ref_on')

# cells adjacent to one another are connected
# for diffusion we include main diagonal
# equivalent to 3 wide diagonal
diff_connections = (np.eye(NCells,k=-1) + np.eye(NCells,k=0) + np.eye(NCells,k=1)) > 0
# i: left -> right
# j: bottom -> top
centers = np.empty((NCells,2)) # a center for each cell
for i in xrange(ncolumns):
    for j in xrange(nrows):
        c = np.array([float(i) + 0.5*(j % 2),(np.sqrt(3)/2)*float(j)])
        centers[i + j*ncolumns,:] = c

# can add noise to centers
# centers += np.random.normal(0.0,0.15,(NCells,2))        

# place each cell at these vertices
cells = [Cell(c) for c in centers]

# add these cells to the simulation
sim = Simulation()
for i in xrange(NCells):
    sim.add_cell(cells[i])

im_id = sim.add_internal_model(IM)

# set all cells to have the same internal model
sim.set_internal_model(range(NCells),im_id)

# set up reflecting boundary conditions at bottom edge
# sim.set_boundary_conditions(range(ncolumns),'ref_on')
sim.set_boundary_conditions(range((nrows-1)*ncolumns,nrows*ncolumns),'abs_on')

# need to figure out which cells are connect to which
connections = np.zeros((NCells,NCells)) > 0 # default boolean false array
tri = Delaunay(centers)
        for wrkld in workloads:
            smt_process = LiveProcess()
            smt_process.executable = wrkld
            smt_process.cmd = wrkld + " " + options.options
            if inputs and inputs[smt_idx]:
                smt_process.input = inputs[smt_idx]
            if outputs and outputs[smt_idx]:
                smt_process.output = outputs[smt_idx]
            if errouts and errouts[smt_idx]:
                smt_process.errout = errouts[smt_idx]
            process += [smt_process, ]
            smt_idx += 1
    numThreads = len(workloads)

(CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
CPUClass.clock = options.clock
CPUClass.numThreads = numThreads;

system = System(cpu = [CPUClass(cpu_id=i) for i in xrange(np)],
                physmem = DRAM,
                membus = RR_CoherentBus(num_pids=options.numpids),
                #membus = CoherentBus(),                                        
                mem_mode = test_mem_mode,
                numPids = options.numpids,
                fast_forward = (options.fast_forward != None),
                fixAddr = options.fixaddr)

# Sanity check
if options.fastmem and (options.caches or options.l2cache):
    fatal("You cannot use fastmem in combination with caches!")
# i: left -> right
# j: bottom -> top
centers = np.empty((NCells,2)) # a center for each cell
for i in xrange(ncolumns):
    for j in xrange(nrows):
        c = np.array([float(i) + 0.5*(j % 2),(np.sqrt(3)/2)*float(j)])
        centers[i + j*ncolumns,:] = c

# can add noise to centers
# centers += np.random.normal(0.0,0.15,(NCells,2))        

# place each cell at these vertices
cells = [Cell(c) for c in centers]

# add these cells to the simulation
sim = Simulation()
for i in xrange(NCells):
    sim.add_cell(cells[i])

im_id = sim.add_internal_model(IM)

# set all cells to have the same internal model
sim.set_internal_model(range(NCells),im_id)

# set up reflecting boundary conditions at bottom edge
# sim.set_boundary_conditions(range(ncolumns),'ref_on')
# sim.set_boundary_conditions(range((nrows-1)*ncolumns,nrows*ncolumns),'abs_on')

# sim.set_boundary_conditions(range(ncolumns),'ref_on')
# sim.set_boundary_conditions(range((nrows-1)*ncolumns,nrows*ncolumns),'ref_on')
        else:
            rents_paid.append(rent)
            pos = (pos + moves_forward) % Simulation.no_of_squares

        # print moves_forward
        # print "Rent paid = ", rent
        # print "Current position = ", Simulation.square_names[pos], "\n"

        # Code for dice roll

        # If not IN JAIL, do a normal move
        if pos != -1:

            # print "Starting position = ", Simulation.square_names[pos]
            doubles, triples, mr_monopoly, bus_ticket, moves_forward = Simulation.roll_dice()

            square_ix = (pos + moves_forward) % Simulation.no_of_squares
            square_name = Simulation.square_names[(pos + moves_forward) % Simulation.no_of_squares]
            square_type = Simulation.square_type[square_ix]

            if square_type == 'RR':
                rent = Simulation.rent_value_3[square_ix]

            elif square_type == 'UY':
                rent = Simulation.rent_value_2[square_ix] / 10000 * moves_forward

            else:
                rent = Simulation.rent_value_S[square_ix]

            if rent < 0:
Beispiel #54
0
            else:
                exec("workload = %s(buildEnv['TARGET_ISA', 'linux', '%s')" % (
                        app, options.spec_input))
            multiprocesses.append(workload.makeLiveProcess())
        except:
            print >>sys.stderr, "Unable to find workload for %s: %s" % (
                    buildEnv['TARGET_ISA'], app)
            sys.exit(1)
elif options.cmd:
    multiprocesses, numThreads = get_processes(options)
else:
    print >> sys.stderr, "No workload specified. Exiting!\n"
    sys.exit(1)


(CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
CPUClass.numThreads = numThreads

# Check -- do not allow SMT with multiple CPUs
if options.smt and options.num_cpus > 1:
    fatal("You cannot use SMT with multiple CPUs!")

np = options.num_cpus
system = System(cpu = [CPUClass(cpu_id=i) for i in xrange(np)],
                mem_mode = test_mem_mode,
                mem_ranges = [AddrRange(options.mem_size)],
                cache_line_size = options.cacheline_size)

# Create a top-level voltage domain
system.voltage_domain = VoltageDomain(voltage = options.sys_voltage)
Beispiel #55
0
def main(start_day=1, end_day=80, extend_days=0, price_per_kg=0.25, food_cost=0.35, facility_cost=2.89, r_value=0.00, cycles_per_year=2, restriction=0.05):

	sim = Simulation(start_day, end_day, extend_days, price_per_kg, food_cost, facility_cost, r_value, cycles_per_year, restriction)
	sim.simulate()
	sim.print_end_costs()
	return sim
Beispiel #56
0
execfile(os.path.join(config_root, "common", "Options.py"))

(options, args) = parser.parse_args()

if args:
    print "Error: script doesn't take any positional arguments"
    sys.exit(1)

# driver system CPU is always simple... note this is an assignment of
# a class, not an instance.
DriveCPUClass = AtomicSimpleCPU
drive_mem_mode = 'atomic'

# system under test can be any CPU
(TestCPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)

TestCPUClass.clock = '2GHz'
DriveCPUClass.clock = '2GHz'

if options.benchmark:
    try:
        bm = Benchmarks[options.benchmark]
    except KeyError:
        print "Error benchmark %s has not been defined." % options.benchmark
        print "Valid benchmarks are: %s" % DefinedBenchmarks
        sys.exit(1)
else:
    if options.dual:
        bm = [SysConfig(), SysConfig()]
    else:
Beispiel #57
0
if options.benchmark:
    try:
        bm = Benchmarks[options.benchmark]
    except KeyError:
        print "Error benchmark %s has not been defined." % options.benchmark
        print "Valid benchmarks are: %s" % DefinedBenchmarks
        sys.exit(1)
else:
    bm = [SysConfig(disk=options.disk_image, mem=options.mem_size)]

# Check for timing mode because ruby does not support atomic accesses
if not (options.cpu_type == "detailed" or options.cpu_type == "timing"):
    print >> sys.stderr, "Ruby requires TimingSimpleCPU or O3CPU!!"
    sys.exit(1)
(CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)

CPUClass.clock = options.clock

if buildEnv['TARGET_ISA'] == "alpha":
    system = makeLinuxAlphaRubySystem(test_mem_mode, bm[0])
elif buildEnv['TARGET_ISA'] == "x86":
    system = makeLinuxX86System(test_mem_mode, options.num_cpus, bm[0], True)
    #system = addExternalDisk(system)
    Simulation.setWorkCountOptions(system, options)
else:
    fatal("incapable of building non-alpha or non-x86 full system!")
if options.mem_size:
    bm[0]=SysConfig(disk=bm[0].disk, mem=options.mem_size,script=bm[0].script())
if options.kernel is not None:
    system.kernel = binary(options.kernel)
Beispiel #58
0
from Simulation import *
from function_names import *
import numpy as np
from numpy import *

functions = {}
args = {}
real_fun(functions)

states = genfromtxt('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj7state.txt', delimiter=',',dtype=float32)
actions = genfromtxt('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj7action.txt' ,dtype=float32)


T,d = states.shape
#Create simulation
Sim = Simulation(function=functions["Traj7"], args=[[0,0,3],0])
Sim.restart()

for x in range(T):
    Sim.forward(actions[x,:].tolist())
    #Sim.forward()
    print(controller.getDif(Sim.cid,Sim.copter,Sim.target))
    print(actions[x,:])
    raw_input()
    Sim.sync()