def get_batteries(self): """ Retrieve batteries from csv and create battery objects. """ if self.advanced == True: random_batteries = get_random_batteries(self.district) labels, clusters = get_clusters(self.district, random_batteries) clusters = clusters.tolist() for battery_id, battery in enumerate(random_batteries, 1): cluster = random.choice(clusters) clusters.remove(cluster) x = cluster[0] y = cluster[1] capacity = battery[1]["capacity"] cost = battery[1]["price"] b = Battery(battery_id, x, y, capacity, cost) self.batteries.append(b) else: f = open(f'data/district{self.district_nr}_batteries.csv') batteries_data = csv.reader(f) next(batteries_data) for battery_id, row in enumerate(batteries_data, 1): x, y = eval(row[0])[0], eval(row[0])[1] capacity = eval(row[1]) battery = Battery(battery_id, x, y, capacity) self.batteries.append(battery)
def check_events(color, events, units, screen, flags, cprof): """ watch keyboard/mouse for events When close window button is pressed, exit the game. Other functionality may come later. """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.unicode == "q": color = "blue" if event.unicode == "e": color = "green" if event.unicode == "z": if color == "blue": units.append( Company(screen, 0, *pygame.mouse.get_pos(), 2, 2, color, flags, 500)) if color == "green": units.append( Company(screen, 0, *pygame.mouse.get_pos(), 2, 2, color, flags, 500, False)) if event.unicode == "x": if color == "blue": units.append( Battery(screen, 0, *pygame.mouse.get_pos(), 3, color, flags, 12)) if color == "green": units.append( Battery(screen, 0, *pygame.mouse.get_pos(), 3, color, flags, 12, False)) if event.unicode == "c": if color == "blue": units.append( Squadron(screen, 0, *pygame.mouse.get_pos(), 2, 2, color, flags, 120)) if color == "green": units.append( Squadron(screen, 0, *pygame.mouse.get_pos(), 2, 2, color, flags, 120, False)) if event.unicode == "f": units = [] flags = [] if event.unicode == "g": cprof.print_stats('tottime') for event in events: units = event.check(units) if event.triggered: events.remove(event) return color, units
def load_batteries(self, filename): """" Load batteries from filename. returns a dictionary of "id" : Battery objects """ battery_data = [] with open(filename, "r") as file: for line in file: line = line.strip('\n') battery_data.append(line.split(',')) batteries = {} id_nr = 0 for battery in battery_data: id = id_nr battery.insert(0, id) x = int(battery[1]) y = int(battery[2]) capacity = float(battery[3]) id_nr += 1 #initialize a house object and put it in a dict with id as key battery = Battery(id, x, y, capacity) batteries[id] = battery return batteries
def test_charge(self): bat = Battery(3.0, cells=4) # Can't charge a battery if voltage under battery's current voltage bat.charge(volts=14.0, amps=3, seconds=60) self.assertEqual(bat.charge_state, 1.5) self.assertEqual(bat.voltage, 14.4) # Can charge battery if voltage over battery's current voltage bat.charge(volts=16.6, amps=3, seconds=60) # Basic properties haven't changed: self.assertEqual(bat.capacity, 3.0) self.assertEqual(bat.cells, 4) self.assertEqual(bat.minimum_voltage, 3.0) self.assertEqual(bat.maximum_voltage, 4.2) # Charge state has changed self.assertEqual(bat.charge_state, 1.55) # Voltage has risen slightly self.assertGreater(bat.voltage, 14.4) # At this stage we can push a battery beyond the charge voltage if we # give a long enough duration, but we can't go over the battery's # capacity. bat.charge(volts=16.6, amps=3, seconds=3600) # Should be well over # But capacity is limited to self.assertEqual(bat.charge_state, bat.capacity) # And voltage is maxed out self.assertEqual(bat.voltage, 16.8)
def __init__(self, make, model, year, odometer): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer = odometer self.battery = Battery(0.5)
def load_batteries(self): """ Parses through text file and saves batteries as battery.Battery objects. Returns instances in dict to __init__ """ with open(batt_file) as batteries_text: # read text file per line data_batteries = batteries_text.readlines() # delete headers data_batteries.pop(0) batteries = {} # Library color list toevoegen COLOUR_LIST = [ "m", "g", "c", "y", "b", "grey", "maroon", "yellow", "orange", "fuchsia", "lime", "peru" ] # for every batterie isolate coordinates and capacity for id, battery in enumerate(data_batteries): coordinates = battery.split("\t", 1)[0] cap = battery.split("\t", 1)[1].strip() x = re.sub("\D", "", coordinates.split(",", 1)[0]) y = re.sub("\D", "", coordinates.split(",", 1)[1]) colour = COLOUR_LIST[id] batteries[id] = Battery(cap, x, y, colour) # return dict to INIT return batteries
def __init__(self, uss, comm, q): """ コンストラクタです。 """ self.logger = logging.getLogger(__name__) self.pipe_uss = uss self.pipe_comm = comm self.uss = [] self.req = {} self.q = q sleep(1) # 先に起動すると困る PeriodicTask.__init__(self) self.cmds = [] self.recv() self.batt = Battery(self.req["btA"], self.req["btB"]) self.movement = Run() self.ms = [] for pin in IO.PIN: self.ms.append(IO(pin, IO.IN, True)) self.ms = tuple(self.ms)
def load_batteries(self): global diax global diay # reading the battery file batteryfile = open("data/wijk1_batterijen.txt", "r") list_batteries = [] # making battery instances and adding to list counter = 0 for line in batteryfile: if counter != 0: check = line.split() x_value = check[0].strip('[').strip(',') y_value = check[1].strip(']') capacity = check[2] list_batteries.append(Battery(x_value, y_value, capacity)) counter = 1 battery_change = list_batteries[0] battery_change.set_xval(diay) battery_change.set_yval(diax) dia += 1 return list_batteries
def load_batteries(): """ Parses through text file and saves batteries as battery.Battery objects. Returns instances in dict to __init__ """ # find specific directory with the data subpath = f"Huizen&Batterijen\wijk{INPUT}_batterijen.txt" path = str(Path.cwd()).replace("scripts", subpath) with open(path) as batteries_text: # read text file per line data_batteries = batteries_text.readlines() # delete headers data_batteries.pop(0) batteries = {} # Library color list toevoegen COLOUR_LIST = ["m", "g", "c", "y", "b", "grey", "maroon", "yellow", "orange", "fuchsia", "lime", "peru"] # for every batterie isolate coordinates and capacity for id, battery in enumerate(data_batteries): coordinates = battery.split("\t", 1)[0] cap = battery.split("\t", 1)[1].strip() x = re.sub("\D", "", coordinates.split(",", 1)[0]) y = re.sub("\D", "", coordinates.split(",", 1)[1]) colour = COLOUR_LIST[id] batteries[id] = Battery(cap, x, y, colour) # return dict to INIT return batteries
def load_batteries(self, filename): ''' Load batteries file to python ''' with open(filename, "r") as f: content = f.readlines() innitial_batteries = [] self.batteries = [] # loop through and replace all the "bad" characters with nothing. After that split values for i in content: i = i.replace("\t", " ") i = i.replace(",", "") i = i.replace("[", "") i = i.replace("]", "") i = i.strip('\n') innitial_batteries.append(i.split()) # load batteries into list (id, x, y, max_amp) for i, battery in enumerate(innitial_batteries[1:]): self.batteries.append( Battery(i, int(battery[0]), int(battery[1]), float(battery[2]))) return self.batteries
def load_batteries(self): cwd = os.getcwd() cwd = os.path.dirname(cwd) path = os.path.join(*[cwd, "data", f"{INPUT_BATTERIES}"]) sys.path.append(path) with open(path) as batteries_text: # read text file per line data_batteries = batteries_text.readlines() # delete headers data_batteries.pop(0) batteries = {} # for every batterie isolate coordinates and capacity for id, battery in enumerate(data_batteries): coordinates = battery.split("\t", 1)[0] cap = battery.split("\t", 1)[1] cap = cap.strip() x = coordinates.split(",", 1)[0] y = coordinates.split(",", 1)[1] x = re.sub("\D", "", x) y = re.sub("\D", "", y) # colour = self.colour_list[id] colour = COLOUR_LIST[id] batteries[id] = Battery(cap, x, y, colour) # return dict to INIT return batteries
def __init__(self, make, model, year): """ Initialize attributes of the parent class. Then initialize attributes specific to an electric car. """ super().__init__(make, model, year) self.battery = Battery()
def runSimulator(over, under): battery = Battery() priceData = loadMarketData() matrix = convertTo2D(priceData) day_mean, mean, day_median, median = calculatePriceStats(matrix) for data in priceData: interval = data[0] - 1 bid = 0 if (interval < 288): bid = median[interval] if (bid * (1 + over)) > day_median: action = (0, 1, (bid * (1 + over))) battery.step(action) elif (bid * under) < day_median: action = (1, 0, (bid * under)) battery.step(action) elif bid == 0: action = (0, 0, bid) battery.step(action) else: action = (0, 0, bid) battery.step(action) revenue = battery.state()[2] print("Run Finished: Over bid:" + str((over) * 100) + " Under Bid: " + str(under * 100) + " Total Revenue: " + str(revenue)) battery.reset() return revenue
def __init__(self): super(Pod, self).__init__() capsule = self.add('capsule', PassengerCapsule(), promotes=['n_rows', 'row_len']) tube = self.add('tube', TubeStructural(), promotes=['tube_P', 'tube_T', 'tube_r', 'tube_area', 'fill_area']) inlet = self.add('inlet', InletGeom(), promotes=['hub_to_tip', 'tube_area', 'bypass_area', 'cross_section', 'area_frontal']) battery = self.add('battery', Battery(), promotes=['time_mission', 'energy', 'cross_section']) aero = self.add('aero', Aero(), promotes=['rho', 'gross_thrust', 'net_force', 'coef_drag', 'velocity_capsule', 'area_frontal'])
def __init__(self, make, model, year): """ 初始化父类的属性 经过测试:父类有多少个参数, super这里就必须传入多少个 默认参数不用 """ super().__init__(make, model, year) self.battery = Battery() # 将实例用作属性
def innitialize(self): self.batteries = [] # innitialize batteries for i, house in enumerate(self.houses): battery = Battery(i, house.x, house.y, 1508) battery.costs = 5000 # Later via Battery()? self.batteries.append(battery)
def __init__(self, make, model, year): super().__init__(make, model, year) # Python 2.7 # super(ElectricCar, self).__init__(make, model, year) # 将实例用作属性 self.battery_size = 70 # 将实例用作属性:提取类 self.battery = Battery()
def __init__(self, duration=24, day=1, loadRow=0): self.PV = PV() self.Battery = Battery() self.totalPrices = totalPrices self.totalPvGen = totalPvGen self.totalLoad = totalLoad self.totalAverageLoad = totalLoad.mean(axis=1) self.__timeDuration = duration self.__day = day self.loadRow = loadRow
def dictToBattery(client): eMin = client["eMin"] eMax = client["eMax"] pMin = client["pMin"] pMax = client["pMax"] tEnd = client["tEnd"] e = client["e"] p = client["p"] CID = client["CID"] return Battery(eMin, eMax, pMin, pMax, tEnd, e, p, CID)
def configure(self): #Add Components capsule = self.add('capsule', PassengerCapsule()) tube = self.add('tube', TubeStructural()) inlet = self.add('inlet', InletGeom()) battery = self.add('battery', Battery()) aero = self.add('aero', Aero()) #Boundary Input Connections #Pod -> Capsule self.connect('n_rows', 'capsule.n_rows') self.connect('length_row', 'capsule.length_row') #Pod->Tube self.connect('radius_tube_inner', 'tube.radius_inner') self.connect('Ps_tube', 'tube.Ps_tube') #Pod->Inlet self.connect('area_inlet_in', 'inlet.area_in') self.connect('area_inlet_out', 'inlet.area_out') self.connect('hub_to_tip', 'inlet.hub_to_tip') #Pod -> Battery self.connect('time_mission', 'battery.time_mission') self.connect('energy', 'battery.energy') #Pod -> Aero self.connect('coef_drag', 'aero.coef_drag') self.connect('rho_air', 'aero.rho') self.connect('speed_max', 'aero.velocity_capsule') self.connect('F_net', 'aero.gross_thrust') #Inter Component Connections #Capsule -> Inlet self.connect('capsule.area_cross_section', 'inlet.area_passenger_capsule') #Capsule -> Battery self.connect('capsule.area_cross_section', 'battery.area_cross_section') #Inlet -> Aero self.connect('inlet.area_frontal', 'aero.area_capsule') #Boundary Output Connections #Capsule -> Pod self.connect('capsule.area_cross_section', 'area_cross_section') #Tube->Pod self.connect('tube.radius_outer', 'radius_tube_outer') #Inlet->Pod self.connect('inlet.radius_back_outer', 'radius_inlet_back_outer') self.connect('inlet.area_bypass', 'area_compressor_bypass') #Aero -> Pod self.connect( 'aero.net_force', 'net_force') #not currently used, eventually passed to mission #Declare Solver Workflow self.driver.workflow.add( ['capsule', 'tube', 'inlet', 'battery', 'aero'])
def initPopulationGenerator(populationNumbers, timeIntervals): workerBattery = Battery() for i in range(populationNumbers): matrix = generateMatrix(timeIntervals) randomizeInputMatrix(matrix, battery) simulate(matrix, battery) spawn_queue.put([matrix[6, -1], 0, matrix.copy()])
def init_assets(): battery1 = Battery(soc=30, simulationSeconds=60, state=Battery.State.IDLE) battery1.setName('Battery 1') battery1.set_state(Battery.State.DISCHARGING) sm1 = SmartMeter('Electricity') light1 = SmartLight('Living Room Main Light') home_assets.append(battery1) home_assets.append(sm1) home_assets.append(light1) for asset in home_assets: asset.start()
def __init__(self, width=1920, height=1080): # Create Screen with the provided resolution self.width = width #1920 self.height = height #1080 self.screen = Screen(width, height) self.logo = self.screen.load_image("logo.png") #self.logo = self.screen.scale(self.logo, 500,100) #self.screen.set_fps(10) # NOTE: Remove comment on next line to add Full screen #self.screen.set_full_screen() size = self.screen.get_size() self.border = 10 b = self.border # Just to make the next line more readable self.battery = Battery(self.screen, x=20, y=self.height - 355, width=140, height=300) # Creates a wyndow with a margin to make it pritty <3 self.window = Window(self.screen, b + 180, b + 130, size[0] - (b * 2 + 270), size[1] - (b * 2 + 180)) self.window.set_all_colors((100, 100, 100)) self.window.set_border_color((200, 200, 200)) self.window.set_border_width(10) self.chart_og = Chart() self.chart_og.set_width(8) self.chart_og.set_color((255, 150, 0)) self.chart_og.add_point([1, 0]) self.chart_og.add_point([2, 0]) self.window.add_chart(self.chart_og) self.chart_optimised = Chart() self.chart_optimised.set_width(8) self.chart_optimised.set_color((0, 150, 255)) self.chart_optimised.add_point([1, 0]) self.chart_optimised.add_point([2, 0]) self.window.add_chart(self.chart_optimised) # Next we add a function that converts the X values to # something the window class can work with, simple numbers # the window class does not know how to handle dates # so they need to be converted to intigers. These X values # are still used as labels in the x axis so format them # wisely. # NOTE: Remove comment on the fallowing line to add convertion function #self.chart.set_conv_funct(self.convert) self.data = Value(self.screen, 22, 150)
def test_basic_properties(self): bat = Battery(3.0, cells=4) # Properties set in init self.assertEqual(bat.capacity, 3.0) self.assertEqual(bat.cells, 4) self.assertEqual(bat.charge_state, 1.5) # half of capacity default # Class properties self.assertEqual(bat.minimum_voltage, 3.0) self.assertEqual(bat.maximum_voltage, 4.2) # Calculated properties # Half charge state, middle of voltage range self.assertEqual(bat.voltage, 14.4) self.assertEqual(repr(bat), "3.0Ah 4S battery with 1.500Ah charge")
def __init__(self, site_id=1, period_id=1, battery_id=1): """ Resets the state of the environment and returns an initial observation. # Returns observation (object): The initial observation of the space. Initial reward is assumed to be 0. """ self.actual_previous_pv = [] self.actual_previous_load = [] self.battery_charge = [] self.battery_energy = [] self.grid_energy = [] self.money_saved = [] self.score = [] self.current_timestep_idx = 0 simulation_dir = (Path(__file__) / os.pardir / os.pardir).resolve() data_dir = simulation_dir / 'data' # load available metadata to determine the runs metadata_path = data_dir / 'metadata.csv' metadata = pd.read_csv(metadata_path, index_col=0) self.site_id = site_id self.period_id = period_id self.battery_id = battery_id site_data_path = data_dir / "submit" / f"{self.site_id}.csv" site_data = pd.read_csv(site_data_path, parse_dates=['timestamp'], index_col='timestamp') parameters = metadata.loc[self.site_id] battery = Battery( capacity=parameters[f"Battery_{self.battery_id}_Capacity"] * 1000, charging_power_limit=parameters[f"Battery_{self.battery_id}_Power"] * 1000, discharging_power_limit=-parameters[ f"Battery_{self.battery_id}_Power"] * 1000, charging_efficiency=parameters[ f"Battery_{self.battery_id}_Charge_Efficiency"], discharging_efficiency=parameters[ f"Battery_{self.battery_id}_Discharge_Efficiency"]) # n_periods = site_data.period_id.nunique() # keep as comment for now, might be useful later g_df = site_data[site_data.period_id == self.period_id] self.simulation = Simulation(g_df, battery, self.site_id) self.battery_controller = BatteryContoller()
def initialization(init_gy521=True, init_ds18=True, init_bat=True, init_wifi=True): """ Initialize GY521 module, battery ADC pin and wifi NOTE: VPP pin must be turned on in order to initialize the GY521 module """ if init_gy521: from gy521 import GY521 # Initialize the GY521 module print('Initializing GY521 module') try: gy521_sensor = GY521(GY521_SDA, GY521_SCL) except Exception as e: print(e) gy521_sensor = None else: gy521_sensor = None if init_ds18: from tempsensor import Ds18Sensors, SingleTempSensor print('Initializing DS18B20 sensor') try: ow = Ds18Sensors(OW_PIN) romcode_string = ow.get_device_list()[0].get('value') ds18_sensor = SingleTempSensor(ow, romcode_string) except Exception as e: print(e) ds18_sensor = None else: ds18_sensor = None if init_bat: from battery import Battery # Initialize the battery power management print('Initializing power management') lipo = Battery(BAT_ADC_PIN) else: lipo = None if init_wifi: from wifi import WiFi # Initialize Wifi print('Initializing WiFi') wlan = WiFi() else: wlan = None return gy521_sensor, ds18_sensor, lipo, wlan
def system(data, horizon): pv_model = PV(area=4) HP_model = HP(efficiency=0.9) battery = Battery(charge_efficiency=0.95, bat_capacity=15, discharging_rate=1.5, charging_rate=2,horizon=optimization_horizon) ED_model = ED() TD_model = TD() pv = pv_model.get_PV_data('data-openideas.csv', 'solar', horizon, data) HP = HP_model.get_td_data('data-openideas.csv', 'out_QradD', 'out_QradN', 35, horizon, data) ed = ED_model.get_ED_data('linear data.csv', horizon, data) battery.do_action(data, compute_energy_cost=False) TD = TD_model.get_TD_data('data-openideas.csv', 'out_QradD', 'out_QradN', horizon, data) return data
def createNextGeneration(spawns, populationNumber): workerBattery = Battery() mutate_rate = 0.01 mutate_frequency = 0.5 for i in range(0, populationNumber): idx_a = random.randint(0, (len(spawns) - 1)) idx_b = random.randint(0, (len(spawns) - 1)) parent_a = spawns[idx_a][2] parent_b = spawns[idx_b][2] new_spawn = mate(parent_a, parent_b) mu = random.random() if (mu < mutate_frequency): mutate(new_spawn, mutate_rate) simulate(new_spawn, battery) spawn_queue.put([new_spawn[6, -1], 0, new_spawn.copy()])
def cli(arg, save, path, every, details, exclude, header, style, text, graph, mark) -> None: """ ** Displays Disk Usage in the terminal, graphically. ** Customize visuals by setting colors and attributes. COLORS: light_red, red, dark_red, dark_blue, blue, cyan, yellow, green, pink, white, black, purple, neon, grey, beige, orange, magenta, peach. ATTRIBUTES: bold, dim, underlined, blink, reverse. """ options: Options = Options() if mark: options.symbol = mark if header: options.header_color = header if text: options.text_color = text if graph: options.graph_color = graph if style: options.header_style = style exclude_list = list(exclude) if arg == 'battery': try: battery = Battery() battery.print_charts() except: print('Battery not found!') elif arg == 'cpu': cpus = CPUFreq() cpus.display_separately() else: # renderer = None renderer = DiskUsage( path=path, exclude=exclude_list, details=details, every=every ) if save: renderer.save_data(save) renderer.print_charts(options)
def load_batteries(self): # reading the battery file batteryfile = open("data/wijk2_batterijen.txt", "r") list_batteries = [] # making battery instances and adding to list counter = 0 for line in batteryfile: if counter != 0: check = line.split() x_value = check[0].strip('[').strip(',') y_value = check[1].strip(']') capacity = check[2] list_batteries.append(Battery(x_value, y_value, capacity)) counter = 1 return list_batteries