Exemplo n.º 1
0
    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²
Exemplo n.º 2
0
 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)
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
 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, 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()
Exemplo n.º 6
0
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
Exemplo n.º 7
0
    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()
Exemplo n.º 8
0
 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__()
Exemplo n.º 9
0
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, "",
                ""))
Exemplo n.º 10
0
    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"])
Exemplo n.º 11
0
 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()
Exemplo n.º 12
0
    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()
Exemplo n.º 13
0
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
Exemplo n.º 14
0
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))
Exemplo n.º 15
0
    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()
Exemplo n.º 16
0
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')
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
Exemplo n.º 18
0
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:
Exemplo n.º 19
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()
Exemplo n.º 20
0
from flask import Flask, jsonify
from datetime import datetime
from Actions import Actions
from TouchSensor import Button
from Battery import Battery

# Initialize movement speed
speed = 100

# Start Touch Sensor thread
button = Button(speed)

# Start Battery thread
battery = Battery(speed)

# Declare movement
actions = Actions(speed)

# Get current time HH:MM:SS
now = datetime.now()
time = str(now.strftime("%H:%M:%S"))

print(time + "\tLaunching program\n")

app = Flask (__name__)

# Move vehicle in the given direction
@app.route('/GET/Ev3/F1/movement/<action>', methods = ['GET'])
def movement(action):

    # Get current time HH:MM:SS
Exemplo n.º 21
0
 def __init__(self, make, model, year):
     super().__init__(make, model, year)
     self.battery = Battery(85)
Exemplo n.º 22
0
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"])
Exemplo n.º 23
0
 def __init__(self, speed, marka="Tesla", condey=True):
     super().__init__(marka, speed, condey)
     #с помощью мы получаем доступ к атрибутам класса родителя
     self.battery = Battery(120, 10)
Exemplo n.º 24
0
 def __init__(self, make, model, year):
     """ Initialize Attributes of the parent class. """
     super(ElectricCar, self).__init__(make, model, year)
     self.battery = Battery()
Exemplo n.º 25
0
                ag.max_qty = int(agent["max_qty"])

            if "target_qty" in agent:
                ag.target_qty = int(agent["target_qty"])

            if "power_when_on" in agent:
                ag.power_when_on = int(agent["power_when_on"])

            if "end_before" in agent:
                ag.endsBefore(int(agent["end_before"]))

            if "start_after" in agent:
                ag.startAfter(int(agent["start_after"]))

        elif agent_type == "battery":
            ag = Battery(id_number, range(0, 96), port_number, simulation=True)

            if "max_capacity" in agent:
                ag.max_capacity = int(agent["max_capacity"])

            if "charge" in agent:
                ag.charge = int(agent["charge"])

            if "max_power" in agent:
                ag.setMaxPower(int(agent["max_power"]))
        else:
            raise NameError("Impossibile creare un agente per {}".format(
                str(agent["type"])))

        if ag != None:
            agents.append(ag)
Exemplo n.º 26
0
# 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
Exemplo n.º 27
0
    try:
        # Create client socket
        client = socket.socket()

        # Connect to server
        client.connect(('192.168.1.68', 4200))

        message = client.recv(1024).decode()
        print("Server message: " + message)

        # Start Ev3 screen
        display = RobotDisplay('maker')
        display.startScreen()

        # Starting battery thread
        battery = Battery(client, display)

        # Starting button thread
        button = Button(client, display)

        # Declare movement
        action = Actions()

        print("Start main thread\n")

        while True:
            action.movement(client, display)

    # Server is not connected
    except ConnectionRefusedError:
        # Declare movement
Exemplo n.º 28
0
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
Exemplo n.º 29
0
# 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: