Пример #1
0
	def test_multiple_dimensions(self):
		'''Simulator: Running a multidimensional simulator returns the correct result.'''
		simulator = Simulator({(0, .3): 1.0, (.3, .7): 0, (.7, 1): -1.0}, 3, 3, seed=1234)
		self.assertTrue(np.array_equal(simulator.run(), np.array(
			[[1, 0, 0],
			[-1, -1, 1],
			[1, -1, -1]]
			)))
Пример #2
0
 def __init__(self, parent = None):
     QDialog.__init__(self, parent)
     self.setupUi(self)
     self.simulator=Simulator()
     self.displaytext = ''
     self.thread1 = Thread()
     self.thread2 = Thread()
     self.opentxt=None
     self.savetxt=None
     self.loadyet = False
     self.terminateFlag = False
     self.connect(self.thread1, SIGNAL("next()"), self.step)
     self.connect(self.thread1, SIGNAL("terminate()"), self.terminate)
     self.connect(self.loadButton,SIGNAL("clicked()"),self.openFile)
     self.connect(self.saveButton,SIGNAL("clicked()"),self.saveFile)
     self.connect(self.runButton,SIGNAL("clicked()"),self.run)
     self.connect(self.pauseButton,SIGNAL("clicked()"),self.pause)
     #self.connect(self.begin,SIGNAL("clicked()"),self.loadFile)
     self.connect(self.stepButton,SIGNAL("clicked()"),self.step)
     self.connect(self.backButton,SIGNAL("clicked()"),self.back)
     self.connect(self.resetButton,SIGNAL("clicked()"),self.reset)
     self.frequency.setText('2.0s')
     highlighter.MyHighlighter1( self.Code, 'Classic' )
     highlighter.MemoryHighlighter( self.Memory, 'Classic' )
     highlighter.CacheHighlighter(self.Cache, 'Classic')
Пример #3
0
def S_c(c):
  
  from Simulator import *
  import numpy as np
  
  s = Simulator(50000, 5.0e-3, c)
  s.trajectory()
  #s.draw_trajectory()
  #s.draw_energy()
  #m = s.force_dipole()
  #print m
  #c = s.correlation(10000)
  #print c
  t,x = s.correlation_spectrum(110.0,100)
  spec = s.correlation_integral(100.0,t,x)
  return spec
Пример #4
0
def runRoutesOverDays(s, dates, routesFile):
    messageLimit = 10
    warningLimit = 10
    
    rawInstructions = Serialization.loadInstructionsFromFile(routesFile)
#    if Array.length parseWarnings > 0 then
#        printfn "%d instruction parse warnings" (Array.length parseWarnings)    
    routes = InstructionParser.ConvertRawInstructions(s.projection, rawInstructions)
    flightCountsAndCosts = {}

    for date in dates:
#        weather = s.weather[date]
        flights = s.flights[date]
        airports = s.airports #.[date]
        airspace = s.airspace[date]

        print "Simulating " + str(date)
#        airports = None
#        print routes
#        raw_input('routes')
        weather = None
        results = Simulator.simulateFlights(s.simulationParameters,
                                            airports,
                                            airspace,
                                            weather,
                                            flights,
                                            routes)
        # return a map of FlightId to 
     #   print results
     #   raw_input('next')
#        countArrived = [ x.ReachedDestination for x in results]
#        cost = [x.Cost for x in results]
        flightCosts = {} 
        cost = []
        countArrived = 0
        for k, v in results.iteritems():
            flightCosts[k] = v['CostDetail']
            countArrived += 1 if v['ReachedDestination'] else 0
            cost.append(v['Cost']) 
        print 'countArrived'
        print countArrived
        print 'cost'
        print cost
        flightCountsAndCosts[date] = {
            'date' : date,
            'flightCount' : countArrived,
            'meanCost' : sum(cost) / len(cost),
            #flightLogs = logs
            'flightCosts' : flightCosts
        }
    return flightCountsAndCosts
Пример #5
0
 def reset(self):
     self.thread1.terminate()
     self.simulator=Simulator()
     self.loadFile()
     for item in [self.ZF, self.SF, self.OF, 
             self.F_stat, self.F_predPC, 
             self.D_stat,self.D_icode,self.D_ifun, self.D_rA, self.D_rB, self.D_valC, self.D_valP, 
             self.E_stat,self.E_icode, self.E_ifun,self.E_valC, self.E_valA, self.E_valB, self.E_srcA, self.E_srcB, self.E_dstE, self.E_dstM, 
             self.M_stat,self.M_icode,self.M_bch,  self.M_valE, self.M_valA, self.M_dstE, self.M_dstM, 
             self.W_stat, self.W_icode, self.W_valE, self.W_valM, self.W_dstE, self.W_dstM, 
             self.eax, self.ecx, self.edx, self.ebx, self.esp, self.ebp, self.esi, self.edi, self.cycle]:
         item.clear()
     self.runButton.setEnabled(True)
     self.stepButton.setEnabled(True)
     self.backButton.setEnabled(True)
Пример #6
0
	def test_returns_correct_result(self):
		'''Simulator: running a one-dimensional simulator returns the correct result'''
		simulator = Simulator({(0, .51): 1.0, (.51, 1): -1.0}, 1, 1, seed=1234)

		self.assertEqual(simulator.run(), np.array([[1.0]]))
		self.assertEqual(simulator.run(), np.array([[-1.0]]))
		self.assertEqual(simulator.run(), np.array([[1.0]]))
		self.assertEqual(simulator.run(), np.array([[-1.0]]))
		self.assertEqual(simulator.run(), np.array([[-1.0]]))
		self.assertEqual(simulator.run(), np.array([[1.0]]))


		simulator = Simulator({(0, .51): 1.0, (.51, 1): -1.0}, 1, 5, seed=1234)
		self.assertTrue(np.array_equal(simulator.run(), np.array([[1, -1, 1, -1, -1]])))

		# Make sure a single outcome returns a single result
		simulator = Simulator({(0, 1): 21}, 1, 5, seed=1234)
		self.assertTrue(np.array_equal(simulator.run(), np.array([[21, 21, 21, 21, 21]])))
Пример #7
0
def J(hgt_spd, fullCoreFunctions, simulationParameters, 
                         airportEnvironment, 
                         airspace,
                         costParameters, weather, flightState, 
                         flightParams, instruction):
    """
    hgt_spd is a list of  length twice as instruction
    first half of hgt_spd is the altitude / 10000 
    send half of hgt_spd is air speed / 400
    """
    hgt_spd = bulk_hgt_spd (hgt_spd, len(instruction))
    
    hgt_spd = [np.max([1e-2,ii]) for ii in  hgt_spd]
    cur_instruction = update_instr(hgt_spd, instruction)
    result = Simulator.simulateFlight(fullCoreFunctions, simulationParameters, 
                         airportEnvironment, 
                         airspace,
                         costParameters, weather, flightState, 
                         flightParams, cur_instruction) 

    return result['Cost']
Пример #8
0
def J(hgt_spd, fullCoreFunctions, simulationParameters, 
                         airportEnvironment, 
                         airspace,
                         costParameters, weather, flightState, 
                         flightParams, instruction):
    """
    hgt_spd is a list of  length twice as instruction
    first half of hgt_spd is the altitude / 10000 
    send half of hgt_spd is air speed / 400
    """
    
    if np.min(hgt_spd) < 0:
        import pdb
        pdb.set_trace()
    cur_instruction = update_instr(hgt_spd, instruction)
    result = Simulator.simulateFlight(fullCoreFunctions, simulationParameters, 
                         airportEnvironment, 
                         airspace,
                         costParameters, weather, flightState, 
                         flightParams, cur_instruction) 

    print result['Cost'] 
    return result['Cost']
Пример #9
0
class TestSimulator(TestCase):
    """
    Tests for ``Simulator`` implementation.
    """
    def setUp(self):
        self.sim = Simulator()

    def test_update(self):
        """
        Tests that the update functions returns an object of World type.
        """
        self.assertIsInstance(self.sim.update(), World)

    def test_get_generation(self):
        """
        Tests whether get_generation returns the correct value:
            - Generation should be 0 when Simulator just created;
            - Generation should be 2 after 2 updates.
        """
        self.assertIs(self.sim.generation, self.sim.get_generation())
        self.assertEqual(self.sim.get_generation(), 0)
        self.sim.update()
        self.sim.update()
        self.assertEqual(self.sim.get_generation(), 2)

    def test_get_world(self):
        """
        Tests whether the object passed when get_world() is called is of World type, and has the required dimensions.
        When no argument passed to construction of Simulator, world is square shaped with size 20.
        """
        self.assertIs(self.sim.world, self.sim.get_world())
        self.assertEqual(self.sim.get_world().width, 20)
        self.assertEqual(self.sim.get_world().height, 20)

    def test_set_world(self):
        """
        Tests functionality of set_world function.
        """
        world = World(10)
        self.sim.set_world(world)
        self.assertIsInstance(self.sim.get_world(), World)
        self.assertIs(self.sim.get_world(), world)

    def test_rules(self):
        """"
        Tests the basic set of rules on https://canvas.hu.nl/courses/20308/assignments/108690

        Sets a random amount (max. a quarter of the grid) of squares with status 1.

        Loops through every single square in the grid.
            Gets the amount of neighbors.
            Gets the status of the previous generation.

            A cell with three neighbours, should always be alive in the next generation
            despite if it was previously alive or not. (birth)

            A cell with two neighbours, should be alive in the next generation if it was alive
            in the generation prior to that. A dead cell with two neighbours stays dead. (survival)

            A cell with one or less, or four or more neighbours are always dead in the next
            generation (exposure/overcrowding)
        """
        for _ in range(
                randint(0,
                        (self.sim.world.width * self.sim.world.height) / 4)):
            self.sim.world.set(randint(0, self.sim.world.width),
                               randint(0, self.sim.world.height), 1)

        self.worldOld = deepcopy(
            self.sim.world
        )  # Deep copies the old instance of the world, to compare it with later.
        self.sim.update()  # Go to the next generation in the original world.

        #  For every position in the grid.
        for x in range(self.sim.world.width):
            for y in range(self.sim.world.height):
                neighborCount = np.count_nonzero(
                    self.worldOld.get_neighbours(
                        x, y))  # Counts amount of neighbours.

                status = self.worldOld.get(
                    x, y)  # Gets the old status of cell (dead/alive, 0/1)

                if 2 <= neighborCount <= 3:
                    if neighborCount == 3:  # Cells with three neighbours should ALWAYS be alive in generation n+1.
                        self.assertEqual(self.sim.world.get(x, y), 1)

                    elif neighborCount == 2:  # Cells with two neighbors should stay unchanged (survival).
                        if status == 0:  # Dead cells with two neighbors should stay dead.
                            self.assertEqual(self.sim.world.get(x, y), 0)

                        elif status != 0:  # Alive cells with two neighbors should stay alive.
                            self.assertEqual(self.sim.world.get(x, y), 1)

                else:  # If a cell has less than two, or more than three neighbours, they die (exposure/overcrowding).
                    self.assertEqual(self.sim.world.get(x, y), 0)
