Example #1
0
    def __init__(self):
        # Dictionary containing a street object for each street name (key)
        self.streets = dict()
        self.corresponding_intersections = dict()
        self.adjacent_street_names = dict()

        street_config_root = XmlParser.parse("streetconfig.xml").getroot()
        xml_street_list = street_config_root[0]
        for xml_street in xml_street_list:
            street = Street()
            street.street_name = xml_street.attrib['name']
            street.traffic_light_number = int(
                xml_street.attrib['trafficLightNumber'])
            for xml_street_child in xml_street.iter('RoadComponent'):
                start_point = MapPoint(int(xml_street_child[0].attrib['x']),
                                       int(xml_street_child[0].attrib['y']))
                end_point = MapPoint(int(xml_street_child[1].attrib['x']),
                                     int(xml_street_child[1].attrib['y']))
                road_component = RoadComponent(
                    heading=MapHeading[xml_street_child.attrib['heading']],
                    start=start_point,
                    end=end_point)
                street.road_component_list.append(road_component)
            # Insert adjacent streets
            self.adjacent_street_names[street.street_name] = list()
            for xml_adjacent_street in xml_street.iter('AdjacentStreet'):
                self.adjacent_street_names[street.street_name].append(
                    xml_adjacent_street.attrib['streetName'])
            # Append street to dictionary
            self.streets[street.street_name] = street

        self.build_intersections()
Example #2
0
    def test_f(self):
        '''
        '''
        cases = {}
        # Each case: t, N, Dmax, Smax, c_h, adaptive, slope, placement_optimistic, bcharge, pt = result
        # Case 1a: consumer first, thus generator last, who creates negative 1
        #          consumer always adds 2.75
        cases[(26, 10, 3, 1, 1.2, True, .5, True, 0, .5)] = (round(5 * 2.787 + 5 * -1, 4), -1)
        # Case 1b: Now price is adapted, so they buy 2.887
        cases[(26, 10, 3, 1, 1.2, True, .5, True, 0, .3)] = (round(5 * 2.887 + 5 * -1, 4), -1)
        # Case 1c: Now try pessimistic
        cases[(26, 10, 3, 1, 1.2, True, .5, False, 0, .3)] = (round(5 * 2.887 + 5 * -1, 4), -5)
        # Case 2: try higher N
        cases[(26, 30, 3, 1, 1.2, True, .5, True, 0, .3)] = (round(15 * 2.887 + 15 * -1, 4), -1)
        # Case 3: test non-adaptive case. They buy 2.924
        cases[(26, 10, 3, 1, 1.2, False, .5, True, 0, .3)] = (round(5 * 2.924 + 5 * -1, 4), -1)
        # Case 4: different time step: let house batteries charge, no PV
        cases[(38, 10, 3, 1, 1.2, True, .5, True, 0, .3)] = (round(5 * 3.887, 4), 0)
        # Case 5a: our battery charges 0.6
        cases[(26, 10, 3, 1, 1.2, True, .5, True, 0.6, .3)] = \
                        (round(.6 + (5 * 2.887  + 5 * -1), 4), -1 + 0.6)
        # Case 5b: and discharge
        cases[(26, 10, 3, 1, 1.2, True, .5, True, -0.6, .3)] = \
                        (round(-.6 + (5 * 2.887  + 5 * -1), 4), -1 - 0.6)

        for c in cases.keys():
            T = c[0]
            s = Street(T=T+1, N=c[1], C=None, Dmax=c[2], Smax=c[3], pmax=.452, pmin=.074, c_h=c[4],
                       adaptive=c[5], slope=c[6], placement_optimistic=c[7])
            #s.draw(T, c[8], c[9])
            fp, fm = s.f(T, c[8], c[9])
            self.assertEqual((round(fp, 4), round(fm, 4)), cases[c])
Example #3
0
def add_street(street_name, nodes):
    """
    add street to database and process
    :param street_name: str
    :param nodes: [Point]
    """
    streets.append(Street(street_name, nodes))
Example #4
0
 def parsing (self,value):
     if 'vertices' in value:
         for i in value['vertices']:
             tmpVertex = Vertex()
             tmpVertex.parsing(i)
             self.verticesList.append(tmpVertex)
     if 'streets' in value:
         for i in value['streets']:
             tmpStreet = Street()
             tmpStreet.parsing(i)
             self.streetsList.append(tmpStreet)
     if 'bridges' in value:
         for i in value['bridges']:
             tmpBridge = Bridge()
             tmpBridge.parsing(i)
             self.bridgesList.append(tmpBridge)
     if 'weight' in value:
         self.weight.parsing(value['weight'])
