Ejemplo n.º 1
0
    def __init__(self, parameters_dict):

        super(TaxiDARA, self).__init__(parameters_dict)
        parameters_dict = Wrapper(parameters_dict)

        self.grouping_columns = parameters_dict.grouping_columns
        self.df = pd.read_csv(
            parameters_dict.df,
            nrows=parameters_dict.df_nrows,
            parse_dates=[self.closeTimeColumnName, self.openTimeColumnName],
            infer_datetime_format=True)
        self.preprocess = parameters_dict.preprocess
        self.is_weather = parameters_dict.is_weather

        if self.is_weather:
            self.weather_pkl = parameters_dict.weather_pkl
            self.temperature_pkl = parameters_dict.temperature_pkl
            self.humidity_pkl = parameters_dict.humidity_pkl
            self.weather_resolution = parameters_dict.weather_resolution

        if 'approx_pickup' in parameters_dict.keys():
            self.approx_pickup = parameters_dict.approx_pickup
        else:
            self.approx_pickup = 2

        if self.preprocess:

            self.pickup_longitude = parameters_dict.pickup_longitude
            self.pickup_latitude = parameters_dict.pickup_latitude
            self.dropoff_longitude = parameters_dict.dropoff_longitude
            self.dropoff_latitude = parameters_dict.dropoff_latitude
Ejemplo n.º 2
0
    def __init__(self):
        self.distributor = Distributor()

        self.distributor.add(GetServerTime())
        self.distributor.add(Multiply())
        self.distributor.add(GetReqCount())
        logging.info('added 3 request types')

        self.wrapper = Wrapper(distributor=self.distributor)
        self.wrapper.run(port=4657)
Ejemplo n.º 3
0
    def run(self):
        print("[Controller] Controller is starting.")

        # Set variables
        self.config = self.loadConfiguration("/data/options.json")
        self.haToken = os.environ['SUPERVISOR_TOKEN']

        # Create State object
        self.state = State.State()

        # Create Ffmpeg wrapper
        for camera in self.config["cameras"]:
            self.ffmpegWrappers.append(Wrapper.FfmpegWrapper(self, camera, 10))

        # Setup home assistant listener
        self.haListener = HAListener.HAListener(self)
        
        # Start tasks
        loop = asyncio.get_event_loop()
        listener = asyncio.ensure_future(self.haListener.start())

        # Get initial toggle value
        initialState = self.getToggleValue()
        print(f'[Controller] Initial toggle status: {initialState}.')
        self.state.isCameraEnabled = initialState

        print("[Controller] Controller is running.")
        loop.run_forever()
        print("[Controller] Exiting.")
Ejemplo n.º 4
0
 def opt_fun(par):
     try:
         # parameters
         
         #run the model
         _, q_out = Wrapper.Lumped(ConceptualModel,data,par,p2,init_st,
                            snow,Routing, RoutingFn)
         
         # calculate performance of the model
         try:
             error=OF(Q_obs,q_out,*OF_args)
         except TypeError: # if no of inputs less than what the function needs
             assert 1==5, "the objective function you have entered needs more inputs please enter then in a list as *args"
             
         # print error
         if printError != 0:
             print(error)
             print(par)
         
         fail = 0
     except:
         error = np.nan
         fail = 1
         
     return error, [], fail 
Ejemplo n.º 5
0
 def opt_fun(par):
     try:
         # parameters
         klb=float(par[-2])
         kub=float(par[-1])
         par=par[:-2]
                     
         par_dist=SpatialVarFun(par,*SpatialVarArgs,kub=kub,klb=klb)    
         
         #run the model
         _, q_out, q_uz_routed, q_lz_trans=Wrapper.Dist_model(ConceptualModel,
                                                              acc, fd, prec, evap,
                                                              temp, par_dist, p2,
                                                              snow , init_st)
         
         # calculate performance of the model
         try:
             error=OF(Q_obs,q_out,q_uz_routed,q_lz_trans,*OF_args)
         except TypeError: # if no of inputs less than what the function needs
             assert 1==5, "the objective function you have entered needs more inputs please enter then in a list as *args"
             
         # print error
         if printError != 0:
             print(error)
             print(par)
         
         fail = 0
     except:
         error = np.nan
         fail = 1
         
     return error, [], fail 