Пример #10
0
import scipy
import matplotlib.pyplot as plt

import ObjectLibrary as OL
import FunctionLibrary as FL
import Ship_nofilter as Ship
import Simulator as S
import KalmanFilter as KF

f = open('log', 'w')
'''
SIMULATION STEP 1
Read / Generate coast, initialize simulator
'''
coastlength = 600
Sim = S.Simulator()

coast = Sim.SimulateCoast(coastlength)
startpos = OL.O_PosData(-80, -80, 1, 0)
Sim.SetDynamicModel(1, 1, 1, 1, 1, startpos)
'''
EMBEDDED STEP 1
Init AAUSHIP
'''
Startpos = OL.O_PosData(-80, -80, 0, 1)
AAUSHIP = Ship.O_Ship(Startpos, f)
'''
EMBEDDED OPTIONAL STEP 2/A
Waypoint planning
'''
Пример #11
0
            allocs[n,:]=row
            n = n+1
  allocs = allocs[0:n,:]
  print allocs
  print len(allocs)
  return allocs

if __name__ == '__main__':
  symbols = ['AXP', 'HPQ', 'IBM', 'HNZ']
  synbols = ['AAPL', 'GOOG', 'IBM', 'MSTF']
  startdate = dt.datetime(2011, 1, 1)
  enddate = dt.datetime(2011, 12, 31)
  allocation = [0.2, 0.2, 0.2, 0.4]
  minAllocatioon = allocation
  #result = s.simulate(startdate, enddate, symbols, allocation)
  maxResult = s.simulate(startdate, enddate, symbols, allocation)
  minResult = maxResult  
  matrix = np.array(map(list, filter(lambda x: sum(x) == 1, itertools.product(np.linspace(0,1,11), repeat=4))))
  count = len(matrix)
  #matrix = np.array([[0.2, 0.2, 0.2, 0.4], [0.5, 0.0, 0.5, 0.0], [0.1, 0.1, 0.8, 0.0], [0.2, 0.0, 0.8, 0.0]])
  #matrix = matrix2()
  print '%d = %d' % (count, len(matrix))
  
  for i in range(0, len(matrix)):
    local = s.simulate(startdate, enddate, symbols, matrix[i])
    print '%s = %f ' % (matrix[i], local[2])
    if (maxResult[2] < local[2]):
      maxResult = local
      allocation = matrix[i]
    if (minResult[2] > local[2]):
      minResult = local
Пример #12
0
 def press_(self):
     Simulator.delay(1.2)
     TimedActionFixture.press_(self)
Пример #13
0
convergeNumTaps = range(0,38,2)
#snapNumTaps = range(12,42,2)
#convergeNumTaps = range(0,30,2)
bands = [0.0, 1, 2, 50.0]
weights = [1, 0]

# Simulate the transmission and part of the reconstruction
startTimeTotal = time.time()
testData = []
staticJumps = [ [ [], [], [] ], 
			    [ [], [], [] ],
				[ [], [], [] ],
			    [ [], [], [] ] ]
for inputFile in inputFiles:
	simulationData = sim.simulateTransmission(inputFile, logDir, predictionInterval, 
											  samplingInterval, heartbeat, drThreshold, 
											  delay, jitter, packetLoss)
	simNumber = inputFile.split('/')[-2][-1]
	snapReconstruction = sim.simulateSnapRecon(simulationData[4], logDir, simNumber, samplingInterval)[0]
	snapLimitReconstruction = sim.simulateSnapLimitRecon(simulationData[4], logDir, simNumber, samplingInterval,
														 interpolationType, closeThreshold, snapLimit)[0]
	convergedReconstruction = sim.simulateLinearConvergence(simulationData[4], logDir, simNumber, samplingInterval,
						  			                 		interpolationType, closeThreshold)[0]
	testData.append([simulationData[0], simulationData[4], snapReconstruction, 
					 snapLimitReconstruction, convergedReconstruction])
	
	# Find intra-sample jump
	threshold = 0
	spacing = 1
	jumpDataSets = []
	jumpDataSets.append( sim.findDistanceBetweenSamples(simulationData[0], threshold, spacing) )
startTimeTotal = time.time()
transmittedData = []
for i, networkParam in enumerate(networkParams):
	delay = networkParam[0]
	jitter = networkParam[1]
	packetLoss = networkParam[2]
	transmittedData.append([])
	print "Simulating the transmission for network params: " + \
	      str(delay) + " " + str(jitter) + " " + str(packetLoss)
	
	for inputFile in inputFiles:
		simNumber = inputFile.split('/')[-2][-1]
		print "Simulating the transmission for data set: " + str(simNumber)

		data = s.transmitData(inputFile, logDir, predictionInterval,
							  samplingInterval, heartbeat, drThreshold,
							  delay, jitter, packetLoss)
		transmittedData[-1].append(data)
	print

print "Total time spent simulating the transmission: " + str(time.time() - \
															 startTimeTotal)
print
	
# Simulate the reconstruction of the data
#------------------------------------------------------------------------------
startTimeRecon = time.time()
for i, txDataSets in enumerate(transmittedData):
	startTimeData = time.time()
	networkParam = networkParams[i]
	delay = networkParam[0]
Пример #15
0
import Simulator
import YourController
import YourObserver

your_controller=YourController.controller()
your_observer=YourObserver.observer()
your_simulator=Simulator.simulator(total_step=1000,simulation_cycle=0.01,controller=your_controller,
                                    observer=your_observer,GUI=True)
your_simulator.run()

Пример #16
0
from Visualisation import *
from Simulator import *
import time

# Configuratie
VISUALISATION = True

if __name__ == "__main__":
    w = World(110)
    sim = Simulator(w)

    change_parameters = input(
        'Do you wanna change the parameters? Right now we are using the standard B3/S23 rules. (Y/N): '
    )
    if change_parameters == 'Y' or 'y':
        survived = []
        birthed = []
        while True:
            survive = input(
                'What number of neighbours do you want a cell to have in order to surive? (name one number): '
            )
            continuee = input('Do you want to add another number?: ')
            if type(survive) != int and 0 <= int(survive) <= 8:
                survived.append(int(survive))
            if continuee != 'Y' and continuee != 'y':
                break

        while True:
            birth = input(
                'What number of neighbours do you want a dead cell to have in order to become alive? (name one number): '
            )
Пример #17
0
import Simulator
import pygame
import numpy as np
from sklearn.preprocessing import StandardScaler
import ai_model


def get_action():
    max_ = len(simulator.control_manager.controls)
    return np.random.randint(0, max_)


simulator = Simulator.Simulator('172.16.175.136')
# simulator = Simulator.Simulator()

model = ai_model.Model(simulator, 6, len(simulator.control_manager.controls))

running = simulator.running
observation = simulator.get_observation()
prev = pygame.time.get_ticks()
curr_reward = 0
clock = pygame.time.Clock()

while running:
    action = model.predict(observation)
    curr = pygame.time.get_ticks()
    observation, reward, done, _ = simulator.step(action)
    curr_reward += reward
    if (curr - prev) > 1000 / 200:
        # print("Reward: ",simulator.reward_system.curr_reward)
        # print(observation, end='\n\n')
    def _runSimulation(self, parameters, initValues, blocks, threads):

        totalThreads = blocks * threads
        experiments = len(parameters)

        #simulation specific parameters
        param = np.zeros(
            (totalThreads / self._beta + 1, self._parameterNumber),
            dtype=np.float32)
        try:
            for i in range(experiments):
                for j in range(self._parameterNumber):
                    param[i][j] = parameters[i][j]
        except IndexError:
            pass

        if (not self._putIntoShared):
            # parameter texture
            ary = sim.create_2D_array(param)
            sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4,
                                     totalThreads / self._beta + 1)
            self._param_tex.set_array(ary)
            sharedMemoryParameters = 0
        else:
            # parameter shared Mem
            sharedMemoryParameters = self._parameterNumber * (
                threads / self._beta + 2) * 4

        sharedMemoryPerBlockForRNG = threads / self._warp_size * self._state_words * 4
        sharedTot = sharedMemoryPerBlockForRNG + sharedMemoryParameters

        if (self._putIntoShared):
            parametersInput = np.zeros(self._parameterNumber * totalThreads /
                                       self._beta,
                                       dtype=np.float32)
        speciesInput = np.zeros(self._speciesNumber * totalThreads,
                                dtype=np.float32)
        result = np.zeros(self._speciesNumber * totalThreads *
                          self._resultNumber,
                          dtype=np.float32)

        #non coalesced
        try:
            for i in range(len(initValues)):
                for j in range(self._speciesNumber):
                    speciesInput[i * self._speciesNumber +
                                 j] = initValues[i][j]
        except IndexError:
            pass
        if (self._putIntoShared):
            try:
                for i in range(experiments):
                    for j in range(self._parameterNumber):
                        parametersInput[i * self._parameterNumber +
                                        j] = parameters[i][j]
            except IndexError:
                pass

        #set seeds using python rng
        seeds = np.zeros(totalThreads / self._warp_size * self._state_words,
                         dtype=np.uint32)
        for i in range(len(seeds)):
            seeds[i] = np.uint32(4294967296 * np.random.uniform(0, 1))
            #seeds[i] =  np.random.random_integers(0,4294967295)

        species_gpu = driver.mem_alloc(speciesInput.nbytes)
        if (self._putIntoShared):
            parameters_gpu = driver.mem_alloc(parametersInput.nbytes)
        seeds_gpu = driver.mem_alloc(seeds.nbytes)
        result_gpu = driver.mem_alloc(result.nbytes)

        driver.memcpy_htod(species_gpu, speciesInput)
        if (self._putIntoShared):
            driver.memcpy_htod(parameters_gpu, parametersInput)
        driver.memcpy_htod(seeds_gpu, seeds)
        driver.memcpy_htod(result_gpu, result)

        # run code
        if (self._putIntoShared):
            self._compiledRunMethod(species_gpu,
                                    parameters_gpu,
                                    seeds_gpu,
                                    result_gpu,
                                    block=(threads, 1, 1),
                                    grid=(blocks, 1),
                                    shared=sharedTot)
        else:
            self._compiledRunMethod(species_gpu,
                                    seeds_gpu,
                                    result_gpu,
                                    block=(threads, 1, 1),
                                    grid=(blocks, 1),
                                    shared=sharedTot)

        # fetch from GPU memory
        driver.memcpy_dtoh(result, result_gpu)

        # reshape result
        result = result[0:experiments * self._beta * self._resultNumber *
                        self._speciesNumber]
        result.shape = (experiments, self._beta, self._resultNumber,
                        self._speciesNumber)

        return result
