Exemplo n.º 1
0
    def __init__(self,
                 path: str = None,
                 citySep: str = ".",
                 fileSep: str = "_") -> None:
        """

        :param path: path where network structure is saved. It contains folders with csv files
        :param citySep: separator of city (instead space), e.g. "Warszawa Centralna" to "Warszawa.Centralna"
        :param fileSep: separator of file name. It concatenates city name and city bilkomCode, e.g. "Siemiatycze_5103355"
        """
        super().__init__()
        if path is not None:
            for cityFromFile in os.listdir(path):
                if isdir(join(path, cityFromFile)):
                    cityFromFileSep = cityFromFile.split(fileSep)
                    cityFrom = cityFromFileSep[0].replace(citySep, " ")
                    codeFrom = cityFromFileSep[1]
                    cityCodeFrom = Station(cityFrom, codeFrom)
                    self.stationList.append(cityCodeFrom)
                    self[cityFrom] = {}
                    for cityToFile in os.listdir(join(path, cityFromFile)):
                        cityToFilePath = join(path, cityFromFile, cityToFile)
                        if isfile(cityToFilePath):
                            cityToFileSep = cityToFile.split(fileSep)
                            cityTo = cityToFileSep[0].replace(citySep, " ")
                            codeTo = cityToFileSep[1]
                            cityCodeTo = Station(cityTo, codeTo)
                            self.stationList.append(cityCodeTo)
                            self[cityFrom][cityTo] = pd.read_csv(
                                cityToFilePath)
Exemplo n.º 2
0
def main():
    """
    all the test of the class Line
    """
    #Header
    print("*******************")
    print(" Line module test")
    print("*******************")
    #creation of 5 stations
    A = Station("A", [1., 0.])
    B = Station("B", [2., 0.])
    C = Station("C", [3., 0.])
    D = Station("D", [4., 0.])
    E = Station("E", [5., 0.])
    Line_1 = Line([A, B, C, D, E], "underground", "Line_1")
    ############################################################################
    #                           Declaration TEST                               #
    ############################################################################
    assert Line_1.station == [A, B, C, D, E]
    print("self.station    OK")
    assert Line_1.mode == "underground"
    print("self.mode       OK")
    assert Line_1.name == "Line_1"
    print("self.name       OK")
    ############################################################################
    #                               Message end                                #
    ############################################################################
    print("Line is         OK")
    print("*******************")
    print(Line_1._repr_())
Exemplo n.º 3
0
def getFilePathFromUser():
    try:
        print 'Podaj sciezke do pliku txt, np.: ./dane/plik_z_depeszami.txt '
        filePath = raw_input()
        synop = gS.getSynopFile(path=filePath)
        station = St.Station(synopCode=synop[0], getSynopType='file')
        dateFirst = station.decodeDate()
        wrongDateSum = 0
        for eggs in synop:
            station = St.Station(synopCode=eggs, getSynopType='file')
            date = station.decodeDate()
            if dateFirst == date:
                pass
            else:
                wrongDateSum += 1
        if wrongDateSum > 0:
            print 'Depesze pochodza z roznych okresow, mozliwy bedzie jedynie wydruk pliku Xlsx!'
            rep = synop
            return True, False, rep
        else:
            rep = synop
            return True, True, rep
    except IOError:
        rep = 'Niepoprawnie wprowadzono sciezke do pliku!'
        return False, False, rep
    except IndexError:
        rep = 'Podano pusty plik!'
        return False, False, rep
    def testScheduleCompletion(self):
        #Verify scheduling completion of an arrival
        simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(500)
        #create first station
        station1 = Station.Station(1, 20.0)
        #create second station
        station2 = Station.Station(2, 40.0)
        #add stations to simulator
        simulator.addStation(station1)
        simulator.addStation(station2)

        #create frame
        msg1 = Frame(1, 'Hello Station 2', 1, 2)

        #create event
        evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1)

        #add event to q
        simulator.addEvent(evt1)

        #process event
        simulator.processSingleEvent()
        evtQ = simulator.evtQ
        self.assertEquals(evtQ._qsize(), 2)

        #evt2 = evtQ[0]
        evt2 = evtQ.get()
        self.assertEquals(evt2.eventType, Event.TRANSMIT_COMPLETE)
        self.assertAlmostEquals(evt2.time, 126.73)
        self.assertEquals(evt2.stationId, 1)
        #evt3 = evtQ[1]
        evt3 = evtQ.get()