Ejemplo n.º 6
0
    def __init__(self, parameters_dict):
        '''

        :param parameters_dict: dict with many parameters
        -resolution : time granulation
        -statistics columns list : list of columns to integrate into dara format
        -open/close column names : self explanatory
        -save prefix : string for saving the final result
        '''

        if parameters_dict is None:
            parameters_dict = Wrapper({})
        else:
            parameters_dict = Wrapper(parameters_dict)

        self.resolution = parameters_dict.resolution
        self.statistics_columns_list = parameters_dict.statistics_columns_list
        self.openTimeColumnName = parameters_dict.openTimeColumnName
        self.closeTimeColumnName = parameters_dict.closeTimeColumnName
        self.save_prefix = parameters_dict.save_prefix
Ejemplo n.º 7
0
def receive_data():
    # machine\ntype,value\ntype,value\ntype,value
    dataReceived = str(request.get_data(), 'utf-8').split("\n")

    machineID = dataReceived.pop(0)
    for line in dataReceived:
        valuetype = line.split(",")[0]
        value = line.split(",")[1]

        # If there is a central server, resend the data
        if server_dir != "":
            resend_data(Wrapper.timestamp(), machineID, valuetype, value,
                        "WIFI")
        else:  # Otherwise, insert it into our database
            db.insert(Wrapper.timestamp(), machineID, shard, valuetype, value,
                      "WIFI")
        log.log("The device " + machineID + " sent the value " + value +
                " of type " + valuetype)

    return "OK"
Ejemplo n.º 8
0
    def __init__(self, parameters_dict):

        super(Forex, self).__init__(parameters_dict)
        parameters_dict = Wrapper(parameters_dict)

        self.grouping_columns = parameters_dict.grouping_columns
        self.df = pd.read_csv(
            parameters_dict.df,
            nrows=parameters_dict.df_nrows,
            parse_dates=[self.closeTimeColumnName, self.openTimeColumnName],
            infer_datetime_format=True)
        self.preprocess = parameters_dict.preprocess
Ejemplo n.º 9
0
    def run(self):
        print("[Controller] Controller is starting.")

        # Set variables
        self.config = self.loadConfiguration("/data/options.json")

        # Create Ffmpeg wrapper
        self.ffmpegWrapper = Wrapper.FfmpegWrapper(self, 10)
        self.ffmpegWrapper.startProcess()

        # Start tasks
        loop = asyncio.get_event_loop()

        print("[Controller] Controller is running.")
        loop.run_forever()
        print("[Controller] Exiting.")
Ejemplo n.º 10
0
def GetSummaryStats(region, ident):
    global key, address, version
    #r = urllib.request.urlopen("http://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/21593392/summary?api_key=2fd18e36-698e-4757-b401-2bf43c119f9a")
    r = urllib.request.urlopen(address+region+"/" + version4 + "/stats/by-summoner/"+ident+"/summary?api_key="+key)
    return Wrapper.asSummaryStatsList(json.loads(r.read().decode('utf-8')))
Ejemplo n.º 11
0
def GetRankedStats(region, season, ident):
    global key, address, version
    r = urllib.request.urlopen(address+region+"/" + version4 + "/stats/by-summoner/"+ident+"/ranked?season=SEASON"+str(season)+"&api_key="+key)
    #return r.read().decode('utf-8')
    return Wrapper.asRankedStats(json.loads(r.read().decode('utf-8')))
Ejemplo n.º 12
0
def GetLeagues(region, ident):
    global key, address, version
    r = urllib.request.urlopen(address+region+"/" + version5 + "/league/by-summoner/"+ident+"?api_key="+key)
    return Wrapper.asLeagues(json.loads(r.read().decode('utf-8')))
