예제 #1
0
def computeLineString(bounding_box, pos, long_lats):
    bbx = box(bounding_box[0], bounding_box[1], bounding_box[2],
              bounding_box[3])
    basedist = point.Point(bounding_box[0], bounding_box[1]).distance(
        point.Point(bounding_box[0], bounding_box[3])) * 1.2
    start = pos
    end = pos + 1
    while (start > 0):
        p = point.Point(long_lats[start][0], long_lats[start][1])
        if (bbx.contains(p) or (basedist > bbx.distance(p))):
            start -= 1
        else:
            break
    while (end < len(long_lats)):
        p = point.Point(long_lats[end][0], long_lats[end][1])
        if (bbx.contains(p) or (basedist > bbx.distance(p))):
            end += 1
        else:
            break
    end += 1
    if (end > len(long_lats)):
        end = len(long_lats)
    if (end - start == 1):
        if (start > 0):
            start -= 1
        if (end < len(long_lats)):
            end += 1
    return linestring.LineString([(long_lats[i][0], long_lats[i][1])
                                  for i in range(start, end)])
예제 #2
0
def create_citydist(create_environment, create_building):
    """
    Pytest fixture function to generate city district with three
    res. buildings (with demands) on positions (0, 0), (0, 10), (10, 10)

    Parameters
    ----------
    create_environment : object
        Environment object (as fixture of pytest)

    Returns
    -------
    create_citydistrict : object
        CityDistrict object of PyCity
    """
    create_citydist = citydist.CityDistrict()

    #  Add environment
    create_empty_citydist.environment = create_environment

    create_citydist.addEntity(entity=create_building,
                              position=point.Point(0, 0))
    create_citydist.addEntity(entity=create_building,
                              position=point.Point(0, 10))
    create_citydist.addEntity(entity=create_building,
                              position=point.Point(10, 10))

    return create_citydist
예제 #3
0
    def test_mutation(self):
        dict_restr = {'boi': [1],
                      'tes': [2],
                      'chp': [3],
                      'hp_aw': [4],
                      'hp_ww': [5],
                      'eh': [6],
                      'bat': [8]}

        b_dict = {'boi': 10,
                  'chp': 20,
                  'hp_aw': 0,
                  'hp_ww': 0,
                  'eh': 50,
                  'tes': 60,
                  'pv': 70,
                  'bat': 80}

        ind = {1001: b_dict,
               1002: copy.copy(b_dict),
               1003: copy.copy(b_dict),
               1008: copy.copy(b_dict),
               'lhn': []}

        dict_max_pv_area = {1001: 100,
                            1002: 100,
                            1003: 100,
                            1008: 100}

        p1 = point.Point(0, 0)
        p2 = point.Point(10, 0)
        p3 = point.Point(20, 0)
        p8 = point.Point(30, 0)

        dict_pos = {1001: p1, 1002: p2, 1003: p3, 1008: p8}
        dict_sh = {1001: 1, 1002: 1, 1003: 1, 1008: 1}

        ind_new = mutate.do_mutate(ind=ind, prob_mut=1, prob_lhn=1,
                                   dict_restr=dict_restr,
                                   dict_max_pv_area=dict_max_pv_area,
                                   pv_min=10,
                                   dict_pos=dict_pos,
                                   list_prob_lhn_and_esys=[0, 0, 1],
                                   # Only esys mutation
                                   list_prob_mute_type=[1, 0],
                                   # Only attribute changes
                                   list_prob_lhn_gen_mut=[0.3, 0.7],
                                   # Not used, here
                                   max_dist=None,
                                   dict_sh=dict_sh,
                                   dict_heatloads=dict_sh)

        assert ind_new[1001]['boi'] == 1
        assert ind_new[1001]['tes'] == 2
        assert ind_new[1001]['chp'] == 3
        assert ind_new[1001]['hp_aw'] == 0
        assert ind_new[1001]['hp_ww'] == 0
        assert ind_new[1001]['eh'] == 6
        assert ind_new[1001]['pv'] > 0
        assert ind_new[1001]['bat'] == 8
