Exemplo n.º 1
0
 def send_module(self, module=None, station="", extras=[],cost=200000000):
     if not self.scenario: return None
     if not station and self.scenario.stations: 
         station = self.scenario.focus_station.id
                                
     
     modDrag = DragonCargoModule() 
     modDrag.location = np.array([ -100000 , 0 , 0 ]) 
     newStation = Station(modDrag,'AddStation', self.logger) 
     self.counter += 1                        
     
     if module: 
         module.location = np.array([ -100000 , 0 , 0 ])               
         newStation.dock_module(None,None,module, None, True)                      
     vessel = VesselPlan( station = newStation, target_station_id = station )
     self.vessel_queue.append( vessel )                                   
     
     self.player_nasa_funds -= cost 
     if module is not None:
         self.last_module = self.time_elapsed
         self.module_available = False     
     else:
         self.last_resupply = self.time_elapsed
         self.resupply_available = False  
     return newStation
Exemplo n.º 2
0
    def test_close_station(self):
        a = Station(1)
        b = Station(2)
        a.add_connection(b)

        self.assertEqual(len(b), 1)
        a.close()
        self.assertEqual(len(b), 0)
Exemplo n.º 3
0
    def __init__(self,name='DEFAULT',logger=util.generic_logger):
        if name=='BERTNERNIE':

            modA  = DestinyModule()
            modDock = UnityModule()    
            modB   = ZvezdaModule()
            modDrag = DragonCargoModule()
            modDrag.setup_simple_resupply()
                   
            self.station = Station(modDock, "BnE Station", logger)
            self.station.berth_module(None,None,modB, None, True)
            self.station.berth_module(None,None,modA, None, True)    
            self.station.berth_module(None,None,modDrag, None, True)
            
            '''rob = Robot('Robby')     
            rob.station = station
            station.actors[rob.id]=rob
            rob.location = modB.node('hall0')
            rob.xyz = modB.location'''
            
            ernie = Human('Ernest',station=self.station,logger=self.station.logger)
            self.station.actors[ernie.id] = ernie
            ernie.location = modA.node('hall0')
            ernie.xyz = modA.location
            
            bert = Human('Bertholomew',station=self.station,logger=self.station.logger)
            self.station.actors[bert.id] = bert
            bert.location = modB.node('hall0')
            bert.xyz = modB.location
            
            ernie.needs['WasteCapacityLiquid'].amt=0.1
            ernie.needs['Food'].set_amt_to_severity('HIGH')
            ernie.nutrition = [0.5, 0.5, 0.5, 0.5, 0.5]
            #modB.equipment['Electrolyzer'][3].broken=True

        elif name == 'DOCKINGTEST':
            '''Ernie, in a station badly needing resupply, gets a Dragon shipment.
                He installs a docking computer, docks Dragon, unloads food, loads waste, undocks Dragon, Dragon reenters'''
   
            modB   = ZvezdaModule()
            self.station = Station(modB, "Docker Station", logger)
            
            modDrag = DragonCargoModule()
            modDrag.setup_simple_resupply()
                       
            #TODO: position Dragon on "docking" approach, add docking task
            self.station.begin_docking_approach(modDrag)
            print modDrag.location, modDrag.orientation
            
            ernie = Human('Ernest',station=self.station,logger=self.station.logger)
            self.station.actors[ernie.id] = ernie
            ernie.location = modB.node('hall0')
            ernie.xyz = modB.location
                                    
        else: #'DEFAULT'
            modDock = UnityModule()                   
            self.station = Station(modDock, 'NewbieStation',logger)
Exemplo n.º 4
0
 def __init__(self, idx, internal_id):
   Station.__init__(self, idx)
   self.number = internal_id
   """
    Takes too long to instantiate all the stations, but the
    smartbike API does not give any useful information for
    starters.. :(
   """
   self.update()
Exemplo n.º 5
0
    def test_human_move(self):
        s1 = Station(1)
        s2 = Station(2)
        h = Human(1, s1)

        s1.add_connection(s2)
        self.assertEqual(h.state, s1)
        self.assertEqual(h.memory, [s1])
        h.action()
        self.assertEqual(h.state, s2)
        self.assertEqual(h.memory, [s1, s2])
Exemplo n.º 6
0
    def test_cat_move(self):
        s1 = Station(1)
        s2 = Station(2)
        c = Cat(1, s1)

        s1.add_connection(s2)
        self.assertEqual(c.state, s1)
        c.action()
        self.assertEqual(c.state, s2)
        c.action()
        self.assertEqual(c.state, s1)