Ejemplo n.º 13
0
def GetSummonerMasteries(region, ident):
    global key, address, version
    r = urllib.request.urlopen(address+region+"/" + version + "/summoner/"+ident+"/masteries/?api_key="+key)
    return Wrapper.asMasteryPages(json.loads(r.read().decode('utf-8')), ident)
Ejemplo n.º 14
0
def GetSummonerByName(region, name):
    global key, address, version
    r = urllib.request.urlopen(address+region+"/" + version + "/summoner/by-name/"+name+"?api_key="+key)
    return Wrapper.asSummoner(json.loads(r.read().decode('utf-8')), name.lower())
Ejemplo n.º 15
0
def run_Distributed_model():
    performance.text = str("<h2>processing...<h2>")
    # read values of parameters

    # data validation

    #    _area = float(w_area.value)
    #    pars222222 = [_k1, _k2, _k3, _k4, _d1, _d2, _s1, _s2]
    #    extra_pars22222 = [_dt, _area]

    performance_Q = {}
    calc_Q = pd.DataFrame(index=index)

    calc_Q['Q'], _, _, _, _, _ = Wrapper.Dist_model(
        lake_data_A,
        extra_pars,
        curve,
        lakecell,
        DEM,
        flow_acc_table,
        flow_acc,
        sp_prec_c,
        sp_et_c,
        sp_temp_c,
        pars,
        kub,
        klb,
        jiboa_initial=jiboa_initial,
        lake_initial=lake_initial,
        ll_temp=None,
        q_0=None)

    # Calculate model performance
    performance.text = str("<h2>calculating model performance..<h2>")

    WS = {
    }  #------------------------------------------------------------------------
    WS['type'] = 1  #------------------------------------------------------------------------
    WS['N'] = 3  #------------------------------------------------------------------------

    performance_Q['c_error_hf'] = Performance_criteria.rmseHF(
        lake_data['Q'], calc_Q['Q'], WS['type'], WS['N'], 0.75
    )  #------------------------------------------------------------------------
    performance_Q['c_error_lf'] = Performance_criteria.rmseLF(
        lake_data['Q'], calc_Q['Q'], WS['type'], WS['N'], 0.75
    )  #------------------------------------------------------------------------
    performance_Q['c_nsehf'] = Performance_criteria.nse(
        lake_data_A[:, -1], calc_Q['Q']
    )  #------------------------------------------------------------------------
    performance_Q['c_rmse'] = Performance_criteria.rmse(
        lake_data_A[:, -1], calc_Q['Q']
    )  #------------------------------------------------------------------------
    performance_Q['c_nself'] = Performance_criteria.nse(
        np.log(lake_data_A[:, -1]), np.log(calc_Q['Q'])
    )  #------------------------------------------------------------------------
    performance_Q['c_KGE'] = Performance_criteria.KGE(
        lake_data_A[:, -1], calc_Q['Q']
    )  #------------------------------------------------------------------------
    performance_Q['c_wb'] = Performance_criteria.WB(
        lake_data_A[:, -1], calc_Q['Q']
    )  #------------------------------------------------------------------------

    # update data source
    ds_sim.data = (dict(q_sim=calc_Q['Q'].tolist(), ds_time=index))

    performance.text = str("<h2>Model perfomance(RMSE) is %s<h2>" %
                           round(performance_Q['c_rmse'], 3))