예제 #4
0
    def test_add_lhn(self):
        dict_restr = {
            'boi': [1],
            'tes': [2],
            'chp': [3],
            'hp_aw': [4],
            'hp_ww': [5],
            'eh': [6],
            'pv': [7],
            'bat': [8]
        }

        b_dict = {
            'boi': 0,
            'chp': 0,
            'hp_aw': 20,
            'hp_ww': 0,
            'eh': 0,
            'tes': 30,
            'pv': 0,
            'bat': 0
        }

        ind = {
            1001: b_dict,
            1002: copy.copy(b_dict),
            1003: copy.copy(b_dict),
            1008: copy.copy(b_dict),
            'lhn': []
        }

        dict_max_pv_area = {1001: 10, 1002: 20, 1003: 30, 1008: 40}

        p1 = point.Point(0, 0)
        p2 = point.Point(10, 0)
        p3 = point.Point(20, 0)
        p8 = point.Point(30, 0)

        dict_pos = {1001: p1, 1002: p2, 1003: p3, 1008: p8}

        lhnchanges.add_lhn(ind=ind,
                           dict_restr=dict_restr,
                           pv_min=0,
                           dict_max_pv_area=dict_max_pv_area,
                           dict_pos=dict_pos,
                           list_prob_lhn=[1, 0],
                           prob_gen_method=[1, 0, 0])

        assert len(ind['lhn'][0]) > 0

        count_chp = 0
        count_tes = 0
        for i in [1001, 1002, 1003, 1008]:
            if ind[i]['chp'] > 0:
                count_chp += 1
            if ind[i]['tes'] > 0:
                count_tes += 1

        assert count_chp > 0
        assert count_tes > 0
예제 #5
0
    def test_kmeans_clustering(self):
        p1 = point.Point(0, 0)
        p2 = point.Point(1, 0)
        p3 = point.Point(12, 0)
        p4 = point.Point(15, 3)
        p5 = point.Point(10, 10)
        p6 = point.Point(20, 20)
        p7 = point.Point(24, 20)
        p8 = point.Point(0, 10)

        dict_pos = {
            1001: p1,
            1002: p2,
            1003: p3,
            1004: p4,
            1005: p5,
            1006: p6,
            1007: p7,
            1008: p8
        }

        list_av_ids = [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008]

        nb_clusters = 2

        dict_clusters = clust.kmeans_clustering(dict_pos=dict_pos,
                                                list_av_ids=list_av_ids,
                                                nb_clusters=nb_clusters)
예제 #6
0
    def test_mutation_loop(self):
        dict_restr = {'boi': [1, 2],
                      'tes': [2, 3],
                      'chp': [3, 4],
                      'hp_aw': [4, 5],
                      'hp_ww': [5, 6],
                      'eh': [6, 7],
                      'bat': [8, 9]}

        b_dict = {'boi': 10,
                  'chp': 20,
                  'hp_aw': 0,
                  'hp_ww': 0,
                  'eh': 0,
                  'tes': 60,
                  'pv': 70,
                  'bat': 80}

        ind = {1001: b_dict,
               1002: copy.copy(b_dict),
               1003: copy.copy(b_dict),
               1004: copy.copy(b_dict),
               1005: copy.copy(b_dict),
               1006: copy.copy(b_dict),
               1007: copy.copy(b_dict),
               1008: copy.copy(b_dict),
               'lhn': [[1001, 1002, 1003, 1004]]}

        dict_max_pv_area = {1001: 100,
                            1002: 100,
                            1003: 100,
                            1004: 100,
                            1005: 100,
                            1006: 100,
                            1007: 100,
                            1008: 100}

        p1 = point.Point(0, 0)
        p2 = point.Point(10, 0)
        p3 = point.Point(20, 0)
        p4 = point.Point(0, 10)
        p5 = point.Point(10, 10)
        p6 = point.Point(20, 10)
        p7 = point.Point(30, 10)
        p8 = point.Point(30, 20)

        dict_pos = {1001: p1, 1002: p2, 1003: p3, 1004: p4,
                    1005: p5, 1006: p6, 1007: p7, 1008: p8}
        dict_sh = {1001: 1, 1002: 1, 1003: 1, 1004: 1,
                    1005: 1, 1006: 1, 1007: 1, 1008: 1}

        for i in range(500):
            mutate.do_mutate(ind=ind, prob_mut=0.7, prob_lhn=0.7,
                             dict_restr=dict_restr,
                             dict_max_pv_area=dict_max_pv_area,
                             pv_min=10,
                             dict_pos=dict_pos, dict_sh=dict_sh,
                             dict_heatloads=dict_sh)
    def test_add_multiple_entities(self, create_empty_citydist,
                                   create_building):
        #  Create empty citydistrict
        city = create_empty_citydist

        #  Create building
        building = create_building
        position_1 = point.Point(0, 0)
        position_2 = point.Point(0, 10)
        pos_list = [position_1, position_2]

        #  Add entity
        city.addMultipleEntities(entities=[building, building],
                                 positions=pos_list)

        assert len(city.nodelist_building) == 2
