• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

DaveFoss / DAVE_data / 10689762467

03 Sep 2024 08:00PM UTC coverage: 78.98% (-7.4%) from 86.4%
10689762467

Pull #10

github

uvchik
Rename module to just polygon.py
Pull Request #10: Add basic functions

66 of 90 branches covered (73.33%)

Branch coverage included in aggregate %.

160 of 211 new or added lines in 7 files covered. (75.83%)

2 existing lines in 1 file now uncovered.

321 of 400 relevant lines covered (80.25%)

4.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.37
/src/dave_data/geometry/polygon.py
1
from geopandas import read_file
5✔
2

3
from dave_data.geometry.layers import get_federal_state_layer
5✔
4
from dave_data.geometry.layers import get_nuts_layer
5✔
5
from dave_data.geometry.layers import get_postcode_layer
5✔
6

7
dave_data_settings = {"crs_main": "EPSG:4326"}
5✔
8

9

10
def postalcode_to_polygon(postalcode):
5✔
11
    """
12
    Creating a polygon based on postalcodes
13

14
    Parameters
15
    ----------
16
    postalcode : int, str, list of str, list of int
17
          Postalcodes areas which define the polygon. Use ['ALL'] for all
18
          postalcode areas in germany
19

20
    Returns
21
    -------
22
    polygon : Shapely Polygon / MultiPolygon
23

24
    Examples
25
    --------
26
    >>> from dave_data.geometry.polygon import postalcode_to_polygon
27
    >>> from shapely.geometry import MultiPolygon
28
    >>> polygon_postal = postalcode_to_polygon(postalcode=['34225', '34117'])
29
    >>> isinstance(polygon_postal, MultiPolygon)
30
    True
31
    """
32
    # convert single values to list
33
    if isinstance(postalcode, (int, str)):
5✔
NEW
34
        postalcode = [str(postalcode).zfill(5)]
×
35

36
    # convert all values to str and check if string values are valid numbers
37
    postalcode = [str(int(p)).zfill(5) for p in postalcode]
5✔
38

39
    # get postcode map
40
    postal, meta_data = get_postcode_layer()
5✔
41

42
    # return one polygon containing all postcode polygons
43
    return postal.loc[postalcode].union_all()
5✔
44

45

46
def ags2polygon(ags):
5✔
47
    """
48
    Returns the polygon of the given region.
49

50
    Find the ags-code of any town in Germany:
51
    https://www.statistikportal.de/de/gemeindeverzeichnis
52

53
    Parameters
54
    ----------
55
    ags : str or int
56

57
    Returns
58
    -------
59
    shapely.polygon : Outline of the given region
60

61
    """
NEW
62
    raise NotImplementedError("ags2polygon is not implemented so far.")
×
63

64

65
def town_to_polygon(town):
5✔
66
    """
67
    Create a polygon based on town names
68

69
    Parameters
70
    ----------
71
    town : str
72
        Town areas which define the polygon. Use ['ALL'] for all town areas
73
        in germany
74

75
    Returns
76
    -------
77
    polygon : Shapely Polygon / MultiPolygon
78

79
    Examples
80
    --------
81
    >>> from shapely.geometry import MultiPolygon
82
    >>> from dave_data.geometry.polygon import town_to_polygon
83
    >>> polygon_town = town_to_polygon(town='Kassel')
84
    >>> isinstance(polygon_town, MultiPolygon)
85
    True
86
    """
87
    postal, meta_data = get_postcode_layer()
5✔
88

89
    town = postal.loc[postal["note"].str.lower().str.find(town.lower()) >= 0]
5✔
90

91
    return town.union_all()
5✔
92

93

94
def federal_state_to_polygon(federal_state):
5✔
95
    """
96
    Create a polygon based on federal states
97

98
    Parameters
99
    ----------
100
    federal_state : str
101
        Federal state areas which define the polygon. Use ['ALL'] for all
102
        Federal state areas in germany
103

104
    Returns
105
    -------
106
    polygon : Shapely Polygon / MultiPolygon
107

108
    Examples
109
    --------
110
    >>> from dave_data.geometry.polygon import federal_state_to_polygon
111
    >>> from shapely.geometry import MultiPolygon, Polygon
112
    >>> polygon_fed = federal_state_to_polygon(federal_state='Hessen')
113
    >>> isinstance(polygon_fed, (MultiPolygon, Polygon))
114
    True
115
    """