Ejemplo n.º 16
0
def main():
    global Score

    s = w.Arduino_Controller("COM3")

    fumen = read_json()

    #print(json.dumps(fumen))
    thread = threading.Thread(target=play_music)
    thread.deamon = True
    thread.start()
    time.sleep(0.2)

    #Score = 0

    Sums = [0, 0, 0, 0]
    Pushed = [0, 0, 0, 0]

    for i in range(len(fumen)):

        for j in range(4):
            Sums[j] += fumen[i][str(i)][j]

        print(str(Sums) + " : " + str(Score))
        #s.show_state()

        #Print
        for offset in range(6):
            print_place = i + offset - 1
            if (print_place <= 0 or len(fumen) <= print_place):
                continue
            for j in range(4):
                print_data = fumen[print_place][str(print_place)][j]
                print_led = (5 - offset) + 6 * j
                if (print_data == 1 and not Pushed[j] == 1):
                    s.LED_switch(print_led, True)
                if (print_data == -1 or (offset == 0 and Pushed[j] == 1)):
                    s.LED_switch(print_led, False)

        #Score
        Pushed = [0, 0, 0, 0]
        for j in range(4):
            if (s.switch[j + 10] == 1):
                if (Sums[j] == 1):

                    #print("OK")

                    Score += 2
                    #押したらLED消す処理(手抜きなのでLEDどころか譜面が消し飛ぶが)
                    #fumen[i][j] = 0 #悪魔の力
                    #それはさすがにないわ。修正
                    Pushed[j] = 1

                else:
                    Score -= 1
                    """
		if(len(fumen) - i < 6) :
			continue

		for _n in range(6) :
			n = i + _n
			for j in range(4) :
				if(fumen[n][str(n)][j] == 1) :
					s.LED_switch((6 - _n) * 6 + j,True)
				else :
					s.LED_switch((6 - _n) * 6 + j,False)
		"""

        time.sleep(0.2)

    s.exit_code = False
    Voice()

    print(Score)
Ejemplo n.º 17
0
import numpy as np
import Wrapper as w
import time as t
import threading

oks = [0] * 4
ac = w.Arduino_Controler("COM7")


def main():
    for i in range(100):
        for j in range(6):
            ac.LED_switch((i % 4) * 6 + j, 1)
            oks[i % 4] = 0
            thread = threading.Thread(target=check, args=(i % 4, ))
            thread.start()
            t.sleep(0.5)
            thread.alive = False
            ac.LED_switch((i % 4) * 6 + j, 0)

            if (j == 4 and oks[i % 4]):
                break

        t.sleep(1)


def check(num):
    while True:
        if ac.get_state(num):
            oks[num] = 1
            break
Ejemplo n.º 18
0
from Extractor import *
from Wrapper import *
from Sender import *

if __name__ == '__main__':

    extractor = Extractor()
    wrapper = Wrapper()
    sender = Sender()

    rawData = extractor.get_site()
    dataModel = wrapper.packData()


    print(rawData)
Ejemplo n.º 19
0
def GetTeam(region, ident):
    global key, address, version
    r = urllib.request.urlopen(address+region+"/" + version2 + "/team/by-summoner/"+ident+"?api_key="+key)
    #return r.read().decode('utf-8')
    return Wrapper.asTeams(json.loads(r.read().decode('utf-8')))