def calcAlignment(backPos, walls, wallProbVec, dR):
    """
    calculating object alignment, currently only w.r.t. supporting wall  
    backPos - vector of objects' back position (numpy array)
    walls - list of walls, each represented as a line (end points) 
    wallProbVec - probability vector of objects' to stand against the wall
    dR - space diagonal (scalar) 
    """

    #
    #  ====>  DIDNOT check direction, i.e. that object is parallel/perpendicular to wall
    #

    nW = len(walls)
    nO = len(backPos)
    wLines = []
    for iW in range(nW):
        wLines.append(sgls.LineString((walls[iW][0], walls[iW][1])))

    wSum = 0
    for iO in range(nO):
        dP = np.array([])
        for iW in range(nW):
            # shortest distance to wall
            dP = np.append(dP, wLines[iW].distance(spt.Point(backPos[iO])))
        wSum += wallProbVec[iO] * min(dP)

    wSum /= (nO * dR)
    return wSum
예제 #9
0
 def create_point(longitude_x, latitude_y) -> point:
     """
     Returns a shapely point object containing the provided coordinates.
     :param longitude_x: Longitude value
     :param latitude_y: Latitude value
     :return point:
     """
     return point.Point(float(longitude_x), float(latitude_y))
예제 #10
0
    def test_get_ids_sorted_by_dist(self):
        id = 1001

        p1 = point.Point(0, 0)
        p4 = point.Point(10, 0)
        p2 = point.Point(20, 0)
        p3 = point.Point(30, 0)
        p5 = point.Point(30, 10)

        dict_pos = {1001: p1, 1002: p2, 1003: p3, 1004: p4, 1005: p5}

        list_av = [1001, 1002, 1003, 1004, 1005]

        list_sorted = analyse. \
            get_ids_sorted_by_dist(id=id, dict_pos=dict_pos, list_av=list_av)

        assert list_sorted == [1004, 1002, 1003, 1005]
예제 #11
0
def create_ellipse(center, lengths, angle=0):
    """
    create a shapely ellipse. adapted from
    https://gis.stackexchange.com/a/243462
    """
    circ = shp.Point(center).buffer(1)
    ell = sh.affinity.scale(circ, (lengths[0]), (lengths[1]))
    ellr = sh.affinity.rotate(ell, angle)
    return ellr
예제 #12
0
 def getHexagonCoordsForPoint(self, x, y):
     ((minColumn, minRow),
      (maxColumn,
       maxRow)) = self.getHexagonCoordSpanForBoundingBox(x, y, x, y)
     for xCol in range(minColumn, maxColumn + 1):
         for yRow in range(minRow, maxRow + 1):
             if self.getHexagon(xCol, yRow).contains(point.Point(x, y)):
                 return xCol, yRow
     raise Exception(
         "No Hexagon matched; possible edge case (point on hexagon boundary)"
     )
def calcGoldenSec(objPos, roomRect, dR):
    """
    calculating objects location w.r.t. golden section lines
     objPos: objects' center position
     roomRect: 4 points of room (or sub-area) rectangle  
     dR: room diagonal
    """

    # make sure the vertices are ordered
    tmpRect = sgp.Polygon(roomRect)
    tmpRect = tmpRect.convex_hull
    t_rect = tmpRect.exterior.coords[0:-1]

    # creating golden lines. Assuming gsRatio = 13/21
    # go over the 2 consecutive pair of vertices and generate the 4-lines, 2 in each side
    gsr = 13.0 / 21.0

    line1 = sgls.LineString((t_rect[0], t_rect[1]))
    length = npla.norm(np.array(t_rect[0]) - np.array(t_rect[1]))
    pt11 = line1.interpolate(length * (1.0 - gsr))
    pt12 = line1.interpolate(length * gsr)
    line3 = sgls.LineString((t_rect[2], t_rect[3]))
    length = npla.norm(np.array(t_rect[2]) - np.array(t_rect[3]))
    pt32 = line3.interpolate(length * (1.0 - gsr))
    pt31 = line3.interpolate(length * gsr)

    line2 = sgls.LineString((t_rect[1], t_rect[2]))
    length = npla.norm(np.array(t_rect[1]) - np.array(t_rect[2]))
    pt21 = line2.interpolate(length * (1.0 - gsr))
    pt22 = line2.interpolate(length * gsr)
    line4 = sgls.LineString((t_rect[3], t_rect[0]))
    length = npla.norm(np.array(t_rect[3]) - np.array(t_rect[0]))
    pt42 = line4.interpolate(length * (1.0 - gsr))
    pt41 = line4.interpolate(length * gsr)

    gsLines = []
    gsLines.append(sgls.LineString((pt11, pt31)))
    gsLines.append(sgls.LineString((pt12, pt32)))
    gsLines.append(sgls.LineString((pt21, pt41)))
    gsLines.append(sgls.LineString((pt22, pt42)))

    dObjGs = []
    for i in range(len(objPos)):
        dd = []
        for j in range(len(gsLines)):
            dd.append(gsLines[j].distance(spt.Point(objPos[i])))
        dObjGs.append(min(dd))

    gP = np.sum(dObjGs)
    gP /= (1.0 * dR * len(objPos))

    return gP