Пример #19
0
#Author: Alex Dawson-Elli
"""
noseTests.py:
provides tests for the methods and data structures used in
this project. The tests are organized by class, and can be 
run from the command line, using the nosetest command
"""
#-------------------------import libraries------------------------------
import Simulator as Sim
import AnalysisTools as Analysis
from nose.tools import *

#-------------------------Simulator Tests--------------------------------

#instantiate Simulator object
sim = Sim.Simulator()


def test_simulateTime():
    t1 = sim.simulateTime()
    t2 = sim.simulateTime()
    assert t1 - t2 == 0.0


def test_packageSample():
    sample = sim.packageSample(123.456, (0.0, 3.5, 0.0))
    assert sample['time'] == 123.456
    assert sample['orientation'] == (0.0, 3.5, 0.0)
    assert sample == {'time': 123.456, 'orientation': (0.0, 3.5, 0.0)}

    sample = sim.packageSample(0.0, (0, 0, 0))
Пример #20
0
 def initializeState(self, state):
     self.simulator = Simulator.Simulator(self.simulation_duration, self.dt)
     self.s = state
Пример #21
0
def main():

    SynUI = UI.SynapseUI(className='Synapse UI')
    SynUI.initialize(Sim.Simulator())
    SynUI.mainloop()
Пример #22
0
 def setUp(self):
     self.sim = Simulator()
Пример #23
0
    def handle(self, event):  # event = air event
        if event.m_event_type is AirportEvent.PLANE_ARRIVES:
            self.m_in_the_air += 1
            event.m_arriving_time = Simulator.get_current_time()
            print(
                str(Simulator.get_current_time()) + ": " +
                str(event.m_plane.m_name) + " arrived at " +
                str(self.m_airport_name))
            if (Simulator.get_current_time() -
                    self.old_weather_time) >= self.duration:
                rnd = random.randint(0, len(self.weather_array) - 1)
                self.weather = self.weather_array[rnd]
                self.duration = 10 - (
                    Simulator.get_current_time() -
                    (self.old_weather_time + self.duration)) % 10
                self.old_weather_time = Simulator.get_current_time()
            if not self.weather:
                temp = AirportEvent(event.m_plane, 1, self,
                                    AirportEvent.PLANE_ARRIVES, 3)
                Simulator.schedule(temp)
            else:
                self.arriving_queue.put(event)
                if self.m_land_1:
                    self.m_land_1 = False
                    first_arriving_event_1 = self.arriving_queue.get(
                    )  # airport Event
                    print(
                        str(Simulator.get_current_time()) + ": " +
                        str(event.m_plane.m_name) +
                        " start landing at the first landing runway of " +
                        str(self.m_airport_name))
                    first_arriving_event_1.m_arrived_time = Simulator.get_current_time(
                    )
                    self.m_circling_time += first_arriving_event_1.get_wait_time(
                    )

                    self.m_arriving_passengers += first_arriving_event_1.m_plane.m_number_passengers

                    landed_event_1 = AirportEvent(
                        first_arriving_event_1.m_plane,
                        self.m_runway_time_to_land, self,
                        AirportEvent.PLANE_LANDED, 0)
                    Simulator.schedule(landed_event_1)

                elif self.m_land_2:
                    self.m_land_2 = False
                    first_arriving_event_2 = self.arriving_queue.get(
                    )  # airport Event
                    print(
                        str(Simulator.get_current_time()) + ": " +
                        str(event.m_plane.m_name) +
                        " start landing at the first landing runway of " +
                        str(self.m_airport_name))
                    first_arriving_event_2.m_arrived_time = Simulator.get_current_time(
                    )
                    self.m_circling_time += first_arriving_event_2.get_wait_time(
                    )

                    self.m_arriving_passengers += first_arriving_event_2.m_plane.m_number_passengers

                    landed_event_2 = AirportEvent(
                        first_arriving_event_2.m_plane,
                        self.m_runway_time_to_land, self,
                        AirportEvent.PLANE_LANDED, 0)
                    Simulator.schedule(landed_event_2)

        if event.m_event_type is AirportEvent.PLANE_TAKEOFF:
            if (Simulator.get_current_time() -
                    self.old_weather_time) >= self.duration:
                rnd = random.randint(0, len(self.weather_array) - 1)
                self.weather = self.weather_array[rnd]
                self.duration = 10 - (
                    Simulator.get_current_time() -
                    (self.old_weather_time + self.duration)) % 10
                self.old_weather_time = Simulator.get_current_time()
            if not self.weather:
                temp = AirportEvent(event.m_plane, 1, self,
                                    AirportEvent.PLANE_DEPARTS, 3)
                Simulator.schedule(temp)
            else:
                self.departure_queue.put(event)
                if self.m_takeoff_1:
                    self.m_takeoff_1 = False
                    first_departure_event = self.departure_queue.get()
                    print(
                        str(Simulator.get_current_time()) + ": " +
                        str(first_departure_event.m_plane.m_name) +
                        " takeoff from the first takeoff runway of" +
                        str(self.m_airport_name))
                    takeoff_event = AirportEvent(
                        first_departure_event.m_plane,
                        self.m_runway_time_to_take_off, self,
                        AirportEvent.PLANE_DEPARTS, 2)
                    Simulator.schedule(takeoff_event)

        if event.m_event_type is AirportEvent.PLANE_DEPARTS:
            self.m_on_the_ground -= 1
            print(
                str(Simulator.get_current_time()) + ": " +
                str(event.m_plane.m_name) + " departs from " +
                str(self.m_airport_name))
            event.m_plane.set_number_passengers()
            self.m_departing_passengers += event.m_plane.m_number_passengers
            airport_1 = self.m_airport_name
            index = random.randint(0, len(AirportSim.airports) - 1)
            while AirportSim.airports[index] is self:
                index = random.randint(0, len(AirportSim.airports) - 1)
            destination = AirportSim.airports[index]
            airport_2 = destination.m_airport_name
            distance = Airport.cal_distance(airport_1, airport_2)
            speed = event.m_plane.m_speed
            self.m_flight_time = distance / speed
            temp = event.m_plane

            self.gas_consumed_traveling += temp.cal_gas(
                self.m_flight_time, temp.gas_speed_traveling)

            depart_event = AirportEvent(temp, self.m_flight_time, destination,
                                        AirportEvent.PLANE_ARRIVES,
                                        3)  # airport event
            Simulator.schedule(depart_event)
            if self.departure_queue.qsize() is not 0:
                first_departure_event = self.departure_queue.get()
                print(
                    str(Simulator.get_current_time()) + ": " +
                    str(first_departure_event.m_plane.m_name) +
                    " takeoff from the first takeoff runway of " +
                    str(self.m_airport_name))
                takeoff_event = AirportEvent(first_departure_event.m_plane,
                                             self.m_runway_time_to_take_off,
                                             self, AirportEvent.PLANE_DEPARTS,
                                             2)
                Simulator.schedule(takeoff_event)
            else:
                self.m_takeoff_1 = True

        if event.m_event_type is AirportEvent.PLANE_LANDED:
            self.m_in_the_air -= 1
            self.m_on_the_ground += 1
            print(
                str(Simulator.get_current_time()) + ": " +
                str(event.m_plane.m_name) + " lands at " +
                str(self.m_airport_name))
            departure_event = AirportEvent(event.m_plane,
                                           self.m_required_time_on_ground,
                                           self, AirportEvent.PLANE_TAKEOFF, 2)
            Simulator.schedule(departure_event)
            runway = event.m_runway
            if runway == 0:
                self.m_land_1 = True
            if runway == 1:
                self.m_land_2 = True
            if self.arriving_queue.qsize() != 0:
                if self.m_land_1:
                    self.m_land_1 = False
                    first_arriving_event_1 = self.arriving_queue.get()
                    print(
                        str(Simulator.get_current_time()) + ": " +
                        str(first_arriving_event_1.m_plane.m_name) +
                        " start landing at the first landing runway of " +
                        str(self.m_airport_name))
                    first_arriving_event_1.m_arrived_time = Simulator.get_current_time(
                    )
                    self.m_circling_time += first_arriving_event_1.get_wait_time(
                    )

                    temp_1 = event.m_plane

                    self.gas_consumed_circulating += temp_1.cal_gas(
                        first_arriving_event_1.get_wait_time(),
                        temp_1.gas_speed_circulating)

                    print("airport" + str(self.m_airport_name) +
                          "circulating time1" + str(self.m_circling_time))
                    print("airport" + str(self.m_airport_name) +
                          "circulating gas consume" +
                          str(self.gas_consumed_circulating))

                    self.m_arriving_passengers += first_arriving_event_1.m_plane.m_number_passengers

                    landed_event_1 = AirportEvent(
                        first_arriving_event_1.m_plane,
                        self.m_runway_time_to_land, self,
                        AirportEvent.PLANE_LANDED, 0)
                    Simulator.schedule(landed_event_1)
                elif self.m_land_2:
                    self.m_land_2 = False
                    first_arriving_event_2 = self.arriving_queue.get()
                    print(Simulator.get_current_time() + ": " +
                          first_arriving_event_2.m_plane.m_name +
                          " start landing at the first landing runway of " +
                          self.m_airport_name)
                    first_arriving_event_2.m_arrived_time = Simulator.get_current_time(
                    )
                    self.m_circling_time += first_arriving_event_2.get_wait_time(
                    )

                    temp_2 = event.m_plane()

                    self.gas_consumed_circulating += temp_2.cal_gas(
                        first_arriving_event_2.get_wait_time(),
                        temp_2.gas_speed_circulating)

                    print("airport" + self.m_airport_name +
                          "circulating time2" + self.m_circling_time)
                    print("airport" + self.m_airport_name +
                          "circulating gas consume" +
                          self.gas_consumed_circulating)

                    self.m_arriving_passengers += first_arriving_event_2.m_plane.m_number_passengers

                    landed_event_2 = AirportEvent(
                        first_arriving_event_2.m_plane,
                        self.m_runway_time_to_land, self,
                        AirportEvent.PLANE_LANDED, 1)
                    Simulator.schedule(landed_event_2)
Пример #24
0
packetLoss = 0

# Filter parameters
samplingFreq = 100
numberOfTaps = range(2,52,2)
weights = [1, 0]
minFreq = 0
maxFreq = 50
cutoffFreqs = [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]