Ejemplo n.º 20
0
def RunModel(ConceptualModel, Paths, ParPath, p2, init_st, snow):
    """
    =======================================================================
        RunModel(PrecPath, Evap_Path, TempPath, DemPath, FlowAccPath, FlowDPath, ParPath, p2)
    =======================================================================
    this function runs the conceptual distributed hydrological model
    
    Inputs:
        1-Paths:
            1-PrecPath:
                [String] path to the Folder contains precipitation rasters
            2-Evap_Path:
                [String] path to the Folder contains Evapotranspiration rasters
            3-TempPath:
                [String] path to the Folder contains Temperature rasters
            4-FlowAccPath:
                [String] path to the Flow Accumulation raster of the catchment (it should
                include the raster name and extension)
            5-FlowDPath:
                [String] path to the Flow Direction raster of the catchment (it should
                include the raster name and extension)
        7-ParPath:
            [String] path to the Folder contains parameters rasters of the catchment 
        8-p2:
            [List] list of unoptimized parameters
            p2[0] = tfac, 1 for hourly, 0.25 for 15 min time step and 24 for daily time step
            p2[1] = catchment area in km2
    Outputs:
        1- st:
            [4D array] state variables
        2- q_out:
            [1D array] calculated Discharge at the outlet of the catchment
        3- q_uz:
            [3D array] Distributed discharge for each cell
    Example:
        PrecPath = prec_path="meteodata/4000/calib/prec"
        Evap_Path = evap_path="meteodata/4000/calib/evap"
        TempPath = temp_path="meteodata/4000/calib/temp"
        DemPath = "GIS/4000/dem4000.tif"
        FlowAccPath = "GIS/4000/acc4000.tif"
        FlowDPath = "GIS/4000/fd4000.tif"
        ParPath = "meteodata/4000/parameters"
        p2=[1, 227.31]
        st, q_out, q_uz_routed = RunModel(PrecPath,Evap_Path,TempPath,DemPath,
                                          FlowAccPath,FlowDPath,ParPath,p2)
    """
    # input data validation
    assert len(Paths) == 5, "Paths should include 5 folder pathes " +str(len(Paths))+" paths are only provided"
    
    PrecPath=Paths[0]
    Evap_Path=Paths[1]
    TempPath=Paths[2]
#    DemPath=Paths[3]
    FlowAccPath=Paths[3]
    FlowDPath=Paths[4]
    
    # data type
    assert type(PrecPath)== str, "PrecPath input should be string type"
    assert type(Evap_Path)== str, "Evap_Path input should be string type"
    assert type(TempPath)== str, "TempPath input should be string type"
#    assert type(DemPath)== str, "DemPath input should be string type"
    assert type(FlowAccPath)== str, "FlowAccPath input should be string type"
    assert type(FlowDPath)== str, "FlowDPath input should be string type"
    assert type(ParPath)== str, "ParPath input should be string type"
    
    
    # input values
#    dem_ext=DemPath[-4:]
#    assert dem_ext == ".tif", "please add the extension at the end of the DEM raster path input"
    acc_ext=FlowAccPath[-4:]
    assert acc_ext == ".tif", "please add the extension at the end of the Flow accumulation raster path input"
    fd_ext=FlowDPath[-4:]
    assert fd_ext == ".tif", "please add the extension at the end of the Flow Direction path input"
    # check wether the path exists or not
    assert os.path.exists(PrecPath), PrecPath + " you have provided does not exist"
    assert os.path.exists(Evap_Path), Evap_Path+" path you have provided does not exist"
    assert os.path.exists(TempPath), TempPath+" path you have provided does not exist"
#    assert os.path.exists(DemPath), DemPath+ " you have provided does not exist"
    assert os.path.exists(FlowAccPath), FlowAccPath + " you have provided does not exist"
    assert os.path.exists(FlowDPath), FlowDPath+ " you have provided does not exist"
    # check wether the folder has the rasters or not 
    assert len(os.listdir(PrecPath)) > 0, PrecPath+" folder you have provided is empty"
    assert len(os.listdir(Evap_Path)) > 0, Evap_Path+" folder you have provided is empty"
    assert len(os.listdir(TempPath)) > 0, TempPath+" folder you have provided is empty"
    
    # read data
    ### meteorological data
    prec=GIS.ReadRastersFolder(PrecPath)
    evap=GIS.ReadRastersFolder(Evap_Path)
    temp=GIS.ReadRastersFolder(TempPath)
    print("meteorological data are read successfully")
    
    #### GIS data
#    dem= gdal.Open(DemPath) 
    acc=gdal.Open(FlowAccPath)
    fd=gdal.Open(FlowDPath)
    print("GIS data are read successfully")
    
    # parameters
    parameters=GIS.ReadRastersFolder(ParPath)
    print("Parameters are read successfully")
    
    #run the model
    st, q_out, q_uz, q_lz = Wrapper.Dist_model(ConceptualModel, acc, fd, prec, evap,
                                               temp, parameters, p2, snow, init_st)
    
    return st, q_out, q_uz, q_lz