Exemplo n.º 5
0
    def init_city(self):
        """we set some Stations in place."""

        if 'init' in DEBUG: print("Setting main station...")
        self.stations.append(Station.Station(self,(int((MAX_X-RIGHT_OFFSET)/2), int (MAX_Y/2)),\
                                "square"))
        # TODO: make sure that every shape exists
        if 'init' in DEBUG: print("Setting stations...")
        for i in range(0, MAXSTATIONS):
            pos = self.random_pos()
            if pos:
                s = Station.Station(self, pos)
                self.stations.append(s)
        def testBackoff1(self):
            #Test retransmission after one collision, using specified
            #rather than random backoff
            simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(500)
            station1 = Station.Station(1, 20.0)
            simulator.addStation(station1)
            msg1 = Frame(1, 'Hello Station 2', 1, 2)
            evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1)
            station2 = Station.Station(2, 40.0)
            simulator.addEvent(evt1)
            simulator.addStation(station1)
            simulator.addStation(station2)
            msg2 = Frame(2, 'Hello Station 1', 2, 1)
            evt2 = Event(Event.ARRIVAL, 123.50, 2, msg2)
            simulator.addEvent(evt2)
            simulator.processSingleEvent()

            self.assertAlmostEquals(simulator.simTime, 123.45)
            simulator.processSingleEvent()  #should transmit msg2
            #and schedule collision detection

            evtQ = simulator.evtQ
            self.assertEquals(evtQ._qsize(), 2)
            evt3 = evtQ.get()
            self.assertEquals(evt3.eventType, Event.COLLISION_DETECT)
            self.assertAlmostEquals(evt3.time, 123.45, 0)
            self.assertEquals(evt3.stationId, 2)
            evt4 = evtQ.get()
            self.assertEquals(evt4.eventType, Event.COLLISION_DETECT)
            self.assertAlmostEquals(evt4.time, 126.45, 0)
            self.assertEquals(evt4.stationId, 1)

            simulator.processSingleEvent()
            evt4 = evtQ.get()
            self.assertEquals(evt4.eventType, Event.JAMMING_END)
            simulator.processSingleEvent()
            evt5 = evtQ.get()
            self.assertEquals(evt5.eventType, Event.JAMMING_END)

            simulator.processSingleEvent()
            simulator.set_back_off_time(1.5)
            evt6 = evtQ.get()
            self.assertEquals(evt6.eventType, Event.TRANSMIT_ATTEMPT)
            self.assertAlmostEquals(evt6.time, 126.45 + 1.5)

            simulator.processSingleEvent()
            simulator.set_back_off_time(.9)
            evt7 = evtQ.get()
            self.assertEquals(evt7.eventType, Event.TRANSMIT_ATTEMPT)
            self.assertAlmostEquals(evt7.time, 126.45 + .9)