예제 #14
0
def main():
  surnames = read_surnames()
  europe = Europe()
  projection = crs.PlateCarree()
  ax = pyplot.axes(projection=europe)
  kosovo_geometry = None
  for country in shapereader.Reader('ne_110m_admin_0_countries').records():
    country_geometry = country.geometry
    geometry = europe.project_geometry(
        projection.project_geometry(country_geometry))
    if geometry.is_empty:
      continue
    centroid = geometry.centroid
    name = country.attributes['name_long']
    if name == 'Russian Federation':  # Workaround.
      centroid = point.Point(3.6e6, 2.6e6)
    elif name == 'Albania':
      centroid = point.Point(centroid.x, centroid.y - 25e3)
    elif name == 'Bosnia and Herzegovina':
      centroid = point.Point(centroid.x, centroid.y - 67e3)
    elif name == 'Croatia':
      centroid = point.Point(centroid.x, centroid.y + 25e3)
    elif name == 'Kosovo':
      kosovo_geometry = country_geometry
      continue
    elif name == 'Macedonia':
      centroid = point.Point(centroid.x + 100e3, centroid.y)
    elif name == 'Montenegro':
      centroid = point.Point(centroid.x - 100e3, centroid.y)
    elif name == 'Serbia':
      country_geometry = (country_geometry.union(kosovo_geometry),)
    try:
      surname = surnames[name]
      ax.add_geometries(
          country_geometry,
          projection,
          facecolor=COLORS[surname[1]],
          edgecolor=BORDER_COLOR)
      ax.text(
          centroid.x,
          centroid.y,
          surname[0],
          ha='center',
          va='center',
          size=10)
    except KeyError:
      ax.add_geometries(
          country_geometry,
          projection,
          facecolor=DEFAULT_COLOR,
          edgecolor=BORDER_COLOR)
  # Workaround for Catalonia and Kosovo.
  ax.text(1100e3, 800e3, '(Ferrer)', ha='center', va='center', size=9)
  ax.text(2800e3, 850e3, '(Hoxha)', ha='center', va='center', size=9)
  legend_handles = [
      patches.Circle((0.5, 0.5), color=COLORS[k]) for k in COLORS]
  pyplot.figlegend(legend_handles, COLORS.keys(), 'upper left', fontsize=10)
  pyplot.savefig('surnames.png')
예제 #15
0
def circle_group_area(radiuses, positions):
    circles = []
    for i in range(len(radiuses)):
        circles.append(
            point.Point(positions[i][0], positions[i][1]).buffer(radiuses[i]))

    union = ops.unary_union(circles)
    result = [geom for geom in ops.polygonize(union)]

    completeareas = [list(ops.polygonize(g.exterior))[0].area for g in result]
    max_index = np.argmax(completeareas)
    result_area = result[max_index].area

    return result_area