Exemplo n.º 7
0
Arquivo: plugin.py Projeto: NSBum/EC
	def validateDeviceConfigUi(self, valuesDict, typeId, devId):
		stationID = valuesDict['address'].encode('ascii','ignore').lower()
		province = valuesDict['province'].encode('ascii','ignore').upper()
		station = Station(province,stationID)
		indigo.server.log(station.url())
		try:
			urllib2.urlopen(station.url())
		except urllib2.HTTPError, e:
			errorsDict = indigo.Dict()
			errorsDict['address'] = "Station not found or isn't responding"
			self.errorLog("Error getting station %s data: %s" % (stationID, str(e)))
			return (False, valuesDict, errorsDict)
Exemplo n.º 8
0
    def fetch_requirements(self, requirements):
        result = Station()

        for adapter in self.available_adapters:
            try:
                result += self.adapter_fetch(adapter)
                if result.requires(requirements):
                    break
            except StationError as error:
                print error

        return result
Exemplo n.º 9
0
  def __init__(self, station_id, x, y, network, p, pe, ge, scale):
    Station.__init__(self, station_id, x, y, scale)
    self.__bts_list = set()
    self.bts = None
    self.pref_network = network
    self.p = p
    self.pe = pe
    self.ge = ge
    self.dtx = random.choice((True, False))

    self.__rxlev_dl = []
    self.__rxlev_up = []
    self.__rxqual_up = []
    self.__rxqual_dl = []

    self.__nb_means_rxlev_up = 0
    self.__nb_means_rxlev_dl = 0
    self.__nb_means_rxqual_up = 0
    self.__nb_means_rxqual_dl = 0
    self.__nb_means_distance = 0

    self.__rxlev_up_mean = []
    self.__rxlev_dl_mean = []
    self.__rxqual_up_mean = []
    self.__rxqual_dl_mean = []
    self.__distanceMsBts_mean = {}
    self.__rxlev_ncell_mean = {}

    self.__nbsamples = -1
    self.__nb_means = -1
    self.__distanceMsBts = {}
    self.__rxlev_ncell = {}
    for aBts in self.__bts_list:
      self.__distanceMsBts[aBts] = []
      self.__rxlev_ncell[aBts] = []

    self.__bts_candidate = None
    self.__nb_request = 0


    self.__bts_mutex = QtCore.QMutex()

    self.__last_move = random.randint(0, 7)

    self.__handover_timer = QtCore.QTimer()
    self.__handover_timer.timeout.connect(self.measure)
    self.set_speed(1)

    self.__start_timer = QtCore.QTimer()
    self.__start_timer.timeout.connect(self.__handover_timer.start)
    self.__start_timer.setSingleShot(random.randint(0, 480))
    self.__start_timer.start()
Exemplo n.º 10
0
    def fetch_until_score(self, score, weights = {}):
        result = Station()

        for adapter in self.available_adapters:
            print 'TEST'
            try:
                result += self.adapter_fetch(adapter)
                if result.score(weights) >= score:
                    break
            except StationError as error:
                print error

        return result
Exemplo n.º 11
0
    def info(inData):
        from auth import Auth
        pureData=Sensor.select(inData)

        stationInfo={}
        authInfo={}
        userInfo={}

        stationQuery=session.query(Station)
        authQuery=session.query(Auth)
        userQuery=session.query(User)
        for tmp in pureData['data']:
            t=tmp['stationId']

            tmpAllStation=Station.select({'id': int(t)})
            if(len(tmpAllStation['data'])==0):
                tmp['stationName']='not find'
            else:
                tmp['stationName']=tmpAllStation['data'][0]['name']

            tmpAllAuth=Auth.select({'sensorId': int(tmp['id'])})
            if(len(tmpAllAuth['data'])==0):
                tmp['username']='******'
                tmp['userId']=-1
            else:
                tmpAllUser=User.select({'id': int(tmpAllAuth['data'][0]['userId'])})
                if(len(tmpAllUser['data'])==0):
                    tmp['username']='******'
                    tmp['userId']=-1
                else:
                    tmp['username']=tmpAllUser['data'][0]['username']
                    tmp['userId']=tmpAllUser['data'][0]['id']

        return pureData
Exemplo n.º 12
0
    def info(inData):
        from user import User
        from sensor import Sensor
        from station import Station
        pureData=Auth.select(inData)

        userInfo={}
        sensorInfo={}
        stationInfo={}
        #print(pureData)

        for tmp in pureData['data']:
            t=tmp['sensorId']
            if(not(t in sensorInfo)):
                curSensor=Sensor.select({'id': t})
                sensorInfo[t]=curSensor
            tmp['sensorName']=sensorInfo[t]['data'][0]['name']

            t=sensorInfo[t]['data'][0]['stationId']
            if(not(t in stationInfo)):
                curStation=Station.select({id: t})
                stationInfo[t]=curStation
            tmp['stationName']=stationInfo[t]['data'][0]['name']

            t=tmp['userId']
            if(not(t in userInfo)):
                curUser=User.select({'id':t})
                userInfo[t]=curUser
            tmp['userName']=userInfo[t]['data'][0]['username']


        return pureData
