示例#1
0
 def __init__(self):
     self.eta_b = 1
     self.wf = 0  # fuel flow
     self.fgrc = 0  # corrected fuel to gas ratio
     self.in_station = st.Station()
     self.out_station = st.Station()
     self.current_fuel = fuel.Fuel()
     self.current_fluid = cl.CeaFluid()
示例#2
0
def generateStations(numAmbulances, transitTime):
    s1 = station.Station(numAmbulances, transitTime)
    s2 = station.Station(numAmbulances, transitTime)
    s3 = station.Station(numAmbulances, transitTime)
    s4 = station.Station(numAmbulances, transitTime)
    s5 = station.Station(numAmbulances, transitTime)
    s6 = station.Station(numAmbulances, transitTime)
    s7 = station.Station(numAmbulances, transitTime)
    s8 = station.Station(numAmbulances, transitTime)
    s9 = station.Station(numAmbulances, transitTime)
    s10 = station.Station(numAmbulances, transitTime)

    stations = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10]

    return stations
示例#3
0
 def load(self, config):
     # save the config
     self.config = config
     # create the pallet source and sink
     self.source = source.PalletSource(config['num_pallets'],
                                       config['pal_len'])
     self.sink = sink.PalletSink()
     # create the conveyor
     # only one supported right now
     if len(config['conveyors']) > 1:
         error("Only one conveyor supported at this time")
     conv_config = config['conveyors'][0]
     self.conveyor = conveyor.Conveyor(conv_config['conv_spd'],
                                       conv_config['conv_len'],
                                       config['pal_len'])
     # connect the source, conveyor and sink
     self.source.connect_output(self.conveyor)
     self.conveyor.connect_input(self.source)
     self.sink.connect_input(self.conveyor)
     self.conveyor.connect_output(self.sink)
     # create the stations
     for stn in conv_config['stations']:
         # create it
         new_station = station.Station(stn['sta_num'], stn['sta_pos'],
                                       stn['sta_type'],
                                       stn['sta_cycle_time'])
         # keep a pointer to it, though don't do anything with it now
         self.stations.append(new_station)
         # add it to the conveyor
         self.conveyor.add_station(new_station)
     # set the length of the time tick to time for pallet to go one pallet length
     self.tick_len = config['pal_len'] * 5 / conv_config['conv_spd']
     # create the array of things to call in the right order
     self.top_level_objects = [self.sink, self.conveyor, self.source]
     self.display()
示例#4
0
def start_fn(cmd):
    global THREADS
    global N_THREADS

    # Verify command correctness
    cmd = cmd.split(" ")
    if (len(cmd) != 2 or cmd[0] != "start"):
        print("  Usage: start <station-name>\n")
        return False
    if (N_THREADS == 2):
        print("  Two stations already running:")
        i = 0
        for key in THREADS:
            print("  STATION " + str(i) + " -> '" + key + "'")
            i += 1
        return False
    if (cmd[1] in THREADS):
        print("  A stations with the same name is already running\n")
        return False

    # Start new station thread, update global variables, print feedback
    thread = station.Station(cmd[1], N_THREADS + 1)
    THREADS[cmd[1]] = thread
    N_THREADS += 1
    thread.start()
    print("  Station '" + cmd[1] + "' started")
    return True
示例#5
0
def getStationList():
	
	stationDict = {}	
	
	try:
		fp = open("google_transit/stops.txt", "r")

		fp.readline() #done to skip the heading line of the file

		for line in fp:
			fileLine = line.split(",", 5)
			stationName = fileLine[1]
			stationSuburb = stationName[stationName.find("(")+1:stationName.find(")")]
			cleanLat = fileLine[2].translate(None, "\"")
			cleanLong = fileLine[3].translate(None, "\"")
			cleanLong = cleanLong.translate(None, "\n")
			newStation = station.Station(stationName, stationSuburb, cleanLat, cleanLong)
			stationDict[stationSuburb] = newStation
	except:
		inLoadingError = True
	finally:
		if fp != None:	
			fp.close()	

	return stationDict
示例#6
0
def _make_station(sy, st, keep_data=False):
    sysobj = _make_known_system(
        sy, keep_data) if not isinstance(sy, system.KnownSystem) else sy
    stnobj = station.Station(st, sysobj)
    if keep_data:
        stnobj.data = st
    return stnobj
示例#7
0
def main():
    s = station.Station()
    s.printConfig()

    if len(sys.argv) < 2:
        s.initReadings()
    else:
        s.testSensor(sys.argv[1])
示例#8
0
 def _init_station(self):
     self._station_list = []
     # name, position, uid, estate_value, status, street_id
     for s in self._station_list_data["data"]:
         new_block = station.Station(s['name'], s['block_id'],
                                     s['position'], s['uid'],
                                     s['estate_value'], s['status'])
         self._station_list.append(new_block)
         self._block_list[new_block.position] = new_block
         self._epic_bank.add_asset(new_block)
示例#9
0
    def read_input_data(self, input_filename):
        """
        Read the metro network form the file
        :param input_filename: filename contains metro network information with the right format
        :return: None
        """
        for one_line in open(input_filename, "r"):
            one_line = one_line.rstrip('\n')
            if "#" in one_line:
                current_line = line.Line(one_line.split("#")[1].rstrip())
                current_line.stations = []
                self.lines.append(current_line)

            if "START" in one_line:
                current_line = None
                new_start = one_line.split(':')
                self.start_station = station.Station(
                    new_start[0].split("=")[1], int(new_start[1]), "", "S")

            if "END" in one_line:
                current_line = None
                new_end = one_line.split(':')
                self.end_station = station.Station(new_end[0].split("=")[1],
                                                   int(new_end[1]), "", "E")

            if 'TRAINS' in one_line:
                current_line = None
                train_num = int(one_line.split('=')[1])
                for one_train in range(1, train_num + 1):
                    new_train = train.Train("T." + str(one_train),
                                            self.start_station.code)
                    self.trains.append(new_train)

                # update trains statistic value
                self.total_train = len(self.trains)

            if ":" in one_line and current_line is not None:
                station_infos = one_line.split(':')
                if len(station_infos) > 1:
                    new_station = station.Station(current_line.name,
                                                  int(station_infos[0]),
                                                  station_infos[1])
                    current_line.stations.append(new_station)