Example #5
0
 def parsing(self, value):
     if 'vertices' in value:
         for i in value['vertices']:
             tmpVertex = Vertex()
             tmpVertex.parsing(i)
             self.verticesList.append(tmpVertex)
     if 'streets' in value:
         for i in value['streets']:
             tmpStreet = Street()
             tmpStreet.parsing(i)
             self.streetsList.append(tmpStreet)
     if 'bridges' in value:
         for i in value['bridges']:
             tmpBridge = Bridge()
             tmpBridge.parsing(i)
             self.bridgesList.append(tmpBridge)
     if 'weight' in value:
         self.weight.parsing(value['weight'])
def base_add_street(street_name, coordinates):
    # create the street
    new_street = Street(street_name, coordinates)

    # check for any intersections with the existing streets
    for street in streets.values():
        intersections = street.find_intersections(new_street)

        # add the intersections to the graph
        for intersection in intersections:
            graph.add_vertex(intersection)

    # add the street to the database (dictionary)
    streets[street_name] = new_street
Example #7
0
    def new_street(self,
                   from_: str,
                   to: str,
                   distance: float,
                   max_speed: Optional[float] = None) -> None:
        """Cria um novo trecho de rua (:class:`Street`) de um nó
        para outro

        :param from\_: nó inicial
        :param to: nó objetivo
        :param distance: distância do trecho
        :param max_speed: velocidade máxima do trecho,
            se for diferente da velocidade máxima geral
        """
        speed = max_speed or self._max_speed
        self.make_edge(from_, to, Street(distance, speed))
    def __init__(self, *args, **kwargs):
        super(ApartmentBlock, self).__init__(width=ApartmentBlock.WIDTH,
                                             *args,
                                             **kwargs)

        builds = []
        #######################################################################
        # build entire apt block from spans:
        # "concrete" structure (smooth stone)
        builds.append(
            BuildingBlock(ApartmentBlock.APT_BLOCK_SPAN[0],
                          block.STONE,
                          ApartmentBlock.APT_BLOCK_SPAN[1],
                          description="Apt block stone super structure"))

        # 17 apt wall sections per floor can be done using 5 wood spans & 6 interior spaces
        # build wood plank spans
        for key, span in ApartmentBlock.WOOD_PLANK_SPANS.items():
            for pos in ApartmentBlock.WOOD_PLANK_POS[key]:
                # ground floor
                builds.append(
                    BuildingBlock(span[0] + pos,
                                  block.WOOD_PLANKS,
                                  span[1] + pos,
                                  description="%s wood span ground floor" %
                                  (key)))

                # 2nd floor
                builds.append(
                    BuildingBlock(span[0] + pos + Vec3(0, 4, 0),
                                  block.WOOD_PLANKS,
                                  span[1] + pos + Vec3(0, 4, 0),
                                  description="%s wood span 2nd floor" %
                                  (key)))
        # clear apt interiors (this will leave concrete floors & ceilings)
        for pos in ApartmentBlock.APT_INTERIOR_POS:
            # ground floor
            builds.append(
                BuildingBlock(ApartmentBlock.APT_INTERIOR_SPAN[0] + pos,
                              block.AIR,
                              ApartmentBlock.APT_INTERIOR_SPAN[1] + pos,
                              description="Clear apt interior ground floor"))

            # 2nd floor
            builds.append(
                BuildingBlock(
                    ApartmentBlock.APT_INTERIOR_SPAN[0] + pos + Vec3(0, 4, 0),
                    block.AIR,
                    ApartmentBlock.APT_INTERIOR_SPAN[1] + pos + Vec3(0, 4, 0),
                    description="Clear apt interior 2nd floor"))

        # add torch to SW croner of block to indicte when this section has completed buiding in game
        #builds.append(Torch(Vec3(-11,3,-3), block.TORCH.withData(Torch.WEST),
        #					description="section complete indicator"))

        self._add_section("Apt block super structure", builds)

        # doors & torches
        # TODO: debug this: East side apartments have doors "facing" east (built on east side of block)
        #					East side apts torches should face west, but applied on east face of containing block (west face of support block)
        # TODO: add doc strings to doors and torches on what the orientation means
        for pos in ApartmentBlock.APT_DOORS_POS["East"]:
            # ground floor
            builds.append(
                Door(Door.HINGE_RIGHT,
                     pos,
                     block.DOOR_WOOD.withData(Door.EAST),
                     description="Ground floor door east side"))
            builds.append(
                Torch(pos + Vec3(-1, 2, 0),
                      block.TORCH.withData(Torch.WEST),
                      description="Ground floor interior torch"))
            builds.append(
                Torch(pos + Vec3(1, 2, 0),
                      block.TORCH.withData(Torch.EAST),
                      description="Ground floor exterior torch"))
            # 2nd floor
            builds.append(
                Door(Door.HINGE_RIGHT,
                     pos + Vec3(0, 4, 0),
                     block.DOOR_WOOD.withData(Door.EAST),
                     description="2nd floor door east side"))
            builds.append(
                Torch(pos + Vec3(-1, 6, 0),
                      block.TORCH.withData(Torch.WEST),
                      description="2nd floor interior torch"))
            builds.append(
                Torch(pos + Vec3(1, 6, 0),
                      block.TORCH.withData(Torch.EAST),
                      description="2nd floor exterior torch"))

        for pos in ApartmentBlock.APT_DOORS_POS["West"]:
            # ground floor
            builds.append(
                Door(Door.HINGE_LEFT,
                     pos,
                     block.DOOR_WOOD.withData(Door.WEST),
                     description="Ground floor door west side"))
            builds.append(
                Torch(pos + Vec3(1, 2, 0),
                      block.TORCH.withData(Torch.EAST),
                      description="Ground floor interior torch"))
            builds.append(
                Torch(pos + Vec3(-1, 2, 0),
                      block.TORCH.withData(Torch.WEST),
                      description="Ground floor exterior torch"))
            # 2nd floor
            builds.append(
                Door(Door.HINGE_LEFT,
                     pos + Vec3(0, 4, 0),
                     block.DOOR_WOOD.withData(Door.WEST),
                     description="2nd floor door west side"))
            builds.append(
                Torch(pos + Vec3(1, 6, 0),
                      block.TORCH.withData(Torch.EAST),
                      description="2nd floor interior torch"))
            builds.append(
                Torch(pos + Vec3(-1, 6, 0),
                      block.TORCH.withData(Torch.WEST),
                      description="2nd floor exterior torch"))

        # windows
        for pos in ApartmentBlock.APT_WINS_POS:
            builds.append(
                BuildingBlock(pos,
                              block.GLASS_PANE,
                              description="ground floor window"))
            builds.append(
                BuildingBlock(pos + Vec3(0, 4, 0),
                              block.GLASS_PANE,
                              description="2nd floor window"))

        # add torch to SW croner of block to indicte when this section has completed buiding in game
        #builds.append(Torch(Vec3(-11,2,-3), block.TORCH.withData(Torch.WEST),
        #					description="section complete indicator"))

        self._add_section("Apt block fittings", builds)

        #######################################################################
        # Ground floor walkway & steps
        # stone walk way
        builds.extend(self._add_walkway(block.STONE, 0))
        # stone steps at end of each walkway
        # TODO: block data for stone brick stairs
        builds.append(
            Stair(ApartmentBlock.CORNER_POS['South East'] + Vec3(0, 0, 1),
                  Block(109).withData(Stair.NORTH),
                  ApartmentBlock.CORNER_POS['South East'] + Vec3(-1, 0, 1),
                  description="Ground floor steps"))
        builds.append(
            Stair(ApartmentBlock.CORNER_POS['South West'] + Vec3(1, 0, 1),
                  Block(109).withData(Stair.NORTH),
                  ApartmentBlock.CORNER_POS['South West'] + Vec3(0, 0, 1),
                  description="Ground floor steps"))

        self._add_section("Ground floor walkway", builds)

        #######################################################################
        # Support posts for 2nd floor walkway
        for pos in ApartmentBlock.CORNER_POS.values():
            builds.append(
                BuildingBlock(pos + Vec3(0, 1, 0),
                              block.FENCE,
                              pos + Vec3(0, 3, 0),
                              description="Corner post"))

        self._add_section("2nd floor support posts", builds)

        #######################################################################
        # 2nd floor walkway
        # wooden walk way around 2nd floor
        builds.extend(self._add_walkway(block.WOOD_PLANKS, 4))
        self._add_section("2nd floor wooden walkway", builds)

        #######################################################################
        # Stairs to 2nd floor
        for i in range(0, 5):
            # wooden steps to 2nd floor.
            builds.append(
                Stair(ApartmentBlock.CORNER_POS['South East'] +
                      Vec3(-8 + i, i, 1),
                      block.STAIRS_WOOD.withData(Stair.EAST),
                      description="Steps to upper floor"))
            # TODO: figure out block data for upside down stairs and use this instead of support block
            builds.append(
                BuildingBlock(ApartmentBlock.CORNER_POS['South East'] +
                              Vec3(-7 + i, i, 1),
                              block.WOOD_PLANKS,
                              description="stair support"))

        self._add_section("Stairs to 2nd floor", builds)

        #######################################################################
        if DO_2ND_FLOOR_RAILINGS:
            # 2nd floor walkway railings (should extend these out by 1 block all around so walkway is 2 blocks wide)
            # west side railings
            builds.append(
                BuildingBlock(
                    ApartmentBlock.CORNER_POS['North West'] + Vec3(0, 5, 0),
                    block.FENCE,
                    ApartmentBlock.CORNER_POS['South West'] + Vec3(0, 5, 0),
                    description="Balcony railings"))
            # close off west side railings on north end
            builds.append(
                BuildingBlock(ApartmentBlock.CORNER_POS['North West'] +
                              Vec3(1, 5, 0),
                              block.FENCE,
                              description="Balcony railings"))
            # east side railings
            builds.append(
                BuildingBlock(
                    ApartmentBlock.CORNER_POS['North East'] + Vec3(0, 5, 0),
                    block.FENCE,
                    ApartmentBlock.CORNER_POS['South East'] + Vec3(0, 5, 0),
                    description="Balcony railings"))
            # close off east side railings on north end
            builds.append(
                BuildingBlock(ApartmentBlock.CORNER_POS['North East'] +
                              Vec3(-1, 5, 0),
                              block.FENCE,
                              description="Balcony railings"))

            # south balcony railings
            builds.append(
                BuildingBlock(
                    ApartmentBlock.CORNER_POS['South East'] + Vec3(0, 5, 0),
                    block.FENCE,
                    ApartmentBlock.CORNER_POS['South East'] + Vec3(-5, 5, 0),
                    description="Balcony railings"))
            builds.append(
                BuildingBlock(
                    ApartmentBlock.CORNER_POS['South West'] + Vec3(0, 5, 0),
                    block.FENCE,
                    ApartmentBlock.CORNER_POS['South West'] + Vec3(6, 5, 0),
                    description="Balcony railings"))

            self._add_section("2nd floor railings", builds)

        #######################################################################
        # Add the streets between as subbuildings
        street_ew = Street(9, Building.WEST)
        street_ns = Street(8, Building.NORTH)

        builds.append(
            SubBuilding(street_ew, Building.SE_CORNER_POS + Vec3(0, 0, 1)))
        builds.append(
            SubBuilding(street_ew, Building.SE_CORNER_POS + Vec3(0, 0, -24)))
        builds.append(
            SubBuilding(street_ns, Building.SE_CORNER_POS + Vec3(-13, 0, 0)))

        self._add_section("Streets", builds)

        #######################################################################
        # Add the farm subbuildings
        farms = [Farm(Building.WEST), LargeFarm(Building.NORTH)]

        for pos in ApartmentBlock.WEST_FARMS_POS:
            builds.append(SubBuilding(farms[0], pos))

        self._add_section("West Farms", builds)

        for pos in ApartmentBlock.NORTH_FARMS_POS:
            builds.append(SubBuilding(farms[1], pos))

        self._add_section("North Double Farms", builds)

        #######################################################################
        self._set_orientation()