Exemplo n.º 13
0
	def start(self):
		# parse arguments
		parser = argparse.ArgumentParser(description="Plays music from Songza in your terminal")
		# parser.add_argument("--query", metavar="Query Text", help="Query text used to search for stations; the app will start with query results pre-populated")
		parser.add_argument("--station_id", metavar="1234567", help="This is the station ID used internally by Songza")
		parser.add_argument("--debug", action="store_true", help="Add this flag to dump debug info to a file.")

		args = parser.parse_args()

		# instatiate a player and station
		self.player = VlcPlayer(args.debug)
		self.station = Station(self.player, 0, args.debug)

		# start streaming music, if station id was provided
		if args.station_id:
			self.station.station_id = args.station_id
			self.play_next()
			self.station.update_track_info()

		# build out the screen
		self.setup_screen()

		palette = [
			("bold", "default,bold", "default"),
			("reversed", "standout", ""),
			("logo", "default", "black")
		]

		# start the run loop
		loop = urwid.MainLoop(self.ui["container"], palette, unhandled_input=self.handle_input)
		loop.set_alarm_in(1, self.stream)
		loop.set_alarm_in(.5, self.update_player_ui)
		loop.run()
Exemplo n.º 14
0
def create_stations(filename='data/stops.txt'):
    """
    Reads in lines of stops GTFS file and creates stops objects
    parameters: 
        filename - string, the filename of the GTFS stops file
    returns:
        list of stations in the file, as Station objects
    """
    with open(filename, newline='') as stops:
        station_info = csv.reader(stops) 
        # skip first line, which is just attribute names
        next(station_info)
        # empty list to hold stations
        stations = []
        # parse all the lines and create stations
        for row in station_info:
            # assign each attribute of Station based on line in file

            (stop_id, stop_code, stop_name, stop_desc, platform_code, platform_name,\
                stop_lat, stop_lon, zone_id, stop_address, stop_url, level_id,\
                location_type, parent_station, wheelchair_boarding, municipality, on_street, at_street,vehicle_type) = tuple(row)
            # create Station instance with those attributes
            try:
                stations.append(Station(stop_id, stop_code, stop_name, stop_desc, \
                    platform_code, platform_name, stop_lat, stop_lon, stop_address, \
                    zone_id, stop_url, level_id, location_type, parent_station,\
                    wheelchair_boarding, municipality, on_street, at_street,vehicle_type))
            except ValueError:
                print("Value error at row : "+str(row)+"\n")
                
    return stations
Exemplo n.º 15
0
Arquivo: plugin.py Projeto: NSBum/EC
	def update(self,device):
		"""Updates a single device owned by this plugin.

		Args:
			device (indigo.dev): The plugin device to update.
		"""
		self.debugLog("Updating device: " + device.name)

		#	construct the url to fetch xml
		addr = device.pluginProps["address"]
		province = device.pluginProps["province"]
		station = Station(province,addr)
		#	try to fetch station xml
		try:
			response = urllib2.urlopen(station.url())
		except urllib2.HTTPError, e:
			errMsg = "HTTP error updating station {0}: {1}".format(addr,str(e))
			indigo.server.log(errMsg,isError=True)
			return
Exemplo n.º 16
0
 def getValues(self):
     if self.save:
         station = Station(str(self.name), self.technology, self.lat, self.lon, self.capacity, self.turbine, self.rotor,
                   self.no_turbines, self.area, self.scenario, power_file=self.power_file)
         if self.grid_line is not None:
             station.grid_line = self.grid_line
         if 'PV' in self.technology:
             if self.direction is not None:
                 station.direction = self.direction
             if self.tilt is not None:
                 station.tilt = self.tilt
         if self.storage_hours is not None:
             if self.technology == 'CST':
                 try:
                     if self.storage_hours != self.cst_tshours:
                         station.storage_hours = float(self.storage_hours)
                 except:
                     pass
             elif self.technology == 'Solar Thermal':
                 try:
                     if self.storage_hours != self.st_tshours:
                         station.storage_hours = float(self.storage_hours)
                 except:
                     pass
         return station
     else:
         return None
Exemplo n.º 17
0
  def __init__(self, station_id, x, y, network, ho_margin, ms_txpwr_max,
  bts_txpwr_max, rxlev_min, max_ms_range, l_rxqual_h, l_rxlev_dl_h,
  l_rxlev_up_h, pe, ge, f, scale):
    Station.__init__(self, station_id, x, y, scale)
    self.ms_list = set()
    self.network = network
    self.ho_margin = ho_margin
    self.ms_txpwr_max = ms_txpwr_max
    self.bts_txpwr_max = bts_txpwr_max
    self.rxlev_min = rxlev_min
    self.max_ms_range = max_ms_range
    self.l_rxqual_h = l_rxqual_h
    self.l_rxlev_dl_h = l_rxlev_dl_h
    self.l_rxlev_up_h = l_rxlev_up_h
    self.pe = pe
    self.ge = ge
    self.f = f

    #log_range = (ge + pe)/20. + 6.628 - math.log10(f)
    #self.nominal_range = pow(10, log_range) / scale
    # TODO
    log_range = (-32.44 - 20 * math.log10(f) + ge + 105 + pe)/20 / 3
    self.nominal_range = pow(10, log_range) * 1000 / scale