Exemplo n.º 7
0
def main():
    """
    all the test of the class Station
    """
    #Header 
    print ("*******************")
    print ("Station module test")
    print ("*******************")
    #creation of 3 stations
    orsay_ville  = Station("Orsay Ville",[1.5,3.14],"RER B")
    orsay_ville2 = Station("Orsay",[1.5,3.14],"RER B")
    orsay = Station("Orsay Ville",[1.5,3.14],"RER B")
    gare_est = Station("Gare de l'est",[1.5,3.14],"RER P")
    ############################################################################
    #                           Declaration TEST                               #
    ############################################################################
    assert gare_est.name == "Gare de l'est"
    print("self.name       OK")
    assert gare_est.position == [1.5,3.14]
    print("self.position   OK")
    assert gare_est.in_line == "RER P"
    print("self.in_line    OK")
    ############################################################################
    #                                __eq__ TEST                               #
    ############################################################################
    assert orsay_ville._eq_(orsay) == True
    print("self._eq_       OK")
    ############################################################################
    #                                __lt__ TEST                               #
    ############################################################################
    A = Station("aaaab",[1.5,3.14],"RER B")
    B = Station("aaaaa",[1.5,3.14],"RER B")
    C = Station("aaaab",[1.5,3.14],"RER B")
    D = Station("aaaab",[1.5,3.14],"RER P")
    assert A._lt_(B) == "aaaaa"
    assert D._lt_(C) == "aaaab"
    print("self._lt_       OK")
    ############################################################################
    #                              __hash__ TEST                               #
    ############################################################################    
    assert orsay_ville._hash_() ==  orsay._hash_()
    print("self._hash_     OK")
    ############################################################################
    #                               __str__ TEST                               #
    ############################################################################
    msg  = "************************\n"
    msg += "* Station Informations *\n"
    msg += "************************\n"
    msg += "Name     = " + str(gare_est.name) + "\n"
    msg += "Position = " + str(gare_est.position) + "\n"
    msg += "Line     = " + str(gare_est.in_line) + "\n"
    msg += "************************"
    assert gare_est._str_() == msg
    print("self._str_      OK")
    ############################################################################
    #                               Message end                                #
    ############################################################################
    print ("Station is      OK")
    print ("*******************")
Exemplo n.º 8
0
    def load(self):
        file = open(self.DATA_FILE, "rb")
        count = int.from_bytes(file.read(4), "little")
        index = int.from_bytes(file.read(4), "little")
        for i in range(0, count):
            type = int.from_bytes(file.read(4), "little")
            if type == CanvasItem.OBSTACLE:
                item = Obstacle(self)
                self._obs[item.get_index] = item
            elif type == CanvasItem.ACCESS:
                item = Ap(self)
                self._aps[item.get_index] = item
            elif type == CanvasItem.STATION:
                item = Station(self)
                self._sts[item.get_index] = item
            item.load(file)
            self._items[item.get_index()] = item

        if index == 31337:
            index = self.NO_SELECTION
        self._index = index
        items = self._items.values()
        for item in items:
            item.draw()
        file.close()
Exemplo n.º 9
0
    def make_station_at_planet(self, planet, elements, universe):
        station = Station.Station(universe, 32)
        station.mass.enter_orbit(planet, planet.mass.universe_radius*1.5, self.R.random()*math.pi*2.0, 0.000001*self.R.randint(-20,20))
        station.name = planet.name+" Station"
        elements.append(station)

        self.make_ship_at_station( station, elements, universe)
 def testAddEvent(self):
     #test adding events to the simulator
     simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(
         500)  #500 meters diameter
     station1 = Station.Station(1, 20.0)
     station2 = Station.Station(2, 80.0)
     simulator.addStation(station1)
     simulator.addStation(station2)
     msg1 = Frame(1, 'Hello Station 2', 1, 2)
     msg2 = Frame(2, 'Hello Station 1', 2, 1)
     evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1)
     evt2 = Event(Event.ARRIVAL, 234.56, 2, msg2)
     simulator.addEvent(evt2)
     simulator.addEvent(evt1)  # not in time order
     evtQ = simulator.evtQ
     self.assertEquals(evtQ._qsize(), 2)