示例#10
0
def xmlRootGetStation(root, whenCreated):
    """Get the station object from the XML root element and given date."""
    lineCode = root.findtext("{http://trackernet.lul.co.uk}Line")
    lineName = root.findtext("{http://trackernet.lul.co.uk}LineName")
    stationElement = root.find("{http://trackernet.lul.co.uk}S")
    code = stationElement.get("Code")
    name = stationElement.get("N")
    stationObj = station.Station(code, name, lineCode, lineName)
    xmlStationGetPlatforms(stationObj, stationElement, whenCreated)
    return stationObj
示例#11
0
    def __init__(self, header, data):
        """! @brief
             @returns
        """
        # variables
        self.port = 0
        self.datakind = ''
        self.pid = 0
        self.callform = ''
        self.callto = ''
        self.via = None
        self.datalen = 0
        self.time = ''
        self.header = header
        self.data = data

        s = self.header.split()
        #print 'ui_split: ',s

        # head:   2:Fm PE1NAT-2 To APZ023 Via PI1FLD,PE1FVU-4*,WIDE3-3 <UI pid=F0 Len=49 >
        # [20:43:45]
        # data:  =5242.43N/00450.83E#PHG5260/DIGI_NED voor Linux.
        # ui_split:  ['2:Fm', 'PE1NAT-2', 'To', 'APZ023', 'Via', 'PI1FLD,PE1FVU-4*,WIDE3-3
        # ', '<UI', 'pid=F0', 'Len=49', '>[20:43:45]']

        # Process Port, From and To. After that, delete first 4 entries of the list
        self.port = int(s[0][0:1])
        self.callfrom = s[1]
        self.callto = s[3]
        s = s[4:]
        #print 'after del: ',s

        # If there is a route indicated, process the route, and delete the first 2 entries of the list
        if s[0] == 'Via':
            self.via = string.split(s[1], ',')
            # Now we have a list of Via calls
            print 'VIA ', self.via
            s = s[2:]
            #print 'after del via: ',s
        #print '--> ',self.port,self.callfrom,self.callto,self.via

        self.pid = s[1][4:]
        self.datalen = s[2][4:]
        self.time = s[3][2:10]
        #print '--> ',self.pid,self.datalen,self.time
        #print
        #print 'Decoded: ',self.port,self.callfrom,self.callto,self.via,self.pid,self.datalen,self.time
        print '> ', header
        print '> ', data

        x = station.Station(self.callfrom)
        #aprs.show_id(self.data)
        pos = aprs.position(self.data)
        if pos:
            x.position(pos)
示例#12
0
def test_new_mode():
    '''
    This test tests the mode system of the station class, and will make a new mode lambda and test it.
    '''
    import station
    s = station.Station()
    s.add_record(5)
    s.add_record(3)
    s.add_record(10)
    s.add_record(3)
    lengthiest = lambda x: max(x.m_records)
    assert s.get_record(lengthiest) == 10
示例#13
0
def test():
    """! test
         @returns Nothing
    """

    logging.basicConfig(level=logging.DEBUG,
                        format='%(levelname)s %(message)s')

    #    f = open('../log_20060214_1.txt.txt')
    #    s = f.read()
    #    f.close()
    #
    #    lines = s.split('\n')

    format = "APRSD"

    f = open('testdata.txt')
    lines = f.read()
    f.close()
    lines = lines.split('\n')

    for s in lines:
        logging.debug(s)
        if len(s) < 3:
            continue
        if s[0] == '#':
            continue
        data = info(s)
        print(aprs.type_description(data))
        print(fromcall(s))
        print(tocall(s))

        stat = station.Station()
        stat.set_callsign(fromcall(s))

        station.stationlist.append(stat)

    print('%d stations heared' % len(station.stationlist))
    for stat in station.stationlist:
        print(stat.callsign)
示例#14
0
def retrieve_station_data(n_clicks, api_key, start_year, end_year):
    if n_clicks > 0:
        Station = station.Station('GHCND:USC00210075', api_key)
        Station.retrieve_temperature_data(datetime.date(start_year, 1, 1),
                                          datetime.date(end_year, 1, 2))

        temp_data = pd.DataFrame(Station.temperature_data)
        temp_data['date'] = temp_data['date'].apply(lambda x: parser.parse(x))
        fig = px.scatter(x=temp_data['date'],
                         y=temp_data['value'],
                         color=temp_data['datatype'])
        fig.update_xaxes(title='Date')

        fig.update_yaxes(title='Temperature')
        return fig
    else:
        fig = px.scatter(x=[1, 2], y=[1, 2])
        fig.update_xaxes(title='Date')

        fig.update_yaxes(title='Temperature')

        return fig
示例#15
0
    def loginAction(self):
        
        email = self.mainWindow.loginId_lineEdit.text()
        password = self.mainWindow.password_lineEdit.text()

        self.station = station.Station(email)
        if self.usr.login(email,password)==True and self.station.user()!=False:
            self.usr.info()
            self.mainWindow.main_stackedWidget.setCurrentIndex(0)
            self.selectStation_comboBox_text(tuple(self.usr.stations))
            self.mainWindow.loginId_lineEdit.clear()
            self.mainWindow.password_lineEdit.clear()
            _translate = QtCore.QCoreApplication.translate
            self.mainWindow.username_label.setText(_translate("MainWindow", self.usr.first_name)+' '+self.usr.last_name)
            self.fuelType()
        elif self.usr.login(email,password)==True and self.station.user()==False:
            self.mainWindow.main_stackedWidget.setCurrentIndex(2)
            self.mainWindow.loginId_lineEdit.clear()
            self.mainWindow.password_lineEdit.clear()
        else:
            error = self.field.error([self.usr.login(email,password)])
            self.mainWindow.msgBoxError(self.error[error])
示例#16
0
 def createStation(self):
     self.usr.info()
     self.station = station.Station(self.usr.email)
     user_id = self.usr.id
     self.station.create(self.setupStation_info)
     station_id = self.station.stationId
     tanks = tank.Tank(station_id)
     tanks.create(self.tankData)
     self.usr.add_station(station_id)
     self.usr.info()
     self.mainWindow.msgBox("Station has been created")
     self.mainWindow.main_stackedWidget.setCurrentIndex(0)
     self.mainWindow.loginId_lineEdit.clear()
     _translate = QtCore.QCoreApplication.translate
     self.mainWindow.username_label.setText(_translate("MainWindow", self.usr.first_name)+' '+self.usr.last_name)
     self.station_id = self.station.stationId
     self.fuelType()
     self.selectStation_comboBox_text(tuple(self.usr.stations))
     self.mainWindow.tableWidget.clear()
     self.mainWindow.stationName_lineEdit.clear()
     self.mainWindow.streetAddress_lineEdit.clear()
     self.mainWindow.city_lineEdit.clear()
     self.mainWindow.department_lineEdit.clear()
def plot_burn_temp_comparison(p_in, t_in, w_in, t_fuel=382.5948):
    # load large and reduced chemestry set data from CEA website
    FileNames = [
        'data/online_cea_combustion/reducedChemSet_EQR_below1.dat',
        'data/online_cea_combustion/reducedChemSet_EQR_above1.dat',
        'data/online_cea_combustion/largeChemSet_EQR_below1.dat',
        'data/online_cea_combustion/largeChemSet_EQR_above1.dat'
    ]

    # read data from loaded files
    T = np.array([])
    CP = np.array([])
    EQR = np.array([])

    for i, inFile in enumerate(FileNames):
        if i == 2:
            Tred = T
            CPred = CP
            EQRred = EQR

            T = np.array([])
            CP = np.array([])
            EQR = np.array([])
        inputFile = open(inFile, 'r')

        for line in inputFile:
            if 'T, K' in line:
                line = line.split()
                T = np.append(T, float(line[2]))
            if 'Cp, KJ/(KG)(K)' in line:
                line = line.split()
                CP = np.append(CP, float(line[2]))
            if 'EQ.RATIO' in line:
                line = line.split(',')
                EQR = np.append(EQR, float(line[-1].split('=')[1]))

        inputFile.close()

    # reduced set of species using my cea calculation
    dummy_fluid = cl.CeaFluid()
    std_air = cl.Composition('Air')
    dummy_fluid.set_humidity(StandartTemperature + 20,
                             StandartPressure,
                             std_air,
                             RH=1)

    # set up combustor
    comb = cmb.Combustor()
    comb.current_fluid = cl.CeaFluid()
    comb.in_station = stat.Station(t_in, p_in * PressureConversion,
                                   w_in * FLowConversion, std_air)
    comb.out_station = stat.Station(t_in, p_in * PressureConversion,
                                    w_in * FLowConversion, std_air)
    comb.current_fuel.tf = t_fuel

    eqr_vec = np.linspace(0.25, 2, 20)
    far_vec = eqr_vec * FARStoi
    wf_vec = far_vec * comb.in_station.w * AirToFuelFlow

    t_cea = np.array([])

    for fuel_flow in np.nditer(wf_vec):
        comb.wf = fuel_flow
        comb.heat_balance_calcs()
        t_cea = np.append(t_cea, comb.out_station.t)

    comb.current_fluid = cl.RRDFluid()
    comb.current_fuel.burn_model = 'RRD'

    t_rrd = np.array([])

    for fuel_flow in np.nditer(wf_vec):
        comb.wf = fuel_flow
        comb.heat_balance_calcs()
        t_rrd = np.append(t_rrd, comb.out_station.t)

    diff_CP = (CPred - CP) / CP
    diff_T = (Tred - T) / T
    diff_T_cea = (np.interp(EQR, eqr_vec, t_cea) - T) / T
    diff_T_rrd = (np.interp(EQR, eqr_vec, t_rrd) - T) / T

    ######## CANTERA calculation ############
    # Get all of the Species objects defined in the GRI 3.0 mechanism
    species = {S.name: S for S in ct.Species.listFromFile('nasa.cti')}
    # Create an IdealGas object including incomplete combustion species
    complete_species = [
        species[S] for S in ('Jet-A(g)', 'O2', 'N2', 'CO2', 'H2O', 'Ar')
    ]
    gas2 = ct.Solution(thermo='IdealGas',
                       species=complete_species)  #species.values())
    T_incomplete = np.zeros(EQR.shape)
    for i in range(len(EQR)):
        gas2.TP = t_in, p_in * PressureConversion
        gas2.set_equivalence_ratio(
            EQR[i], 'Jet-A(g)',
            'O2:0.19775868763, N2:0.7371626995, AR:0.008841156551, CO2:0.0003011563203 , H2O: 0.05593629993'
        )
        gas2.equilibrate('HP')
        T_incomplete[i] = gas2.T

    ##### PLOT
    fig = plt.figure()

    ax = fig.add_subplot(1, 2, 1)
    ax.plot(EQRred, Tred)
    ax.plot(EQR, T)
    ax.plot(eqr_vec, t_cea)
    ax.plot(eqr_vec, t_rrd)
    ax.plot(EQR, T_incomplete)

    plt.xlim(0.25, 1.5)
    plt.xlabel('Equivalence ratio, $\phi$')
    plt.ylabel('Temperature [K]')
    plt.grid(True)
    plt.legend(
        ['Onl. CEA RCS', 'Onl. CEA full CS', 'My CEA', 'RRD', 'Cantera'])

    ax = fig.add_subplot(1, 2, 2)
    ax.plot(EQRred, diff_T)
    ax.plot(EQR, diff_T_cea)
    ax.plot(EQR, diff_T_rrd)
    plt.grid(True)

    plt.xlabel('Equivalence ratio, $\phi$')
    plt.ylabel('delta T')

    plt.xlim(0.25, 1.5)
    plt.legend(['Onl. CEA RCS', 'My CEA', 'RRD'])

    plt.show()