Exemplo n.º 18
0
    def info(inData):
        from user import User
        from sensor import Sensor
        from station import Station
        from auth import Auth
        allEqpData=Eqp.select(inData)

        userInfo={}
        sensorInfo={}
        stationInfo={}
        authInfo={}
        #print(allEqpData)

        for tmp in allEqpData['data']:
            
            t=tmp['number']
            tmpAllSensor=Sensor.select({'number': t})
            if(len(tmpAllSensor['data'])==0):
                tmp['sensorName']='not find'
                tmp['stationName']='not find'
                tmp['username']='******'
            else:
                curSensor=tmpAllSensor['pureData'][0]
                tmp['sensorName']=curSensor.name

                tmpAllStation=Station.select({'id': curSensor.stationId})
                if(len(tmpAllStation['data'])==0):
                    tmp['stationName']='not find'
                else:
                    curStation=tmpAllStation['pureData'][0]
                    tmp['stationName']=curStation.name
                    tmp['userName']=curStation.supervisor

                tmpAllAuth=Auth.select({'sensorId': curSensor.id})
                # if(len(tmpAllAuth['data'])==0):
                #     tmp['username']='******'
                # else:
                #     tmpAllUser=User.select({'id': tmpAllAuth['pureData'][0].userId})
                #     if(len(tmpAllUser['data'])==0):
                #         tmp['username']='******'
                #     else:
                #         tmp['username']=tmpAllUser['data'][0]['username']


        return allEqpData
Exemplo n.º 19
0
    def from_dict(cls, dct):  # type: (dict) -> LineupMap
        """

        :param dct:
        :return:
        """
        lineup_map = cls()

        lineup_map.stations = Station.from_iterable(dct.pop("stations"))

        lineup_map.channels = Channel.from_iterable(dct.pop("map"))

        for channel in lineup_map.channels:
            channel.station = lineup_map.get_station(channel.station_id)

        lineup_map.lineup = Lineup.from_dict(dct.pop("metadata"))

        if len(dct) != 0:
            logging.warn("Key(s) not processed for LineupMap: %s", ", ".join(dct.keys()))

        return lineup_map
Exemplo n.º 20
0
 def send_resupply(self,stat_id,amt):
     '''Station stat_id wants amt goods'''
     #sanity checks
     print amt
     if stat_id not in globalvars.stations: return False
     stat = globalvars.stations[stat_id]
     if stat.location not in ['LEO','GEO','ISS','HEO']: return False
     dv = botex.Course(botex.earthSurface,botex.fetchLocation(stat.location)).deltavee()
     amount_to_ship = 13150* (10.366/(math.exp((dv)/(450*9.8)) - 1))
     if stat.financial_account < amount_to_ship*get_launch_cost(): return False #cost of launch + supplies
     
     cargo_vessel = Station()
     cargo_vessel.location = stat.location
     #cargo_vessel.modules.append(module.DragonCargoModule().id)
     #cargo_vessel.add_item('MMH',412.8)
     #cargo_vessel.add_item('NTO',877.2)
     
     #check sum
     tot = 0
     for a in amt:
         assert amt[a] > 0
         tot += amt[a]*amount_to_ship
         cargo_vessel.add_item(a,amount_to_ship*amt[a])
     
     assert tot <= 14000 #3320
     #print amount_to_ship, tot
     #quit()
     
     stat.financial_account -= get_launch_cost()*cargo_vessel.mass
     
     global launch_rate
     launch_rate += 1
     
     #launched!  WOOO!
     print 'LAUNCHED!',amt
     
     #dock vessel to stat
     #cargo_vessel.home_station = stat_id
     #cargo_vessel.home_relationship = 'Wholly-Owned Subsidiary'
     cargo_vessel.dock(stat_id)
     return True
Exemplo n.º 21
0
    def check2(inData):
        '''
        :param name:
        :param number:
        :param stationId:
        1: success
        2: username repeat
        ret: {
            0: 'error',
            1: success,
            2:'no name in inData',
            3:'name is empty',
            4:'no number in inData',
            5:'number is empty',
            6:'no ip in inData',
            7:'ip is empty',
            8:'no mac in inData',
            9:'mac is empty',
            10:'no stationId in inData',
            11:'stationId is illegal',
            12:'name repeat',
            13:'number repeat',
            14:'mac repeat',
        }
        '''
        ret=1
        if(not inData.has_key('name')):
            ret=2
            return ret
        else:
            if(inData['name']==''):
                ret=3
                return ret
        if(not inData.has_key('number')):
            ret=4
            return ret
        else:
            if(inData['number']==''):
                ret=5
                return ret
        if(not inData.has_key('ip')):
            ret=6
            return 6
        else:
            if(inData['ip']==''):
                ret=7
                return ret
        if(not inData.has_key('mac')):
            ret=8
            return ret
        else:
            if(inData['mac']==''):
                ret=9
                return ret

        if(not inData.has_key('stationId')):
            ret=10
            return ret
        else:
            #print('111111111111', inData['stationId'])
            if(inData['stationId']==''):
                ret=11
                return ret
            if(int(inData['stationId'])!=0):
                tmpAllStation=Station.select({'id': int(inData['stationId'])})
                if(len(tmpAllStation['data'])==0):
                    ret=11
                    return ret

        query=session.query(Sensor)
        tmpSensor=query.filter(or_(Sensor.name==inData['name'], Sensor.number==inData['number'], Sensor.mac==inData['mac'])).all()
        for tSensor in tmpSensor:
            if(tSensor.name==inData['name']):
                ret=12
                return ret
            if(tSensor.number==inData['number']):
                ret=13
                return ret
            if(tSensor.mac==inData['mac']):
                ret=14
                return ret

        ret=1
        return ret
Exemplo n.º 22
0
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    #create formatter
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    #add formatter to ch
    ch.setFormatter(formatter)
    #add ch to logger
    logger.addHandler(ch)

    modA  = DestinyModule()
    modDock = UnityModule()    
    modB   = ZvezdaModule()
    modDrag = DragonCargoModule()
    modDrag.setup_simple_resupply()
           
    station = Station(modDock, 'NewbieStation', logger)
    station.berth_module(modDock,'CBM0',modA, None, True)
    station.berth_module(modDock,'CBM3',modB, None, True)    
    station.berth_module(modA,None,modDrag, None, True)
    
    '''rob = Robot('Robby')     
    rob.station = station
    station.actors[rob.id]=rob
    rob.location = modB.node('hall0')
    rob.xyz = modB.location'''
    
    ernie= Human('Bela Lugosi',station=station,logger=station.logger)
    station.actors[ernie.id] = ernie
    ernie.location = modA.node('hall0')
    ernie.xyz = modA.location
    
Exemplo n.º 23
0
from station import Station
from rhoa import rho_a
from phi import phi
import sys

if (__name__=="__main__"):
    arq_jformat=sys.argv[1]
    component=sys.argv[2]

    stn=Station()
    stn.read(arq_jformat)

    T, rho, rho_err = rho_a(stn.Z[component])
    
    T, phi, phi_err = phi(stn.Z[component])
    
    print "> %s %s" % (stn.stationName, component)
    print "\tT \tRho \tRho_err \tPhi \tPhi_err"
    for j in range(0,len(T)):
        print "%10.4e %10.4e %10.4e %10.4e %10.4e" % \
            (T[j], rho[j], rho_err[j],phi[j],phi_err[j])
Exemplo n.º 24
0
 def __init__(self):
     Station.__init__(self,name='Earthside',location = 'Earthside')
     
     for i in ['Food','Water','General Consumables','Parts','Nitrogen','Brine','Solid Waste','Liquid Waste']:
         self.storage_avg_price[i] = 0
         self.storage_tariff[i] = get_launch_cost()
Exemplo n.º 25
0
    #print fuel
    #leogeoDV = 450*9.8*math.log(fuel+m1/m1)
    # fuel+m1/m1 = math.exp(leogeoDV/(450*9.8))
    #fuel = (math.exp(leogeoDV/(450*9.8)) - 1)*m1
    #m1 = fuel/(math.exp(leogeoDV/(450*9.8)) - 1)    
    #print fuel/(math.exp((leoDV)/(450*9.8)) - 1)
    #quit()
    '''print botex.Course(botex.earthSurface,botex.highEarthOrbit).deltavee()        
    print botex.Course(botex.earthSurface,botex.stationaryEarthOrbit).deltavee()    
    print get_launch_cost(),get_launch_cost(4.0)
    print
    print botex.plot(botex.earthSurface,botex.marsSurface)
    '''
    
    from time import sleep         
    test = Station('Test Station')        
    
    import module
    import actors
    import util

    test.modules.append(module.SolarPowerModule().id)
    
    #Solar Power Plant
    for r in range(1,350):
        test.modules.append(module.SolarPowerModule().id)
    
        
    #test.modules.append(module.BasicLivingModule().id)
    #test.modules.append(module.BasicHydroponicsModule().id)        
    #test.modules.append(module.BasicHabitationModule().id)
Exemplo n.º 26
0
def main():
    station = Station()
    gen = DataGenerator(station=station)
    sch = Scheduler(station=station)
    fex = FrameExtractor(channel=sch.mapper.channel)

    imsi_list = []
    user_equipments = []

    # generate a list of user equipments with unique ID
    for i in range(getattr(settings, 'NB_USERS', 5)):
        imsi = generate_imsi()
        if not imsi in imsi_list:
            imsi_list.append(imsi)
            user_equipments.append(UserEquipment(id=imsi))

    # connect all user equipments to the station
    for ue in user_equipments:
        station.connect_user_equipment(ue)
        ue.connect_to_station(station, fex)

    gen.start()
    sch.start()
    fex.start()

    for ue in user_equipments:
        ue.start()

    app = App()
    gui = DrawPanel(station, sch, user_equipments)
    gui.Show()
    app.MainLoop()

    sch.join()
    fex.stop()
    gen.stop()

    for ue in user_equipments:
        ue.stop()

    try:  # let's plot(graph) all this
        from plots import (
            graph_users_throughputs,
            graph_users_th_throughputs,
            graph_users_cqis,
            graph_users_rbgs
        )

        graph_users_throughputs(
            station.users_throughput,
            sch.algorithm.__class__.__name__
        )
        graph_users_th_throughputs(
            station.users_th_throughput,
            sch.algorithm.__class__.__name__
        )
        graph_users_cqis(station.users_cqis_hist)
        graph_users_rbgs(
            station.users_rbgs_hist,
            sch.algorithm.__class__.__name__
        )
    except ImportError:
        print "WARNING: matplotlib is not installed," \
            + "no plot will be generated"
def generateRDFs():
	with open(CSV_PATH, 'r') as stdoc:
		#Each line of CSV represents an station. Content of each line: OBJECTID, IDEST, NAME, DIR, POBL, URL, ZONE, URL_ZONE, PROV_COD,..., XUTM, YUTM
		reader = csv.reader(stdoc, delimiter=';', quoting=csv.QUOTE_NONE)
		for details in reader:
			#It only saves an station if it has an URL (details[5])
			if ("http://" in details[5]):
				lat = None
				lng = None

				#Call to "utmll" library for converting from UTM to LatLng coordinates
				#lat, lng = UTMtoLL(23, float(details[-2].replace(',', '.')), float(details[-1].replace(',', '.')), "30T")

				#Transformation from UTM to Spherical Mercator, and from SM to Lat Long (WGS84) with "pyproj"
				utm = pyproj.Proj(init='epsg:23030')
				sm = pyproj.Proj(init='epsg:3785')
				wgs = pyproj.Proj(init='epsg:4326')
				sm_x, sm_y = pyproj.transform(utm, sm, float(details[-2].replace(',', '.')), float(details[-1].replace(',', '.')))
				lng, lat = pyproj.transform(sm, wgs, sm_x, sm_y)

				#Get codes and format as needed
				cod = re.sub('CodEst=', '', re.findall('CodEst=.+\&', details[5])[0])
				cod = formatCod(cod = utf8encoding(cod))
				codzone = re.sub('CodZona=\@', '', re.findall('CodZona=\@.+\&', details[5])[0])
				codzone = formatCod(cod = utf8encoding(codzone))

				if cod == "ZUMARR":
					lat = float(43.08395)
					lng = float(-2.315733)

				#Get internal id
				id = re.split(',', details[1])[0]

				geonamesuri = get_geonames_uri(lat=lat, lng=lng)

				#Get and format url (quote) avoiding errors with special characters
				url = utf8encoding(details[5])
				url = url[:-1] if url[-1] == '"' else url
				url = "http:" + urllib.quote(url[5:])

				#Get address and province
				try:
					address = utf8encoding(details[3])
				except:
					address = None

				prov = utf8encoding(details[8])

				zonedesc = utf8encoding(details[6])

				print utf8encoding(details[2])

				#Create station
				station = Station(cod=cod, codzone=codzone, id=id, name=utf8encoding(details[2]), location=utf8encoding(details[4]), url=url, lat=lat, lng=lng, address=address, prov=prov, zonedesc=zonedesc, geonames=geonamesuri)

				#Generate all RDFs
				sparql = None
				path = None
				if ST_PATH:
					path = ST_PATH + station.internal_id + "_" + station.cod + "_at_" + station.codzone + ".rdf"
				else:
					sparql = VIRTUOSO_URL

				if cod.find("BETO") == -1:
					station.generateRDF(resourceuri=RESOURCE_URI, sparql=sparql, path=path)
			else:
				pass#print "SIN WEB: " + details[2].decode('latin-1').encode('utf-8')