Exemplo n.º 11
0
def createStations(config):
    """
    createStations(config) ==> None

    For each station defined in the config file createStations()
    will create a station object and populate it with the correct
    list of probes.  It will then add the new station to the
    dictionary of stations.
    """
    trace("createStations()")
    for section in config.sections():
        if section.capitalize().startswith("Station"):
            myPressureProbes = myHumidityProbes = []
            myTemperatureProbes = []
            name = section.capitalize()
            for option in config.options(section):
                value = config.get(section, option)
                opt = option.capitalize()
                if opt == "Name":
                    name = value.capitalize()
                elif opt == "Temperature":
                    myTemperatureProbes = getProbeList(value,
                                                       temperatureProbes)
                elif opt == "Pressure":
                    myPressureProbes = getProbeList(value, pressureProbes)
                elif opt == "Humidity":
                    myHumidityProbes = getProbeList(value, humidityProbes)
            stations[name] = Station.Station(myTemperatureProbes,
                                             myPressureProbes,
                                             myHumidityProbes, name)
Exemplo n.º 12
0
def secondReactXlsx(synop, synopType, fileNameAndPath):
    statList = []
    for eggs in synop:
        station = St.Station(getSynopType=synopType, synopCode=eggs)
        statList.append(station)
    pXR.printXlsx(station=statList,
                  fileName=fileNameAndPath[0],
                  path=fileNameAndPath[1])
Exemplo n.º 13
0
 def addStop(self, stop_properties):
     """
     stop_properties = [stop_id, stop_name, stop_desc, stop_lat, stop_lon]
     """
     if stop_properties[0] not in self.StopList:
         self.numStop = self.numStop + 1
         newStop = Station.Station(*stop_properties)
         self.StopList[newStop.id] = newStop
Exemplo n.º 14
0
def build_all_stations(df):
    # takes all items of the stopID dataset to build stations
    l = []
    for index, row in df.iterrows():
        l.append(
            st.Station(row['stop_id'], row['stop_name'], row['stop_desc'],
                       row['stop_lat'], row['stop_lon']))
        if index == 60:
            pdb.set_trace()
    return l
    def testMediaBusy(self):
        #Test whether the media is bus
        simulator2 = CSMA_CD_Simulator.CSMA_CD_Simulator(500)
        station1 = Station.Station(1, 20.0)
        station2 = Station.Station(2, 40.0)
        simulator2.addStation(station1)
        simulator2.addStation(station2)
        msg1 = Frame(1, 'Hello Station 2', 1, 2)
        evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1)
        simulator2.addEvent(evt1)

        simulator2.processSingleEvent()  #should transmit msg
        #and schedule completion

        self.assertFalse(simulator2.media_busy(40, 123.50))
        self.assertTrue(simulator2.media_busy(40, 123.60))
        #check media after the transmission is completed at 126.73
        self.assertFalse(simulator2.media_busy(40, 126.85))
        self.assertTrue(simulator2.media_busy(60, 126.85))
Exemplo n.º 16
0
def build_all_stations(df_stops):
    # takes all items of the stopID dataset to build stations
    # df_trips à filtrer à 0;+5h ensuite pour ne pas alourdir.
    l = {}
    for index, row in df_stops.iterrows():
        newstation = st.Station(row['stop_id'], row['stop_name'],
                                row['stop_desc'], row['stop_lat'],
                                row['stop_lon'])
        l[row.stop_id] = newstation
    return l
Exemplo n.º 17
0
 def __init__(self, filename):
     self.train = {"stationIndex": 0, "occupants": []}
     self.stations = []
     self.passengerCount = 1
     infile = open(filename)
     i = 1
     for line in infile:
         self.train["occupants"].append(Queue())
         self.stations.append(Station(line[:-1], False, i, Queue()))
         i += 1
     self.stations[0].trainHere = True
     infile.close()
Exemplo n.º 18
0
def checkDate(stationList):
    dateList = []
    for spam in stationList:
        station = St.Station(getSynopType='file', depesza=spam)
        dateList.append(station.decodeDate())
    sumListLen = 0
    listLen = len(stationList) + 1
    for eggs in range(listLen):
        if eggs == dateList[eggs]:
            sumListLen += 1
    if sumListLen == listLen:
        return True
    else:
        return False
Exemplo n.º 19
0
    def add_item(self, type):
        if type == CanvasItem.ACCESS:
            item = Ap(self, self.SPAWN_X, self.SPAWN_Y)
            self._aps[item.get_index()] = item
        elif type == CanvasItem.STATION:
            item = Station(self, self.SPAWN_X, self.SPAWN_Y)
            self._sts[item.get_index()] = item
        elif type == CanvasItem.OBSTACLE:
            item = Obstacle(self, self.SPAWN_X, self.SPAWN_Y)
            self._obs[item.get_index()] = item

        self._items[item.get_index()] = item
        self._index = item.get_index()
        item.draw()
        self.connect(item)
        def testJamming(self):
            simulator = CSMA_CD_Simulator.CSMA_CD_Simulator(500)
            station1 = Station.Station(1, 20.0)
            simulator.addStation(station1)
            msg1 = Frame(1, 'Hello Station 2', 1, 2)
            evt1 = Event(Event.ARRIVAL, 123.45, 1, msg1)
            station2 = Station.Station(2, 40.0)
            simulator.addEvent(evt1)
            simulator.addStation(station1)
            simulator.addStation(station2)
            msg2 = Frame(2, 'Hello Station 1', 2, 1)
            evt2 = Event(Event.ARRIVAL, 123.50, 2, msg2)
            simulator.addEvent(evt2)
            simulator.processSingleEvent()

            self.assertAlmostEquals(simulator.simTime, 123.45)
            simulator.processSingleEvent()  #should transmit msg2
            #and schedule collision detection

            evtQ = simulator.evtQ
            self.assertEquals(evtQ._qsize(), 2)
            evt3 = evtQ.get()
            self.assertEquals(evt3.eventType, Event.COLLISION_DETECT)
            self.assertAlmostEquals(evt3.time, 123.45, 0)
            self.assertEquals(evt3.stationId, 2)
            evt4 = evtQ.get()
            self.assertEquals(evt4.eventType, Event.COLLISION_DETECT)
            self.assertAlmostEquals(evt4.time, 126.45, 0)
            self.assertEquals(evt4.stationId, 1)
            #test jamming
            simulator.processSingleEvent()
            evt4 = evtQ.get()
            self.assertEquals(evt4.eventType, Event.JAMMING_END)
            simulator.processSingleEvent()
            evt5 = evtQ.get()
            self.assertEquals(evt5.eventType, Event.JAMMING_END)
Exemplo n.º 21
0
    def build_station(self, pos):
        """builds a random station at position pos"""

        if not self.building_place(pos):
            if 'station' in DEBUG: print "can't build at ", pos
            self.status = "No place for station here."
            return
        if self.score >= STATIONCOST:
            station = Station.Station(self, pos)
            self.stations.append(station)
            if 'station' in DEBUG: print "build station at ", pos
            self.status = "build station for $" + str(STATIONCOST)
            self.score -= STATIONCOST
        else:
            self.status = "Not enough money left to build station. You need $" + str(
                STATIONCOST)
Exemplo n.º 22
0
    def editStation(self):
        if len(self.stations) == 0:
            print "You have not added any stations. Please add stations and try again"
            return

        print "Please choose a station to edit"
        for index, station in enumerate(self.stations):
            print index + 1, " ", station

        try:
            choice = int(raw_input())
        except ValueError:
            print "Please enter a valid integer"
            return

        if choice < 1 or choice > len(self.stations):
            print "Please enter a valid integer"
            return

        self.stations[choice - 1] = Station.Station()
Exemplo n.º 23
0
def main():
    #Constants for ease of use/test
    TIMEPARKED_CONST = 5
    SOC_CONST = 44
    BATCAPACITY_CONST = 60
    MAXCHARGERATE_CONST = 10

    print('Ford EV Smart Charge - Charging Station Simulation')
    chargingStation = Station()

    while(1):
        print('What would you like to do?\n' ,
              '1. Add car to parking spot on station\n' ,
              '2. Remove car from parking spot on station\n',
              '3. Display current parking spot configuration\n'
              '...\n',
              '9. Quit simulation', sep="")
        option = int(input(""))

        if option == 1:
            if len(chargingStation.cars) >= 6:
                print('All parking spots are currently full.\n')
            else:
                SOC = float(input('Enter current state of charge of battery (%): '))
                batCapacity = float(input('Enter max capacity of battery (kWh): '))
                maxChargeRate = float(input('Enter max rate of charge battery can handle (kW): '))


            car = Car(SOC, batCapacity, maxChargeRate)
            chargingStation.add_car(car)
            print('Car\'s parking spot is', car.parkingSpot)
            chargingStation.calc_rate_options(car)

        elif option == 2:
            chargingStation.remove_car(car)

        elif option == 3:
            chargingStation.display_parking_spots()

        elif option == 9:
            return
Exemplo n.º 24
0
def secondReactChart(obsType, synop, synopType, name, path):
    valuesDict = {}
    date = 'YYYYMMDDHHMM'
    for eggs in synop:
        station = St.Station(getSynopType=synopType, synopCode=eggs)
        if obsType[0] == 1:
            valuesDict[station.decodeCityCountry()
                       ['miasto']] = station.decodeTemp()
        elif obsType[0] == 2:
            valuesDict[station.decodeCityCountry()
                       ['miasto']] = station.decodeDewPointTemp()
        elif obsType[0] == 3:
            valuesDict[station.decodeCityCountry()
                       ['miasto']] = station.decodeStationAtmPressure()
        elif obsType[0] == 4:
            valuesDict[station.decodeCityCountry()
                       ['miasto']] = station.decodeSeaLvlPressure()
        date = station.decodeDate()
    pC.drawChart(valuesDict=valuesDict,
                 dataType=obsType[1],
                 date=date,
                 fileName=name,
                 outputPath=path)
    return 'Wydrukowano wykres'
Exemplo n.º 25
0
def main():
	stagnation = Station()
	chamber = Station()
	throat = Station()
	internal = Station()
	external = Station()
	atmosphere = Station()

# inputs

	atmosphere.pressure = 0.032 # Pa
	atmosphere.temperature = 3 # K

	stagnation.pressure = 20*(101325/14.696) # Pa
	stagnation.temperature = ((1000.0-32.0)*(5.0/9.0))+273.15 # K

	chamber.area_ratio = 150.0
	external.area_ratio = 5.0

	total_thrust = 0.125 # N

	gravity = 9.81 # m/s^2
	gamma = 1.4
	R = 287 # J/kg.K
