def __init__( self, building_path="data/building_oib_16linie.xlsx", kWp=1, # PV kWp battery_kWh=1): # Battery kWh ###### Compononets ##### # (Other classes and parts, that form the model) self.building = Building(path=building_path) self.HVAC = HVAC() self.PV = PV(csv="data/pv_1kWp.csv", kWp=1) self.PV.set_kWp(kWp) self.battery = Battery(kWh=battery_kWh) ###### Parameters ##### self.cp_air = 0.34 # spez. Wärme kapazität Luft (Wh/m3K) self.price_grid = 0.19 # €/kWh self.price_feedin = 0.05 # €/kWh ###### Timeseries ##### # load Usage characteristics self.Usage = pd.read_csv("data/usage_profiles.csv", encoding="cp1252") # load climate data self.TA = np.genfromtxt("data/climate.csv", delimiter=";")[1:, 1] # load solar gains self.QS = np.genfromtxt("data/Solar_gains.csv") # W/m²
def __init__(self, config): self.Pmax = config["pmax"] self.m_pl = config["mpl"] self.Pice_max = config["pice"] self.ice = ICE(Pmax=self.Pice_max) self.Pice_opt = self.ice.Popt self.Nice = self.ice.N_opt self.Mice = self.Pice_opt / N2omega(self.Nice) self.Pemot_max = max(self.Pmax - self.Pice_max, 0) self.emot = Emotor(self.Pemot_max) self.Pmax = self.ice.Pmax + self.emot.Pmax self.bat = Battery(config["cbat"], config["pbat"]) self.fuel = config["fuel"] super(self.__class__, self).__init__()
def test_start_stop(self): drone = Drone(5, (10, 20), (10, 20, 0), 0.2, (0, 0), Battery(300, 100, 3)) self.assertEqual(drone.start(), 0) self.assertEqual(drone.start(), -1) self.assertEqual(drone.stop(), 0) self.assertEqual(drone.stop(), -1)
def __init__(self): # To avoid memory errors setup display ASAP and surround in garbabe collection to improvce chances gc.collect() disp = epaper.Display('R', mode=epaper.FAST) gc.collect() # Pass display to draw Class self.screen = draw(disp) #Create battery ADC interface currentADC = BatteryCurrentADC() # Initialise batteries can be test or normal #self.battery1 = testBattery(pyb.Pin.board.X11, currentADC, AfuncArg='chan 0_1', # initialcharge=100, batteryAH=100) #self.battery2 = testBattery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 2_3', # initialcharge=100, batteryAH=100) self.mount_fram() try: Aoff1, Aoff2 = self.config() except: Aoff1 = 0 Aoff2 = 0 print('no config') self.battery1 = Battery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 0_1', initialcharge = 65, batteryAH = 100, Aoffset=Aoff1) self.battery2 =self.battery1 # TODO: initialise CMD self.CMD = BatCMD(self.battery1, self.battery2) # initialse logger and file things up self.last_write = 0 self.update()
def __init__(self, config): self.Pmax = config["pmax"] self.m_pl = config["mpl"] self.ice = ICE(Pmax=self.Pmax) self.bat = Battery(0., 0.) self.bat.SoC = 0. self.fuel = config["fuel"] super(self.__class__, self).__init__()
def __init__(self, _id, state='alive'): self._id = _id self.radio = Radio() self.state = state self.battery = Battery() self.ger_consumo = Consumo() self.pos_x = np.random.uniform(0, config.AREA_WIDTH) self.pos_y = np.random.uniform(0, config.AREA_LENGHT)
def setup(self, args=None): '''Set up arguments to be used, and initialize Battery and Brightness mangager.''' arguments = { "verbose": True, "manual": False, "fade": .25, "time": 2, "profile": None } if args is not None: for arg in args.keys(): if arg in arguments: arguments[arg] = args[arg] self.arguments = arguments if self.arguments["verbose"]: print("Arguments", flush=True) print("=====================") for key, value in self.arguments.items(): print(key, ":", value, flush=True) print("=====================\n") self.brightness_manager = BrightnessManager() self.battery = Battery() self.brightness = self.brightness_manager.get_brightness() self.charging = self.battery.is_charging() self.percent = self.battery.percent() self.level = None self.min_percent = None self.max_percent = None if self.arguments["profile"] is None: cur_dir = os.path.abspath(os.path.dirname(__file__)) if self.arguments["verbose"]: print("Default settings loaded", flush=True) self.settings = Settings(os.path.join(cur_dir, "settings.json")) else: self.settings = Settings(arguments["profile"])
def __init__(self, brand, model, type): # calling super class contructor with class name Vehicle.__init__(self, brand, model, type) # calling super class contructor with super() function # super().__init__(brand, model, type) self.battery_size = 85 self.charge_level = 0 from Battery import Battery # Storing an instance of a class in an attribute self.battery = Battery()
def innit_data(houseslist, batterieslist, rand, batteries): houses = [] for house in houseslist: # clean up data temp = house.replace(' ', '').split(',') temp = [float(i) for i in temp] houses.append(House((temp[0], temp[1]), temp[2])) # save battery coords it they do not need to be random if rand == False: coords = [batteries[i].coord for i in batteries] batteries = {} for i in range(len(batterieslist)): cap = batterieslist[i][2] # place the batteries random if rand == True: battery_locations = [] house_locations = [house.coord for house in houses] coord = (random.randint(0, 50), random.randint(0, 50)) # try to get a battery placing where there is no house or other battery while coord in (house_locations + battery_locations): # make sure the battery is more than 15 places away from any ohter battery skip = -1 while skip < len(battery_locations): skip = 0 # get random coord coord = (random.randint(0, 50), random.randint(0, 50)) for location in battery_locations: if manhatten_distance(coord, location) < 10: break else: skip += 1 battery_locations.append(coord) # use coords previously saved else: coord = coords[i] batteries[i] = (Battery(coord, cap, i)) # calculate distances to all batteries from houses for house in houses: house.calc_distances(batteries) # calculate all distances to houses from batteries for battery in batteries: batteries[battery].calculate_distances(houses) return batteries, houses
def test_if_full_battery_level(self): # check number high limit battery_test = Battery(bet(0,0,100)) self.assertTrue(battery_test.if_full_battery_level(),"full battey") # check number up the limit battery_test = Battery(bet(0,0,101)) self.assertTrue(battery_test.if_full_battery_level(),"full battey") # check number low the limit battery_test = Battery(bet(0,0,50)) self.assertFalse(battery_test.if_full_battery_level(),"full battey") # check number low the limit (99) battery_test = Battery(bet(0,0,99)) self.assertFalse(battery_test.if_full_battery_level(),"full battey")
def show(self): self.battery = Battery() self.wifi = Wifi() self.url = QUrl("qt.html") self.web = QWebView() self.web.loadFinished.connect(self.onLoad) self.web.load(self.url) self.web.show()
def test_if_low_battery_level(self): # check number zero the limit battery_test = Battery(bet(0,0,0)) self.assertTrue(battery_test.if_low_battery_level(),"battey low") battery_test = Battery(bet(0,0,4)) self.assertTrue(battery_test.if_low_battery_level(),"battey low") battery_test = Battery(bet(0,0,5)) self.assertTrue(battery_test.if_low_battery_level(),"battey low") battery_test = Battery(bet(0,0,6)) self.assertFalse(battery_test.if_low_battery_level(),"battey low")
def __init__(self, demand_ranges = None, batteryParams = None, loadID = None, with_agent=False, look_ahead = 1): if loadID is None: loadID = Load.num_loads Load.num_loads += 1 if demand_ranges is None: #Because http://docs.python-guide.org/en/latest/writing/gotchas/ if self.RANDOMIZE_DEMANDS: demand_ranges = [[DemandRange.default_lower_bound,DemandRange.default_upper_bound]] * 288 else: demand_ranges = [] with open(self.csv_input_file, 'r') as csv_file: reader = csv.reader(csv_file) for line in reader: try: _demands = None # ignore initial lines of csv file if line[0].startswith("#") or len(line)<2: next(reader) continue except IndexError: _demands = [[float(val) for val in value] for value in reader] # [0] is lower bounds, [1] is upper bounds print(len(_demands), len(_demands[0]), len(_demands[1])) if _demands is None or len(_demands) != 2 or len(_demands[0]) != 288 or len(_demands[1]) != 288: raise AssertionError("Expected timestep size of 5 mins. Data doesn't match.") for i in range(len(_demands[0])): demand_ranges.append([_demands[0][i], _demands[1][i]]) if batteryParams is None: batteryParams = {} self.demand_ranges = [] for demand_range in demand_ranges: self.demand_ranges.append(DemandRange(float(demand_range[0]), float(demand_range[1]))) self.battery = Battery(**batteryParams) self.demands = list() self.loadID = loadID self.with_agent = with_agent self.costs = list() self.look_ahead = look_ahead self.demand_bounds = Bounds()
def __init__(self): # To avoid memory errors setup display ASAP and surround in garbabe collection to improvce chances gc.collect() disp = epaper.Display('R', mode=epaper.FAST) gc.collect() # Pass display to draw Class self.screen = draw(disp) #Create battery ADC interface currentADC = BatteryCurrentADC() # Initialise batteries can be test or normal #self.battery1 = testBattery(pyb.Pin.board.X11, currentADC, AfuncArg='chan 0_1', # initialcharge=100, batteryAH=100) #self.battery2 = testBattery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 2_3', # initialcharge=100, batteryAH=100) self.mount_fram() try: Aoff1, Aoff2 = self.config() except: Aoff1 = 0 Aoff2 = 0 print('no config') self.battery1 = Battery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 0_1', initialcharge=65, batteryAH=100, Aoffset=Aoff1) self.battery2 = self.battery1 # TODO: initialise CMD self.CMD = BatCMD(self.battery1, self.battery2) # initialse logger and file things up self.last_write = 0 self.update()
def create_battery(x, y, reach): if x + reach > len(tiles) - 1 or x - reach < 0 or y + reach > len( tiles[0]) - 1 or y - reach < 0: return my_tile = tiles[x][y] main_battery = my_tile.tile_type == tile_types["batteryMain"] battery_on = not (my_tile.tile_type == tile_types["batteryOff"]) surrounding_tiles = [] for offset in range(1, reach + 1): surrounding_tiles.append(tiles[x + offset][y]) surrounding_tiles.append(tiles[x - offset][y]) surrounding_tiles.append(tiles[x][y + offset]) surrounding_tiles.append(tiles[x][y - offset]) batteries.append( Battery(x, y, world, main_battery, battery_on, surrounding_tiles, "", ""))
def setup(self, args=None): '''Set up arguments to be used, and initialize Battery and Brightness mangager.''' arguments = { "verbose": False, "manual": False, "fade": .25, "time": 2, "profile": None } if args is not None: for arg in args.keys(): if arg in arguments: arguments[arg] = args[arg] self.arguments = arguments if self.arguments["verbose"]: print("Arguments", flush = True) print("=====================") for key, value in self.arguments.items(): print(key, ":", value, flush=True) print("=====================\n") self.brightness_manager = BrightnessManager() self.battery = Battery() self.brightness = self.brightness_manager.get_brightness() self.charging = self.battery.is_charging() self.percent = self.battery.percent() self.level = None self.min_percent = None self.max_percent = None if self.arguments["profile"] is None: cur_dir = os.path.abspath(os.path.dirname(__file__)) if self.arguments["verbose"]: print("Default settings loaded", flush=True) self.settings = Settings(os.path.join(cur_dir, "settings.json")) else: self.settings = Settings(arguments["profile"])
def __init__(self): """Initializes the data""" #create empty object properties self.mass = None self.wheel = Wheel() self.motor = Motor() self.GearRatio = None self.GearEfficieny = None self.Cd = None self.Af = None self.battery = Battery()
def ReadTechnologies(filename,soc_start=0.8,num_periods=8760): """Reads an input file and returns a list of the technologies available for purchase. filename -- input file name soc_start -- the starting state of charge for any batteries purchased num_periods -- lenght of time horizon, in periods. retval -- a list of DieselGenerator, PVArray, and Battery objects. """ technologies =[] tech_file = open(filename, 'rU') tech_reader = csv.reader(tech_file) keys = next(tech_reader) keys = [key.strip() for key in keys] for line in tech_reader: attributes = {} #print ', '.join(line) attributes["name"] = line[0] for i in range(1,len(line)): attributes[keys[i]] = line[i] #Make the appropriate technology based on the technology type. The #index given in the first column, "tech", is what we need. Because the #notation is a letter-number combination, e.g. "G1", we use the #first character as a guide for the technology we create. if attributes["name"][0] == 'G': #make a DieselGenerator technologies.append(DieselGenerator(attributes, 0)) #technologies[-1].SetFuelCost(fuel_cost) elif attributes["name"][0] == 'S': #make a PVArray technologies.append(PVArray(attributes, 0)) elif attributes["name"][0] == 'B': #make a Battery technologies.append(Battery(attributes, 0) ) technologies[-1].SetSOC(soc_start) else: assert False, "Error: invalid technology type." tech_file.close() return technologies
def create_battery_advanced(x, y, left_reach, right_reach, up_reach, down_reach, upper_limit, lower_limit): if x + right_reach > len( tiles) - 1 or x - left_reach < 0 or y + down_reach > len( tiles[0]) - 1 or y - up_reach < 0: return my_tile = tiles[x][y] battery_on = not (my_tile.tile_type == tile_types["batteryOff"]) and not ( my_tile.tile_type == tile_types["batteryEnd"]) main_battery = my_tile.tile_type == tile_types["batteryMain"] surrounding_tiles = [] for iii in range(1, left_reach + 1): surrounding_tiles.append(tiles[x - iii][y]) for iii in range(1, right_reach + 1): surrounding_tiles.append(tiles[x + iii][y]) for iii in range(1, up_reach + 1): surrounding_tiles.append(tiles[x][y - iii]) for iii in range(1, down_reach + 1): surrounding_tiles.append(tiles[x][y + iii]) batteries.append( Battery(x, y, world, main_battery, battery_on, surrounding_tiles, upper_limit, lower_limit))
def __init__(self, make, model, year): super().__init__(make, model, year) self.battery = Battery(85)
def test_set_current(self): sitl = SITL() sitl.download('copter', '3.3', verbose=True) sitl_args = ['-I0', '--model', 'quad', '--home=-35.363261,149.165230,584,353'] sitl.launch(sitl_args, await_ready=True, restart=True) print "Connecting to vehicle on: 'tcp:127.0.0.1:5760'" vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True) print " Battery: %s" % vehicle.battery battery_test = Battery(vehicle.battery) # check number negative the limit battery_test.set_current(NEGATIVE_NUMBER) self.assertEqual(battery_test.current, 0) # check number positive the limit battery_test.set_current(POSITIVE_NUMBER) self.assertEqual(battery_test.get_current(), POSITIVE_NUMBER) # check ZERO battery_test.set_current(0) self.assertEqual(battery_test.get_current(), 0) #check char that non number battery_test.set_current(CHARACTER) self.assertEqual(battery_test.get_current(), 0) #check char that number battery_test.set_current(CHAR_NUMBER) self.assertEqual(battery_test.get_current(), int(CHAR_NUMBER)) sitl.stop()
from Battery import Battery print ("Test Encoder") battery = Battery(); while(True): battery.updateMeasurement(); print(battery.getVoltage())
TAG = "MAIN" log.flags = log.LOG_ALL_ENABLE # log test log.info(TAG, "Simulator started"); with open("config.json") as simu_cfg_file: simu_cfg = json.load(simu_cfg_file) # Ajout des objets dans le worldstate drones = simu_cfg['drones'] stations = simu_cfg['stations'] for drone in drones: battery = Battery(drone["battery"]["maxCycle"], drone["battery"]["lvl"], drone["battery"]["consumption"]) el = Drone(drone["name"],(drone["homeLocation"]["x"], drone["homeLocation"]["y"]), (drone["position"]["x"], drone["position"]["y"]), drone["position"]["z"], drone["failureFrequency"], drone["averageSpeed"], battery) WorldObjects.drones.append(el) for station in stations: chargingBatteries = [] chargedBatteries = [] for battery in station["chargingBatteries"]: chargingBatteries.append(Battery(battery["maxCycle"], battery["lvl"], battery["consumption"])) for battery in station["chargedBatteries"]: chargedBatteries.append(Battery(battery["maxCycle"],battery["lvl"], battery["consumption"])) el = Station(station["name"], (station["position"]["x"], station["position"]["y"]), chargedBatteries, station["storageCapacity"], station["chargingTime"], station["chargingSlots"], station["changeDuration"], station["failureFrequency"])
def main(): sendSMS = SendSMS() battery = Battery(ws) delivery = Delivery(ws) result = ws.recv() result = json.loads(result) pprint("RESULTADO %s" % result) resposta = "" global total_steps global current_step # nivelBateria = GPIO.input(12) if result.get('type') == None: show = result.get('message') pprint(show) # result if show.get('type') == "Change": print "ESTADO DA BATERIA MUDOU " global nivelBateria global sendSMSAdmin nivelBateria = "Medio" sendSMSAdmin = "true" if show.get('type') == "Delivery": destination = show.get('destination').get('departament_name') key_access = show.get('key_access') global tracker tracker = show.get('tracker') print "\n Pedido Gerado para %s com o ID %s e PASSWORD %s" % ( destination, tracker, key_access) # Capturar a rota de envio e direcionar para o carrinho route = show.get('route').get('name') total_steps = show.get('route').get('total_steps') current_step = show.get('route').get('current_step') print total_steps print current_step sender_name = show.get('sender').get('employee_name') sender_number = show.get('sender').get('contacts')[0].get( 'description') recipient_name = show.get('recipient').get('employee_name') recipient_number = show.get('recipient').get('contacts')[0].get( 'description') sendSMS.smsForSender(recipient_name, recipient_number, destination, tracker, key_access) start_delivery(route) resposta = "Deslocamento" if show.get('type') == "Open": pass if show.get('type') == "infoAdmin": pprint(show.get('admins')) admins = show.get('admins') for admin in admins: print("---------- Informando Admins ----------") admin_name = admin.get('name') admin_contact = admin.get('contact') sendSMS.informStatusBatterry(admin_name, admin_contact) if nivelBateria == "Baixo": pass if nivelBateria == "Medio": if sendSMSAdmin == 'true': global sendSMSAdmin battery.get_admins("MESSAGE") battery.inform("Mudando Status") global nivelBateria sendSMSAdmin = 'false' nivelBateria = "Alto" if nivelBateria == "Alto": pass # resposta = ser.readline() # if (resposta == "Deslocamento") : # deslocamento = ser.readline() #NUMERO DE VEZES QUE DESLOCOU NO EIXO X. print "Current %s" % current_step print "Total %s" % total_steps while current_step < total_steps: if (resposta == "Deslocamento"): #deslocamento = ser.readline() #NUMERO DE VEZES QUE DESLOCOU NO EIXO X. # while info < 10: global tracker print tracker delivery.update_delivery(info, tracker) time.sleep(7) global info info = info + 1 current_step = info print "Aqui -----" # sendSMS.stop_delivery("ed") else: pass
# 11 Mar, 2018 from Battery import Battery b = Battery() print(b.get_current_battery_percentage()) # should be 100.0 b.update_battery_percentage(b.get_battery_capacity() / 2) print(b.get_current_battery_percentage()) # should be 50.0 b.set_current_battery_percentage(25.0) print(b.get_current_battery_percentage()) # should be 25.0
############# # Constants ############# CADENCE_PIN = 31 # GPIO.BOARD SPEED_PIN = 29 # GPIO.BOARD UPDATE_INTERVAL = 0.5 # Target amount of time between OSD updates TX_INTERVAL = 3 # Time between radio transmits ############# # Setup ############# cadenceModule = Cadence(CADENCE_PIN) speedAndDistanceModule = SpeedAndDistance(SPEED_PIN) osdModule = Osd() radioModule = Radio(1, 2) batteryModule = Battery() txIntervalCount = 0 emergency = 0 logFileName = "{}.log".format(time.strftime('%y%m%d-%H%M%S', time.localtime())) logFile = open(logFileName, "w+") ############# # Main ############# try: while True: start_time = time.clock() speedKph = speedAndDistanceModule.get_speed()
class Model: simulated = [] # this is not strictly neccessary # it uses a class variable to save # all simulated instances of a model # they get recorded at the end of the # Model.simulate() method def __init__( self, building_path="data/building_oib_16linie.xlsx", kWp=1, # PV kWp battery_kWh=1): # Battery kWh ###### Compononets ##### # (Other classes and parts, that form the model) self.building = Building(path=building_path) self.HVAC = HVAC() self.PV = PV(csv="data/pv_1kWp.csv", kWp=1) self.PV.set_kWp(kWp) self.battery = Battery(kWh=battery_kWh) ###### Parameters ##### self.cp_air = 0.34 # spez. Wärme kapazität Luft (Wh/m3K) self.price_grid = 0.19 # €/kWh self.price_feedin = 0.05 # €/kWh ###### Timeseries ##### # load Usage characteristics self.Usage = pd.read_csv("data/usage_profiles.csv", encoding="cp1252") # load climate data self.TA = np.genfromtxt("data/climate.csv", delimiter=";")[1:, 1] # load solar gains self.QS = np.genfromtxt("data/Solar_gains.csv") # W/m² def init_sim(self): # (re)load profiles from self.Usage #this is neccessary if the PV model has changed inbetween simulations self.QI_winter = self.Usage["Qi Winter W/m²"].to_numpy() self.QI_summer = self.Usage["Qi Sommer W/m²"].to_numpy() self.ACH_V = self.Usage["Luftwechsel_Anlage_1_h"].to_numpy() self.ACH_I = self.Usage["Luftwechsel_Infiltration_1_h"].to_numpy() self.Qdhw = self.Usage["Warmwasserbedarf_W_m2"].to_numpy() self.ED_user = self.Usage["Nutzerstrom_W_m2"].to_numpy() # (re)load PV profiles #this is neccessary if the PV model has changed inbetween simulations self.PV_prod = self.PV.TSD * 1000 / self.building.bgf # everything is in Wh/m² self.PV_use = np.zeros(8760) self.PV_feedin = np.zeros(8760) self.PV_to_battery = np.zeros(8760) # initialize result arrays self.timestamp = pd.Series( np.arange('2020-01-01 00:00', '2021-01-01 00:00', dtype='datetime64[h]')) self.QV = np.zeros(8760) # ventilation losses self.QT = np.zeros(8760) # transmission losses self.QI = np.zeros(8760) # Internal losses self.Q_loss = np.zeros(8760) # total losses without heating/cooling self.TI = np.zeros(8760) # indoor temperature self.QH = np.zeros(8760) # Heating demand Wh/m² self.QC = np.zeros(8760) # Cooling demand Wh/m² # Energy demands self.ED_QH = np.zeros(8760) # Electricity demand for heating Wh/m² self.ED_QC = np.zeros(8760) # Electricity demand for cooling Wh/m² #self.ED_Qdhw = 0 self.ED = np.zeros(8760) # Electricity demand Wh/m² self.ED_grid = np.zeros(8760) self.Btt_to_ED = np.zeros(8760) ## initialize starting conditions self.TI[0] = self.HVAC.minimum_room_temperature def calc_QV(self, t): """Ventilation heat losses [W/m²BGF] at timestep t""" dT = self.TA[t - 1] - self.TI[t - 1] room_height = self.building.net_storey_height cp_air = self.cp_air # thermally effective air change eff_airchange = self.ACH_I[t] + self.ACH_V[ t] # * M.VentilationSystem.share_cs * rel_ACH_after_heat_recovery self.QV[t] = eff_airchange * room_height * cp_air * dT def calc_QT(self, t): """Transmission heat losses [W/m²BGF] at timestep t""" dT = self.TA[t - 1] - self.TI[t - 1] self.QT[t] = self.building.LT * dT def calc_QI(self, t): heat = self.timestamp[t].month in self.HVAC.heating_months cool = self.timestamp[t].month in self.HVAC.cooling_months if (heat and cool) or ( not heat and not cool): # wenn beides oder keinss von beiden, mittelwert self.QI[t] = (self.QI_winter[t] + self.QI_summer[t]) / 2 elif heat: self.QI[t] = self.QI_winter[t] elif cool: self.QI[t] = self.QI_summer[t] else: raise NotImplementedError("Case not defined!") def handle_losses(self, t): # determine losses self.Q_loss[t] = (self.QT[t] + self.QV[t]) + self.QS[t] + self.QI[t] # determine indoor temperature after losses self.TI[t] = self.TI_after_Q(self.TI[t - 1], self.Q_loss[t], self.building.heat_capacity) def TI_after_Q(self, TI_before, Q, cp): """cp = spec. building heat_capacity""" return TI_before + Q / cp def is_heating_on(self, t, TI_new): if self.HVAC.heating_system == True: if self.timestamp[t].month in self.HVAC.heating_months: if TI_new < self.HVAC.minimum_room_temperature: return True return False def is_cooling_on(self, t, TI_new): """ Determines, whether all conditions are met to use cooling """ c1 = self.HVAC.cooling_system == True c2 = self.timestamp[t].month in self.HVAC.cooling_months c3 = TI_new > self.HVAC.maximum_room_temperature return all( [c1, c2, c3] ) # returns True if all conditions are true, False otherwise. similarly, any(). You can stack this way more cleanly def minimum_Q(self, TI, set_min, set_max, cp): """calculates the minimum Q (positive or negative) to reach the setpoint targets""" if TI < set_min: return (set_min - TI) * cp if TI > set_max: return (set_max - TI) * cp else: return 0. def handle_heating(self, t): """Handles the use of a heating system, applies changes to self.QH, self.ED_QH, self.TI if neccessary""" TI = self.TI[t] if self.is_heating_on(t, TI): required_QH = self.minimum_Q( TI=TI, set_min=self.HVAC.minimum_room_temperature, set_max=self.HVAC.maximum_room_temperature, cp=self.building.heat_capacity) required_ED = required_QH / self.HVAC.HP_COP / self.HVAC.heating_eff available_power = self.HVAC.HP_heating_power self.ED_QH[t] = min(required_ED, available_power) self.QH[ t] = self.ED_QH[t] * self.HVAC.HP_COP * self.HVAC.heating_eff self.TI[t] = self.TI_after_Q(TI, self.QH[t], self.building.heat_capacity) def handle_cooling(self, t): """Handles the use of a heating system, applies changes to self.QH, self.ED_QH, self.TI if neccessary""" TI = self.TI[t] if self.is_cooling_on(t, TI): required_QC = self.minimum_Q( TI=TI, set_min=self.HVAC.minimum_room_temperature, set_max=self.HVAC.maximum_room_temperature, cp=self.building.heat_capacity) required_ED = -required_QC / self.HVAC.HP_COP / self.HVAC.heating_eff available_power = self.HVAC.HP_heating_power self.ED_QC[t] = min(required_ED, available_power) self.QC[ t] = -self.ED_QC[t] * self.HVAC.HP_COP * self.HVAC.heating_eff self.TI[t] = self.TI_after_Q(TI, self.QC[t], self.building.heat_capacity) def calc_ED(self, t): self.ED[t] = self.ED_QH[t] + self.ED_QC[t] + self.ED_user[t] def handle_PV(self, t): """allocates the PV to direct and battery charge use""" #calculate the direct Use of PV self.PV_use[t] = min(self.PV_prod[t], self.ED[t]) remain = self.PV_prod[t] - self.PV_use[t] #calculate the remaining PV to Battery self.PV_to_battery[t] = self.battery.charge( remain * self.building.bgf / 1000) * 1000 / self.building.bgf remain = remain - self.PV_to_battery[t] #calculate the remaining PV to Battery self.PV_feedin[t] = max(remain - self.ED[t], 0) def handle_grid(self, t): """calculate the remaining grid demand: Total Energy demand [ED] - PVuse - Battery_discharge""" self.ED_grid[t] = self.ED[t] - self.PV_use[t] - self.Btt_to_ED[t] def handle_battery(self, t): # Lower SoC by hourly losses self.battery.SoC = (1 - self.battery.discharge_per_hour) \ * self.battery.SoC # calculate remaining electricity demand not covered after PV use for time t remaining_ED = (self.ED[t] - self.PV_use[t] ) * self.building.bgf / 1000 #kW not W/m² # conditions # if remaining energy demand > 0 AND battery.SoC > 0 c1 = (remaining_ED > 0) c2 = (self.battery.SoC > 0) if all([c1, c2]): self.Btt_to_ED[t] = self.battery.discharge(remaining_ED) def calc_cost(self, years=20, verbose=True): """calculates the total cost of the system""" # calc investment self.investment_cost = self.building.differential_cost * self.building.bgf + self.PV.cost + self.battery.cost self.operational_cost = self.building.bgf * ( - self.PV_feedin.sum()/1000 * self.price_feedin \ + self.ED_grid.sum()/1000 * self.price_grid) self.total_cost = self.investment_cost + self.operational_cost * years if verbose: print(f"Investment cost: {round(self.investment_cost):>20.2f} €") print( f"Operational cost: {round(self.operational_cost):>20.2f} €/annum" ) print( f"Total cost after {years} years: {round(self.total_cost):>11,.2f} €" ) return self.total_cost def simulate(self): self.init_sim() # don't forget to intialize the first timestep = 0 # with sensible starting values # like TI[0] = self.minimum_room_temperature for t in range(1, 8760): #### Verluste self.calc_QV(t) self.calc_QT(t) self.calc_QI(t) self.handle_losses(t) #### Heizung self.handle_heating(t) #### Kühlung self.handle_cooling(t) #calc total energy demand self.calc_ED(t) #allocate pv self.handle_PV(t) # discharge battery self.handle_battery(t) # handle grid self.handle_grid(t) self.calc_cost(verbose=False) Model.simulated.append( self) # this adds the model result to the base class (optional) return True # the simulate() method does not NEEd to return something # but it can be used to check if the simulation ran successfully def plot(self, show=True, start=1, end=8760, month=None): fig, ax = plt.subplots(2, 2) #,figsize=(8,12)) #tight_layout=True) ax = ax.flatten() self.plot_heat_balance(fig, ax[0], start=start, end=end) self.plot_temperatures(fig, ax[1], start=start, end=end) self.plot_electricity_demand(fig, ax[2], start=start, end=end) self.plot_electricity_use(fig, ax=ax[3], start=start, end=end) if show: dummy = plt.figure() # create a dummy figure new_manager = dummy.canvas.manager # and use its manager to display "fig" new_manager.canvas.figure = fig fig.set_canvas(new_manager.canvas) fig.show() def plot_heat_balance(self, fig=None, ax=None, start=1, end=8760, **kwargs): if (fig, ax) == (None, None): fig, ax = plt.subplots(1, 1) self.plot_arrays( ax=ax, start=start, end=end, arrays=[self.QT, self.QV, self.QS, self.QI, self.QH, self.QC], **kwargs) ax.legend([ "Transmissionsverluste", "Lüftungsverluste", "Solare Gewinne", "Innere Lasten", "Heizwärmebdedarf", "Kühlbedarf" ]) ax.set_title("Wärmebilanz") ax.set_ylabel("W/m²") plt.show() def plot_temperatures(self, fig=None, ax=None, start=1, end=8760, **kwargs): if (fig, ax) == (None, None): fig, ax = plt.subplots(1, 1) self.plot_arrays(ax=ax, start=start, end=end, arrays=[self.TI, self.TA], **kwargs) ax.legend(["Innenraum", "Außenluft"]) ax.set_title("Temperatur") ax.set_ylabel("Temperatur [°C]") plt.show() def plot_electricity_demand(self, fig=None, ax=None, start=1, end=8760, **kwargs): # FigureCanvas(fig) # not needed in mpl >= 3.1 if (fig, ax) == (None, None): fig, ax = plt.subplots(1, 1) self.plot_arrays( ax=ax, start=start, end=end, arrays=[self.PV_prod, self.ED_QH, self.ED_QC, self.ED_user], **kwargs) ax.set_title("Strom") ax.set_ylabel("W/m²") ax.legend(["PV", "WP Heizen", "WP Kühlen", "Nutzerstrom"]) plt.show() def plot_electricity_use(self, fig=None, ax=None, start=1, end=8760, **kwargs): """plots the electricity supply and use""" if (fig, ax) == (None, None): fig, ax = plt.subplots(1, 1) self.plot_arrays(ax=ax, start=start, end=end, arrays=[ self.PV_use, self.Btt_to_ED, self.ED_grid, self.PV_to_battery, self.PV_feedin ], **kwargs) ax.set_title("PV Nutzung") ax.set_ylabel("W/m²") ax.legend([ 'PV Eigenverbrauch', 'Batterie-Entladung', 'Netzstrom', 'Batterie-Beladung', 'Einspeisung' ]) plt.show() def plot_arrays(self, ax, start, end, arrays: list, **kwargs): for array in arrays: ax.plot(array[start:end], **kwargs) def __repr__(self): width = len(self.building.file) return f"""
class PowerSaver: def __init__(self, args=None): self.setup(args) def setup(self, args=None): '''Set up arguments to be used, and initialize Battery and Brightness mangager.''' arguments = { "verbose": True, "manual": False, "fade": .25, "time": 2, "profile": None } if args is not None: for arg in args.keys(): if arg in arguments: arguments[arg] = args[arg] self.arguments = arguments if self.arguments["verbose"]: print("Arguments", flush=True) print("=====================") for key, value in self.arguments.items(): print(key, ":", value, flush=True) print("=====================\n") self.brightness_manager = BrightnessManager() self.battery = Battery() self.brightness = self.brightness_manager.get_brightness() self.charging = self.battery.is_charging() self.percent = self.battery.percent() self.level = None self.min_percent = None self.max_percent = None if self.arguments["profile"] is None: cur_dir = os.path.abspath(os.path.dirname(__file__)) if self.arguments["verbose"]: print("Default settings loaded", flush=True) self.settings = Settings(os.path.join(cur_dir, "settings.json")) else: self.settings = Settings(arguments["profile"]) def poll(self): '''Poll the battery and brightness. If the battery level defined in settings has changed, update the screen brightness.''' poll_time = self.arguments["time"] while True: time.sleep(poll_time) update = False # Get percent, charge status, and brightness self.percent = self.battery.percent() charging = self.battery.is_charging() brightness = self.brightness_manager.get_brightness() # Close the program if the brightness # was changed manually and not set in # command line args. if brightness != self.brightness: if not self.arguments["manual"]: if self.arguments["verbose"]: print("Brightness Manually Changed, Exiting") exit(1) # If the battery level ("low", "medium", "high") is None, # then initialize it. and set the brightness to the # brightness value corresponding to the level # of the battery's percent is currently at if self.level is None: if self.arguments["verbose"]: print("Battery Level Initializing.", flush=True) update = True # If the battery percent has moved out of the range of the # battery level, then update to change the brightness. elif self.percent not in range(self.min_percent, self.max_percent + 1): if self.arguments["verbose"]: print("Battery level changed.", flush=True) update = True # If the battery's charging status has changed, # determine if the screen should brighten for charging # or dim for discharging. elif charging != self.charging: if self.arguments["verbose"]: print("Charging status changed:", charging, flush=True) update = True # Print out the battery percent if verbose was set. if self.arguments["verbose"]: print(self.percent, flush=True) # Only update the brightness if one of the # above requirements are met. if update: self.charging = charging # Check what level the battery percent is ("low", "medium", "high") # and cache the range that level is in. for battery_level, battery_range in self.settings.contents[ "levels"].items(): # If the current percent of the battery is in the range specified in the # battery level, then that is the level needed to get brightness values. if self.percent in range(battery_range[0], battery_range[1] + 1): self.level = battery_level self.min_percent, self.max_percent = battery_range if self.arguments["verbose"]: print("Battery Level: ", self.level, flush=True) break # If the battery is charging, handle brightness settings # for charging in the settings file. if self.charging: target_brightness = self.settings.contents[ "on_charge_brightness"][self.level] if target_brightness != self.brightness: if target_brightness < self.brightness: levels = reversed( range(target_brightness, self.brightness + 1)) else: levels = range(self.brightness, target_brightness + 1) for brightness_level in levels: self.brightness_manager.set_brightness( brightness_level) if self.arguments["verbose"]: print("Setting Brightness:", brightness_level, flush=True) time.sleep(self.arguments["fade"]) # Otherwise, handle brightness settings # for battery usage in the settings file else: target_brightness = self.settings.contents[ "on_battery_brightness"][self.level] if target_brightness != self.brightness: if target_brightness < self.brightness: levels = reversed( range(target_brightness, self.brightness + 1)) else: levels = range(self.brightness, target_brightness + 1) for brightness_level in levels: self.brightness_manager.set_brightness( brightness_level) if self.arguments["verbose"]: print("Setting Brightness:", brightness_level, flush=True) time.sleep(self.arguments["fade"]) # Get the brightness after everything has changed. self.brightness = self.brightness_manager.get_brightness()
# set path to the datafiles housespath = '../Data/wijk1_huizen.csv' batterypath = '../Data/wijk1_batterijen.csv' # load in data houses = loadhouse(housespath) batterijennew = loadbattery(batterypath) lowpoint = 10000 scores = [] for i in range(10000): # store the batteries in a dictionary with coords as key and class as value batterydict = {} for battery in batterijennew: batterydict[(battery[0], battery[1])] = Battery( (battery[0], battery[1]), battery[2], 1) # store houses in a dictionary with coords as key an class as value housesdict = {} for house in houses: # clean the data temp = house.replace(' ', '').split(',') temp = [float(i) for i in temp] housesdict[(temp[0], temp[1])] = House((temp[0], temp[1]), temp[2]) # loop over all batteries for battery in batterydict: # loop until the capacity of the battery is reached while True:
class Monitor: def __init__(self): # To avoid memory errors setup display ASAP and surround in garbabe collection to improvce chances gc.collect() disp = epaper.Display('R', mode=epaper.FAST) gc.collect() # Pass display to draw Class self.screen = draw(disp) #Create battery ADC interface currentADC = BatteryCurrentADC() # Initialise batteries can be test or normal #self.battery1 = testBattery(pyb.Pin.board.X11, currentADC, AfuncArg='chan 0_1', # initialcharge=100, batteryAH=100) #self.battery2 = testBattery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 2_3', # initialcharge=100, batteryAH=100) self.mount_fram() try: Aoff1, Aoff2 = self.config() except: Aoff1 = 0 Aoff2 = 0 print('no config') self.battery1 = Battery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 0_1', initialcharge=65, batteryAH=100, Aoffset=Aoff1) self.battery2 = self.battery1 # TODO: initialise CMD self.CMD = BatCMD(self.battery1, self.battery2) # initialse logger and file things up self.last_write = 0 self.update() # Main functional loop of the program def run(self): self.screen.update(self.battery1, self.battery2) self.last_write = time() screen_timer = pyb.millis() while True: # Update battery data and screen every 10 seconds if pyb.elapsed_millis(screen_timer) > 10000: screen_timer = self.update() self.log_test() gc.collect() self.CMD.Poll() # TODO - check for command interface # Function to update battery data and screen def update(self): self.battery1.update() self.battery2.update() self.screen.update(self.battery1, self.battery2) screen_timer = pyb.millis() return screen_timer # Function to check if log is to be written # and if so write log and tidy files def log_test(self): current_time = time() if localtime(current_time)[4] % 15 == 0 and localtime( current_time - self.last_write)[4] > 5: # write log # get current filenames # note:adjust time by 5 minutes to ensure midnight appears on previous days log fn1, fn2 = self.filename(current_time - 300) self.check_files(fn1, fn2) self.write_log(fn1, self.battery1.log(current_time)) self.write_log(fn2, self.battery2.log(current_time)) self.last_write = current_time # TODO: remove debug sentence print('written to {}'.format(fn1)) # Static function to determine filenames on the basis of current time @staticmethod def filename(ctime): tt = localtime(ctime) fn1 = "/fram/Bat1-{0}-{1}-{2}".format(tt[2], tt[1], tt[0]) fn2 = "/fram/Bat2-{0}-{1}-{2}".format(tt[2], tt[1], tt[0]) return fn1, fn2 # Static function to write data to file @staticmethod def write_log(fn, data): with open(fn, 'a') as f: f.write(data) sync() # Static function to move old files out of fram and into logs folder of SD drive @staticmethod def check_files(fn1, fn2): ld = listdir('/fram') if len(ld) > 2: for f in ld: #ignore config file if f != 'config': fullname = '/fram/' + f if fullname != fn1 and fullname != fn2: # file not current so move cp(fullname, '/sd/logs/') remove(fullname) sync() # Static function to mount fram drive at startup @staticmethod def mount_fram(): i2c = pyb.I2C(1, pyb.I2C.MASTER) f = FRAM(i2c) try: pyb.mount(None, '/fram') except: pass pyb.mount(f, '/fram') # Function to setup Fram and read config file values for calibration def config(self): with open('/fram/config', 'r') as f: Aoff1 = f.readline() Aoff2 = f.readline() return float(Aoff1), float(Aoff2) def write_config(self, Aoff1, Aoff2): with open('/fram/config', 'w') as f: f.write("{0}\r\n".format(Aoff1)) f.write("{0}\r\n".format(Aoff2)) sync()
class PowerSaver: def __init__(self, args=None): self.setup(args) def setup(self, args=None): '''Set up arguments to be used, and initialize Battery and Brightness mangager.''' arguments = { "verbose": False, "manual": False, "fade": .25, "time": 2, "profile": None } if args is not None: for arg in args.keys(): if arg in arguments: arguments[arg] = args[arg] self.arguments = arguments if self.arguments["verbose"]: print("Arguments", flush = True) print("=====================") for key, value in self.arguments.items(): print(key, ":", value, flush=True) print("=====================\n") self.brightness_manager = BrightnessManager() self.battery = Battery() self.brightness = self.brightness_manager.get_brightness() self.charging = self.battery.is_charging() self.percent = self.battery.percent() self.level = None self.min_percent = None self.max_percent = None if self.arguments["profile"] is None: cur_dir = os.path.abspath(os.path.dirname(__file__)) if self.arguments["verbose"]: print("Default settings loaded", flush=True) self.settings = Settings(os.path.join(cur_dir, "settings.json")) else: self.settings = Settings(arguments["profile"]) def poll(self): '''Poll the battery and brightness. If the battery level defined in settings has changed, update the screen brightness.''' poll_time = self.arguments["time"] while True: time.sleep(poll_time) update = False # Get percent, charge status, and brightness self.percent = self.battery.percent() charging = self.battery.is_charging() brightness = self.brightness_manager.get_brightness() # Close the program if the brightness # was changed manually and not set in # command line args. if brightness != self.brightness: if not self.arguments["manual"]: if self.arguments["verbose"]: print("Brightness Manually Changed, Exiting") exit(1) # If the battery level ("low", "medium", "high") is None, # then initialize it. and set the brightness to the # brightness value corresponding to the level # of the battery's percent is currently at if self.level is None: if self.arguments["verbose"]: print("Battery Level Initializing.", flush=True) update = True # If the battery percent has moved out of the range of the # battery level, then update to change the brightness. elif self.percent not in range(self.min_percent, self.max_percent + 1): if self.arguments["verbose"]: print("Battery level changed.", flush=True) update = True # If the battery's charging status has changed, # determine if the screen should brighten for charging # or dim for discharging. elif charging != self.charging: if self.arguments["verbose"]: print("Charging status changed:", charging, flush=True) update = True # Print out the battery percent if verbose was set. if self.arguments["verbose"]: print(self.percent, flush=True) # Only update the brightness if one of the # above requirements are met. if update: self.charging = charging # Check what level the battery percent is ("low", "medium", "high") # and cache the range that level is in. for battery_level, battery_range in self.settings.contents["levels"].items(): # If the current percent of the battery is in the range specified in the # battery level, then that is the level needed to get brightness values. if self.percent in range(battery_range[0], battery_range[1] + 1): self.level = battery_level self.min_percent, self.max_percent = battery_range if self.arguments["verbose"]: print("Battery Level: ", self.level, flush=True) break # If the battery is charging, handle brightness settings # for charging in the settings file. if self.charging: target_brightness = self.settings.contents["on_charge_brightness"][self.level] if target_brightness != self.brightness: if target_brightness < self.brightness: levels = reversed(range(target_brightness, self.brightness + 1)) else: levels = range(self.brightness, target_brightness + 1) for brightness_level in levels: self.brightness_manager.set_brightness(brightness_level) if self.arguments["verbose"]: print("Setting Brightness:", brightness_level, flush=True) time.sleep(self.arguments["fade"]) # Otherwise, handle brightness settings # for battery usage in the settings file else: target_brightness = self.settings.contents["on_battery_brightness"][self.level] if target_brightness != self.brightness: if target_brightness < self.brightness: levels = reversed(range(target_brightness, self.brightness + 1)) else: levels = range(self.brightness, target_brightness + 1) for brightness_level in levels: self.brightness_manager.set_brightness(brightness_level) if self.arguments["verbose"]: print("Setting Brightness:", brightness_level, flush=True) time.sleep(self.arguments["fade"]) # Get the brightness after everything has changed. self.brightness = self.brightness_manager.get_brightness()
class SeriellHybrid(Propulsion): ''' Konstruktor für seriellen Hybrid initialisiert "ICE", "Battery" ''' def __init__(self, config): self.Pemot_max = config["pmax"] self.m_pl = config["mpl"] self.Pice_max = config["pice"] self.ice = ICE(Pmax=self.Pice_max) self.Pice_opt = self.ice.Popt self.m_pl = config["mpl"] self.Nice = self.ice.N_opt self.Mice = self.Pice_opt / N2omega(self.Nice) self.emot = Emotor(self.Pemot_max) self.Pmax = self.Pemot_max self.bat = Battery(config["cbat"], config["pbat"]) self.fuel = config["fuel"] super(self.__class__, self).__init__() ''' Rückgabe: Propellerdrehzahl, passen zu Leistung "P" ''' def calcNProp(self, P): #return self.ice.calcNProp(self.Pmax) return self.ice.getNforP(P, self.Pmax, verbose=False) / c.GEAR_RATIO ''' berechnet die nötige Wellenleistung Rückgabe: Pshaft, Nprop ''' def calcPshaft(self, h, tas, F): Pold = self.Pshaft Nprop = self.calcNProp(Pold) Pshaft = self.Pshaft #first guess eta, Nprop = self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=c.PROP_MAX_N, fixN=True) Pshaft = self.calcNeededP(tas, F, eta, c.GEAR_EFF_SERI) itegrationLimit = 0.1 i = 0 while (abs(Pshaft - Pold) > itegrationLimit): Pold = Pshaft etaOld = eta Nprop = self.calcNProp(Pshaft) eta, Nprop = self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=c.PROP_MAX_N, fixN=True) Pshaft = self.calcNeededP(tas, F, eta, c.GEAR_EFF_SERI) i += 1 if (i > 100 and Pshaft > Pold): if (self.verbose): print("endlosschleife -> " + str(Pshaft) + " != [" + str(Pold) + "]") Pshaft = (Pshaft + Pold) / 2 eta = (eta + etaOld) / 2 Nprop = self.calcNProp(Pshaft) eta, Nprop = self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=c.PROP_MAX_N, fixN=True) Pshaft = self.calcNeededP(tas, F, eta, c.GEAR_EFF_PARA) break #SHOW FINAL DEBUG INFO self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=c.PROP_MAX_N, verbose=True) self.Pshaft = Pshaft if (self.verbose): print('[Propulsion] needed Thrust = ' + str(F)) print('[Propulsion] TAS = ' + str(tas)) print('[Propulsion] Pshaft = ' + str(Pshaft)) print('[Propulsion] Nprop = ' + str(Nprop)) print('[Propulsion] etaProp = ' + str(eta)) print( '[Propulsion] needed Iterations for calculation of Pshaft: ' + str(i)) return Pshaft, Nprop ''' berechnet erst benötigte Wellenleistung und dann motorverbrauch und Betriebsparameter Rückgabe: Pshaft, Nprop, m_f, We, Pice, Nice, Pemot, Wcharge ''' def calcConsumption(self, h, tas, F, dt): if (F <= 0 and self.bat.full()): Pshaft = 0 Nprop = 0 else: Pshaft, Nprop = self.calcPshaft(h, tas, F) return self.calcMotorConsumption(h, Pshaft, Nprop, dt) ''' berechnet motorverbrauch und Betriebsparameter Rückgabe: Pshaft, Nprop, m_f, We, Pice, Nice, Pemot, Wcharge ''' def calcMotorConsumption(self, h, Pshaft, Nprop, dt): if (Pshaft <= 0 and self.bat.full()): Nprop = 0 Mprop = 0 Nice = self.ice.getNidle() m_f = 0 FF = 0 Pice = 0 We_ice = 0 We = 0 We_bat = 0 else: Mprop = Pshaft / N2omega(Nprop) Nice = self.Nice Mice = self.Mice Pice = self.Pice_opt #needed elec-Power We = self.emot.calcConsumption(Nprop, Mprop, dt) We_ice = We if (self.bat.empty()): We_ice = We + self.bat.getMaxChargeRate() Pice = self.ice.calcNeededICEPower(We_ice, dt) Pice = min(Pice, self.ice.Pmax) Nice = self.ice.calcNIce(Pice) Mice = Pice / N2omega(Nice) m_f, FF = self.ice.calcConsumption(Nice, Mice, dt) We_ice = self.ice.calcGeneratorWe(Pice, dt) We_bat = We_ice - We self.SoF -= self.ice.calcConsumtionToL(m_f, dt) / self.fuel #self.V_tank We, Wcharge = self.bat.charge(We_bat, dt) if (self.verbose): print('[Propulsion] Nice = ' + str(Nice)) print('[Propulsion] Pice = ' + str(Pice)) print('[Propulsion] FF = ' + str(FF)) print('[Propulsion] SoC = ' + str(self.bat.SoC)) print('[Propulsion] SoF = ' + str(self.SoF)) return Pshaft, Nprop, m_f, We, Pice, Nice, Pshaft, Wcharge ''' Berechnet Antriebskomponentenmassen und speichert sie in Klassenvariable "mass" (dict) Rückgabe: Gesamtantriebsmasse ''' def calcPropulsionMasses(self): self.mass["ICE"] = 0. self.mass["Gen"] = 0. self.mass["Umr2"] = 0. if (self.Pice_max > 0): self.mass["ICE"] = (self.Pice_max / c.PD_ice) + c.PD_ice_add self.mass["Gen"] = (self.Pice_max / c.PD_emot) + c.PD_emot_add self.mass["Umr2"] = (self.Pice_max / c.PD_inv) + c.PD_inv_add self.mass["EMot"] = (self.Pmax / c.PD_emot) + c.PD_emot_add self.mass["Umr"] = (self.Pmax / c.PD_inv) + c.PD_inv_add self.mass["Bat"] = 0. if (self.bat.C > 0.): self.mass["Bat"] = self.bat.calcMass() return sum(self.mass.values())
from Battery import Battery from Resistor import Resistor def dc_sweep(comps, bat, to_measure, start, end): for i in range(start, end): bat.value = i circ = MNACircuit(comps) circ_sol = circ.solve() cur = circ_sol.get_current_for_resistor(to_measure) print(i, cur) if __name__ == '__main__': bat1 = Battery(0, 1, 9) res1 = Resistor(1, 2, 5) res2 = Resistor(1, 2, 10) res3 = Resistor(2, 0, 7) comps = [bat1, res1, res2, res3] cir = MNACircuit(comps) sol = cir.solve() print("\n\nSolutions:\n") for c in comps: print(c, c.value) if c.type == ElementType.RESISTOR:
class ParallelHybrid(Propulsion): ''' Konstruktor für parallelen Hybrid initialisiert "ICE", "Battery" ''' def __init__(self, config): self.Pmax = config["pmax"] self.m_pl = config["mpl"] self.Pice_max = config["pice"] self.ice = ICE(Pmax=self.Pice_max) self.Pice_opt = self.ice.Popt self.Nice = self.ice.N_opt self.Mice = self.Pice_opt / N2omega(self.Nice) self.Pemot_max = max(self.Pmax - self.Pice_max, 0) self.emot = Emotor(self.Pemot_max) self.Pmax = self.ice.Pmax + self.emot.Pmax self.bat = Battery(config["cbat"], config["pbat"]) self.fuel = config["fuel"] super(self.__class__, self).__init__() ''' Rückgabe: Propellerdrehzahl, passen zu Leistung "P" ''' def calcNProp(self, P): if (self.Pice_max == 0): return self.ice.getNforP(P, self.Pmax, verbose=False) / c.GEAR_RATIO return self.ice.calcNProp(P) ''' berechnet die nötige Wellenleistung Rückgabe: Pshaft, Nprop ''' def calcPshaft(self, h, tas, F): gearEff = c.GEAR_EFF_PARA #Getriebewirkungsgrad bei Wegfall des Getriebes if (self.Pice_max == 0): gearEff = c.GEAR_EFF_SERI Pold = self.Pshaft Nprop = self.calcNProp(Pold) Pshaft = self.Pshaft #first guess eta, Nprop = self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=self.ice.NiceToNprop( self.ice.getNmax()), fixN=True) Pshaft = self.calcNeededP(tas, F, eta, gearEff) itegrationLimit = 0.1 i = 0 eta_s = [] Nprop_s = [] Pshaft_s = [] while (abs(Pshaft - Pold) > itegrationLimit): Pold = Pshaft etaOld = eta Nprop = self.calcNProp(Pshaft) #print("------- " + str(i) + " -------") eta, Nprop = self.prop.calcEfficiency( h, tas, Nprop, Pshaft, NpropMax=self.ice.NiceToNprop(self.ice.getNmax()), fixN=True) Pshaft = self.calcNeededP(tas, F, eta, gearEff) i += 1 if (i > 100 and Pshaft > Pold): if (self.verbose): print("keine konvergenz -> " + str(Pshaft) + " != [" + str(Pold) + "]") Pshaft = (Pshaft + Pold) / 2 eta = (eta + etaOld) / 2 Nprop = self.calcNProp(Pshaft) eta, Nprop = self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=c.PROP_MAX_N, fixN=True) Pshaft = self.calcNeededP(tas, F, eta, gearEff) break #SHOW FINAL DEBUG INFO self.prop.calcEfficiency(h, tas, Nprop, Pshaft, NpropMax=self.ice.NiceToNprop( self.ice.getNmax()), verbose=True) Nice = self.ice.NpropToNice(Nprop) self.Pshaft = Pshaft if (self.verbose): print('[Propulsion] needed Thrust = ' + str(F)) print('[Propulsion] TAS = ' + str(tas)) print('[Propulsion] Nice = ' + str(Nice)) print('[Propulsion] Pshaft = ' + str(Pshaft)) print('[Propulsion] Nprop = ' + str(Nprop)) print('[Propulsion] etaProp = ' + str(eta)) print( '[Propulsion] needed Iterations for calculation of Pshaft: ' + str(i)) return Pshaft, Nprop ''' berechnet erst benötigte Wellenleistung und dann motorverbrauch und Betriebsparameter Rückgabe: Pshaft, Nprop, m_f, We, Pice, Nice, Pemot, Wcharge ''' def calcConsumption(self, h, tas, F, dt): if (F <= 0 and self.bat.full()): Nprop = 0 Pshaft = 0 else: Pshaft, Nprop = self.calcPshaft(h, tas, F) return self.calcMotorConsumption(h, Pshaft, Nprop, dt) ''' berechnet motorverbrauch und Betriebsparameter Rückgabe: Pshaft, Nprop, m_f, We, Pice, Nice, Pemot, Wcharge ''' def calcMotorConsumption(self, h, Pshaft, Nprop, dt): Nice = self.ice.NpropToNice(Nprop) if (Pshaft <= 0 and self.bat.full()): Pice = 0 Pemot = 0 Nice = self.ice.getNidle() Mice = 0 Memot = 0 else: Pice = Pshaft Pemot = 0 if (Pshaft > self.Pice_max): Pice = self.Pice_max Pemot = Pshaft - Pice Mice = Pice / N2omega(Nice) Memot = Pemot / N2omega(Nice) m_f, FF = self.ice.calcConsumption(Nice, Mice, dt) We_ice = 0 We = self.emot.calcConsumption(Nice, Memot, dt) self.SoF -= self.ice.calcConsumtionToL(m_f, dt) / self.fuel #self.V_tank We, Wcharge = self.bat.charge(We_ice - We, dt) if (self.verbose): print('[Propulsion] Pice = ' + str(Pice)) print('[Propulsion] Pemot = ' + str(Pemot)) print('[Propulsion] FF = ' + str(FF)) print('[Propulsion] SoC = ' + str(self.bat.SoC)) print('[Propulsion] SoF = ' + str(self.SoF)) return Pshaft, Nprop, m_f, We, Pice, Nice, Pemot, Wcharge ''' Berechnet Antriebskomponentenmassen und speichert sie in Klassenvariable "mass" (dict) Rückgabe: Gesamtantriebsmasse ''' def calcPropulsionMasses(self): self.mass["ICE"] = 0. if (self.Pice_max > 0): self.mass["ICE"] = (self.Pice_max / c.PD_ice) + c.PD_ice_add self.mass["Umr"] = 0. self.mass["EMot"] = 0. if (self.Pemot_max > 0): self.mass["Umr"] = (self.Pemot_max / c.PD_inv) + c.PD_inv_add self.mass["EMot"] = (self.Pemot_max / c.PD_emot) + c.PD_emot_add self.mass["Bat"] = 0. if (self.bat.C > 0.): self.mass["Bat"] = self.bat.calcMass() return sum(self.mass.values())
import os from Error import Error from Hydrate import Hydrate from Battery import Battery from Prosumer import Prosumer error = Error() hydrate = Hydrate() battery = Battery() prosumer = Prosumer() class Generator: error = Error() def __init__(self): print("init generators") def choise(self): print("Generator choise") generators = {1: "Hydrate generator", 2: "Battery", 3: "Prosumer"} while (True): print("Choise what do you want") for i in generators: print i, "-", generators[i] print("0 - exit") choise = input("Enter your choise: ") os.system('clear')
class Monitor: def __init__(self): # To avoid memory errors setup display ASAP and surround in garbabe collection to improvce chances gc.collect() disp = epaper.Display('R', mode=epaper.FAST) gc.collect() # Pass display to draw Class self.screen = draw(disp) #Create battery ADC interface currentADC = BatteryCurrentADC() # Initialise batteries can be test or normal #self.battery1 = testBattery(pyb.Pin.board.X11, currentADC, AfuncArg='chan 0_1', # initialcharge=100, batteryAH=100) #self.battery2 = testBattery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 2_3', # initialcharge=100, batteryAH=100) self.mount_fram() try: Aoff1, Aoff2 = self.config() except: Aoff1 = 0 Aoff2 = 0 print('no config') self.battery1 = Battery(pyb.Pin.board.X12, currentADC, AfuncArg='chan 0_1', initialcharge = 65, batteryAH = 100, Aoffset=Aoff1) self.battery2 =self.battery1 # TODO: initialise CMD self.CMD = BatCMD(self.battery1, self.battery2) # initialse logger and file things up self.last_write = 0 self.update() # Main functional loop of the program def run(self): self.screen.update(self.battery1, self.battery2) self.last_write = time() screen_timer = pyb.millis() while True: # Update battery data and screen every 10 seconds if pyb.elapsed_millis(screen_timer) > 10000: screen_timer = self.update() self.log_test() gc.collect() self.CMD.Poll() # TODO - check for command interface # Function to update battery data and screen def update(self): self.battery1.update() self.battery2.update() self.screen.update(self.battery1, self.battery2) screen_timer = pyb.millis() return screen_timer # Function to check if log is to be written # and if so write log and tidy files def log_test(self): current_time = time() if localtime(current_time)[4] % 15 == 0 and localtime(current_time - self.last_write)[4] > 5: # write log # get current filenames # note:adjust time by 5 minutes to ensure midnight appears on previous days log fn1, fn2 = self.filename(current_time - 300) self.check_files(fn1, fn2) self.write_log(fn1, self.battery1.log(current_time)) self.write_log(fn2, self.battery2.log(current_time)) self.last_write = current_time # TODO: remove debug sentence print('written to {}'.format(fn1)) # Static function to determine filenames on the basis of current time @staticmethod def filename(ctime): tt = localtime(ctime) fn1 = "/fram/Bat1-{0}-{1}-{2}".format(tt[2], tt[1], tt[0]) fn2 = "/fram/Bat2-{0}-{1}-{2}".format(tt[2], tt[1], tt[0]) return fn1, fn2 # Static function to write data to file @staticmethod def write_log(fn, data): with open(fn, 'a')as f: f.write(data) sync() # Static function to move old files out of fram and into logs folder of SD drive @staticmethod def check_files(fn1, fn2): ld = listdir('/fram') if len(ld) > 2: for f in ld: #ignore config file if f !='config': fullname = '/fram/' + f if fullname != fn1 and fullname != fn2: # file not current so move cp(fullname, '/sd/logs/') remove(fullname) sync() # Static function to mount fram drive at startup @staticmethod def mount_fram(): i2c = pyb.I2C(1, pyb.I2C.MASTER) f = FRAM(i2c) try: pyb.mount(None, '/fram') except: pass pyb.mount(f, '/fram') # Function to setup Fram and read config file values for calibration def config(self): with open('/fram/config', 'r') as f: Aoff1 = f.readline() Aoff2 = f.readline() return float(Aoff1), float(Aoff2) def write_config(self, Aoff1, Aoff2): with open('/fram/config', 'w') as f: f.write("{0}\r\n".format(Aoff1)) f.write("{0}\r\n".format(Aoff2)) sync()
for i in range(1000): attempt += 1 # load houses object in a list houses = [] for house in houseslist: # clean up data temp = house.replace(' ', '').split(',') temp = [float(i) for i in temp] houses.append(House((temp[0], temp[1]), temp[2])) # load batteries in a dict with index as key and object as value batteries = {} for i in range(len(batterieslist)): battery = batterieslist[i] batteries[i] = Battery((battery[0], battery[1]), battery[2], i) # calculate distances to all batteries from houses for house in houses: house.calc_distances(batteries) # calculate all distances to houses from batteries for battery in batteries: batteries[battery].calculate_distances(houses) # batteries, houses, houses_left = connect_houses(batteries, houses) batteries, houses, houses_left = connect_houses(batteries, houses) if len(houses_left) > 0: continue # get results in json format
def test_set_battery_from_vehicle(self): # check number zero the limit battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,0,0) battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(NEGATIVE_NUMBER,0,0) # check number NEGATIVE number one the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,NEGATIVE_NUMBER,0) # check number NEGATIVE number two the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,0,NEGATIVE_NUMBER) # check number NEGATIVE number three the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(POSITIVE_NUMBER,0,0) # check number POSITIVE number one the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, POSITIVE_NUMBER) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,0,POSITIVE_NUMBER) # check number POSITIVE number two the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, POSITIVE_NUMBER) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,POSITIVE_NUMBER,0) # check number POSITIVE number three the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, POSITIVE_NUMBER) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(CHAR_NUMBER,0,0) # check number char number number one the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, int(CHAR_NUMBER)) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,0,CHAR_NUMBER) # check number char number number two the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, int(CHAR_NUMBER)) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,CHAR_NUMBER,0) # check number char number number three the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, int(CHAR_NUMBER)) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(CHARACTER,0,0) # check number char number one the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,CHARACTER,0) # check number char number two the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0) battery_test = Battery(bet(0,0,0)) battery_test_copy = bet(0,0,CHARACTER) # check number char number three the limit battery_test.set_battery_from_vehicle(battery_test_copy) self.assertEqual(battery_test.volt, 0) self.assertEqual(battery_test.level, 0) self.assertEqual(battery_test.current, 0)