def generateMissingRDFs():
	lat, lng = 43.285890624612605, -2.0001983642578125
	station = Station(cod="ANORGA", codzone="DONOS", id=100, name="Añorga", location="Donostia", url="http://www.ingurumena.ejgv.euskadi.net/r49-n82/es/vima_ai_vigilancia/estaciones.apl?CodZona=@DONOS&CodEst=A%D1ORGA&lenguaje=C", lat=lat, lng=lng, address=None, prov="GIPUZKOA", zonedesc="Donostialdea", geonames=get_geonames_uri(lat=lat, lng=lng))
	station.generateRDF(resourceuri=RESOURCE_URI, sparql=VIRTUOSO_URL, path=None)

	lat, lng = UTMtoLL(23, 537791.53, 4775458.32, "30T")
	station = Station(cod="ELORIO", codzone="IBDEB", id=51, name="Elorrio", location="Elorrio", url="http://www.ingurumena.ejgv.euskadi.net/r49-n82/es/vima_ai_vigilancia/estaciones.apl?CodZona=@IBDEB&CodEst=ELORIO&lenguaje=C", lat=lat, lng=lng, address=None, prov="BIZKAIA", zonedesc="Ibaizabal-Alto Deba/Ibaizabal-Deba garaia", geonames=get_geonames_uri(lat=lat, lng=lng))
	station.generateRDF(resourceuri=RESOURCE_URI, sparql=VIRTUOSO_URL, path=None)

	lat, lng = UTMtoLL(23, 528629.73, 4746400.9, "30T")
	station = Station(cod="BETONO", codzone="LLALV", id=19, name="Betoño", location="Vitoria-Gasteiz", url="http://www.ingurumena.ejgv.euskadi.net/r49-n82/es/vima_ai_vigilancia/estaciones.apl?CodZona=@LLALV&codest=BETO%D1O&lenguaje=c", lat=lat, lng=lng, address="Portal de Vergara,10", prov="ARABA", zonedesc="Llanada Alavesa/Arabako lautada", geonames=get_geonames_uri(lat=lat, lng=lng))
	station.generateRDF(resourceuri=RESOURCE_URI, sparql=VIRTUOSO_URL, path=None)

	lat, lng = UTMtoLL(23, 504952.62, 4789929.93, "30T")
	station = Station(cod="INDAUC", codzone="BJNVN", id=35, name="Indautxu Reubicada", location="Bilbao", url="http://www.ingurumena.ejgv.euskadi.net/r49-n82/es/vima_ai_vigilancia/estaciones.apl?CodZona=@BJNVN&codest=INDAUC&lenguaje=c", lat=lat, lng=lng, address=None, prov="BIZKAIA", zonedesc="Bajo Nervión/Nerbioi behera", geonames=get_geonames_uri(lat=lat, lng=lng))
	station.generateRDF(resourceuri=RESOURCE_URI, sparql=VIRTUOSO_URL, path=None)
Exemplo n.º 29
0
def get_container_id():
    station = Station(stationname)
    station.fetch_station_id()
    container = Container(containername, station)
    container.fetch_container_id()
    return container.containerid
Exemplo n.º 30
0
    def __init__(self, a_station_list=None):
        """
        Pass in the absolute file name to the station list and it well be parsed and
        put into a dictionary accessible with iterators.
        """
        if a_station_list is None:
            print("Error reading station list - Null Station List")
            sys.exit(-1)
        self.a_station_filename = a_station_list

        # Start with empty station list
        self.site_list = []

        # Open file
        try:
            station_file = open(self.a_station_filename, "r")
        except IOError:
            print("Error opening station list file : ", a_station_list)
            sys.exit(-1)

        # Read lines one by one
        for line in station_file:
            if line.startswith("#"):
                continue
            sta = line.split()

            if len(sta) >= 3:
                station = Station()
                station.lon = float(sta[0])
                station.lat = float(sta[1])
                station.scode = sta[2]
                if len(station.scode) > MAX_STATION_NAME_LEN:
                    print("Error: station name %s too long!" % (station.scode))
                    print("Maximum limit is %d!" % (MAX_STATION_NAME_LEN))
                    sys.exit(-1)
                if len(sta) >= 4:
                    station.vs30 = int(float(sta[3]))
                if len(sta) >= 6:
                    # We have lf and hf, make sure they are not zero!
                    if float(sta[4]) <= 0:
                        print("warning: station %s has lf<=0, using 1e-15" %
                              (sta[2]))
                        station.low_freq_corner = 1.0e-15
                    else:
                        station.low_freq_corner = float(sta[4])
                    if float(sta[5]) <= 0:
                        print("warning: station %s has hf<=0, using 1e+15" %
                              (sta[2]))
                        station.high_freq_corner = 1.0e+15
                    else:
                        station.high_freq_corner = float(sta[5])
                self.site_list.append(station)
        # Remember to close the file
        try:
            station_file.close
        except IOError:
            print("Error closing station list file :", a_station_list)
        # Error message if we weren't able to read any stations
        if len(self.site_list) == 0:
            print("No stations read from station file :", a_station_list)
            sys.exit(-1)