Exemplo n.º 26
0
def main():
    # These variables can be changed to fit simulation needs
    STATION_TOTAL_POWER = 40 # kW
    PORT_MAX_POWER = 30 #kW
    STATION_PORTS = 4
    x = 0

    time = np.arange(6., 20., 0.25) # time sampling array
    total_power_line = [STATION_TOTAL_POWER] * len(time)

    pause_time = 0
    if ADD_CAR:
        pause_time = float(input("Enter time to pause simulation (6 - 20): "))
        print("Pause time is", pause_time )


    # ------------ initialize the day of vehicles for simulation ------------ #

    # init vehicle arrays (packCapacity, arrival, departure, requestedCharge, maxChargeRate, initialSOC, time)
    vehicles_port0 = [Vehicle(40., 7.5,   11.5, 32., 16., 20., time),   # 7:30 am - 11:30 am
                      Vehicle(50., 13.25, 17.,  40., 16., 15., time),   # 1:15 pm - 5 pm
                      Vehicle(23., 17.5,  18.,  15., 50., 14., time)]   # 5:30 pm - 6 pm

    vehicles_port1 = [Vehicle(35., 7.75,  14.5, 30., 16., 10., time),   # 7:45 am  - 2:30 pm
                      Vehicle(40., 14.75, 17.,  25., 16., 20., time),   # 2:45 pm - 5 pm
                      Vehicle(50., 17.25, 18.,  40., 50., 30., time)]   # 5:15 pm  - 6 pm

    vehicles_port2 = [Vehicle(40., 7.5,  11.5, 32., 16., 30., time),    # 7:30 am - 11:30 am
                      Vehicle(50., 11.5, 17.,  40., 16., 2., time),     # 11:30 am - 5 pm
                      Vehicle(50., 17.5, 18.,  40., 50., 37., time)]    # 5:30 pm - 6 pm

    vehicles_port3 = [Vehicle(50., 7.75,  13.5, 50., 20., 34., time),   # 7:45 am - 1:30 pm
                      Vehicle(40., 13.5,  17.,  30., 19., 20., time),   # 1:30 pm - 5 pm
                      #Vehicle(30., 17.5 , 18.,  15., 30., 10., time)]  # 5:30 pm - 6 pm
                      None]     # Where vehicle from app interaction goes

    # init ports
    station_ports = [Port(vehicles_port0, PORT_MAX_POWER, time),
                     Port(vehicles_port1, PORT_MAX_POWER, time),
                     Port(vehicles_port2, PORT_MAX_POWER, time),
                     Port(vehicles_port3, PORT_MAX_POWER, time)]

    # init station
    station = Station(station_ports, STATION_TOTAL_POWER, time)

    # ----------------------------------------------------------------------- #

    # run the algorithm
    stationAlg(station, time, pause_time)

    # print out if vehicles were satisfied
    y=0
    for port in station.ports:
        print("At Port %d:" % y)
        x=0
        y+=1
        for vehicle in port.vehicles:
            if (vehicle != None):
                if (vehicle.finalCharge >= vehicle.requestedCharge):
                    print("   Vehicle ", x, " - SATISFIED: %.2f" % vehicle.finalCharge, "/%.2f kWh" % vehicle.requestedCharge, sep="", end="\n")
                else:
                    print("   Vehicle ", x, " - UNSATISFIED: %.2f" % vehicle.finalCharge, "/%.2f kWh" % vehicle.requestedCharge, sep="", end="\n")
            x+=1

    # ---------------------- plot all simulation data ----------------------- #


    plt.figure(1)

    # subplot for port 0 delivered power
    plt.subplot(2, 2, 1)
    plt.plot(time, station.ports[0].delivered_power, 'bo-')
    plt.xlabel('Time of Day (6 am - 8 pm)')
    plt.ylabel('Plug Power (kW)')
    plt.title('Port 0 Delivered Power')
    plt.grid(True)

    # subplot for port 1 delivered power
    plt.subplot(2, 2, 2)
    plt.plot(time, station.ports[1].delivered_power, 'bo-')
    plt.xlabel('Time of Day (6 am - 8 pm)')
    plt.ylabel('Plug Power (kW)')
    plt.title('Port 1 Delivered Power')
    plt.grid(True)

    # subplot for port 2 delivered power
    plt.subplot(2, 2, 3)
    plt.plot(time, station.ports[2].delivered_power, 'bo-')
    plt.xlabel('Time of Day (6 am - 8 pm)')
    plt.ylabel('Plug Power (kW)')
    plt.title('Port 2 Delivered Power')
    plt.grid(True)

    # subplot for port 3 delivered power
    plt.subplot(2, 2, 4)
    plt.plot(time, station.ports[3].delivered_power, 'bo-')
    plt.xlabel('Time of Day (6 am - 8 pm)')
    plt.ylabel('Plug Power (kW)')
    plt.title('Port 3 Delivered Power')
    plt.grid(True)

    # plot of station total delivered power
    plt.figure(2)
    plt.plot(time, station.delivered_power, 'bo-', time, total_power_line, 'r-')
    plt.ylim(0,station.total_power+10)
    plt.annotate('Total Station Power Available', xy=(10, station.total_power), xytext=(10.5, station.total_power+5),
            arrowprops=dict(facecolor='black', width=1, headwidth=5, headlength=5),
            )
    plt.xlabel('Time of Day (6 am - 8 pm)')
    plt.ylabel('Station Power (kW)')
    plt.title('Station Delivered Power')
    plt.grid(True)

    plt.show()
Exemplo n.º 27
0
 def addStation(self):
     try:
         self.stations.append(Station.Station())
     except ValueError:
         print "Capacity should be an integer. Please try again"
Exemplo n.º 28
0
                    datefmt='%Y-%m-%d %H:%M:%S')

#get soil moisture reading
# soilMeter = SoilHygrometer("P9_39")
# soilMeter.setup()
#reading = soilMeter.read()

#Duration
durationInMin = 8 * 60
#durationInMin = 10

#set up the relay objects
relays = ["P8_10", "P8_11", "P8_12", "P8_13"]

#use a dictionary comprehension to create Stations
holder = {pinNum: Station(name=pinNum, pinNum=pinNum) for pinNum in relays}

for x in holder:
    holder[x].setup()
    print("Station name is " + holder[x].name + ". Station pinNum is " +
          holder[x].pinNum)

# This is a timer that will pause for 1 second.
sleep(1)

#check to see if it is raining
lat = "34.203194"
lon = "-118.371566"
url = "https://api.openweathermap.org/data/2.5/weather?appid=b7057926f8211721b670ca7795400a58&lat=" + lat + "&lon=" + lon

r = requests.get(url)
Exemplo n.º 29
0
from BikeAlg import *
from Station import *
from EndLocation import *
from DisPair import *
from SugPair import *
#pip install geopy

#stations are created using custom inputs for all stations, but use coordinates found in actual station data
s1 = Station(id = '1', capacity = 16, longitude = -77.0532,latitude = 38.8589, demand = 0, bikeAvail = 2, docAvail = 14)
s2 = Station(id = '2', capacity = 16, longitude = -77.0533,latitude = 38.8572, demand = 0, bikeAvail = 4, docAvail = 12)
s3 = Station(id = '3', capacity = 16, longitude = -77.0492,latitude = 38.8564, demand = 0, bikeAvail = 8, docAvail = 8)
s4 = Station(id = '4', capacity = 16, longitude = -77.0495,latitude = 38.8601, demand = 0, bikeAvail = 2, docAvail = 13)
s5 = Station(id = '5', capacity = 16, longitude = -77.0594,latitude = 38.8578, demand = 0, bikeAvail = 5, docAvail = 15)
#prop is a field calculated in actual simulation(see station class) and assigned, but we created custom prop for algorithm testing purposes
s1.prop = .5
s2.prop = .5
s3.prop = .5
s4.prop = .5
s5.prop = .5

#Creating dictionary of stations and creating list out of dictionary
dic = {'1':s1, '2':s2, '3':s3, '4':s4, '5':s5}
sl = list(dic.values())
#Instantiaing algorithm taking the parameter (rad) being the radius that the algorithm searches/considers
ba = BikeAlg(5)
loc = EndLocation(-77.0512, 38.8588)
d = 1
ba.preProcess(sl, loc)
ba.getSuggest(loc, 0)
print("Stations within: " + str(d) + " miles");
print()
Exemplo n.º 30
0
import threading
from firebase import firebase
from pyfcm import *

class Event(object):         
    def __init__(self, time, cmd):
        self.time = time
        self.cmd = cmd

global running
running = False

global t
t = 0

station = Station()

# - CREATE FIREBASE CONNECTIONS - #

# Main firebase
fire = firebase.FirebaseApplication('https://ev-charge-8133f.firebaseio.com/', None)

# Initialize Push service
FB_KEY = "AAAA7L2MSt0:APA91bEihBBAZZLVU8qOjsSZzAnMMSnZ64RjWTuXAnxY6IzaBDDLDD9u_Te7BQGawX6fD106DIKHuEQtXKra5Go0ksYIym2lu7zfo5mQV4TFOA3NaW01RvY_-S1-3HOrQbquLoM7MGwJ"
push_service = FCMNotification(api_key=FB_KEY)

# Empty database of residual commands
try:
    diction = fire.delete('/add', None)
except:
    """ nothing in database commands """