示例#18
0
import receiver
import station
import numpy as np

s = station.Station(station.raspi1_noimu)

s.write_event(s.min + s.max * np.random.random(s.max.size))

r = receiver.Receiver(receiver.soapy1)
r.enable()
print(r.read())

示例#19
0
 def demo(self):
     self.stations = [
         st.Station("in", "room1", "in",
                    ["temp", "humid", "pres", "servo", "gas", "co"]),
         st.Station("out", "garden", "out", ["temp", "humid"])
     ]
def main():
    # Constants
    TIME = 1500
    SIZE = random.randint(16, 24)
    CARRIERLEN = SIZE - 1

    # Variables
    s0 = station.Station("s0", 0)
    s1 = station.Station("s1", 8)
    s2 = station.Station("s2", CARRIERLEN)
    stationList = [s0, s1, s2]
    myCarrier = carrier.Carrier(SIZE)
    seqNum = 0
    messageTotal = 0
    collisionTotal = 0
    success = 0
    average = 0.0
    prop = SIZE
    # Loop on ticks
    for i in range(1, TIME):
        # Loop on station
        for s in range(0, len(stationList)):
            # Status Flag for Station
            flag = True
            # Station delay
            delay = 0
            # Probability for sending a message
            p = random.random()
            # Current station and carrier information
            currentStationStatus = stationList[s].getStatus()
            currentStationName = stationList[s].getName()
            currentStationLoc = stationList[s].getLocation()
            currentStationDelay = stationList[s].getDelay()
            currentMsgList = myCarrier.getMsgList()

            # Check if current station is alreaady on delay
            if (currentStationDelay > 0):
                delay = currentStationDelay - 1
            else:
                # Determine if station is ready to send a message
                if (currentStationStatus and p > 0.9):
                    # Station is ready
                    # Check location of messages on myCarrier
                    if (currentMsgList):
                        for m in range(0, len(currentMsgList)):
                            msgLoc = currentMsgList[m].getLocation()
                            # Collision Occurs
                            if (currentStationLoc == msgLoc):
                                delay = random.randint(1, 24)
                                flag = False
                                collisionTotal = collisionTotal + 1
                    else:
                        # Station sends message
                        messageSize = random.randint(1, 3)
                        delay = messageSize
                        seqNum = seqNum + 1
                        if (currentStationName == "s0"):
                            newMsg = message.Message(seqNum,
                                                     currentStationName, i,
                                                     messageSize, 1,
                                                     currentStationLoc)
                            myCarrier.addMessage(newMsg)
                            messageTotal = messageTotal + 1
                        elif (currentStationName == "s2"):
                            newMsg = message.Message(seqNum,
                                                     currentStationName, i,
                                                     messageSize, -1,
                                                     currentStationLoc)
                            myCarrier.addMessage(newMsg)
                            messageTotal = messageTotal + 1
                        elif (currentStationName == "s1"):
                            newMsg = message.Message(seqNum,
                                                     currentStationName, i,
                                                     messageSize, 1,
                                                     currentStationLoc)
                            newMsg2 = message.Message(seqNum,
                                                      currentStationName, i,
                                                      messageSize, -1,
                                                      currentStationLoc)
                            myCarrier.addMessage(newMsg)
                            myCarrier.addMessage(newMsg2)
                            messageTotal = messageTotal + 2
                        flag = False

                # If station is not ready to send
                if (currentStationStatus and p <= 0.9):
                    delay = random.randint(2, 16)
                    flag = False

            # Update current station
            stationList[s].setDelay(delay)

            # Check if delay is now zero and make sure status updates properly
            if (delay == 0):
                flag = True

            stationList[s].setStatus(flag)

            ### Prints for debugging
            print("Station Name:", currentStationName)
            print("Message Total:", messageTotal)
            print("Collision Total:", collisionTotal)
            print("------------------------------------------------")

        # Update carrier
        carrierMsgList = myCarrier.getMsgList()
        # Only update carrier if there are messages on the line
        if (carrierMsgList):
            for m in carrierMsgList:
                # Remove messages that have propagated
                msgSender = m.getSender()
                msgAlive = m.getAlive()
                msgSize = m.getLength()
                msgDirection = m.getDirection()
                msgStart = m.getStart()
                msgTime = i - msgStart
                if (msgSender == "s0" or msgSender == "s2"):
                    if ((msgAlive == CARRIERLEN and msgSize == 1)
                            or (msgAlive == CARRIERLEN + 1 and msgSize == 2)
                            or (msgAlive == CARRIERLEN + 2 and msgSize == 3)):
                        # Message has propagated, calculate latency
                        latency = prop + (msgSize / msgTime)
                        if (msgSender == "s0"):
                            s0.updateLatencyList(latency)
                        if (msgSender == "s2"):
                            s2.updateLatencyList(latency)
                        # Remove message from carrier
                        #success = success + 1
                        carrierMsgList.remove(m)
                    else:
                        m.updateLocation()
                        m.updateAlive()
                if (msgSender == "s1" and msgDirection < 0):
                    if ((msgAlive == 8 and msgSize == 1)
                            or (msgAlive == 9 and msgSize == 2)
                            or (msgAlive == 10 and msgSize == 3)):
                        # Message has propagated, calculate latency
                        latency = prop + (msgSize / msgTime)
                        s1.updateLatencyList(latency)
                        # Remove message from carrier
                        #success = success + 1
                        carrierMsgList.remove(m)
                    else:
                        m.updateLocation()
                        m.updateAlive()
                if (msgSender == "s1" and msgDirection > 0):
                    if ((msgAlive == CARRIERLEN - 8 and msgSize == 1)
                            or (msgAlive == CARRIERLEN - 9 and msgSize == 2)
                            or (msgAlive == CARRIERLEN - 10 and msgSize == 3)):
                        # Message has propagated, calculate latency
                        latency = prop + (msgSize / msgTime)
                        s1.updateLatencyList(latency)
                        # Remove message from carrier
                        #success = success + 1
                        carrierMsgList.remove(m)
                    else:
                        m.updateLocation()
                        m.updateAlive()
                # Update message List
                myCarrier.updateMsgList(carrierMsgList)

    # Print message count
    print("Carrier Length:", myCarrier.getLen())
    print("Total Messages Sent: ", messageTotal)
    print("Total Collisions:", collisionTotal)
    success = messageTotal - collisionTotal
    print("Total Successes:", success)
    if (messageTotal == 0):
        messageTotal = 1
    average = success / messageTotal
    print("Average Throughput:", average)
    print("------------------------------------------------")

    # Calculate average latency per station
    for n in stationList:
        avgStationLatency = 0
        stationLatency = 0
        stationLatencyList = n.getLatencyList()
        #print("Station ", n.getName(), ": ", stationLatencyList)
        for l in range(0, len(stationLatencyList)):
            stationLatency = stationLatency + stationLatencyList[l]

        avgStationLatency = stationLatency / len(stationLatencyList)
        print("Average latency of station", n.getName(), ":",
              avgStationLatency)
def plot_combustion_temperature(t_in,
                                p_in,
                                w_in,
                                comp,
                                models=['RRD', 'CEA', 'CANTERA'],
                                baseline='CANTERA',
                                eqr_range=np.linspace(0, 2, 50)):
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 2, 1)
    ax2 = fig.add_subplot(1, 2, 2)
    legend1 = []
    legend2 = []

    if baseline == 'CANTERA':
        spec = ['O2', 'N2', 'CO2', 'AR', 'H2O']
        structure_cantera = ''
        for s in spec:
            structure_cantera = structure_cantera + s + ':' + str(
                comp.get_fraction(s)) + ','
        structure_cantera = structure_cantera[:-1]
        # Get all of the Species objects
        species = {S.name: S for S in ct.Species.listFromFile('nasa.cti')}
        species2 = {S.name: S for S in ct.Species.listFromFile('gri30.xml')}
        # Create an IdealGas object including incomplete combustion species
        complete_species = [species2[S] for S in species2]
        complete_species.append(species['Jet-A(g)'])
        gas2 = ct.Solution(thermo='IdealGas',
                           species=complete_species)  #species.values())
        t_base = np.zeros(eqr_range.shape)
        #comb_air = 'O2:'+std_air.get_fraction('O2')
        for i, eqr in enumerate(eqr_range):
            gas2.TP = t_in, p_in
            gas2.set_equivalence_ratio(eqr, 'Jet-A(g)', structure_cantera)
            gas2.equilibrate('HP')

            t_base[i] = gas2.T
        # plot baseline values
        ax1.plot(eqr_range, t_base)
        legend1.append('Cantera')
    elif baseline == 'Online CEA':
        eqr_range_cea = []
        t_onl_cea = []
        if comp.WGR_mole > 0:
            file1 = 'data/CEA_tool/cea_full_rh=1.dat'
            with open(file1, 'r') as file1_handle:
                # skip first row
                next(file1_handle)
                for line in file1_handle:
                    line = line.strip().split('  ')
                    eqr_range_cea.append(float(line[0]))
                    t_onl_cea.append(float(line[1]))
                file1_handle.close()
        elif comp.WGR_mole == 0:
            file1 = 'data/online_cea_combustion/largeChemSet_EQR_below1.dat'
            file2 = 'data/online_cea_combustion/largeChemSet_EQR_above1.dat'
            file1_handle = open(file1, 'r')
            for line in file1_handle:
                if 'EQ.RATIO' in line:
                    line = line.strip().split(',')
                    eqr_range_cea.append(float(line[-1].split('=')[-1]))
                elif 'T, K' in line:
                    line = line.strip().split(' ')
                    t_onl_cea.append(float(line[-1]))
            file1_handle.close()
            file2_handle = open(file2, 'r')
            for line in file2_handle:
                if 'EQ.RATIO' in line:
                    line = line.strip().split(',')
                    eqr_range_cea.append(float(line[-1].split('=')[-1]))
                elif 'T, K' in line:
                    line = line.strip().split(' ')
                    t_onl_cea.append(float(line[-1]))
            file2_handle.close()
        eqr_range = np.array(eqr_range_cea)
        t_base = np.array(t_onl_cea)
        # plot baseline values
        ax1.plot(eqr_range, t_base)
        legend1.append('Online CEA')

    # set up combustor
    comb = cmb.Combustor()
    comb.in_station = stat.Station(t_in, p_in, w_in, comp)
    comb.out_station = stat.Station(t_in, p_in, w_in, comp)
    comb.current_fuel.tf = 382.5948
    # get input fuel flow
    far_range = eqr_range * FARStoi
    wf_range = far_range * comb.in_station.w * AirToFuelFlow
    # get RRD values
    if 'RRD' in models:
        # set up combustor for RRD calculation
        comb.current_fluid = cl.RRDFluid()
        comb.current_fuel.burn_model = 'RRD'
        t_rrd = []
        # get t_out for every fuel flow
        for fuel_flow in np.nditer(wf_range):
            comb.wf = fuel_flow
            comb.heat_balance_calcs()
            t_rrd.append(comb.out_station.t)
        t_rrd = np.array(t_rrd)
        diff_t_rrd = (t_rrd - t_base) / t_base * 100
        ax1.plot(eqr_range, t_rrd)
        ax2.plot(eqr_range, diff_t_rrd)
        legend1.append('RRD')
        legend2.append('RRD')

    # get CEA values
    if 'CEA' in models:
        # set up combustor for RRD calculation
        comb.current_fluid = cl.CeaFluid()
        comb.current_fuel.burn_model = 'CEA'
        t_cea = []
        # get t_out for every fuel flow
        for fuel_flow in np.nditer(wf_range):
            comb.wf = fuel_flow
            comb.heat_balance_calcs()
            t_cea.append(comb.out_station.t)
        t_cea = np.array(t_cea)
        diff_t_cea = (t_cea - t_base) / t_base * 100
        ax1.plot(eqr_range, t_cea)
        ax2.plot(eqr_range, diff_t_cea)
        legend1.append('CEA')
        legend2.append('CEA')

    if 'CANTERA' in models:
        spec = ['O2', 'N2', 'CO2', 'AR', 'H2O']
        structure_cantera = ''
        for s in spec:
            structure_cantera = structure_cantera + s + ':' + str(
                comp.get_fraction(s)) + ','
        structure_cantera = structure_cantera[:-1]
        # Get all of the Species objects
        species = {S.name: S for S in ct.Species.listFromFile('nasa.cti')}
        species2 = {S.name: S for S in ct.Species.listFromFile('gri30.xml')}
        # Create an IdealGas object including incomplete combustion species
        complete_species = [species2[S] for S in species2]
        complete_species.append(species['Jet-A(g)'])
        gas2 = ct.Solution(thermo='IdealGas',
                           species=complete_species)  #species.values())
        t_cantera = np.zeros(eqr_range.shape)
        #comb_air = 'O2:'+std_air.get_fraction('O2')
        for i, eqr in enumerate(eqr_range):
            gas2.TP = t_in, p_in
            gas2.set_equivalence_ratio(eqr, 'Jet-A(g)', structure_cantera)
            gas2.equilibrate('HP')

            t_cantera[i] = gas2.T
        diff_t_cantera = (t_cantera - t_base) / t_base * 100
        # plot baseline values
        ax1.plot(eqr_range, t_cantera)
        legend1.append('Cantera')
        ax2.plot(eqr_range, diff_t_cantera)
        legend2.append('Cantera')

    ax1.set_xlabel('Equivalence ratio, $\phi$')
    ax1.set_ylabel('Temperature [K]')
    ax1.grid(True)
    ax1.legend(legend1)

    ax2.set_xlabel('Equivalence ratio, $\phi$')
    ax2.set_ylabel('delta T [%]')
    ax2.grid(True)
    ax2.legend(legend2)

    plt.show()
示例#22
0
                info[31],  # 一等座
                '商务座':
                info[32],  # 商务座
                'xcode14':
                info[33],  # 
                'xcode15':
                info[34],  # 
                'xcode16':
                info[35],  # 
                'exchange':
                info[36]  # 可兑换 [1,0]
            }


if __name__ == '__main__':
    station = station.Station()
    ticket = Ticket(station)
    #回家车票
    #
    ticket.addsearch(
        {
            'train_date': '2020-09-30',
            'from_station': '北京西',
            'to_station': '邢台',
            'purpose_codes': 'ADULT'
        },
        {
            #'state':[],
            #'train_id':[],
            #'have_ticket':['Y','N'],
            # '无座':0,
示例#23
0
    # skip first row
    next(file1_handle)
    # read line by line
    for line in file1_handle:
        # seperate each value
        line = line.strip().split('  ')
        # convert eqr and t to float and append to array
        eqr_range = np.append(eqr_range, float(line[0]))
        t_range = np.append(t_range, float(line[1]))
    # close file handle
    file1_handle.close()

# set up combustor
comb = cmb.Combustor()
# station at inlet of combustor
comb.in_station = stat.Station(t_in, p_in, w_in, comp)
# station at outlet of combustor
comb.out_station = stat.Station(t_in, p_in, w_in, comp)

# get input fuel flow
far_range = eqr_range * FARStoi
wf_range = far_range * comb.in_station.w * AirToFuelFlow

# get RRD values
# set up combustor for RRD calculation
comb.current_fluid = cl.RRDFluid()
comb.current_fuel.burn_model = 'RRD'
t_rrd = np.array([])
# get t_out for every fuel flow
for fuel_flow in np.nditer(wf_range):
    comb.wf = fuel_flow
示例#24
0
def init_game():
    """
    Initialize the game with map, players and bank
    1. generate a map
    2. initialize players
    3. initialize bank
    all of the data
    :return: map, players list and bank
    """
    # generate a map
    parent_addr = os.path.abspath(os.pardir)
    block_list_data = json_reader(
        os.path.join(parent_addr, 'Data/block_data.json'))
    station_list_data = json_reader(
        os.path.join(parent_addr, 'Data/station_data.json'))
    utility_list_data = json_reader(
        os.path.join(parent_addr, 'Data/utility_data.json'))
    estate_list_data = json_reader(
        os.path.join(parent_addr, 'Data/estate_data.json'))
    chest_list_data = json_reader(
        os.path.join(parent_addr, 'Data/chest_data.json'))
    chance_list_data = json_reader(
        os.path.join(parent_addr, 'Data/chance_data.json'))
    block_list = [0 for x in range(40)]
    station_list = []
    utility_list = []
    estate_list = []
    corner_list = []
    chest_block_list = []
    chance_block_list = []
    tax_list = []

    # initialize bank
    epic_bank = bank.Bank('99', 'EpicBank', 32, 12)
    json_writer(os.path.join(parent_addr, 'Data/bank_data.json'), {
        "house_number": epic_bank.cur_house,
        "hotel_number": epic_bank.cur_hotel
    })

    for b in block_list_data["data"]:
        if b['block_type'] == 0:
            # ["Go", "Go to Jail", "In Jail", "Free Parking"]
            if b['name'] == "Go":
                corner_block = block.Go(b['name'], b['block_id'],
                                        b['position'])
            elif b['name'] == "Go to Jail":
                corner_block = block.Go_To_Jail(b['name'], b['block_id'],
                                                b['position'])
            elif b['name'] == "In Jail":
                corner_block = block.In_Jail(b['name'], b['block_id'],
                                             b['position'])
            elif b['name'] == "Free Parking":
                corner_block = block.Free_Parking(b['name'], b['block_id'],
                                                  b['position'])
            else:
                pass
            block_list[corner_block.position] = corner_block
            corner_list.append(corner_block)
        elif b['name'] == "Community Chest":
            # "Community Chest"
            new_block = cardpile.Community_Chest(b['name'], b['block_id'],
                                                 b['position'])
            block_list[new_block.position] = new_block
            chest_block_list.append(new_block)
        elif b['name'] == "Chance":  # "Chance"
            new_block = cardpile.Chance(b['name'], b['block_id'],
                                        b['position'])
            block_list[new_block.position] = new_block
            chance_block_list.append(new_block)
        elif b['block_type'] == 3:
            # ["Income Tax", "Super Tax"]
            if b['name'] == "Income Tax":
                new_block = tax.Income_Tax(b['name'], b['block_id'],
                                           b['position'], 0.10)
            elif b['name'] == "Super Tax":
                new_block = tax.Super_Tax(b['name'], b['block_id'],
                                          b['position'], 0.10)
            else:
                pass
            block_list[new_block.position] = new_block
            tax_list.append(new_block)
    # name, position, uid, estate_value, status, street_id
    for s in station_list_data["data"]:
        new_block = station.Station(s['name'], s['block_id'], s['position'],
                                    s['uid'], s['estate_value'], s['status'])
        station_list.append(new_block)
        block_list[new_block.position] = new_block
        epic_bank.add_asset(new_block)
    # name, position, uid, estate_value, status, street_id
    for u in utility_list_data["data"]:
        new_block = utility.Utility(u['name'], u['block_id'], u['position'],
                                    u['uid'], u['estate_value'], u['status'])
        utility_list.append(new_block)
        block_list[new_block.position] = new_block
        epic_bank.add_asset(new_block)
    for e in estate_list_data["data"]:
        new_block = estate.Estate(e['name'], e['block_id'], e['position'],
                                  e['uid'], e['estate_value'], e['status'],
                                  e['street_id'], e['house_value'])
        estate_list.append(new_block)
        block_list[new_block.position] = new_block
        epic_bank.add_asset(new_block)

    # initialize players
    player_dict_data = json_reader(
        os.path.join(parent_addr, 'Data/player_list.json'))
    player_dict = {}
    player_dict_data = player_dict_data["data"]
    for i in range(len(player_dict_data)):
        p = player.Player(player_dict_data[i]['id'],
                          player_dict_data[i]['name'],
                          player_dict_data[i]['cash'],
                          player_dict_data[i]['alliance'])
        out_put_line = "%d %d %s %s" % (p.cash, p.id, p.name, p.alliance)
        operation.push2all(out_put_line)
        player_dict[player_dict_data[i]['id']] = p

    # initialize chest cards
    chest_list = []
    for chest in chest_list_data["data"]:
        # 0: Collection, 1: Collect_from_players
        if chest['card_type'] == 0 or chest['card_type'] == 1:
            chest_list.append(
                card.CollectCard(chest['card_id'], chest['card_type'],
                                 chest['description'], chest['amount']))
        elif chest['card_type'] == 2 or chest[
                'card_type'] == 3:  # 2: Pay, 3: Pay_for_repair
            # or chest['card_type'] == 8 8: Pay_to_players
            chest_list.append(
                card.PayCard(chest['card_id'], chest['card_type'],
                             chest['description'], chest['amount']))
        # elif chest['card_type'] == 4 or chest['card_type'] == 6:  # 4: Move_indicate_position, 6: Move_nearby
        #     chest_list.append(card.MoveCard(chest['card_id'], chest['card_type'], chest['description'],
        #                                     chest['block_id']))
        # elif chest['card_type'] == 7:  # Move
        #     chest_list.append(card.MoveCard(chest['card_id'], chest['card_type'], chest['description'],
        #                                     chest['steps']))
        elif chest['card_type'] == 5:  # Bailcard
            chest_list.append(
                card.BailCard(chest['card_id'], chest['card_type'],
                              chest['description']))

    # initialize chance cards
    chance_list = []
    for chance in chance_list_data["data"]:
        if chance['card_type'] == 0:  # 0: Collection
            # or chance['card_type'] == 1, 1: Collect_from_players
            chance_list.append(
                card.CollectCard(chance['card_id'], chance['card_type'],
                                 chance['description'], chance['amount']))
        elif chance['card_type'] == 2 or chance['card_type'] == 3 or chance[
                'card_type'] == 8:  # 2: Pay,
            # 3: Pay_for_repair
            # 8: Pay_to_players
            chance_list.append(
                card.PayCard(chance['card_id'], chance['card_type'],
                             chance['description'], chance['amount']))
        # 4: Move_indicate_position, 6: Move_nearby
        elif chance['card_type'] == 4 or chance['card_type'] == 6:
            chance_list.append(
                card.MoveCard(chance['card_id'], chance['card_type'],
                              chance['description'], chance['block_id']))
        elif chance['card_type'] == 7:  # Move
            chance_list.append(
                card.MoveCard(chance['card_id'], chance['card_type'],
                              chance['description'], chance['steps']))
        elif chance['card_type'] == 5:  # Bailcard
            chance_list.append(
                card.BailCard(chance['card_id'], chance['card_type'],
                              chance['description']))

    # initialize chess board
    two_block_street = []
    three_block_street = []
    for e in estate_list:
        if e.street_id == 1 or e.street_id == 8:
            two_block_street.append(e)
        else:
            three_block_street.append(e)
    chess_board_object = board.Board(two_block_street, three_block_street,
                                     station_list, utility_list, block_list,
                                     corner_list, chest_block_list,
                                     chance_block_list, tax_list)

    global data
    data['chess_board'] = block_list
    data['player_dict'] = player_dict
    data['epic_bank'] = epic_bank
    data['chest_list'] = chest_list
    data['chance_list'] = chance_list
    data['station_list'] = station_list
    data['utility_list'] = utility_list
    data['estate_list'] = estate_list
    data['corner_list'] = corner_list
    data['chest_block_list'] = chest_block_list
    data['chance_block_list'] = chance_block_list
    data['tax_list'] = tax_list
    return data
示例#25
0
def createStation(list):
    stat = st.Station(list[0], list[1], list[2], list[3], list[4], list[5],
                      list[6], list[7], list[8])
    return stat
示例#26
0
    format = "APRSD"
    #s = 'IR3BH>APNU19,IQ3MF*,WIDE,qAo,IR3CO-5:!4551.72N/01330.23E# / APRS DIGIPEATER sez.ARI MONFALCONE (GO)'

    lines = load('..\\log\\log_20060214_1.txt')

    frames = []
    for s in lines:
        frame = Frame(s, format )
        frames.append(frame)
        
    callsigns = get_callsigns(frames)
    print callsigns
    
    stationlist= {}        # List of stations
    for call in callsigns:
        s = station.Station(call)
        stationlist[call] = s 
    print stationlist
        
    for f in frames:
        if f.callsign:
            s = stationlist.get(f.callsign,None)
            if s:
                if frame.path:
                    s.path = frame.path
                if frame.position:
                    s.position = frame.position
                if frame.timestamp:
                    s.timestamp = frame.timestamp
                print 'frame: ',f.__dict__
                print 'station: ',s.__dict__
示例#27
0
    def load_stations(self, stations_xml, track_segments):
        all_stations = dict()
        for station_xml in stations_xml.getElementsByTagName('Station'):
            station_label = station_xml.getAttribute('label')
            station_id = int(station_xml.getAttribute('id').split('_')[0])
            try:
                storage_entrance_delay = int(station_xml.getAttribute('storage_entrance_delay'))
            except ValueError:
                logging.warn("station '%s' is missing or has an invalid 'storage_entrance_delay' attribute. Defaulting to 0.", station_label)
                storage_entrance_delay = 0

            try:
                storage_exit_delay = int(station_xml.getAttribute('storage_exit_delay'))
            except ValueError:
                logging.warn("station '%s' is missing or has an invalid 'storage_exit_delay' attribute. Defaulting to 0.", station_label)
                storage_exit_delay = 0

            # Get the TrackSegments
            track_segs = set() # using a set because 'TrackSegmentID' includes the duplicate ts from Platform
            for track_id_xml in station_xml.getElementsByTagName('TrackSegmentID'):
                track_id = self._to_numeric_id(track_id_xml)
                track_segs.add(track_segments[track_id])

            # Make the Storage objects and place them in a dict keyed by model_name
            storage_dict = {}
            for storage_xml in station_xml.getElementsByTagName('Storage'):
                model_name = storage_xml.getAttribute('model_name')
                if len(model_name) == 0:
                    raise common.ScenarioError(
                        "Storage for station '%s' is missing or has an invalid or missing 'model_name' attribute" \
                        % (station_label))

                initial_supply_str = storage_xml.getAttribute('initial_supply').lower()
                if initial_supply_str == 'inf':
                    initial_supply = float('inf')
                else:
                    try:
                        initial_supply = int(storage_xml.getAttribute('initial_supply'))
                    except ValueError:
                        raise common.ScenarioError(
                            "Storage for station '%s' is missing or has an invalid 'initial_supply' attribute: %s." \
                            % (station_label, initial_supply_str))

                max_capacity_str = storage_xml.getAttribute('max_capacity').lower()
                if max_capacity_str == 'inf':
                    max_capacity = float('inf')
                else:
                    try:
                        max_capacity = int(storage_xml.getAttribute('max_capacity'))
                    except ValueError:
                        raise common.ScenarioError(
                            "Storage for station '%s' has an invalid or missing 'max_capacity' attribute: %s." \
                            % (station_label, max_capacity_str))

                storage = station.Storage(model_name,
                                          initial_supply,
                                          max_capacity)
                storage_dict[storage.model_name] = storage

            station_ = station.Station(station_id,
                                       station_label,
                                       track_segs,
                                       storage_entrance_delay,
                                       storage_exit_delay,
                                       storage_dict)

            # Make the Platforms
            platforms_xml = station_xml.getElementsByTagName('Platform')
            platforms = [None]*len(platforms_xml)
            for platform_xml in platforms_xml:
                platform_trackseg_id = self._to_numeric_id(platform_xml.getElementsByTagName('TrackSegmentID')[0])
                platform_trackseg = track_segments[platform_trackseg_id]
                platform_index = int(platform_xml.getAttribute('index'))
                platform = station.Platform(platform_index, platform_trackseg)

                # Make the Berths
                berths_xml = platform_xml.getElementsByTagName('Berth')
                berths = [None]*len(berths_xml)
                for berth_xml in berths_xml:
                    berth_index = int(berth_xml.getAttribute('index'))
                    start_pos = float(berth_xml.getElementsByTagName('StartPosition')[0].firstChild.data)
                    end_pos = float(berth_xml.getElementsByTagName('EndPosition')[0].firstChild.data)
                    unloading = True if berth_xml.getAttribute('unloading') == 'true' else False
                    loading = True if berth_xml.getAttribute('loading') == 'true' else False
                    storage_entrance = True if berth_xml.getAttribute('storage_entrance') == 'true' else False
                    storage_exit = True if berth_xml.getAttribute('storage_exit') == 'true' else False
                    berths[berth_index] = Berth(berth_index, station_,
                                                platform, start_pos, end_pos,
                                                unloading, loading,
                                                storage_entrance, storage_exit)

                platform.berths = berths
                platforms[platform_index] = platform
            station_.platforms = platforms
            all_stations[station_.ID] = station_
        return all_stations