Exemplo n.º 31
0
    def _setupScenario(self, scenario):
        i = scenario.rfind('/')
        if i > 0:
            scen_file = scenario
            scen_filter = scenario[i + 1:]
        else:
            scen_file = self.scenarios + scenario
            scen_filter = scenario
        if os.path.exists(scen_file):
            description = ''
            if scen_file[-4:] == '.xls' or scen_file[-5:] == '.xlsx' or \
             scen_file[-5:] == '.xls~' or scen_file[-6:] == '.xlsx~':
                var = {}
                workbook = xlrd.open_workbook(scen_file)
                worksheet = workbook.sheet_by_index(0)
                num_rows = worksheet.nrows - 1
                num_cols = worksheet.ncols - 1
                if worksheet.cell_value(0, 0) == 'Description:' or worksheet.cell_value(0, 0) == 'Comment:':
                    curr_row = 1
                    description = worksheet.cell_value(0, 1)
                else:
                    curr_row = 0
#               get column names
                curr_col = -1
                while curr_col < num_cols:
                    curr_col += 1
                    var[worksheet.cell_value(curr_row, curr_col)] = curr_col
                while curr_row < num_rows:
                    curr_row += 1
                    try:
                        new_st = Station(str(worksheet.cell_value(curr_row, var['Station Name'])),
                                         str(worksheet.cell_value(curr_row, var['Technology'])),
                                         worksheet.cell_value(curr_row, var['Latitude']),
                                         worksheet.cell_value(curr_row, var['Longitude']),
                                         worksheet.cell_value(curr_row, var['Maximum Capacity (MW)']),
                                         str(worksheet.cell_value(curr_row, var['Turbine'])),
                                         worksheet.cell_value(curr_row, var['Rotor Diam']),
                                         worksheet.cell_value(curr_row, var['No. turbines']),
                                         worksheet.cell_value(curr_row, var['Area']),
                                         scen_filter)
                        name_ok = False
                        new_name = new_st.name
                        ctr = 0
                        while not name_ok:
                            for i in range(len(self._stations.stations)):
                                if self._stations.stations[i].name == new_name:
                                    ctr += 1
                                    new_name = new_st.name + ' ' + str(ctr)
                                    break
                            else:
                                name_ok = True
                        if new_name != new_st.name:
                            new_st.name = new_name
                        if new_st.area == 0 or new_st.area == '':
                            if new_st.technology == 'Wind':
                                new_st.area = self.areas[new_st.technology] * float(new_st.no_turbines) * \
                                              pow((new_st.rotor * .001), 2)
                            else:
                                new_st.area = self.areas[new_st.technology] * float(new_st.capacity)
                        try:
                            power_file = worksheet.cell_value(curr_row, var['Power File'])
                            if power_file != '':
                                new_st.power_file = power_file
                        except:
                            pass
                        try:
                            grid_line = worksheet.cell_value(curr_row, var['Grid Line'])
                            if grid_line != '':
                                new_st.grid_line = grid_line
                        except:
                            pass
                        try:
                            direction = worksheet.cell_value(curr_row, var['Direction'])
                            if direction != '':
                                new_st.direction = direction
                        except:
                            pass
                        try:
                            storage_hours = worksheet.cell_value(curr_row, var['Storage Hours'])
                            if storage_hours != '':
                                new_st.storage_hours = storage_hours
                        except:
                            pass
                        self._stations.stations.append(new_st)
                        self.addStation(self._stations.stations[-1])
                    except:
                        break
            else:
                scene = open(scen_file)
                line = scene.readline()
                if len(line) > 9 and line[:9] ==  'Comment:,' or len(line) > 13 and line[:13] == 'Description:,':
                    if line[:9] ==  'Comment:,':
                        description = line[9:]
                    else:
                        description = line[13:]
                    if description[0] == '"':
                        i = description.rfind('"')
                        description = description[1:i - 1]
                    else:
                        bits = line.split(',')
                        description = bits[1]
                else:
                    scene.seek(0)
                new_stations = csv.DictReader(scene)
                for st in new_stations:
                    new_st = Station(st['Station Name'], st['Technology'], float(st['Latitude']),
                             float(st['Longitude']), float(st['Maximum Capacity (MW)']),
                             st['Turbine'], float(st['Rotor Diam']), int(st['No. turbines']), float(st['Area']), scen_filter)
                    if new_st.area == 0:
                        if new_st.technology == 'Wind':
                            new_st.area = self.areas[new_st.technology] * float(new_st.no_turbines) * \
                                          pow((new_st.rotor * .001), 2)
                        else:
                            new_st.area = self.areas[new_st.technology] * float(new_st.capacity)
                    self._stations.stations.append(new_st)
                    self.addStation(self._stations.stations[-1])
                scene.close()
            self._scenarios.append([scen_filter, False, description])