예제 #16
0
def main():
    p1 = point.Point(0, 0)
    p2 = point.Point(1, 0)
    p3 = point.Point(12, 0)
    p4 = point.Point(15, 3)
    p5 = point.Point(10, 10)
    p6 = point.Point(20, 20)
    p7 = point.Point(24, 20)
    p8 = point.Point(0, 10)

    dict_pos = {1001: p1,
                1002: p2,
                1003: p3,
                1004: p4,
                1005: p5,
                1006: p6,
                1007: p7,
                1008: p8}

    list_av_ids = [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008]

    nb_clusters = 3

    dict_clusters = kmeans_clustering(dict_pos=dict_pos,
                                      list_av_ids=list_av_ids,
                                      nb_clusters=nb_clusters)

    print('Results of kmeans clustering:')
    print(dict_clusters)
    print()
    for key in dict_clusters.keys():
        print('Key: ', key)
        print('Values: ', dict_clusters[key])
        print()
    print('###########################################################')

    dict_clusters = meanshift_clustering(dict_pos=dict_pos,
                                         list_av_ids=list_av_ids)

    print('Results of meanshift clustering:')
    print(dict_clusters)
    print()
    for key in dict_clusters.keys():
        print('Key: ', key)
        print('Values: ', dict_clusters[key])
        print()
    print('###########################################################')
예제 #17
0
def compute_bounds():
    border_points = REFERENCE_POINTS.get('+init=epsg:3857',
                                         REFERENCE_POINTS['default'])

    max_x = max_y = float("-infinity")
    min_x = min_y = float("infinity")

    for point in border_points:

        point = shapelypoint.Point(*point)

        # Project the border points following the projection system
        point = shapelypoint.Point(p_wgs84_3857(point.x, point.y))

        # Ignore the border points which cannot be projected

        if point.x != float("infinity") or point.y != float("infinity"):
            # Compute the smallest bounds containing the border points
            min_x = min(point.x, min_x)
            max_x = max(point.x, max_x)
            min_y = min(point.y, min_y)
            max_y = max(point.y, max_y)

    return min_x, min_y, max_x, max_y
    def test_add_entity_building(self, create_empty_citydist, create_building):
        #  Create empty citydistrict
        city = create_empty_citydist

        #  Create building
        building = create_building
        position_1 = point.Point(0, 0)

        #  Add entity
        node_nb = city.addEntity(entity=building, position=position_1)

        assert city.node[node_nb]['entity']._kind == 'building'
        assert city.node[node_nb]['position'] == position_1
        #  Check uesgraphs attribute
        assert len(city.nodelist_building) == 1
예제 #19
0
    def create_points(data):
        """
        Create shapely geometry from list of dicts
        """
        for row in data:

            if row["x"] and row["y"]:
                try:
                    row["geometry"] = point.Point(float(row["x"]),
                                                  float(row["y"]))
                except:
                    row["geometry"] = None
            else:
                row["geometry"] = None

        return data
예제 #20
0
def process_and_update_vic(**tweets):
    for tweet in tweets:
        geo = tweets[tweet].get('geo')
        if not geo:
            tweets[tweet]['zone'] = 'NoGeo'
        else:
            geo.sort(reverse=True)
            for zone in vic_map:
                if vic_map[zone].contains(point.Point(geo)):
                    tweets[tweet]['zone'] = zone
                    break
            if not tweets[tweet]['zone']:
                tweets[tweet]['zone'] = 'NotVic'
    try:
        resp = requests.post('http://172.26.38.1:8080/api/tweet/trained/zone/vic/', headers=headers, json=tweets)
    except Exception:
        return
예제 #21
0
    def __new__(self, points=None):
        if points is None:
            # allow creation of empty multipoints, to support unpickling
            # TODO better empty constructor
            return shapely.from_wkt("MULTIPOINT EMPTY")
        elif isinstance(points, MultiPoint):
            return points

        m = len(points)
        subs = []
        for i in range(m):
            p = point.Point(points[i])
            if p.is_empty:
                raise EmptyPartError(
                    "Can't create MultiPoint with empty component")
            subs.append(p)

        if len(points) == 0:
            return shapely.from_wkt("MULTIPOINT EMPTY")

        return shapely.multipoints(subs)
예제 #22
0
파일: multipoint.py 프로젝트: 92kns/Shapely
    def __new__(self, points=None):
        """
        Parameters
        ----------
        points : sequence
            A sequence of (x, y [,z]) numeric coordinate pairs or triples or a
            sequence of objects that implement the numpy array interface,
            including instances of Point.

        Example
        -------
        Construct a 2 point collection

          >>> from shapely.geometry import Point
          >>> ob = MultiPoint([[0.0, 0.0], [1.0, 2.0]])
          >>> len(ob.geoms)
          2
          >>> type(ob.geoms[0]) == Point
          True
        """
        if points is None:
            # allow creation of empty multipoints, to support unpickling
            # TODO better empty constructor
            return shapely.from_wkt("MULTIPOINT EMPTY")
        elif isinstance(points, MultiPoint):
            return points

        m = len(points)
        subs = []
        for i in range(m):
            p = point.Point(points[i])
            if p.is_empty:
                raise EmptyPartError(
                    "Can't create MultiPoint with empty component")
            subs.append(p)

        if len(points) == 0:
            return shapely.from_wkt("MULTIPOINT EMPTY")

        return shapely.multipoints(subs)
예제 #23
0
def PntGeoJSONToShp_WGS84(json_fp,
                          shp_fp=None):  #点状GeoJSON文件转成SHP(火星坐标 转 WGS84)
    import coordinate_conversion
    from shapely.geometry import point

    if not json_fp.endswith("json"): return False

    if shp_fp is None:
        shp_fp = "{}_wgs84.shp".format(json_fp[:-5])
    elif not shp_fp.endswith("shp"):
        return False

    gdf = geopandas.read_file(json_fp)
    # GCJ02转WGS84
    for i in range(0, len(gdf)):
        geom = gdf.geometry[i]  # 获取空间属性,即GeoSeries
        lng, lat = geom.x, geom.y  # x=117.967657, y=24.472853
        lng, lat = coordinate_conversion.gcj02towgs84(lng, lat)
        gdf.geometry[i] = point.Point(lng, lat)

    # 设置成WGS84,并保存
    gdf.crs = {'init': 'epsg:4326'}
    gdf.to_file(shp_fp, encoding="utf-8")
    return shp_fp
예제 #24
0
    def test_get_list_ids_sorted_by_dist_to_ref_list(self):
        list_ref = [1001, 1002, 1003]
        list_search = [1004, 1005, 1006]

        p1 = point.Point(0, 0)
        p2 = point.Point(10, 0)
        p3 = point.Point(0, 10)
        p4 = point.Point(0, 30)
        p5 = point.Point(40, 0)
        p6 = point.Point(0, -10)

        dict_pos = {1001: p1, 1002: p2, 1003: p3, 1004: p4, 1005: p5, 1006: p6}

        list_sorted = analyse. \
            get_list_ids_sorted_by_dist_to_ref_list(list_ref=list_ref,
                                                    list_search=list_search,
                                                    dict_pos=dict_pos)

        assert list_sorted == [(1006, 10), (1004, 20), (1005, 30)]
예제 #25
0
    def test_get_ids_closest_dist_to_list_of_build(self):
        list_ref = [1001, 1002, 1003]
        list_search = [1004, 1005, 1006]

        p1 = point.Point(0, 0)
        p2 = point.Point(10, 0)
        p3 = point.Point(0, 10)
        p4 = point.Point(0, 30)
        p5 = point.Point(40, 0)
        p6 = point.Point(0, -10)

        dict_pos = {1001: p1, 1002: p2, 1003: p3, 1004: p4, 1005: p5, 1006: p6}

        dict_dist = analyse. \
            get_ids_closest_dist_to_list_of_build(list_ref=list_ref,
                                                  list_search=list_search,
                                                  dict_pos=dict_pos)

        assert dict_dist == {1004: 20, 1005: 30, 1006: 10}
예제 #26
0
 def shape_factory(self, *args):
     return point.Point(*args)
#  Generate environment
environment = pycity_base.classes.Environment.Environment(timer, weather, prices)

#Network Specification
networksDictionary={}
networksDictionary['Electricity']={'busVoltage':1000,'diameter':0.2,'spConductance':1.68*10**-8}
networksDictionary['Gas']={'diameter':0.5,'gasDensity':0.8,'darcyFactor':0.03}
networksDictionary['Heat']={'diameter':0.5,'spConductance':0.591}
networksDictionary['Water']={'diameter':0.5,'waterDensity':1000,'darcyFactor':0.03}

#Generate city district object
cityDistrict = CityDistrict.CityDistrict(environment,networksDictionary)

#  Generate shapely point positions
location = {}
location[1] = point.Point(-5000, -100)  #Gas Source
location[2] = point.Point(0, 0)         #District Heating CHP
location[3] = point.Point(100, 20)      #Building3
location[4] = point.Point(120, 20)      #Building4
location[5] = point.Point(160, 20)      #Building5
location[6] = point.Point(200, 20)      #Building6
location[7] = point.Point(160, -20)     #Building7
location[8] = point.Point(200, -20)     #Building8
location[9] = point.Point(1500, 50)     #Building9
location[10]= point.Point(1600, 50)     #Building10
location[11]= point.Point(1700, 50)     #Building11
location[12]= point.Point(1800,50)      #Building12
location[13]= point.Point(2000,180)     #Wind Turbine
location[14]= point.Point(2000,100)     #Power-to-Gas Converter
location[15]= point.Point(2000,95)      #Power-to-Gas Storage
location[16]= point.Point(1500,-50)     #Photovoltaic Farm
예제 #28
0
def run_city_generator(gen_mo=0, input_name='test_city_mixed_buildings.txt',
                       output_name=None, use_el_slp=True,
                       gen_dhw_profile=False):
    """
    Function to generate and return city district object

    Parameters
    ----------
    gen_mo : int, optional
        Generation mode number:
        0 - Use data from input file (default)
    input_name : str, optional
        Name of input data file (default: 'test_city_only_buildings.txt')
    output_name : str, optional
        Name of output file (default: None)
        If output_name is None, no output file is generated.
        Else: Pickled output file is saved to output folder
    use_el_slp : bool, optional
        Boolean to define, how electrical load profile should be generated
        (default: True)
        True: Generate el. load profile via el. slp
        False: Use stochastic profile generator (
        only valid for residential buildings!)
    gen_dhw_profile : bool, optional
        Boolean to define, if domestic hot water profile should be generated
        (default: False)
        True: Generate dhw profile (valid for residential buildings!)
        False: Do not generate dhw profile

    Returns
    -------
    city_district : object
        CityDistrict object of PyCity
    """

    #  Generate timer, weather and price objects
    timer = pycity_base.classes.Timer.Timer()
    weather = pycity_base.classes.Weather.Weather(timer)
    prices = pycity_base.classes.Prices.Prices()

    #  Generate environment
    environment = pycity_base.classes.Environment.Environment(timer, weather,
                                                              prices)

    #  Generate city district object
    city_district = citydis.CityDistrict(environment)

    #  Current file path
    curr_path = os.path.dirname(os.path.abspath(__file__))

    #  Choose city district generation method
    if gen_mo == 0:  # Load data from file
        import_path = os.path.join(curr_path, 'input', input_name)
        city_dist_pandas_dataframe = pandas.read_csv(import_path, sep='\t')

        for index, row in city_dist_pandas_dataframe.iterrows():
            curr_name = row['name']  # Building name
            curr_x = row['x_coord / m']  # Building x coordinate in m
            curr_y = row['y_coord / m']  # Building y coordinate in m
            curr_area = row[
                'living_area / m2']
            #  Net floor area (respectively living area) in m2
            curr_th_spec_demand = row[
                'specific_th_demand / kWh/m2a']
            #  Spec. thermal energy demand in kWh/m2a
            curr_el_demand = row[
                'an_el_demand / kWh/a']
            #  Annual electric energy demand in kWh/a
            curr_th_slp = row['th_slp_profile_type']  # Thermal SLP type
            curr_el_slp = row['el_slp_profile_type']  # Electrical SLP type
            curr_total_nb_occupants = row[
                'total_nb_occupants']  # Total number of occupants in building

            #  Assert input values
            assert curr_area > 0
            assert curr_th_spec_demand > 0
            assert curr_el_demand > 0

            print('Processing building', curr_name)

            #  Check if number of occupants is nan
            #  (for non residential buildings)
            if math.isnan(curr_total_nb_occupants):
                curr_total_nb_occupants = None  # Replace nan with None
            else:  # If number of occupants is not nan, convert value
                   # to integer
                curr_total_nb_occupants = int(curr_total_nb_occupants)
                assert curr_total_nb_occupants >= 1
                assert curr_total_nb_occupants <= 5

            # Generate heat demand curve for space heating
            heat_demand = \
                SpaceHeating.SpaceHeating(environment,
                                          method=1,
                                          # Standard load profile
                                          livingArea=curr_area,
                                          specificDemand=curr_th_spec_demand,
                                          profile_type=curr_th_slp)

            if use_el_slp:  # Use el. SLP
                el_method = 1
                occupancy_profile = []  # Dummy value
            else:  # Stochastic profile generator
                   # (only for residential buildings)
                el_method = 2
                #  Generate stochastic occupancy profile
                occupancy_object = \
                    occu.Occupancy(environment,
                                   number_occupants=curr_total_nb_occupants)
                occupancy_profile = occupancy_object.occupancy

            # Generate electrical demand curve
            el_demand = \
                ElectricalDemand.ElectricalDemand(environment,
                                                  method=el_method,
                                                  annualDemand=curr_el_demand,
                                                  profileType=curr_el_slp,
                                                  singleFamilyHouse=True,
                                                  total_nb_occupants=curr_total_nb_occupants,
                                                  randomizeAppliances=True,
                                                  lightConfiguration=0,
                                                  occupancy=occupancy_profile)

            #  Generate apartment and add demand durves
            apartment = Apartment.Apartment(environment)
            apartment.addMultipleEntities([heat_demand, el_demand])

            if gen_dhw_profile:
                #  Generate domestic hot water demand curve
                dhw_annex42 = \
                    DomesticHotWater.DomesticHotWater(environment,
                                                      tFlow=60,
                                                      thermal=True,
                                                      method=1,
                                                      # Annex 42
                                                      dailyConsumption=70,
                                                      supplyTemperature=25)
                apartment.addEntity(dhw_annex42)

            # Generate heating curve
            heatingCurve = HeatingCurve.HeatingCurve(environment)

            #  Generate building and add apartment and heating curve
            building = Building.Building(environment)
            entities = [apartment, heatingCurve]
            building.addMultipleEntities(entities)

            #  Generate shapely point positions
            position = point.Point(curr_x, curr_y)

            #  Add buildings to city district
            city_district.addEntity(entity=building, position=position,
                                    name=curr_name)

            print('Added building', curr_name, ' to city district.')

    # Save results as pickled file
    if output_name is not None:
        output_path = os.path.join(curr_path, 'output', output_name)
        #  Pickle and dump city objects
        pickle.dump(city_district, open(output_path, 'wb'))
        print('Pickled and dumped city object')

    return city_district
예제 #29
0
    def test_get_dict_usable_pv_areas(self):
        #  Create extended environment of pycity_calc
        year = 2010
        timestep = 3600  # Timestep in seconds
        location = (51.529086, 6.944689)  # (latitude, longitute) of Bottrop
        altitude = 55  # Altitude of Bottrop

        #  Generate timer object
        timer = time.TimerExtended(timestep=timestep, year=year)

        #  Generate weather object
        weather = Weather.Weather(timer,
                                  useTRY=True,
                                  location=location,
                                  altitude=altitude)

        #  Generate market object
        market = germarkt.GermanMarket()

        #  Generate co2 emissions object
        co2em = co2.Emissions(year=year)

        #  Generate environment
        environment = env.EnvironmentExtended(timer,
                                              weather,
                                              prices=market,
                                              location=location,
                                              co2em=co2em)

        #  Generate city object
        city_object = city.City(environment=environment)

        use_pv_area_1 = 30

        extended_building = build_ex. \
            BuildingExtended(environment,
                             build_year=1962,
                             mod_year=2003,
                             build_type=0,
                             roof_usabl_pv_area=use_pv_area_1,
                             net_floor_area=150,
                             height_of_floors=3,
                             nb_of_floors=2,
                             neighbour_buildings=0,
                             residential_layout=0,
                             attic=0, cellar=1,
                             construction_type='heavy',
                             dormer=0)

        position = point.Point(0, 0)

        city_object.add_extended_building(extended_building=extended_building,
                                          position=position)

        use_pv_area_2 = 0

        extended_building2 = build_ex. \
            BuildingExtended(environment,
                             build_year=1962,
                             mod_year=2003,
                             build_type=0,
                             roof_usabl_pv_area=use_pv_area_2,
                             net_floor_area=150,
                             height_of_floors=3,
                             nb_of_floors=2,
                             neighbour_buildings=0,
                             residential_layout=0,
                             attic=0, cellar=1,
                             construction_type='heavy',
                             dormer=0)

        position2 = point.Point(0, 50)

        city_object.add_extended_building(extended_building=extended_building2,
                                          position=position2)

        dict_use_pv_area = pvareas.get_dict_usable_pv_areas(city=city_object)

        assert sorted(dict_use_pv_area.keys()) == [1001, 1002]

        assert dict_use_pv_area[1001] == use_pv_area_1
        assert dict_use_pv_area[1002] == use_pv_area_2
예제 #30
0
파일: meshObjects.py 프로젝트: Vay/msmesh
 def getShapelyPoint(self):
     pt = SPoint.Point(self.x, self.y)
     return pt