Example #9
0
def main(conf, log, seed):
    ws = [.05, .2, .5, 1, 2]
    battery_types = (NoBattery, OfflineBattery, BaseBattery,
                     HeuristicBattery, NonDeterministicOfflineBattery)
    #battery_types = (NoBattery, BaseBattery, HeuristicBattery,)

    T = 48  # this is given by the price data structure: half-hour intervals
    N = conf.getint('params', 'N')
    C = conf.getint('params', 'C')
    B = conf.getfloat('params', 'B')
    alpha = conf.getfloat('params', 'alpha')
    max_rate = conf.getfloat('params', 'max_rate')
    econ_slope = conf.getfloat('params', 'econ_slope')
    Dmax = conf.getfloat('params', 'Dmax')
    Smax = conf.getfloat('params', 'Smax')
    pmax = conf.getfloat('params', 'pmax')
    pmin = conf.getfloat('params', 'pmin')
    c_h = conf.getfloat('params', 'c_h')
    adaptive = conf.getboolean('params', 'adaptive')
    placement_optimistic = conf.getboolean('params', 'placement_optimistic')
    LP_max_runtime = conf.getint('params', 'LP_max_runtime')  # in minutes
    LP_max_k = conf.getint('params', 'LP_max_k')  # max. assumed k

    debug = conf.getboolean('params', 'debug')

    # get price series for us to use in this run
    pfile = open('price_data/APXReferencePriceDataUkPowerMarket2012_noweekends.csv', 'r')
    random.seed(seed)
    row = random.randint(1, 219)  # 219: number of days in data
    for _ in range(row):
        pfile.readline()
    line = pfile.readline().strip().split('\t')
    day = line[0]
    actual_prices = [float(p) / 300. for p in line[1:]]

    # get expected prices for the right month from pre-computed avg file
    exp_prices_in = open('price_data/APXReferencePriceDataUkPowerMarket2012_noweekends_avg.csv', 'r')
    exp_prices_in.readline()  # Title
    for line in exp_prices_in.readlines():
        line = line.strip().split('\t')
        if '-{}-'.format(line[0]) in day:  # we reached the correct month
            avg_price = float(line[1])
            exp_prices = [float(p) for p in line[2:]]
            break

    street = Street(T=T, N=N, C=C, Dmax=Dmax, Smax=Smax, pmax=pmax, pmin=pmin,
                    c_h=c_h, adaptive=adaptive, slope=econ_slope,
                    placement_optimistic=placement_optimistic)
    log.write('# w, ')
    for btype in battery_types:
        log.write('{}, '.format(btype.name))
    log.write('\n')
    for w in ws:
        line = '{}, '.format(w)
        for btype in battery_types:
            b = btype(capacity=B, efficiency=alpha, max_rate=max_rate,
                  street=street, exp_prices=exp_prices, avg_price=avg_price,
                  T=T, c_h=c_h)
            if btype in (OfflineBattery, DeterministicH2Battery):
                b.exp_prices = actual_prices
            if btype in (OfflineBattery, NonDeterministicOfflineBattery):
                b.max_runtime = LP_max_runtime
                b.max_k = LP_max_k
                b.solve_offline(w)
            accumulated_costs = 0
            for t in xrange(0, T):
                pt = actual_prices[t]
                bcharge = b.compute_charge(t, pt)
                if debug:
                    fp, fm = street.f(t, bcharge, pt)
                    print("[{}][{}] exp. price: {}, act. price:{}, fp:{}, fm:{}, magnitude before:{}, magnitude after:{}, b.level:{}, bcharge:{}".format(
                                t, b.name, round(exp_prices[t], 2),
                                round(pt, 2), round(fp, 2), round(fm, 2),
                                round(street.maxf(t, 0, pt), 2),
                                round(street.maxf(t, bcharge, pt), 2),
                                round(b.level, 2),
                                round(bcharge, 2)))
                revenue = b.execute_charge(bcharge, pt)
                cost = street.cost(t, bcharge, pt)
                accumulated_costs += w * cost - revenue
            # now sell the rest in the battery at an assumed worth of the
            # average price of that month
            if not btype is NoBattery:
                accumulated_costs -= b.level * avg_price
            b.level = 0
            line += '{},'.format(accumulated_costs)
            if debug:
                print "Acc. Costs: ", accumulated_costs
        log.write('{}\n'.format(line[:-1]))  # write line w/o last comma
    log.flush()
    log.close()
Example #10
0
WHITE = (255, 255, 255)
GREEN = (94, 221, 95)
YELLOW = (100, 85, 0)
BROWN = (118, 92, 72)
GRAY = (175, 175, 175)
#Create Frog object
frog = Frog()
#Create log object
log = Log()
#Create log object
streets = []
number_of_buses = 3
street_height = 400
for _ in range(2):
    streets.append(
        Street(street_height, 'Left', random.randint(1, number_of_buses)))
    streets.append(
        Street(street_height - 40, 'Right', random.randint(1,
                                                           number_of_buses)))
    street_height -= 80

#Game Loop
while True:
    # Tick forward at 60 frames per second
    CLOCK.tick(FPS)

    #Event listener:Listens for an input the player provides
    for event in pygame.event.get():
        #User closes
        if event.type == pygame.QUIT:
            sys.exit()