Ejemplo n.º 21
0
import Wrapper as w
import time

s = w.Arduino_Controller("COM3")

for i in range(25):
    #s.LED_switch(i - 1,False)
    s.LED_switch(i, True)
    time.sleep(0.2)

for i in range(25):
    s.LED_switch(i, False)
time.sleep(2)
for i in range(25):
    s.LED_switch(i, True)
time.sleep(2)
for i in range(25):
    s.LED_switch(i, False)
time.sleep(2)
for i in range(25):
    s.LED_switch(i, True)

s.exit_code = False
Ejemplo n.º 22
0
    def checkBuy(self):
        print(self.data)
        lookback = self.data


if __name__ == '__main__':

    # Create a cerebro entity
    cerebro = bt.Cerebro()

    cerebro.addstrategy(PriceActionBacktest)

    # Get shtuff from Alpaca via a wrapper
    start = pd.Timestamp.now() - pd.Timedelta(days=365)
    dataframe = Wrapper.getData(['BAC'], '15Min', start)

    # Convert column tuples to strings
    for i in range(len(dataframe.columns.values)):
        dataframe.columns.values[i] = dataframe.columns.values[i][1]

    # Create a Data Feed
    data = bt.feeds.PandasData(dataname=dataframe)

    # Add the Data Feed to Cerebro
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(10000.0)

    # Add a FixedSize sizer according to the stake
Ejemplo n.º 23
0
import time
import Wrapper as w

s = w.Arduino_Controler("COM4")

for i in range(200):
    s.LED_switch(0, i % 2)
    time.sleep(0.01)

s.exit_code = False
Ejemplo n.º 24
0
def GetChampions(region):
    global key, address, version
    r = urllib.request.urlopen(address+region+"/" + version3 + "/champion?api_key="+key)
    r#eturn r.read().decode('utf-8')
    return Wrapper.asChampionList(json.loads(r.read().decode('utf-8')))
Ejemplo n.º 25
0
def Main():

    # instanstiated in order to use methods
    gpg = EasyGoPiGo()
    ls = LineFollower()
    wrapper = Wrapper()

    # line sensor reads the current position on the line twice for accuracy
    ls.read()
    ls.read()

    print("Starting controller")
    print("CMDS: stop, rotations, status, exit")
    print("GPG3: read, speed, followline, rp, turnright, turnleft")
    print("Wrapper: wfollowline, wwaiting, wturnright, wturnleft")

    # Starts loop then prompts user for input then goes to sleep until next command is entered
    while True:

        userin = raw_input()

        if userin == "stop":
            print("stopping")
            gpg.stop()

        elif userin == "wfollowline":
            print("follow line")
            wrapper.followline()

        elif userin == "wstraight":
            wrapper.go_straight()

        elif userin == "wturnright":
            wrapper.turn_right()

        elif userin == "wturnleft":
            wrapper.turn_left()

        elif userin == "wwaiting":
            print("waiting status:")
            print(wrapper.waiting())

        elif userin == "straight":
            go_straight()

        elif userin == "turnaround":
            turn_around()

        elif userin == "turnright":
            print("right turn")
            ls.turn_right()

        elif userin == "turnleft":
            print("left turn")
            ls.turn_left()

        elif userin == "rp":
            print "READING POSITION"
            print(ls.read_position())

        elif userin == "rotations":
            print("The left wheel has gone: ")
            print(enc_read(0))
            print("The right wheel has gone: ")
            print(enc_read(1))

        elif userin == "read":
            print("READING")
            print(ls.read())

        elif userin == "followline":
            ls.follow_line()

        elif userin == "status":
            print("Current battery voltage:")
            print(volt())
            print(gpg.volt())

        elif userin == "speed":
            print(read_motor_speed())

        elif userin == "exit":
            print("Exiting\n")
            sys.exit()
            break

        time.sleep(.1)