# Simulate the transmission
startTimeTotal = time.time()
testData = []
for inputFile in inputFiles:
	simulationData = sim.simulateTransmission(inputFile, logDir, predictionInterval, 
											  samplingInterval, heartbeat, drThreshold, 
											  delay, jitter, packetLoss)
	simNumber = inputFile.split('/')[-2][-1]
	reconstruction = sim.simulateSnapRecon(simulationData[4], logDir, simNumber, samplingInterval)
	testData.append([simulationData[0], reconstruction[0]])
	
# Simulate the quality for different filters
print
print "Curves: " + str(len(cutoffFreqs))
print "Taps: " + str(len(numberOfTaps))
print "Data Sets: " + str(len(testData))

errorCurves = []
delayCurves = []
for cutoffFreq in cutoffFreqs:
	print "Working on filter with cutoff frequency: " + str(cutoffFreq)
Пример #25
0
from Visualisation import *
from Simulator import *
import time

# Configuratie
VISUALISATION = True

if __name__ == "__main__":
    w = World(110)
    sim = Simulator("B3/S23/A5", w)

    if VISUALISATION:
        vis = Visualisation(sim)
    else:
        while True:
            # Create new world and print to screen
            print(sim.update())
            # slow down simulation
            time.sleep(0.5)
Пример #26
0
        if len(split_input) == 3:
            b, s, a = split_input[:3]

            b = [int(con) for con in b[1:]]
            s = [int(con) for con in s[1:]]
            a = int(a[1:])
        elif len(split_input) == 2:
            b, s = split_input[:2]
            b = [int(con) for con in b[1:]]
            s = [int(con) for con in s[1:]]
            a = None
        else:
            b = [3]
            s = [2, 3]
            a = None
    else:
        b = [3]
        s = [2, 3]
        a = None

    print(f"Rules;\nb={b}\ts={s}\ta={a}")
    sim = Simulator(w, b=b, s=s, a=a)

    if VISUALISATION:
        vis = Visualisation(sim)
    else:
        while True:
            # Create new world and print to screen
            print(sim.update())
            # slow down simulation
            time.sleep(0.5)
Пример #27
0
from Simulator import *
import time
start_time = time.time()

sim = Simulator(100000)

field = sim.readFile("Initial_setup.txt")


for i in range(4):
    print("Start position", [0 + i, 1])
    red_prob, blue_prob, draw_prob, average_moves, average_moves_red, average_moves_blue, spies_prob = sim.runSimulation([0 + i, 1], field)

    print("Probability that red wins: %s." % round(red_prob[1], 4), "Confidence interval: %s - %s." % (round(red_prob[0], 4), round(red_prob[2], 4))) 
    print("Probability that blue wins: %s." % round(blue_prob[1], 4), "Confidence interval: %s - %s." % (round(blue_prob[0], 4), round(blue_prob[2], 4))) 
    print("Probability of a draw: %s." % round(draw_prob[1], 4), "Confidence interval: %s - %s." % (round(draw_prob[0], 4), round(draw_prob[2], 4))) 
    print("Average moves: %s." % round(average_moves[1], 4), "Confidence interval: %s - %s." % (round(average_moves[0], 4), round(average_moves[2], 4))) 
    print("Average moves given red wins: %s." % round(average_moves_red[1], 4), "Confidence interval: %s - %s." % (round(average_moves_red[0], 4), round(average_moves_red[2], 4))) 
    print("Average moves given blue wins: %s." % round(average_moves_blue[1], 4), "Confidence interval: %s - %s." % (round(average_moves_blue[0], 4), round(average_moves_blue[2], 4))) 
    print("Probability that both spies live: %s." % round(spies_prob[1], 4), "Confidence interval: %s - %s." % (round(spies_prob[0], 3), round(spies_prob[2], 4))) 
    print("")
    
print("--- %s seconds ---" % (time.time() - start_time))
Пример #28
0
from Visualisation import *
from Simulator import *
import time
import random

# Configuratie
VISUALISATION = True

if __name__ == "__main__":
    w = World(20)
    rule = 'b3s23'
    sim = Simulator(w, rule)

    # quick and dirty start setup
    for x in range(sim.get_world().width):
        for y in range(sim.get_world().height):
            if random.randint(0, 1) == 1:
                sim.get_world().set(x, y, 6)

    if VISUALISATION:
        vis = Visualisation(sim)
    else:
        while True:
            # Create new world and print to screen
            print(sim.update())
            # slow down simulation
            time.sleep(0.5)
Пример #29
0
weights = [1, 0]
coefficients = scipy.signal.remez(taps, bands, weights, Hz=samplingFreq)
gain = 1.0 / sum(coefficients)
snapCoefficients = scipy.signal.remez(snapTaps, bands, weights, Hz=samplingFreq)
snapGain = 1.0 / sum(snapCoefficients)

# Plotting paramters
plotTimeDomain = True
plotFreqDomain = True
plotStatistics = True

# Simulate the algorithms
simNumber = inputFile.split('/')[-2][-1]
 
data = s.transmitData(inputFile, logDir, predictionInterval, 
					  samplingInterval, heartbeat, drThreshold, 
					  delay, jitter, packetLoss)
										
rawInputData = data[0]
filteredInputData = data[1]
predictedData = data[2]
drTxPackets = data[3]
drRxPackets = data[4]
drRxFilteredPackets = data[5]
										
snapReconData = s.snapReconstructData(drRxFilteredPackets, logDir, simNumber, samplingInterval)[0]
snapLimitReconData = s.snapLimitReconstructData(drRxFilteredPackets, logDir, simNumber, samplingInterval,
												interpolationType, closeReconThreshold, snapLimit)[0]
closeConvergedData = s.convergeData(drRxFilteredPackets, logDir, simNumber, samplingInterval,
					  			    interpolationType, closeReconThreshold)[0]
farConveredData = s.convergeData(drRxFilteredPackets, logDir, simNumber, samplingInterval,
Пример #30
0
lowerTime = 18000
upperTime = 26500
yMax = 0.45
yMin = 0.05
useDb = False
errorBins = 50
jumpBins = 100
plotTimeDomain = True
plotFreqDomain = False
plotError = False
plotJump = False

# Simulate the algorithms
simNumber = inputFile.split('/')[-2][-1]

data = s.transmitData(inputFile, logDir, predictionInterval, samplingInterval,
                      heartbeat, drThreshold, delay, jitter, packetLoss)

rawInputData = data[0]
filteredInputData = data[1]
predictedData = data[2]
drTxPackets = data[3]
drRxPackets = data[4]
drRxFilteredPackets = data[5]

snapReconData = s.snapReconstructData(drRxFilteredPackets, logDir, simNumber,
                                      samplingInterval)[0]

closeRelSnapLimitData = s.snapLimitReconstructData(drRxFilteredPackets, logDir,
                                                   simNumber, samplingInterval,
                                                   interpolationType,
                                                   SnapLimitType.Relative,
Пример #31
0
convergenceTime = 50
longConvergenceTime = 100

# Calculation parameters
#------------------------------------------------------------------------------
jumpThreshold = 0
jumpSpacing = 1

# Simulate the transmission and reconstruction algorithms
#------------------------------------------------------------------------------
startTimeTotal = time.time()
transmittedData = []
simNumber = inputFile.split('/')[-2][-1]

data = s.transmitData(inputFile, logDir, predictionInterval,
					  samplingInterval, heartbeat, drThreshold,
					  delay, jitter, packetLoss)
snapData = s.snapReconstructData(data[5], 
								 logDir, 
								 simNumber, 
								 samplingInterval)[0]								
convergeData = s.convergeData(data[5], logDir, simNumber, samplingInterval,
			   				  convergenceTime)[0]								
varConvergeData = s.varConvergeData(data[5], logDir, simNumber, samplingInterval,
								    convergenceTime, longConvergenceTime)[0]

data.append(snapData)
data.append(convergeData)
data.append(varConvergeData)

print "Total time spent simulating the transmission: " + str(time.time() - \
Пример #32
0
def runcap():
 import Simulator
 Simulator.run(createCapsule(1,'top'))
Пример #33
0
g_Cs = g_C * np.logspace(-1, 1, num=5)
# gamma_Cs = gamma_C * np.logspace(-1, 1, num=3)
Rs = R * np.logspace(-1, 1, num=5)

r = (25 * ureg.micrometer).to_base_units().magnitude
sigma = (5 * ureg.micrometer).to_base_units().magnitude

hbar = hbar.to_base_units().magnitude
charT = 1 / gamma_C
charL = 1 * np.sqrt(hbar / (2 * m * me * gamma_C))

ringParams = Simulator.ParameterContainer(g_C=g_C,
                                          g_R=g_R,
                                          gamma_C=gamma_C,
                                          gamma_R=gamma_R,
                                          R=R,
                                          m=m,
                                          charL=charL,
                                          charT=charT)
params = ringParams.getGPEParams()

P0 = 4.0 * params['Pth']
pump = UtilityFunctions.AnnularPump(r, P0, sigma)
pumpFunction = pump.scaledFunction(ringParams.charL)
# Make Grid
grid = Simulator.Grid(ringParams.charL, max_XY=max_XY_unscaled, N=N)

x, y = grid.getSpatialGrid()
x_us, y_us = grid.getSpatialGrid(scaled=False)
solver = Simulator.GPESolver(
    params,
Пример #34
0
jitter = 40
packetLoss = 0
reconThresh = 140
reconThresholds = range(20,510, 20)
jumpThreshold = 0.01
spacing = 1

# Output results
errors = []
deltaInput = []
deltaSnap = []
deltaConverge = []

# Simulate the transmission
simulationData = sim.simulateTransmission(inputFile, logDir, predictionInterval, 
										  samplingInterval, heartbeat, drThreshold, 
										  delay, jitter, packetLoss)
inputData = simulationData[0]
snapRxData = sim.simulateSnapRecon(simulationData[4], logDir, "_ex1", samplingInterval)[0]
convergeRxData = sim.simulateLinearConvergence(simulationData[4], logDir, "_ex1", samplingInterval,
									   	   	   interpolationType, reconThresh)[0]

deltaInput = sim.findDistanceBetweenSamples(inputData, jumpThreshold, spacing)
deltaSnap = sim.findDistanceBetweenSamples(snapRxData, jumpThreshold, spacing)	
deltaConverge = sim.findDistanceBetweenSamples(convergeRxData, jumpThreshold, spacing)

inputData = sim.splitData(inputData)
snapRxData = sim.splitData(snapRxData)
convergeTxData = sim.splitData(convergeRxData)
																	
#for reconThreshold in reconThresholds:
Пример #35
0
class TestSimulator(TestCase):
    """
    Tests for ``Simulator`` implementation.
    """
    def setUp(self):
        self.sim = Simulator()

    def test_update(self):
        """
        Tests that the update functions returns an object of World type.
        """
        self.assertIsInstance(self.sim.update(), World)

    def test_get_generation(self):
        """
        Tests whether get_generation returns the correct value:
            - Generation should be 0 when Simulator just created;
            - Generation should be 2 after 2 updates.
        """
        self.assertIs(self.sim.generation, self.sim.get_generation())
        self.assertEqual(self.sim.get_generation(), 0)
        self.sim.update()
        self.sim.update()
        self.assertEqual(self.sim.get_generation(), 2)

    def test_get_world(self):
        """
        Tests whether the object passed when get_world() is called is of World type, and has the required dimensions.
        When no argument passed to construction of Simulator, world is square shaped with size 20.
        """
        self.assertIs(self.sim.world, self.sim.get_world())
        self.assertEqual(self.sim.get_world().width, 20)
        self.assertEqual(self.sim.get_world().height, 20)

    def test_set_world(self):
        """
        Tests functionality of set_world function.
        """
        world = World(10)
        self.sim.set_world(world)
        self.assertIsInstance(self.sim.get_world(), World)
        self.assertIs(self.sim.get_world(), world)
Пример #36
0
lowerTime = 18000
upperTime = 26500
yMax = 0.45
yMin = 0.05

# Simulate the algorithm
stepFunc = []
for i in range(0,5001, 10):
	if i < 200:
		stepFunc.append( Sample(i, 0, 0, 0) )
	else:
		stepFunc.append( Sample(i, 1, 1, 1) )
	
predictor = DRPredictor()
predictedData = predictor.getPredictedData(stepFunc, predictionInterval, samplingInterval)	
s.exportData(logDir + "PredictionData.txt", predictedData)
transmitter = DRTransmitter(heartbeat)
drTxPackets = transmitter.getTransmittedPackets(.9, predictedData)
s.exportData(logDir + "TransmittedData.txt", drTxPackets)
network = Network()
drRxPackets = network.getReceivedPackets(drTxPackets, delay, jitter, packetLoss)
s.exportData(logDir + "ReceivedData.txt", drRxPackets)
receiver = Receiver()
drRxFilteredPackets = receiver.getFilteredData(drRxPackets)	
s.exportData(logDir + "FilteredData.txt", drRxFilteredPackets)							
convergedData = s.convergeData(drRxFilteredPackets, logDir, "-", samplingInterval,
					  		   interpolationType, reconstructionThreshold)[0]

iData = [ [] ] * 4
cData = [ [] ] * 4
Пример #37
0
class TestSimulator(TestCase):
    """
    Tests for ``Simulator`` implementation.
    """
    def setUp(self):
        self.sim = Simulator()

    def test_update(self):
        """
        Tests that the update functions returns an object of World type.
        """
        self.assertIsInstance(self.sim.update(), World)

    def test_get_generation(self):
        """
        Tests whether get_generation returns the correct value:
            - Generation should be 0 when Simulator just created;
            - Generation should be 2 after 2 updates.
        """
        self.assertIs(self.sim.generation, self.sim.get_generation())
        self.assertEqual(self.sim.get_generation(), 0)
        self.sim.update()
        self.sim.update()
        self.assertEqual(self.sim.get_generation(), 2)

    def test_get_world(self):
        """
        Tests whether the object passed when get_world() is called is of World type, and has the required dimensions.
        When no argument passed to construction of Simulator, world is square shaped with size 20.
        """
        self.assertIs(self.sim.world, self.sim.get_world())
        self.assertEqual(self.sim.get_world().width, 20)
        self.assertEqual(self.sim.get_world().height, 20)

    def test_set_world(self):
        """
        Tests functionality of set_world function.
        """
        world = World(10)
        self.sim.set_world(world)
        self.assertIsInstance(self.sim.get_world(), World)
        self.assertIs(self.sim.get_world(), world)

    def test_cell_survive(self):
        # minder dan 2 levende cellen = dood
        self.assertEqual(self.sim.check_cell_survive((2,3,5, 7, 8),[0, 0, 0, 0, 0, 0, 0, 0]), 0)
        self.assertEqual(self.sim.check_cell_survive((2,3,5, 7, 8),[0, 1, 0, 0, 0, 0, 0, 0]), 0)

        # 2 of 3 levende cellen = levend
        self.assertEqual(self.sim.check_cell_survive((2,3,5, 7, 8),[0, 0, 0, 1, 0, 1, 0, 0]), 1)
        self.assertEqual(self.sim.check_cell_survive((2,3,5, 7, 8),[0, 0, 0, 1, 1, 1, 0, 0]), 1)

        # meer dan 3 levende cellen = dood
        self.assertEqual(self.sim.check_cell_survive([0, 1, 1, 0, 1, 1, 0, 1]), 0)


    def get_rule_set(self):

        self.assertEqual(self.sim.get_rule_set("B358/S237"), (2,3,5, 7, 8))
        self.assertEqual(self.sim.get_ruleset("B3/S23"), (2, 3))
        self.assertEqual(self.sim.get_ruleset("B/S"), ())
Пример #38
0
dataRoot = "/Users/fstakem/Data/Movements_5_1_08/"
root = "/Users/fstakem/Research/PhD/2010_Research/OptimalFiltering/"
logDir = root + "code/log/"
outputDir = root + "code/output/"
movement = "Stacking"
inputFile = inputFile = dataRoot + movement + "/Simulation" + str(1) + "/positionLog.txt"

# Parameters for all algorithms
samplingInterval = 10
numPoints = 131072

# Importing the raw data
print "Importing data..."
importer = Importer()
rawInputData = importer.getInputData(inputFile, samplingInterval)
s.exportData(logDir + "RawInputData.txt", rawInputData)

# Filtering input data
print "Filtering data..."
samplingFreq = int(1e3/samplingInterval)
taps = 80
bands = [0.0, 10, 11, 50.0]
weights = [1, 0]
coefficients = scipy.signal.remez(taps, bands, weights, Hz=samplingFreq)
gain = 1.0 / sum(coefficients)
filteredInputData = s.filterData(rawInputData, logDir, "cc", samplingInterval, coefficients)[0]
filteredInputData = s.amplifyData(filteredInputData, gain)
s.exportData(logDir + "FilteredInputData.txt", filteredInputData)

# FFT the data
print "Analyzing the data..."
Пример #39
0
# start server
def bore():
    print("creating..")
    Constants.simulator = Simulator()
    startClient()
    log.startLogging(sys.stdout)
    factory = WebSocketServerFactory(u"ws://127.0.0.1:50050")
    factory.protocol = MyServerProtocol
    reactor.listenTCP(50050, factory)
    reactor.run()
    # p.join()


def startClient():
    server_address = 'localhost'
    client_socket = socket.socket()
    port = 7555
    client_socket.connect(('localhost', port))
    print('Connected to %s on port %s' % (server_address, port))
    Constants.chat_client = client_socket


if __name__ == '__main__':
    # bore()
    Constants.simulator = Simulator()
    Constants.simulator.start()
    #startClient()
    Constants.simulator.loop()
# sim = Simulator()
# sim.loop()
Пример #40
0
'''
Created on 13 Mar 2013

@author: thomas
'''
import datetime as dt
import Simulator as s

if __name__ == '__main__':
  symbols = ["AAPL", "GOOG", "XOM", "GLD"]
  startdate = dt.datetime(2011, 1, 1)
  enddate = dt.datetime(2011, 12, 31)
  allocation = [0.4, 0.0, 0.2, 0.4]
  result = s.simulate(startdate, enddate, symbols, allocation)
  print 'Sharpe ratio: %.11f' % (result[2])
  print 'Volatility %.13f' % (result[0])
  print 'Average Daily Return %.15f' % (result[1])
  print 'Cumulatative return %.11f' % (result[-1])
Пример #41
0
from Visualisation import *
from Simulator import *
import time

# Configuratie
VISUALISATION = True

if __name__ == "__main__":
    w = World(110)
    sim = Simulator(w, 'B3/S23/A5', age=True)

    if VISUALISATION:
        vis = Visualisation(sim)
    else:
        while True:
            # Create new world and print to screen
            print(sim.update())
            # slow down simulation
            time.sleep(0.5)
Пример #42
0
    # Training neural network.
    print("Training network")
    trainer = BackpropTrainer(
        net, dataset=sequenceDataSet, learningrate=0.01, lrdecay=1, momentum=0, weightdecay=0, verbose=True
    )

    if validationTraining:
        trainer.trainUntilConvergence(verbose=True, maxEpochs=100, validationProportion=0.2)
    else:
        for i in range(trainingTimes):
            trainer.train()

            if not i % 10:
                print("Iteration: " + str(i) + " out of " + str(trainingTimes))

    print("Training finished")


"""
    Trained network is saved here.
"""
if saveNetwork:
    pickle.dump(net, open(networkFilename, "wb"))


# testNetwork(net)


if doFaceTest:
    Simulator.testFace(enviroment, tests, speedPreferences, distPreferences, updateTime, robotHeight, net)
Пример #43
0
	outputStats.append([])
	
	for convergenceTime in convergenceTimes:
		outputData[-1].append([])
		outputStats[-1].append([])

# Simulate the transmission of the data
#------------------------------------------------------------------------------
startTimeTotal = time.time()
transmittedData = []
for inputFile in inputFiles:
	simNumber = inputFile.split('/')[-2][-1]
	print "Simulating the transmission for simulation: " + str(simNumber)

	data = s.transmitData(inputFile, logDir, predictionInterval,
						  samplingInterval, heartbeat, drThreshold,
						  delay, jitter, packetLoss)
	snapData = s.snapReconstructData(data[5], 
									 logDir, 
									 simNumber, 
									 samplingInterval)[0]
	filteredData = 	s.filterData(snapData, 
								 logDir, 
								 simNumber, 
							     samplingInterval, 
								 coefficients)[0]
	filteredData = s.amplifyData(filteredData, gain)
	
	data.append(snapData)
	data.append(filteredData)
	transmittedData.append(data)
Пример #44
0
  input_asm_ptr.close()
  for i_trc in range(len(input_trc_list)):
    input_trc_list_ptr[i_trc].close()

  # print(GlobalVar.allcontents_asm)

  Architecture.parseConfig()
  # Cache.parseConfig()
  # VLC.parseConfig()
  # Architecture.checkConfig()
  # Cache.checkConfig()
  # VLC.checkConfig()

  #################################################################

  u_simulator = Simulator()

  u_simulator.simulate()

  GlobalVar.outputptr.close()

  # for i in range(0, 100000):
  #   U_Cache.accessCache(random.randint((256*16)*500,(256*16)*512))
  # U_Cache.accessCache(1)
  # U_Cache.accessCache(12)
  # U_Cache.accessCache(14)
  # U_Cache.accessCache(16)
  # U_Cache.accessCache(10)
  # U_Cache.accessCache(16*256-1)
  # U_Cache.printInfo(-1)
Пример #45
0
                        help='Run on the simulator.',
                        action='store_true')
    parser.add_argument('--hw',
                        help='Run on the hardware.',
                        action='store_true')

    args = parser.parse_args()

    if (args.sim and args.hw) or (not args.sim and not args.hw):
        print("Please use --sim or --hw argument.")
        exit(1)

    if args.sim:
        # A bit of explaining here is needed, because I want to overwrite the GUI with our custom controller.
        # You don't want the simulator to make the GUI for you. So the GUI bool is set to False.
        simulator = Simulator.Simulator(False)

        Interface = SimulatorInterface.SimulatorInterface
        # ======================== SIMULATOR DEFINTIONS (SOFTWARE INTERFACE) ========================
        # Create effector objects
        pumpA = Interface.Effector(
            simulator._Simulator__plant._effectors['pumpA'])
        pumpB = Interface.Effector(
            simulator._Simulator__plant._effectors['pumpB'])
        valveA = Interface.Effector(
            simulator._Simulator__plant._effectors['valveA'])
        valveB = Interface.Effector(
            simulator._Simulator__plant._effectors['valveB'])
        heater = Interface.Effector(
            simulator._Simulator__plant._effectors['heater'])
Пример #46
0
 def feasible(self, position):
     A = sim.State_Space_mats(Gp_n, Gp_d, *position)[0]
     return sim.stable(A[0])
Пример #47
0
from Filters.RockFilter import RockFilter

discount = 0.9
numLocs = 2
numRocks = 2
rockLocs = [0, 0, 1, 1]
robotX, robotY = 0, 1

'''
numLocs = 7
numRocks = 8
rockLocs = [2, 0, 0, 1, 3, 1, 6, 3, 2, 4, 3, 4, 5, 5, 1, 6]
robotX, robotY = 0, 3
'''

rockQuality = [0.5] * numRocks
rockSampled = [0] * numRocks

initial_state = RockState(numLocs, numRocks, rockLocs, rockQuality, rockSampled, robotX, robotY)
goal_state = initial_state

operator_d =        {'amn': {'verbose': 'Moving north'},
                     'ams': {'verbose': 'Moving south'},
                     'ame': {'verbose': 'Moving east'},
                     'amw': {'verbose': 'Moving west'},
                     'as':  {'verbose': 'Sampling'},
                     'ac':  {'verbose': 'Checking rock %d'}}

sim = Simulator(operator_d, RockPlanner(discount),  RockFilter(), RockWorld())
sim.run_sim(initial_state, goal_state, verbose=True, slow=True)
Пример #48
0
rawInstructions = Serialization.loadInstructionsFromFile(routesFile)
# rawInstructions is a dict
rawInstructions[308567953]

s = configL
routes = InstructionParser.ConvertRawInstructions(s.projection, rawInstructions)
date = dates[0]
flights = s.flights[date]
airports = s.airports 
airspace = s.airspace[date]

print "Simulating " + str(date)
weather = None
results = Simulator.simulateFlights(s.simulationParameters,
                                    airports,
                                    airspace,
                                    weather,
                                    flights[1048:],
                                    routes)


# specify which flight you want to optimize
k = 1048
for flightEntry, costParameters in flights[k:(k+1)]:
        print flightEntry

instruction = routes[flightEntry.Id]
(flightParams, flightState) = FlightEntry.generateParametersAndState(
    airports, flightEntry)
airportEnvironment = None
#airportEnvironment = airports[flightEntry.ArrivalAirport][1] # TODO check the snd
fullCoreFunctions = SimulationTypes.SimulationCoreFunctions(
Пример #49
0
delay = 100
jitter = 40
packetLoss = 0
reconThresholds = range(20,510, 100)
jumpThreshold =0.001
spacing = 1

# Output results
errors = []
deltaInput = []
deltaSnap = []
deltaConverge = []

# Simulate the transmission
simulationData = sim.simulateTransmission(inputFile, logDir, predictionInterval, 
										  samplingInterval, heartbeat, drThreshold, 
										  delay, jitter, packetLoss)
inputData = simulationData[0]
deltaInput = sim.findDistanceBetweenSamples(inputData, jumpThreshold, spacing)
																			
for reconThreshold in reconThresholds:
	convergeTxData = sim.simulateLinearConvergence(simulationData[4], logDir, "_ex1", samplingInterval,
										   	   	   interpolationType, reconThreshold)
	snapRxData = sim.simulateSnapRecon(simulationData[4], logDir, "_ex1", samplingInterval)
	errors.append( sim.findDistanceError(inputData, convergeTxData[0]) )
	deltaSnap.append( sim.findDistanceBetweenSamples(snapRxData, jumpThreshold, spacing) )
	deltaConverge.append( sim.findDistanceBetweenSamples(convergeTxData, jumpThreshold, spacing) )

# Prepare the data for plotting
temp = []
for error in errors:
Пример #50
0
def test_Agents():
    prompt = "Please input which Step you'd like to test (0 through 5)\n"
    choice = input(prompt).strip()

    #Test cases for Step 0
    if choice == "0":

        #Testing general output
        for i in range(1000):
            assert 0 == agents.rock_strategy(), "rock_strategy is incorrect"
            assert 1 == agents.paper_strategy(), "paper_strategy is incorrect"
            assert 2 == agents.scissors_strategy(
            ), "scissors_strategy is incorrect"
            assert 0 <= agents.simple_strategy(
            ) <= 2, "simple_strategy is incorrect"

        #Testing simulator runs
        assert Simulator.simulator(
            agents.rock_strategy,
            agents.paper_strategy,
            simulation_count=1000,
            silent=True) == (0, 1, 0), "Simulation failed. Error in strategies"
        assert Simulator.simulator(
            agents.paper_strategy,
            agents.rock_strategy,
            simulation_count=1000,
            silent=True) == (1, 0, 0), "Simulation failed. Error in strategies"

        assert Simulator.simulator(
            agents.scissors_strategy,
            agents.rock_strategy,
            simulation_count=1000,
            silent=True) == (0, 1, 0), "Simulation failed. Error in strategies"
        assert Simulator.simulator(
            agents.rock_strategy,
            agents.scissors_strategy,
            simulation_count=1000,
            silent=True) == (1, 0, 0), "Simulation failed. Error in strategies"

        assert Simulator.simulator(
            agents.paper_strategy,
            agents.scissors_strategy,
            simulation_count=1000,
            silent=True) == (0, 1, 0), "Simulation failed. Error in strategies"
        assert Simulator.simulator(
            agents.scissors_strategy,
            agents.paper_strategy,
            simulation_count=1000,
            silent=True) == (1, 0, 0), "Simulation failed. Error in strategies"

        assert (
            Simulator.simulator(agents.rock_strategy,
                                agents.rock_strategy,
                                simulation_count=1000,
                                silent=True) == Simulator.simulator(
                                    agents.paper_strategy,
                                    agents.paper_strategy,
                                    simulation_count=1000,
                                    silent=True) == Simulator.simulator(
                                        agents.scissors_strategy,
                                        agents.scissors_strategy,
                                        simulation_count=1000,
                                        silent=True) == (0, 0, 1)
        ), "Simulation failed -- when run against each other, the strategies did not completely tie"

        #Simple strategy should always win 1/3, lose 1/3, and tie 1/3 -- no matter the complexity of its opponent
        sr = [
            round(x, 2) for x in Simulator.simulator(
                agents.simple_strategy, agents.rock_strategy, silent=True)
        ]
        sp = [
            round(x, 2) for x in Simulator.simulator(
                agents.simple_strategy, agents.paper_strategy, silent=True)
        ]
        ss = [
            round(x, 2) for x in Simulator.simulator(
                agents.simple_strategy, agents.scissors_strategy, silent=True)
        ]
        assert sr == sp == ss and sr[0] == sr[1] == sr[
            2] == .33, "Simulation failed. Error in strategies"

        print("Passed all tests -- Step 0 complete")

    #"One test I definitely want to do for agents is creating a smart strategy that specifically can trash a reflexive_strategy that ALWAYS picks a move "
    if choice == "1":

        always_rock = agents.biased_strategy(1, 0)
        always_paper = agents.biased_strategy(1, 1)
        always_scissors = agents.biased_strategy(1, 2)

        assert Simulator.simulator(
            agents.rock_strategy,
            always_rock,
            simulation_count=1000,
            silent=True
        ) == (
            0, 0, 1
        ), "Simulation Failed: biased_strategy(1, 0) does not always return rock"
        assert Simulator.simulator(
            agents.paper_strategy,
            always_paper,
            simulation_count=1000,
            silent=True
        ) == (
            0, 0, 1
        ), "Simulation Failed: biased_strategy(1, 0) does not always return paper"
        assert Simulator.simulator(
            agents.scissors_strategy,
            always_scissors,
            simulation_count=1000,
            silent=True
        ) == (
            0, 0, 1
        ), "Simulation Failed: biased_strategy(1, 0) does not always return scissors"

        never_rock = agents.biased_strategy(0, 0)
        never_paper = agents.biased_strategy(0, 1)
        never_scissors = agents.biased_strategy(0, 2)

        never_rock_results = [never_rock for i in range(1000)]
        never_paper_results = [never_paper for i in range(1000)]
        never_scissors_results = [never_scissors for i in range(1000)]

        assert 0 not in never_rock_results, "Error: Invalid value generation for biased_strategy(0, 0)"
        assert 1 not in never_paper_results, "Error: Invalid value generation for biased_strategy(0, 1)"
        assert 2 not in never_scissors_results, "Error: Invalid value generation for biased_strategy(0, 2)"
        print("Passed all tests -- Step 1 complete")

    if choice == "2":

        simple = agents.triple_biased_strategy(1 / 3, 1 / 3, 1 / 3)
        simple_test = simulator(simple_strategy,
                                simple,
                                simulation_count=100000,
                                silent=True)
        assert simple_test[0] >= 0.32 and simple_test[
            0] <= 0.34 and simple_test[1] >= 0.32 and simple_test[
                1] <= 0.34 and simple_test[2] >= 0.32 and simple_test[
                    2] <= 0.34, "Error"

        chance = [i / 1000 for i in range(1000)]
        #Maybe make a function to do this to efficiently assign paper_chance and scissors_chance to i?
        for i in chance:
            rock_chance = i
            paper_chance = round((1 - i) / 2, 3)
            scissors_chance = paper_chance
            strat = triple_biased_strategy(rock_chance, paper_chance,
                                           scissors_chance)
            results = [strat() for _ in range(1000)]
            rock_results = len([i for i in results if i == 0])
            paper_results = len([i for i in results if i == 1])
            scissors_results = len([i for i in results if i == 2])
            assert rock_results / len(
                results) >= rock_chance - 0.01 or rock_results / len(
                    results
                ) <= rock_chance + 0.01, "Check when you're returning rock"
            assert paper_results / len(
                results) >= paper_chance - 0.01 or paper_results / len(
                    results
                ) <= paper_chance + 0.01, "Check when you're returning paper"
            assert scissors_results / len(
                results
            ) >= scissors_chance - 0.01 or scissors_results / len(
                results
            ) <= scissors_chance + 0.01, "Check when you're returing scissors"
            #Try to incorporate History object
        print("Passed all tests -- Step 2 complete")

    if choice == "3":
        strat = agents.deterministic_strategy()
        deterministic_order = [0, 1, 2, 1, 0]
        simple_test_results = []
        for _ in range(len(deterministic_order)):
            simple_test_results.append(strat())
        assert simple_test_results == deterministic_order, "Failed simple test"

        for _ in range(10000):
            random_test_results = []
            strategy = agents.deterministic_strategy()
            turns = random.randint(1, 1000)
            for _ in range(turns):
                random_test_results.append(strategy())
            answer = deterministic_order * (turns // len(deterministic_order))
            for i in range(turns - len(answer)):
                answer.append(deterministic_order[i])

            assert answer == random_test_results, "Deterministic strategy does not match expected output"
        print("Passed all tests -- Step 3 complete")

    if choice == "4":
        agents.history = History.History(agents.rock_strategy,
                                         agents.reflexive_strategy)
        assert round(
            Simulator.simulator(agents.rock_strategy,
                                agents.reflexive_strategy,
                                history_storage=agents.history,
                                simulation_count=1000,
                                silent=True)[1]) == 1
        agents.history = History.History(agents.paper_strategy,
                                         agents.reflexive_strategy)
        assert round(
            Simulator.simulator(agents.paper_strategy,
                                agents.reflexive_strategy,
                                history_storage=agents.history,
                                simulation_count=1000,
                                silent=True)[1]) == 1
        agents.history = History.History(agents.scissors_strategy,
                                         agents.reflexive_strategy)
        assert round(
            Simulator.simulator(agents.scissors_strategy,
                                agents.reflexive_strategy,
                                history_storage=agents.history,
                                simulation_count=1000,
                                silent=True)[1]) == 1
        trials = 1000
        wins = 0
        for _ in range(trials):
            #generate 3 random numbers that add up to 1
            rates = np.random.random(3)
            rates /= rates.sum()
            #rates = (.1, .1, .8)
            strategy1 = agents.triple_biased_strategy(rates[0], rates[1],
                                                      rates[2])
            strategy2 = agents.reflexive_strategy

            agents.history = History.History(strategy1, strategy2)

            results = Simulator.simulator(strategy1,
                                          strategy2,
                                          history_storage=agents.history,
                                          simulation_count=1000,
                                          silent=True)
            if results[1] > results[0]:
                wins += 1
            if results[0] - results[1] > 0:
                assert results[0] - results[1] < 0.1
        assert wins / trials > 0.9, "error"

        print("Passed all tests -- Step 4 complete")

    if choice == "5":
        agents.history = History.History(agents.rock_strategy,
                                         agents.predictive_strategy)
        assert round(
            Simulator.simulator(agents.rock_strategy,
                                agents.predictive_strategy,
                                history_storage=agents.history,
                                simulation_count=1000,
                                silent=True)[1]) == 1

        agents.history = History.History(agents.paper_strategy,
                                         agents.predictive_strategy)
        assert round(
            Simulator.simulator(agents.paper_strategy,
                                agents.predictive_strategy,
                                history_storage=agents.history,
                                simulation_count=1000,
                                silent=True)[1]) == 1

        agents.history = History.History(agents.scissors_strategy,
                                         agents.predictive_strategy)
        assert round(
            Simulator.simulator(agents.paper_strategy,
                                agents.predictive_strategy,
                                history_storage=agents.history,
                                simulation_count=1000,
                                silent=True)[1]) == 1

        trials = 1000
        wins = 0
        for _ in range(trials):
            test_length = random.randint(2, 10)
            test_list = [random.randint(0, 2) for _ in range(test_length)]
            deterministic = deterministic_list(test_list)
            agents.history = History.History(deterministic,
                                             agents.predictive_strategy)
            result = Simulator.simulator(deterministic,
                                         agents.predictive_strategy,
                                         history_storage=agents.history,
                                         simulation_count=1000,
                                         silent=True)
            print(result)
            if result[0] < result[1]:
                wins += 1
        assert wins / trials >= 0.8, "Your strategy does not win enough"

        print("Passed all tests -- Step 5 complete")
files = len(inputFiles)

for convergenceTime in convergenceTimes:
	outputData.append([])
	outputStats.append([])
	
# Simulate the transmission of the data
#------------------------------------------------------------------------------
startTimeTotal = time.time()
transmittedData = []
for inputFile in inputFiles:
	simNumber = inputFile.split('/')[-2][-1]
	print "Simulating the transmission for simulation: " + str(simNumber)

	data = s.transmitData(inputFile, logDir, predictionInterval,
						  samplingInterval, heartbeat, drThreshold,
						  delay, jitter, packetLoss)
	transmittedData.append(data)

print "Total time spent simulating the transmission: " + str(time.time() - \
															 startTimeTotal)
print

# Simulate the reconstruction of the data
#------------------------------------------------------------------------------
# Simulate relative snap reconstruction
startTimeCon = time.time()
print "Simulating convergence reconstruction..."
for i, convergenceTime in enumerate(convergenceTimes):
	print "\t\tSimulating convergence time: " + str(convergenceTime)
	startTimeConverge = time.time()
Пример #52
0
def main():
    fileName = sys.argv[1]
    with open(fileName, 'r') as f:
        params = yaml.load(f)
    simulator = Simulator.Simulator(params)
    simulator.run(52)
upperTime = 26500
yMax = 0.45
yMin = 0.05
useDb = False
errorBins = 50
jumpBins = 100
plotTimeDomain = True
plotFreqDomain = False
plotError = False
plotJump = False

# Simulate the algorithms
simNumber = inputFile.split('/')[-2][-1]
 
data = s.transmitData(inputFile, logDir, predictionInterval, 
					  samplingInterval, heartbeat, drThreshold, 
					  delay, jitter, packetLoss)
										
rawInputData = data[0]
filteredInputData = data[1]
predictedData = data[2]
drTxPackets = data[3]
drRxPackets = data[4]
drRxFilteredPackets = data[5]
										
snapReconData = s.snapReconstructData(drRxFilteredPackets, logDir, simNumber, samplingInterval)[0]

closeRelSnapLimitData = s.snapLimitReconstructData(drRxFilteredPackets, logDir, simNumber, samplingInterval,
												    interpolationType, SnapLimitType.Relative, closeReconThreshold, 
												    closeRelSnapLimit)[0]
closeAbSnapLimitData = s.snapLimitReconstructData(drRxFilteredPackets, logDir, simNumber, samplingInterval,
Пример #54
0
    def _runSimulation(self,
                       parameters,
                       initValues,
                       blocks,
                       threads,
                       in_atol=1e-12,
                       in_rtol=1e-6):

        totalThreads = threads * blocks
        experiments = len(parameters)

        neqn = self._speciesNumber

        # compile
        timer = time.time()
        ## print "Init Common..",
        init_common_Kernel = self._completeCode.get_function("init_common")
        init_common_Kernel(block=(threads, 1, 1), grid=(blocks, 1))
        ## print "finished in", round(time.time()-timer,4), "s"

        start_time = time.time()
        # output array
        ret_xt = np.zeros(
            [totalThreads, 1, self._resultNumber, self._speciesNumber])

        # calculate sizes of work spaces
        isize = 20 + self._speciesNumber
        rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9)

        # local variables
        t = np.zeros([totalThreads], dtype=np.float64)
        jt = np.zeros([totalThreads], dtype=np.int32)
        neq = np.zeros([totalThreads], dtype=np.int32)
        itol = np.zeros([totalThreads], dtype=np.int32)
        iopt = np.zeros([totalThreads], dtype=np.int32)
        rtol = np.zeros([totalThreads], dtype=np.float64)
        iout = np.zeros([totalThreads], dtype=np.int32)
        tout = np.zeros([totalThreads], dtype=np.float64)
        itask = np.zeros([totalThreads], dtype=np.int32)
        istate = np.zeros([totalThreads], dtype=np.int32)
        atol = np.zeros([totalThreads], dtype=np.float64)

        liw = np.zeros([totalThreads], dtype=np.int32)
        lrw = np.zeros([totalThreads], dtype=np.int32)
        iwork = np.zeros([isize * totalThreads], dtype=np.int32)
        rwork = np.zeros([rsize * totalThreads], dtype=np.float64)
        y = np.zeros([self._speciesNumber * totalThreads], dtype=np.float64)

        for i in range(totalThreads):
            neq[i] = neqn
            #t[i] = self._timepoints[0]
            t[i] = 0
            itol[i] = 1
            itask[i] = 1
            istate[i] = 1
            iopt[i] = 0
            jt[i] = 2
            atol[i] = in_atol
            rtol[i] = in_rtol

            liw[i] = isize
            lrw[i] = rsize

            try:
                # initial conditions
                for j in range(self._speciesNumber):
                    # loop over species
                    y[i * self._speciesNumber + j] = initValues[i][j]
                    ret_xt[i, 0, 0, j] = initValues[i][j]
            except IndexError:
                pass

        # allocate on device
        d_t = driver.mem_alloc(t.size * t.dtype.itemsize)
        d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize)
        d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize)
        d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize)
        d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize)
        d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize)
        d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize)
        d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize)
        d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize)
        d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize)
        d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize)
        d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize)
        d_y = driver.mem_alloc(y.size * y.dtype.itemsize)
        d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize)
        d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize)
        d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize)

        # copy to device
        driver.memcpy_htod(d_t, t)
        driver.memcpy_htod(d_jt, jt)
        driver.memcpy_htod(d_neq, neq)
        driver.memcpy_htod(d_liw, liw)
        driver.memcpy_htod(d_lrw, lrw)
        driver.memcpy_htod(d_itol, itol)
        driver.memcpy_htod(d_iopt, iopt)
        driver.memcpy_htod(d_rtol, rtol)
        driver.memcpy_htod(d_iout, iout)
        driver.memcpy_htod(d_tout, tout)
        driver.memcpy_htod(d_itask, itask)
        driver.memcpy_htod(d_istate, istate)
        driver.memcpy_htod(d_y, y)
        driver.memcpy_htod(d_atol, atol)
        driver.memcpy_htod(d_iwork, iwork)
        driver.memcpy_htod(d_rwork, rwork)

        param = np.zeros((totalThreads, self._parameterNumber),
                         dtype=np.float32)
        try:
            for i in range(len(parameters)):
                for j in range(self._parameterNumber):
                    param[i][j] = parameters[i][j]
        except IndexError:
            pass

        # parameter texture
        ary = sim.create_2D_array(param)
        sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4,
                                 totalThreads)
        self._param_tex.set_array(ary)

        if self._dt <= 0:
            start_time = time.time()
            #for i in range(1,self._resultNumber):
            for i in range(0, self._resultNumber):

                for j in range(totalThreads):
                    tout[j] = self._timepoints[i]
                driver.memcpy_htod(d_tout, tout)

                self._compiledRunMethod(d_neq,
                                        d_y,
                                        d_t,
                                        d_tout,
                                        d_itol,
                                        d_rtol,
                                        d_atol,
                                        d_itask,
                                        d_istate,
                                        d_iopt,
                                        d_rwork,
                                        d_lrw,
                                        d_iwork,
                                        d_liw,
                                        d_jt,
                                        block=(threads, 1, 1),
                                        grid=(blocks, 1))

                driver.memcpy_dtoh(t, d_t)
                driver.memcpy_dtoh(y, d_y)
                driver.memcpy_dtoh(istate, d_istate)

                for j in range(totalThreads):
                    for k in range(self._speciesNumber):
                        ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]

            # end of loop over time points

        else:
            tt = self._timepoints[0]

            start_time = time.time()
            #for i in range(1,self._resultNumber):
            for i in range(0, self._resultNumber):
                while 1:

                    next_time = min(tt + self._dt, self._timepoints[i])

                    for j in range(totalThreads):
                        tout[j] = next_time
                    driver.memcpy_htod(d_tout, tout)

                    self._compiledRunMethod(d_neq,
                                            d_y,
                                            d_t,
                                            d_tout,
                                            d_itol,
                                            d_rtol,
                                            d_atol,
                                            d_itask,
                                            d_istate,
                                            d_iopt,
                                            d_rwork,
                                            d_lrw,
                                            d_iwork,
                                            d_liw,
                                            d_jt,
                                            block=(threads, 1, 1),
                                            grid=(blocks, 1))

                    driver.memcpy_dtoh(t, d_t)
                    driver.memcpy_dtoh(y, d_y)
                    driver.memcpy_dtoh(istate, d_istate)

                    if np.abs(next_time - self._timepoints[i]) < 1e-5:
                        tt = next_time
                        break

                    tt = next_time

                for j in range(totalThreads):
                    for k in range(self._speciesNumber):
                        ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k]

            # end of loop over time points

        return ret_xt[0:experiments]
Пример #55
0
 def evaluate(self, position):
     obj = sim.response_gen(
         tfinal, dt, Gp_n, Gp_d, SP, DT, u, *position)
     return cevaluation(position, array([obj[0], obj[1], obj[2], obj[3], obj[4]]))
Пример #56
0
# Network parameters
delay = 100
jitter = 20
packetLoss = 0

# Plotting paramters
lowerTime = 18000
upperTime = 26500
yMax = 0.45
yMin = 0.05

# Simulate the algorithms
simNumber = inputFile.split('/')[-2][-1]

data = s.transmitData(inputFile, logDir, predictionInterval, samplingInterval,
                      heartbeat, drThreshold, delay, jitter, packetLoss)

rawInputData = data[0]
filteredInputData = data[1]
predictedData = data[2]
drTxPackets = data[3]
drRxPackets = data[4]
drRxFilteredPackets = data[5]

snapReconData = s.snapReconstructData(drRxFilteredPackets, logDir, simNumber,
                                      samplingInterval)[0]
hydridSnapData = s.hydridSnapReconstructData(drRxFilteredPackets, logDir,
                                             simNumber, samplingInterval,
                                             interpolationType, snapLimitType,
                                             reconstructionThreshold,
                                             snapLimit)[0]
Пример #57
0
# Filesystem paramters
dataRoot = "/Users/fstakem/Data/Movements_5_1_08/"
root = "/Users/fstakem/Research/OptimalFiltering/"
logDir = root + "code/log/"
outputDir = root + "code/output/"
movement = "Stacking"
inputFile = dataRoot + movement + "/Simulation" + str(1) + "/positionLog.txt"
samplingInterval = 10
upperBounds = 1
lowerBounds = 1

# Import data
print "Importing data..."
importer = Importer()
inputData = importer.getInputData(inputFile, samplingInterval)
t1, x1, y1, z1 = sim.splitData(inputData)

# Filter parameters
samplingFreq = 100
taps = 80
bands = [0.0, 10, 11, 50.0]
weights = [1, 0]
coefficients = scipy.signal.remez(taps, bands, weights, Hz=samplingFreq)
gain = 1.0 / sum(coefficients)

filteredData = sim.simulateFilterRecon(inputData, logDir, "cc", samplingInterval, coefficients)[0]
sim.amplifyData(filteredData, gain)
t2, x2, y2, z2 = sim.splitData(filteredData)

# Plot data
pylab.figure(1)
Пример #58
0
upperTime = 26500
yMax = 0.45
yMin = 0.05

# Simulate the algorithm
stepFunc = []
for i in range(0, 5001, 10):
    if i < 200:
        stepFunc.append(Sample(i, 0, 0, 0))
    else:
        stepFunc.append(Sample(i, 1, 1, 1))

predictor = DRPredictor()
predictedData = predictor.getPredictedData(stepFunc, predictionInterval,
                                           samplingInterval)
s.exportData(logDir + "PredictionData.txt", predictedData)
transmitter = DRTransmitter(heartbeat)
drTxPackets = transmitter.getTransmittedPackets(.9, predictedData)
s.exportData(logDir + "TransmittedData.txt", drTxPackets)
network = Network()
drRxPackets = network.getReceivedPackets(drTxPackets, delay, jitter,
                                         packetLoss)
s.exportData(logDir + "ReceivedData.txt", drRxPackets)
receiver = Receiver()
drRxFilteredPackets = receiver.getFilteredData(drRxPackets)
s.exportData(logDir + "FilteredData.txt", drRxFilteredPackets)
convergedData = s.convergeData(drRxFilteredPackets, logDir, "-",
                               samplingInterval, interpolationType,
                               reconstructionThreshold)[0]

iData = [[]] * 4
Пример #59
0
import Person
import Simulator
import sys


if __name__ == "__main__":

	if len(sys.argv)<2:
		print "Please specify Config file."
		exit(-1)
		
	config = sys.argv[1]
	people = Person.getResponders()
	print "Survey initiated" 
	for person in people:
		print person
		Simulator.take_survey(person, config)
		print "***************************************"
		
Пример #60
0
def runIt(g_C, R, width, rMiddle, P):
    """
    Do a simulation, plot and save a diagnostic plot.
    """
    # if rMiddle <= 10 * ureg.micrometer.to_base_units().magnitude:
    #     N = 512
    # else:
    #     N = 1024
    ringParams = Simulator.ParameterContainer(g_C=g_C,
                                              g_R=2.0 * g_C,
                                              gamma_C=gamma_C,
                                              gamma_R=a * gamma_C,
                                              R=R,
                                              m=m,
                                              charL=charL,
                                              charT=charT)

    # ringParams = Simulator.ParameterContainer(g_C=g_C, g_R=2.0*g_C,
    #                                           gamma_C=gamma_C,
    #                                           gamma_R=a*gamma_C, R=R, m=m)
    params = ringParams.getGPEParams()
    # params['charT'] = ringParams.charT
    P0 = P * params['Pth']
    # Make Grid
    # grid = Simulator.Grid(ringParams.charL, max_XY=max_XY_unscaled, N=N)
    # grid = Simulator.Grid(ringParams.charL, max_XY=3.0 * (rMiddle + width), N=N)
    grid = Simulator.Grid(ringParams.charL,
                          max_XY=2.0 * (rMiddle + width),
                          N=N)
    sigma = grid.toPixels(diffusionLength)
    x, y = grid.getSpatialGrid()
    x_us, y_us = grid.getSpatialGrid(scaled=False)
    pump = UtilityFunctions.AnnularPumpFlat(rMiddle,
                                            width,
                                            P,
                                            params['Pth'],
                                            sigma=sigma)
    # pump = UtilityFunctions.AnnularPumpGaussian(rMiddle, P, params['Pth'],
    #                                         sigma=width)

    # pump = UtilityFunctions.GaussianPump(rMiddle, P, params['Pth'])
    pumpFunction = pump.scaledFunction(ringParams.charL)
    P0 = np.max(pumpFunction(x, y))
    stabParam = (P0 / params['Pth']) / ((params['g_R'] * params['gamma_C']) /
                                        (params['g_C'] * params['gamma_R']))
    # Gaussian in the middle of the trap
    psi0 = UtilityFunctions.GaussianPump(0.2*rMiddle,
                                         0.01, 1, exponent=1.1).\
        scaledFunction(ringParams.charL)
    # psi0 = lambda x, y: 0.01 * pumpFunction(x, y) / P0
    print("Stability parameter %f (should be > 1)" % stabParam)
    dx = grid.dx_scaled
    print("Numerical Stability Parameter %f (should be < 1)" %
          ((np.pi * dt) / dx**2))
    print("P = %f" % P)
    print("Pth = %f" % params['Pth'])
    print("P0 = %f" % P0)
    print("P0/Pth = %f" % (P0 / params['Pth']))

    solver = Simulator.GPESolver(params,
                                 dt,
                                 grid.getSpatialGrid(),
                                 grid.getKSquaredGrid(),
                                 pumpFunction,
                                 psiInitial=psi0,
                                 gpu=True)
    energyTimes, energy = solver.stepTo(T_MAX, stepsPerObservation=100)
    # solver.stepTo(T_MAX, stepsPerObservation=1000)

    f = diagnosticPlot(1e6 * x_us, 1e6 * y_us, solver, energyTimes, energy,
                       pump.scaledFunction(charL=1e-6))
    f.savefig("Snoke" +
              getPlotName(params, r=rMiddle, m=m, sigma=diffusionLength) +
              ".png",
              dpi=800)
    # f.savefig("testNew" + ".png", dpi=800)
    plt.close(f)