116
    states, meta_data = get_federal_state_layer()
5✔
117

118
    state = states.loc[
5✔
119
        states["name"].str.lower().str.find(federal_state.lower()) >= 0
120
    ]
121
    return state.union_all()
5✔
122

123

124
def nuts_to_polygon(nuts, year=2016):
5✔
125
    """
126
    Create a polygon based on nuts regions
127

128
    Parameters
129
    ----------
130
    nuts : List(Str)
131
          Nuts areas which define the polygon. Diffrent nuts levels can
132
          be combined. Use ['ALL'] for all Nuts 3 areas in germany
133

134
    year : scalar(INT), optional(default=2016)
135
          The year which forms the basis of the data set
136

137
    Returns
138
    -------
139
    polygon : Shapely Polygon / MultiPolygon
140

141
    Examples
142
    --------
143
    >>> from dave_data.geometry.polygon import nuts_to_polygon
144
    >>> from shapely.geometry import Polygon
145
    >>> polygon_nuts = nuts_to_polygon(nuts="DE11B", year=2013)
146
    >>> isinstance(polygon_nuts, Polygon)
147
    True
148
    """
149
    # read nuts-3 areas
150
    nuts_all, meta_data = get_nuts_layer(year=year)
5✔
151
    nuts_3 = nuts_all[nuts_all.LEVL_CODE == 3]
5✔
152

153
    nuts_region = nuts_3.loc[nuts_3["NUTS_ID"].str.lower() == nuts.lower()]
5✔
154

155
    return nuts_region.union_all()
5✔
156

157

158
def file_to_polygon(filepath, layer=None):
5✔
159
    """
160
    Create a polygon based on a file including geographical data
161

162
    Parameters
163
    ----------
164
    filepath : scalar(Str)
165
        Absolut Path to a file including geographical data. Possible datatypes
166
        are .shp, .gpkg and .geojson
167

168
    layer : scalar(Str), optional(default=None)
169
          The layer name of the data to be considered. Necessary for datatype
170
          .gpkg
171

172
    Returns
173
    -------
174
    polygon : Shapely Polygon / MultiPolygon
175

176
    Examples
177
    --------
178
    >>> # from dave_data.geometry.area_to_polygon import file_to_polygon
179
    >>> # polygon = file_to_polygon(filepath)
180
    """
181
    # read file
NEW
182
    if filepath.split(".")[-1] in ["shp", "geojson"]:
×
NEW
183
        file_data = read_file(filepath)
×
NEW
184
    elif filepath.split(".")[-1] in ["gpkg"]:
×
NEW
185
        if layer is None:
×
NEW
186
            raise ValueError(
×
187
                "At .gpkg files a layer specification is necessary"
188
            )
NEW
189
        file_data = read_file(filepath, layer=layer)
×
190
    else:
NEW
191
        raise ValueError("The given file is not in a supported format")
×
192
    # check if the given file is empty
NEW
193
    if file_data.empty:
×
NEW
194
        raise ValueError("The given file includes no data")
×
195

196
    # check crs and project to the right one if needed
NEW
197
    if file_data.crs and file_data.crs != dave_data_settings["crs_main"]:
×
NEW
198
        file_data = file_data.to_crs(dave_data_settings["crs_main"])
×
NEW
199
    if "id" in file_data.keys():
×
NEW
200
        file_data = file_data.drop(columns=["id"])
×
NEW
201
    """
×
202
    # convert own area into postal code areas for target_input
203
    postal, meta_data = read_postal()
204
    # filter postal code areas which are within the target area
205
    postal_intersection = intersection_with_area(
206
        postal, target, remove_columns=False
207
    )
208
    # filter duplicated postal codes
209
    own_postal = postal_intersection["postalcode"].unique().tolist()
210
    """
211
    # create polygon from file data
NEW
212
    polygon = file_data.geometry.union_all()
×
NEW
213
    return polygon
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc