def main():
    if args.command == "run":
        run(args)
    elif args.command == "init":
        init(args)
    elif args.command == "simulate":
        simulate(args)
Example #2
0
def simu():
    ref_paths = paths.build_reference_path(30.)
    p1, p2 = ref_paths
    v1 = Vehicle(p1, init_state=(0, 0, 0, 4, 0, 20, 0))
    v2 = Vehicle(p2, init_state=(0, 0, 0, 4, 20, 30, 0))
    simulator.simulate([v1, v2], 1000)
    return v1, v2
Example #3
0
def simulate():
    """
    Simulates the two bandits and returns the simulation results

    :return: simulation results, list, for each entry:
             1 if bandit  beats reference bandit (* 1 + bonus); else 0

    """

    # configuration
    arms = [
        'Configuration a',
        'Configuration b',
        'Configuration c',
        'Configuration d',
        'Configuration e',
        'Configuration f'
    ]

    # instantiate bandits
    bandit = Bandit(arms)
    ref_bandit = ReferenceBandit(arms)
    results = []
    for index in range(0, 20):
        random.seed(index)
        iterations = int(math.floor(1000 * (random.random()) + 0.5))
        bandit_reward = simulator.simulate(bandit, iterations)
        ref_bandit_reward = simulator.simulate(ref_bandit, iterations)
        ref_plus_bonus = ref_bandit_reward * 1.35
        result = 0
        if (bandit_reward > ref_plus_bonus):
            result = 1
        results.append(result)
    return results
Example #4
0
    def simulate_button_press(self):
        self.mode = 'Simulate'
        self.activate_button(self.simulate_button)

        assert self.interp_info is not None

        x1, y1, x2, y2 = self.c.coords(self.car)
        p = self.pixel_to_point_transform(
            np.array([(x1 + x2) / 2, (y1 + y2) / 2]))

        x = p[0]
        y = p[1]
        yaw = self.yaw

        sim.simulate(x,
                     y,
                     np.radians(yaw),
                     start_idx=0,
                     cx=self.interp_info[0],
                     cy=self.interp_info[1],
                     cyaw=self.interp_info[2],
                     ck=self.interp_info[3],
                     s=self.interp_info[4],
                     center_course=self.center,
                     inner_course=self.inner,
                     outer_course=self.outer)
Example #5
0
def main():
    with open('../tmp/LGRC3_plan_map.json') as world_map_file:
        world_map = json.load(world_map_file)

        delivery_mdp = DeliveryMDP(world_map, 'shlomoOffice', 'amrl')
        initial_state = ('mailroom', False)
        
        simulator.simulate(delivery_mdp, initial_state)
Example #6
0
def main():
    with open('../tmp/LGRC_plan_map.json') as world_map_file:
        world_map = json.load(world_map_file)

        escort_mdp = EscortMDP(world_map, 'shlomoOffice', 'AMRL')
        initial_state = ('mailroom', False)

        simulator.simulate(escort_mdp, initial_state)
Example #7
0
def main(argv):

    #set url for serverRequests
    url = ridertrackUrl

    participants = []
    
    if(len(argv) >= 1):
        eventId = argv

    f = open('users.txt','r')

    startingLine = True
    counting = 0
    while (True):
        l = f.readline().strip()
        if (startingLine  == True):
            startingLine = False
            continue
    
        if counting > 5:
            break

        line = l.split(',')
        user = Participant(line[0],line[1],line[2],line[3])
        participants.append(user)
        print (user.email)
        counting = counting + 1
    f.close()

    for p in participants:
        #login or register
        tupleTokenId = ()
        try:
            tupleTokenId = serverRequests.login(url,p.email,p.password)
        except:
            tupleTokenId = serverRequests.register(url,p.name,p.surname,p.email,p.password)
        p.token = tupleTokenId[0]
        p.userId = tupleTokenId[1]
        #enroll users
        serverRequests.enroll(url,p.token,p.userId,eventId)

    #get route
    print ("Enrollment part finished")
    coordinates = serverRequests.getRoute(url,eventId)
    print (coordinates)
    r = Route(coordinates)
    #simulate
    simulator.simulate(url,eventId,participants,r)
Example #8
0
def simulate_nikkei_tsumitate(db_file_name, start_date, end_date, deposit,
                              reserve):

    code = 1321
    stocks = create_stock_data(db_file_name, (code, ), start_date, end_date)

    def get_open_price_func(date, code):
        return stocks[code]['prices']['open'][date]

    def get_close_price_func(date, code):
        return stocks[code]['prices']['close'][date]

    current_month = start_date.month - 1

    def trade_func(date, portfolio):
        nonlocal current_month
        if date.month != current_month:
            # 月初め => 入金 => 購入
            portfolio.add_deposit(reserve)
            current_month = date.month
            return [sim.BuyMarketOrderAsPossible(code, stocks[code]['unit'])]
        return []

    return sim.simulate(start_date, end_date, deposit, trade_func,
                        get_open_price_func, get_close_price_func)
Example #9
0
def PlantResults():
    global plantS
    plantS = simulate(1000)

    TakeOff(plantS)
    Climb(plantS, v1=16, desiredCR=1, desiredHeight=100)
    Climb(plantS, v1=16, desiredCR=3, desiredHeight=200)
    Cruise(plantS, v1=18, distance=2000)
    plantS.CalculateE()

    Plot(plantS,
         'x2',
         'v1v2',
         'energy',
         'power',
         'speed',
         'soc',
         'thrust',
         'pitch',
         'plant',
         'iceeff',
         markers=False,
         save=True,
         title=False,
         direct='simulationPics/plantResults/')
Example #10
0
def main():
    if len(sys.argv) > 1 and sys.argv[1] == '-d':
        units_settings = DEFAULT_SETTINGS
    elif len(sys.argv) == 1:
        units_settings = DEFAULT_SETTINGS
    else:
        units_settings = read_units_settings()

    characteristics = [
        AbsoluteThroughput(TACTS_COUNT),
        RejectProbability(TACTS_COUNT),
        AverageQueueLength(TACTS_COUNT),
        AverageTimeInQueue(TACTS_COUNT)
    ]

    states_statistics, characteristics_results = simulate(
        TRANSITIONS, units_settings, TACTS_COUNT, START_STATE, characteristics)

    print('\nProbabilities:')
    for state, count in sorted(states_statistics.items(),
                               key=lambda x: int(x[0])):
        print('P {} = {}'.format(state, count / TACTS_COUNT))

    print('\nCharacteristics:')

    for name, result in characteristics_results.items():
        print('{} = {}'.format(name, result))
Example #11
0
def callback_func(ch, method, properties, body):
    """
    Callback function for every msg in the rabbit mq
    This method take the timestamp and generate simulated PV
    and write into a csv file
    """
    received_msg = json.loads(body)
    received_msg['timestamp'] = datetime.fromtimestamp(
        received_msg['timestamp'])
    print("Msg received {}".format(received_msg))

    time_data = received_msg['timestamp']
    # Serialize the timestamp to generate simulated PV
    time_serialized = time_data.hour + time_data.minute / 60 + time_data.second / 60 / 60 + time_data.microsecond / 60 / 60 / 60

    # Get the simulated PV
    pv_simulated = simulator.simulate(time_serialized)

    # Format the output
    print("x={} y={}".format(time_serialized, pv_simulated))

    # Write the data into csv file
    with open('pv_results.csv', 'a+') as record_file:
        record_file.write('{},{},{},{}\n'.format(
            received_msg['timestamp'], received_msg['power_value'],
            pv_simulated, pv_simulated + received_msg['power_value']))

    # Acknowledgement
    ch.basic_ack(delivery_tag=method.delivery_tag)
Example #12
0
   def get_QCLs_dist_cpp(self,s,muT,N=20000):
      """Determine the distribution of the CLs test statistic for the supplied signal hypothesis
      (using with muT=1 or muT=0 to set the S+B or B hypotheses as true respectively).            

      This version of get_QCLs_dist uses my custom written c++ module to compute the
      test statistic values. Should be much faster than PyMC. 
      """
      print "Determining qCLs(muT={0}) distribution for s={1}...   ".format(muT,s)

      # Note:
      # self.sys is the SYSTEMATIC uncertainty on the signal RATE. No `natural' Poisson stuff included
      # self.bsystot is the uncertainty on the TOTAL YIELD due to the background. Includes the standard Poisson error PLUS other systematics.
      # The simulator necessarily separates the Poisson error from the error on the rate. So we have to
      # make sure this happens first. The user is permitted to change the statistical error from the
      # Poisson amount, so I am here going to move all of this into the systematic parameter, and let
      # the simulator deal with the Poisson statistics itself.
      # ( note  (np.sqrt(b)/b)**2 = 1/b )
      ssys = self.ssys
      bsys = np.sqrt(self.bsystot**2 - 1/self.b)
      if bsys<0 or np.isnan(bsys): 
        #print self.bsystot
        #print self.bsys
        #print self.bstat
        #print bsys
        #print "Warning, negative background systematic calculated, please check code and inputs... (often just due to rounding error... setting systematic to zero)"
        bsys=0.

      Qsamples = sim.simulate(muT,s,self.b,ssys,bsys,self.sK,N)

      # Possible test statistic values are discrete, so count up occurances of each   
      keys, counts = count_unique(Qsamples)
      normalised_counts = counts/len(Qsamples)
    
      return (keys,normalised_counts)     
Example #13
0
def DropandHover():
    global s

    PP = GetParams()[1]

    s = simulate(500)

    initialHeight = 500

    s.y0 = [0, initialHeight, 0, 0]
    s.x2[s.n] = initialHeight
    s.pitch[s.n] = 90

    s.pitchShape = 'const'
    s.pitchCeiling = 90

    # make the aircraft mass lower because the powerplant is not enough to
    # make the full aircraft hover
    s.totalMass = 4

    weight = s.totalMass * AC['g']

    s.TShape = 'sigmoid'
    s.TFloor = 0
    s.TCeiling = weight
    s.TStart = 0
    s.TEnd = 50

    s.runtime = 200
    s.steps = 200
    s.RunInterval()

    Plot(s,
         'thrust',
         'pitch',
         'x2',
         'v2',
         save=True,
         title=False,
         direct='simulationPics/hover/')

    Fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.plot(s.timeArray[:s.n], s.x2[:s.n], label='Height')
    ax2.plot(s.timeArray[:s.n], s.v2[:s.n], 'r', label='V2')

    ax1.yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}'))

    lines, labels = ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()

    ax1.set_xlabel('time (seconds)')
    ax1.set_ylabel('AGL (m)')
    ax2.set_ylabel('velocity (m/s)')

    ax2.legend(lines + lines2, labels + labels2, loc=0)
    plt.tight_layout()
    plt.savefig('simulationPics/hover/x2v2.png')
    plt.show()
Example #14
0
def main():
    # number of simulations
    SIMS_NO = 1000000
    #SIMS_NO = 10

    # pot size is normalized
    pot_size = 1

    # Optimal play parameters
    P2_bet_size = math.sqrt(2) - 1
    P2_bluff_freq = P2_bet_size / (P2_bet_size + 1)
    P1_call_freq = (1 - P2_bet_size) / (1 + P2_bet_size)
    print('P1 call frequency  = ', round(100 * P1_call_freq, 1), '%\n')
    print('P2 bluff frequency = ', round(100 * P2_bluff_freq, 1), '%')
    print('P2 bet size (pots) = ', round(100 * P2_bet_size, 1), '%')

    call_freq_values = np.linspace(0, 1, 11)
    # 5 unbalanced values and the optimal value
    bluff_freq_values = [1.0, 0.75, 0.50, 0.25, P2_bluff_freq, 0]

    P2_to_P1_EV = []
    #    for i in range(0, len(bluff_freq_values)):
    #        P2_to_P1_EV.append([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

    #    P2_to_P1_EV = [[0 for i in range(11)] for i in range(len(bluff_freq_values))]

    # legends for plotting
    labels = [
        'Unbalanced (P2 bluffs 1.00)', 'Unbalanced (P2 bluffs 0.75)',
        'Unbalanced (P2 bluffs 0.50)', 'Unbalanced (P2 bluffs 0.25)',
        'Balanced (P2 bluffs 0.20)', 'Unbalanced (P2 bluffs 0.00)'
    ]

    for i, P2_bluff_freq in enumerate(bluff_freq_values):
        P2_to_P1_EV.append([])

        for j, P1_call_freq in enumerate(call_freq_values):
            EV = simulate(P1_call_freq, P2_bluff_freq, P2_bet_size, pot_size,
                          SIMS_NO)
            #print(P1_call_freq, '\t', EV[P1] / (float)(SIMS_NO), '\t', EV[P2] / (float)(SIMS_NO), '\t', P2_bluff_freq)

            # P2 to P1 expectation ratio
            P2_to_P1_EV[i].append(EV[P2] / EV[P1])

        # Plot results
        if i == len(bluff_freq_values) - 2:
            plt.plot(call_freq_values, P2_to_P1_EV[i], '--', linewidth=2.0)
        else:
            plt.plot(call_freq_values, P2_to_P1_EV[i], '-')

    plt.xlabel('P1 call frequency')
    plt.ylabel('P2 to P1 expectation ratio')
    plt.axis([0, 1, 0.8, 1.7])
    plt.legend(labels)
    plt.show()
Example #15
0
def sim_test_custom_sf(seed, num_nodes, sf):
    from node_config_custom_sf_setting import get_custom_sf_configurator
    area = DiscArea(300)
    simtime = 3600  # 1 day of simulation
    logfile = 'sim_%d.log' % int(time())
    channel_model = ChannelModel(area)
    net_layers = []
    depl_eng = ConnectedRandomNodeDeployment
    node_config = get_custom_sf_configurator(sf)

    return simulate(num_nodes, area, simtime, logfile, channel_model,
                    net_layers, depl_eng, node_config)
Example #16
0
def startup():
    infected = []
    sub_reference = []
    connections = []
    subreddits = []
    for pickle in pickles:
        sim_tuple = simulator.simulate(pickle)
        connections.append(sim_tuple[0])
        subreddits.append(sim_tuple[1])
        sub_reference.append(sim_tuple[2])

    launch(subreddits, connections, sub_reference)
Example #17
0
def worker(work_queue, done_queue):
    try:
        for job in iter(work_queue.get, 'STOP'):
            result = simulate(job["maze"], job["self"], job["verbose"],
                              job["graphics"], job["max_iter"])
            done_queue.put(
                ("%s - ID: %s, " % (current_process().name, job["id"]), True,
                 result))
    except Exception, e:
        done_queue.put(
            ("%s - ID: %s failed with: %s" %
             (current_process().name, job["id"], e.message), False, 0))
Example #18
0
def sim_test(seed, num_nodes):
    from node_config_slowest_setting import NodeConfigSlowestSetting
    area = DiscArea(300)
    simtime = 3600  # 1 day of simulation
    logfile = 'sim_%d.log' % int(time())
    channel_model = ChannelModel(area)
    net_layers = []
    depl_eng = RandomNodeDeployment
    node_config = NodeConfigSlowestSetting

    return simulate(num_nodes, area, simtime, logfile, channel_model,
                    net_layers, depl_eng, node_config)
Example #19
0
def main():
    # number of simulations
    SIMS_NO = 1000000

    # pot size
    pot_size = 4

    # Optimal play parameters
    P1_call_freq = (pot_size - 1) / (pot_size + 1)
    P2_bluff_freq = 1 / (pot_size + 1)

    print('Pot = ', pot_size)
    print('Optimal values:')
    print('\tP1 call frequency  = ', round(100 * P1_call_freq, 1), '%\n')
    print('\tP2 bluff frequency = ', round(100 * P2_bluff_freq, 1), '%')

    # P1 varies his strategy
    call_freq_values = np.linspace(0, 1, 11)

    # 5 unbalanced values and the optimal value for P2
    bluff_freq_values = [1.0, 0.75, 0.50, 0.25, P2_bluff_freq, 0]

    P2_to_P1_EV = []

    # legends for plotting
    labels = [
        'Unbalanced (P2 bluffs 1.00)', 'Unbalanced (P2 bluffs 0.75)',
        'Unbalanced (P2 bluffs 0.50)', 'Unbalanced (P2 bluffs 0.25)',
        '  Balanced (P2 bluffs 0.20)', 'Unbalanced (P2 bluffs 0.00)'
    ]

    for i, P2_bluff_freq in enumerate(bluff_freq_values):
        P2_to_P1_EV.append([])

        # Try different P1's strategies
        for P1_call_freq in call_freq_values:
            EV = simulate(P1_call_freq, P2_bluff_freq, pot_size, SIMS_NO)

            # P2 to P1 expectation ratio
            P2_to_P1_EV[i].append(EV[P2] / EV[P1])

        # Plot results
        if i == len(bluff_freq_values) - 2:
            plt.plot(call_freq_values, P2_to_P1_EV[i], '--', linewidth=2.0)
        else:
            plt.plot(call_freq_values, P2_to_P1_EV[i], '-')

    plt.xlabel('P1 call frequency')
    plt.ylabel('P2 to P1 expectation ratio')
    plt.axis([0, 1, 0.8, 1.7])
    plt.legend(labels)
    plt.show()
Example #20
0
def simulate_golden_dead_cross(db_file_name,
                               start_date, end_date,
                               code_list,
                               deposit,
                               order_under_limit):
    """deposit: 初期の所持金
      order_order_under_limit: ゴールデンクロス時の最小購入金額 
    """
    
    stocks = create_stock_data(db_file_name, code_list, start_date, end_date)

    # {ゴールデンクロス・デッドクロスが発生した日 : 発生した銘柄のリスト}
    # の辞書を作成
    golden_dict = defaultdict(list)
    dead_dict = defaultdict(list)
    for code in code_list:
        prices = stocks[code]['prices']['close']
        golden, dead = generate_cross_date_list(prices)
        for l, d in zip((golden, dead), (golden_dict, dead_dict)):
            for date in l:
                d[date].append(code)

    def get_open_price_func(date, code):
        return stocks[code]['prices']['open'][date]

    def get_close_price_func(date, code):
        return stocks[code]['prices']['close'][date]

    def trade_func(date, portfolio):
        order_list = []
        # Dead crossが発生していて持っている株があれば売る
        if date in dead_dict:
            for code in dead_dict[date]:
                if code in portfolio.stocks:
                    order_list.append(
                        sim.SellMarketOrder(code,
                                            portfolio.stocks[code].current_count))
        # 保有していない株でgolden crossが発生していたら買う
        if date in golden_dict:
            for code in golden_dict[date]:
                if code not in portfolio.stocks:
                    order_list.append(
                        sim.BuyMarketOrderMoreThan(code,
                                                   stocks[code]['unit'],
                                                   order_under_limit))
        return order_list

    return sim.simulate(start_date, end_date,
                        deposit,
                        trade_func,
                        get_open_price_func, get_close_price_func)
Example #21
0
 def compute_fitness(self, graphics=False):
     """Simulate and visualize some mazes.
      The function simulate can operate on files, programs or vectors.
      If you have problems with visualization (i.e. are a Mac user),
      try running the script from the terminal instead of PyCharm."""
     af = 0
     for m in mazes.mazes_train:
         af += simulate(m,
                        self,
                        verbose=True,
                        graphics=graphics,
                        max_iter=200)
     self.fitness = af / len(mazes.mazes_train)
     return self.fitness
Example #22
0
def handle_request(r):
    """Handle the Simulator request given by the r dictionary
    """
    print "handle_request executed .. "
    print r

    # Parse request ..
    config = SimArgs()
    config.machine = r[u'machine']
    config.overlay = [r[u'topology']] # List of topologies - just one
    config.group = r[u'cores']
    overlay = r[u'topology'].split('-')

    overlay_name = overlay[0]
    overlay_args = overlay[1:]

    if overlay_name == 'hybrid':
        overlay_name = 'cluster'
        config.hybrid = True;
        config.hybrid_cluster = overlay_args[0];
        config.overlay = [u'cluster']

    if overlay_args == 'mm' :
        config.multimessage = True
    elif overlay_args == 'rev' :
        config.reverserecv = True

    c = config

    from simulator import simulate
    (last_nodes, leaf_nodes, root) = simulate(config)

    # Generate response to be sent back to client
    import config
    assert len(config.models)==1 # Exactly one model has been generated

    res = {}
    res['root'] = root
    res['model'] = config.models[0]
    res['last_node'] = last_nodes[0]
    res['leaf_nodes'] = leaf_nodes[0]
    res['git-version'] = helpers.git_version()

    logging.info(('Responding with >>>'))
    logging.info((json.dumps(res)))
    logging.info(('<<<'))

    write_statistics(c.machine)

    return json.dumps(res)
Example #23
0
def simOutput():
    global memoryData, gpRegistersList, flagBitsList, outputs, curIns, finalflagbits, finalmemory, finalorder, finalgenperreg
    simulator.simulate(sendfile_name)

    f = open("./Output/output_sim.link", 'r')
    database = f.read()
    f.close()
    lines = database.splitlines()
    for line in lines:
        finalmemory.append(ast.literal_eval(line))
    f = open("./Output/output_lines.link", 'r')
    database = f.read()
    f.close()
    lines = database.splitlines()
    for line in lines:
        finalorder.append(line)
    f = open("./Output/output_flag.link", 'r')
    database = f.read()
    f.close()
    lines = database.splitlines()
    for line in lines:
        finalflagbits.append(ast.literal_eval(line))
    f = open("./Output/output_gen_per_reg.link", 'r')
    database = f.read()
    f.close()
    lines = database.splitlines()
    for line in lines:
        finalgenperreg.append(ast.literal_eval(line))

    loaded_output = Loader1.loader(sendfile_name)
    for l in range(len(loaded_output)):
        memoryData[l].set(str(loaded_output[l]))
    for v in range(len(gpRegistersList)):
        gpRegistersList[v].set(0)
    for v in range(len(flagBitsList)):
        flagBitsList[v].set(0)
Example #24
0
def simulate_buy_and_hold(db_file_name, start_date, end_date, code, deposit):
    stocks = create_stock_data(db_file_name, (code,), start_date, end_date)

    def get_open_price_func(date, code):
        return stocks[code]['prices']['close'][date]

    def get_close_price_func(date, code):
        return stocks[code]['prices']['close'][date]

    def trade_func(date, portfolio):
        if date == start_date:
            return [sim.BuyMarketOrderAsPossible(code, stocks[code]['unit'])]
        return []

    return sim.simulate(start_date, end_date, deposit, trade_func, get_open_price_func, get_close_price_func)
Example #25
0
def PlotLevelFlightV():
    """Plots the level flight velocity of the aircraft against angle of
    attack"""
    alphaArray = np.linspace(-maxAlpha, maxAlpha, 50)
    vArray = np.zeros(50)
    sim = simulate()
    sim.x2[sim.tost - 1] = 0
    for i in range(len(alphaArray)):
        sim.alpha = alphaArray[i]
        vArray[i] = GetLevelFlightV(sim)

    plt.plot(alphaArray, vArray)
    plt.xlabel('angle of attack in degrees')
    plt.ylabel('level flight velocity (m/s)')
    plt.title('Level Flight Velocity at different angles of attack')
    plt.savefig('simulationPics/levelFlight.png')
Example #26
0
def TestCR():
    s = simulate(50000)

    # take off
    TakeOff(s)

    Climb(s, v1 = 20, desiredCR = 1, desiredHeight=100)
    
    crEstimate = GetExpectedCR(s)
    
    print('Excess power estimate for the climb rate:', crEstimate, 'm/s')
    
    Plot(s, 'thrust', 'pitch', 'v1andv2', title=False, save=True, direct='simulationPics/testCR/', markers=False)
    

    """
Example #27
0
def simulator():
    global purchases
    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Requesting the form results with the name 'period'
        period = int(request.form.get('period'))

        # Requesting the form results with the name 'symbol'
        file = request.form.get('symbol')

        # Requesting the form results with the name 'holding_days'
        holding_days = request.form.get('holding_days')

        # Requesting the form results with the name 'cash_invested'
        cash_invested = request.form.get('cash_invested')

        # Requesting the form results with the name 'min_sd'
        min_sd = request.form.get('min_sd')

        # Requesting the form results with the name 'max_sd'
        max_sd = request.form.get('max_sd')

        # Creating an instance of the class 'simulate'
        #def __init__(self, symbol, period, holding_days, cash_invested):
        simulator = simulate(file, period, holding_days, cash_invested)

        # Running the function 'run_test' from the class 'simulate'
        # def run_simulation(self, symbol, start_sd, end_sd, start_val, end_val, min_sd, max_sd):
        results = simulator.run_simulation(simulator.test_filenames,
                                           simulator.start_sd,
                                           simulator.end_sd,
                                           simulator.start_val,
                                           simulator.end_val, min_sd, max_sd)

        purchases = results[5]

        return render_template("simulatorresults.html",
                               results=results,
                               period=period,
                               money_made=round(results[0], 2),
                               avg_return="{:.5%}".format(results[1]),
                               transactions=results[4],
                               accuracy=results[3])
    else:
        # Return the home page
        return render_template("simulator.html")
Example #28
0
def run_rocket_tests():
    with open('../data/rocket_tests.json') as fin:
        tests = json.load(fin, object_pairs_hook=OrderedDict)

    for test in tests:
        stages = map(Stage.from_json, test['rocket'])
        payload = test['payload']
        ar, dyns = simulate(payload, stages)
        print dyns
        test['resulting_dyns'] = map(repr, dyns)

        expected_dv = test['expected_total_dv']
        assert_almost_equal(ar.dv, expected_dv, delta=1e-3)


    with open('../data/rocket_tests.json', 'w') as fout:
        json.dump(tests, fout, indent=4)
Example #29
0
def FindConstraints():
    """
    Calculates the maximum horizontal and vertical velocities and height which the power-plant
    can achieve. These are stored in a global 3x30 array called limits

    Returns
    -------
    None.

    """
    global limits
    print(['limits' in globals()])
    print(['limits' in locals()])

    limits = np.zeros((3, 15**2))  # (maxv1, maxv2, maxHeight)

    print(['limits' in globals()])
    print(['limits' in locals()])

    v1Array = np.linspace(10, 50, 15)
    hArray = np.linspace(100, 6000, 15)

    s = simulate(10e7)
    counter = 0
    for hndex, h in enumerate(hArray):
        for index, i in enumerate(v1Array):

            T = 0
            maxThrust = 1
            v2 = 0
            while T < maxThrust:
                v2 += 0.5
                v = math.sqrt(i**2 + v2**2)
                maxThrust = float(
                    PropTFun(v, PP['ICEMaprps'][-1], h) +
                    PropTFun(v, PP['maxEMrps'], h))
                T = float(AnalyticalFindTP(s, h, i, v2)[0])

            limits[0, counter] = i
            limits[1, counter] = v2 - 0.5
            limits[2, counter] = h

            counter += 1

    return limits
Example #30
0
def Fly():
    global sim, fly

    _, PP = GetParams()

    # initialize classes
    sim = simulate(700, PP)

    # take off
    TakeOff(sim)

    Climb(sim, v1=13.66, desiredCR=2, desiredHeight=410)

    Cruise(sim, v1=16.9, distance=500)

    Glide(sim, 0)

    sim.CalculateE()
Example #31
0
def psim(xml_input, rmap={}, options={}):
    """Simulate POETS XML.

    Arguments:
      - xml_input  (str) : an XML file or string.
      - rmap      (dict) : device region map [optional].
      - options   (dict) : simulation options [optional].

    See docstring of simulator.simulate for simulation options documentation.

    Return:
      - result (dict) : simulation result.

    """
    xml = read_file(xml_input) if is_file(xml_input) else xml_input
    schema = Schema(xml, rmap)
    result = simulate(schema, options)
    return result
Example #32
0
def generate_train_data():
    num_masses_train = tf_generator.uniform((NUM_TRAIN_SAMPLES, ),
                                            NUM_MASSES_RANGE[0],
                                            NUM_MASSES_RANGE[1],
                                            dtype=tf.int32)
    dist_between_masses_train = tf_generator.uniform(
        (NUM_TRAIN_SAMPLES, ),
        DISTANCE_BETWEEN_MASSES_RANGE[0],
        DISTANCE_BETWEEN_MASSES_RANGE[1],
        dtype=tf.float32)
    train_data = [
        alter_data(base_graph(n, d), NODE_NOISE, EDGE_NOISE, GLOBAL_NOISE,
                   tf_generator)
        for n, d in zip(num_masses_train, dist_between_masses_train)
    ]
    train_data = concat_graphs(train_data)
    train_data_node_rollouts = simulate(sim, train_data, NUM_TIMESTEPS)
    return train_data, train_data_node_rollouts
def run(values, symbol):
  #data = pd.read_csv(values, header=False)
  data = np.loadtxt(values, delimiter=';', skiprows=0)
  values = data[:,3]
  #values = data.values[:,3]
  #invest = values.sum(axis=1)
  normalized_price = values / values[0]
  daily_returns = tsu.daily(normalized_price) 
  mean_daily_return = np.mean(daily_returns) 
  stdev_daily_return = np.std(daily_returns)
  sharpe_ratio = tsu.get_sharpe_ratio(daily_returns)
  total_return = values[-1] / values[0]
  print 'returns', sharpe_ratio, total_return, stdev_daily_return, mean_daily_return
  
  startdate = dt.datetime(int(data[0][0]), int(data[0][1]), int(data[0][2]), 16)
  enddate = dt.datetime(int(data[-1][0]), int(data[-1][1]), int(data[-1][2]), 16)
  allocation = [1.0]
  print 'SPX', startdate, enddate, symbol, allocation
  result = sm.simulate(startdate, enddate, [symbol], allocation, 'close')
  print 'result', result[2], result[3], result[0], result[1]
def run(values, symbol):
  #data = pd.read_csv(values, header=False)
  data = np.loadtxt(values, delimiter=';', skiprows=0)
  #print 'Data', data
  values = data[:,3]
  #print 'Values', values
  #values = data.values[:,3]
  #invest = values.sum(axis=1)
  normalized_price = values / values[0]
  daily_returns = tsu.daily(normalized_price) 
  mean_daily_return = np.mean(daily_returns) 
  stdev_daily_return = np.std(daily_returns)
  sharpe_ratio = tsu.get_sharpe_ratio(daily_returns)
  total_return = values[-1] / values[0]
  print 'Total', values[-1], values[0]
#  print 'returns', sharpe_ratio, total_return, stdev_daily_return, mean_daily_return
  
  startdate = dt.datetime(int(data[0][0]), int(data[0][1]), int(data[0][2]), 16)
  enddate = dt.datetime(int(data[-1][0]), int(data[-1][1]), int(data[-1][2]), 16)
  allocation = [1.0]
#  print 'SPX', startdate, enddate, symbol, allocation
  result = sm.simulate(startdate, enddate, [symbol], allocation, 'close')
#  print 'result', result[2], result[3], result[0], result[1]
  f = data[-1]
  print 'The final value of the portfolio using the sample file is -- %d-%d-%d -> %.2f ' % (f[0], f[1], f[2], f[3]) #2009,12,28,54824.0
  print ''
  print 'Details of the Performance of the portfolio'
  print ''
  print 'Data Range : %d-%d-%d to %d-%d-%d' % (data[0][0], data[0][1], data[0][2], data[-1][0], data[-1][1], data[-1][2])
  print ''
  print 'Sharpe Ratio of Fund : %.12f' % (sharpe_ratio)# 0.527865227084
  print 'Sharpe Ratio of $SPX : %.12f'% (result[2])#-0.184202673931
  print ''
  print 'Total Return of Fund %.12f:' % (total_return)#  1.09648
  print 'Total Return of $SPX %.12f:' % (result[3])# 0.779305674563'
  print ''
  print 'Standard Deviation of Fund : %.12f' % stdev_daily_return# 0.0060854156452
  print 'Standard Deviation of $SPX : %.12f' % result[0]#0.022004631521'
  print ''
  print 'Average Daily Return of Fund : %.12f' % mean_daily_return# 0.000202354576186
  print 'Average Daily Return of $SPX : %.12f' % result[1]#-0.000255334653467'
Example #35
0
#ランダムに試行して最適なパラメータを求める
iteration = 1500
best_parameters = []
best_benefit = 0
from simulator import simulate
from random import randint, random
for i in range(iteration):
    if i% 100 == 0:
        print('iteration {} / {}'.format(i, iteration))
    a, b = random(), random()
    buy_value = max(a,b)
    sell_value = min(a,b)
    loss_cut = randint(1,1000)
    profit_taking = randint(1,1000)
    benefit = simulate(buy_value, sell_value, loss_cut, profit_taking, False, False)
    if benefit > best_benefit:
        best_benefit = benefit
        best_parameters = [buy_value, sell_value, loss_cut, profit_taking]
        print('iteration{}: new best parameter {}'.format(i, benefit))


print('best benefit {}'.format(best_benefit))
print('parameters {}'.format(best_parameters))
simulate(best_parameters[0], best_parameters[1], best_parameters[2], best_parameters[3], False)
simulate(best_parameters[0], best_parameters[1], best_parameters[2], best_parameters[3])
Example #36
0
            float(args["<BAF_threshold>"]),
            float(args["--logr_merge"]),
            float(args["--baf_merge"]),
            5,
            args["--print"],
            args["--BAF"],
        )
    elif args["analyze"] and args["without"] and args["BAF"]:
        segmentum_without_baf(
            int(args["--min_read"]),
            args["<tumor>"],
            args["<normal>"],
            int(args["<window_size>"]),
            float(args["<clogr_threshold>"]),
            float(args["--logr_merge"]),
            5,
            args["--print"],
        )
    elif args["find"] and args["recurrent"] and ["cnLOHs"]:
        chrom_lengths = find_chromosome_length(args["<seg_files>"])
        clogr_thresh = float(args["--clogr_thresh"])
        baf_thresh = float(args["--baf_thresh"])
        loh_regions_chromosome_wise = find_cnloh(args["<seg_files>"], clogr_thresh, baf_thresh)
        find_recurrent(loh_regions_chromosome_wise, chrom_lengths)
    elif args["simulate"]:
        normal_contamination = 1 - float(args["--tumor_purity"])
        output_prefix = args["--output_prefix"]
        read_length = int(args["--read_length"])
        file_path = args["<normal>"]
        simulate(normal_contamination, output_prefix, read_length, file_path)
Example #37
0
def run_simulation(data_a, data_b):
    a = csv_read(data_a)
    b = csv_read(data_b)
    data = simulate(a, b)
    return data
Example #38
0
def run_simulation(data_a, data_b):
    return simulate(csv_read(data_a), csv_read(data_b))
Example #39
0
'''
Run simulator with random data
'''
print('part (a)')
n = 3
m1 = 10 
m2 = 5
sample = 100

a = np.random.rand(1, n) # intercepts
z = np.random.rand(n,m1) # variables with generic coefficients
w = np.random.rand(n,m2) # variables with alternative specific coefficients 
b = np.random.rand(1, m1) # generic coefficients
d = np.random.rand(n,m2) # alternative specific coefficients

results, prob, utilities = simulate(n, z, w, b, d, a, sample)

#r = robjects.r
#mlogit = importr('mlogit')

'''
Run Homework 3 Problem 3 part (b)
'''
print('part (b)')
n = 2
sample = 1000

m1 = 1 
m2 = 0

Example #40
0
    if s1 > 1:
        s1 = 1
    next_state = [s0, s1, s2, s3]
    next_state = [s if s > 0 else 0 for s in next_state]
    return next_state

history = []
score = simulateP(state, regularization=regularization, score_for_transaction=score_for_transaction)

try:
    for i in range(iteration):
        if i% 100 == 0:
            print('iteration {} / {}, T={}, current score{}'.format(i, iteration, tempreture, score))
            mobility_of_rate *= scale_par_100iteration
            mobility_of_money = int( mobility_of_money * scale_par_100iteration)
        current_score = simulate(state[0], state[1], state[2], state[3], False, False, regularization, score_for_transaction)
        next_state = neighbour(state)
        next_score = simulateP(next_state, regularization=regularization, score_for_transaction = score_for_transaction)
        if random() < probability(next_score, score, tempreture):
            state = next_state
            score = next_score
            print('iteration{}: new parameter {}, benefit {}'.format(i, state, score))
        tempreture *= alpha
        history.append(score)
except KeyboardInterrupt:
    print('stopped')
    print('iteration{}: iterationparameter {}, benefit {}'.format(i, state, score))

plt.plot(history, label='benefit')
plt.title('annieling history')
plt.legend()