/
location.py
359 lines (288 loc) · 11.9 KB
/
location.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""
This module contains the Location class.
"""
# Will Holmgren, University of Arizona, 2014-2016.
import datetime
import warnings
import pandas as pd
import pytz
from pvlib import solarposition, clearsky, atmosphere, irradiance
class Location:
"""
Location objects are convenient containers for latitude, longitude,
timezone, and altitude data associated with a particular
geographic location. You can also assign a name to a location object.
Location objects have two timezone attributes:
* ``tz`` is a IANA timezone string.
* ``pytz`` is a pytz timezone object.
Location objects support the print method.
Parameters
----------
latitude : float.
Positive is north of the equator.
Use decimal degrees notation.
longitude : float.
Positive is east of the prime meridian.
Use decimal degrees notation.
tz : str, int, float, or pytz.timezone, default 'UTC'.
See
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
for a list of valid time zones.
pytz.timezone objects will be converted to strings.
ints and floats must be in hours from UTC.
altitude : float, default 0.
Altitude from sea level in meters.
name : None or string, default None.
Sets the name attribute of the Location object.
See also
--------
pvlib.pvsystem.PVSystem
"""
def __init__(self, latitude, longitude, tz='UTC', altitude=0, name=None):
self.latitude = latitude
self.longitude = longitude
if isinstance(tz, str):
self.tz = tz
self.pytz = pytz.timezone(tz)
elif isinstance(tz, datetime.timezone):
self.tz = 'UTC'
self.pytz = pytz.UTC
elif isinstance(tz, datetime.tzinfo):
self.tz = tz.zone
self.pytz = tz
elif isinstance(tz, (int, float)):
self.tz = tz
self.pytz = pytz.FixedOffset(tz*60)
else:
raise TypeError('Invalid tz specification')
self.altitude = altitude
self.name = name
def __repr__(self):
attrs = ['name', 'latitude', 'longitude', 'altitude', 'tz']
return ('Location: \n ' + '\n '.join(
f'{attr}: {getattr(self, attr)}' for attr in attrs))
@classmethod
def from_tmy(cls, tmy_metadata, tmy_data=None, **kwargs):
"""
Create an object based on a metadata
dictionary from tmy2 or tmy3 data readers.
Parameters
----------
tmy_metadata : dict
Returned from tmy.readtmy2 or tmy.readtmy3
tmy_data : None or DataFrame, default None
Optionally attach the TMY data to this object.
Returns
-------
Location
"""
# not complete, but hopefully you get the idea.
# might need code to handle the difference between tmy2 and tmy3
# determine if we're dealing with TMY2 or TMY3 data
tmy2 = tmy_metadata.get('City', False)
latitude = tmy_metadata['latitude']
longitude = tmy_metadata['longitude']
if tmy2:
name = tmy_metadata['City']
else:
name = tmy_metadata['Name']
tz = tmy_metadata['TZ']
altitude = tmy_metadata['altitude']
new_object = cls(latitude, longitude, tz=tz, altitude=altitude,
name=name, **kwargs)
# not sure if this should be assigned regardless of input.
if tmy_data is not None:
new_object.tmy_data = tmy_data
new_object.weather = tmy_data
return new_object
@classmethod
def from_epw(cls, metadata, data=None, **kwargs):
"""
Create a Location object based on a metadata
dictionary from epw data readers.
Parameters
----------
metadata : dict
Returned from epw.read_epw
data : None or DataFrame, default None
Optionally attach the epw data to this object.
Returns
-------
Location object (or the child class of Location that you
called this method from).
"""
latitude = metadata['latitude']
longitude = metadata['longitude']
name = metadata['city']
tz = metadata['TZ']
altitude = metadata['altitude']
new_object = cls(latitude, longitude, tz=tz, altitude=altitude,
name=name, **kwargs)
if data is not None:
new_object.weather = data
return new_object
def get_solarposition(self, times, pressure=None, temperature=12,
**kwargs):
"""
Uses the :py:func:`solarposition.get_solarposition` function
to calculate the solar zenith, azimuth, etc. at this location.
Parameters
----------
times : pandas.DatetimeIndex
Must be localized or UTC will be assumed.
pressure : None, float, or array-like, default None
If None, pressure will be calculated using
:py:func:`atmosphere.alt2pres` and ``self.altitude``.
temperature : None, float, or array-like, default 12
kwargs
passed to :py:func:`solarposition.get_solarposition`
Returns
-------
solar_position : DataFrame
Columns depend on the ``method`` kwarg, but always include
``zenith`` and ``azimuth``.
"""
if pressure is None:
pressure = atmosphere.alt2pres(self.altitude)
return solarposition.get_solarposition(times, latitude=self.latitude,
longitude=self.longitude,
altitude=self.altitude,
pressure=pressure,
temperature=temperature,
**kwargs)
def get_clearsky(self, times, model='ineichen', solar_position=None,
dni_extra=None, **kwargs):
"""
Calculate the clear sky estimates of GHI, DNI, and/or DHI
at this location.
Parameters
----------
times: DatetimeIndex
model: str, default 'ineichen'
The clear sky model to use. Must be one of
'ineichen', 'haurwitz', 'simplified_solis'.
solar_position : None or DataFrame, default None
DataFrame with columns 'apparent_zenith', 'zenith',
'apparent_elevation'.
dni_extra: None or numeric, default None
If None, will be calculated from times.
kwargs
Extra parameters passed to the relevant functions. Climatological
values are assumed in many cases. See source code for details!
Returns
-------
clearsky : DataFrame
Column names are: ``ghi, dni, dhi``.
"""
if dni_extra is None:
dni_extra = irradiance.get_extra_radiation(times)
try:
pressure = kwargs.pop('pressure')
except KeyError:
pressure = atmosphere.alt2pres(self.altitude)
if solar_position is None:
solar_position = self.get_solarposition(times, pressure=pressure,
**kwargs)
apparent_zenith = solar_position['apparent_zenith']
apparent_elevation = solar_position['apparent_elevation']
if model == 'ineichen':
try:
linke_turbidity = kwargs.pop('linke_turbidity')
except KeyError:
interp_turbidity = kwargs.pop('interp_turbidity', True)
linke_turbidity = clearsky.lookup_linke_turbidity(
times, self.latitude, self.longitude,
interp_turbidity=interp_turbidity)
try:
airmass_absolute = kwargs.pop('airmass_absolute')
except KeyError:
airmass_absolute = self.get_airmass(
times, solar_position=solar_position)['airmass_absolute']
cs = clearsky.ineichen(apparent_zenith, airmass_absolute,
linke_turbidity, altitude=self.altitude,
dni_extra=dni_extra, **kwargs)
elif model == 'haurwitz':
cs = clearsky.haurwitz(apparent_zenith)
elif model == 'simplified_solis':
cs = clearsky.simplified_solis(
apparent_elevation, pressure=pressure, dni_extra=dni_extra,
**kwargs)
else:
raise ValueError('{} is not a valid clear sky model. Must be '
'one of ineichen, simplified_solis, haurwitz'
.format(model))
return cs
def get_airmass(self, times=None, solar_position=None,
model='kastenyoung1989'):
"""
Calculate the relative and absolute airmass.
Automatically chooses zenith or apparant zenith
depending on the selected model.
Parameters
----------
times : None or DatetimeIndex, default None
Only used if solar_position is not provided.
solar_position : None or DataFrame, default None
DataFrame with with columns 'apparent_zenith', 'zenith'.
model : str, default 'kastenyoung1989'
Relative airmass model. See
:py:func:`pvlib.atmosphere.get_relative_airmass`
for a list of available models.
Returns
-------
airmass : DataFrame
Columns are 'airmass_relative', 'airmass_absolute'
See also
--------
pvlib.atmosphere.get_relative_airmass
"""
if solar_position is None:
solar_position = self.get_solarposition(times)
if model in atmosphere.APPARENT_ZENITH_MODELS:
zenith = solar_position['apparent_zenith']
elif model in atmosphere.TRUE_ZENITH_MODELS:
zenith = solar_position['zenith']
else:
raise ValueError(f'{model} is not a valid airmass model')
airmass_relative = atmosphere.get_relative_airmass(zenith, model)
pressure = atmosphere.alt2pres(self.altitude)
airmass_absolute = atmosphere.get_absolute_airmass(airmass_relative,
pressure)
airmass = pd.DataFrame(index=solar_position.index)
airmass['airmass_relative'] = airmass_relative
airmass['airmass_absolute'] = airmass_absolute
return airmass
def get_sun_rise_set_transit(self, times, method='pyephem', **kwargs):
"""
Calculate sunrise, sunset and transit times.
Parameters
----------
times : DatetimeIndex
Must be localized to the Location
method : str, default 'pyephem'
'pyephem', 'spa', or 'geometric'
kwargs are passed to the relevant functions. See
solarposition.sun_rise_set_transit_<method> for details.
Returns
-------
result : DataFrame
Column names are: ``sunrise, sunset, transit``.
"""
if method == 'pyephem':
result = solarposition.sun_rise_set_transit_ephem(
times, self.latitude, self.longitude, **kwargs)
elif method == 'spa':
result = solarposition.sun_rise_set_transit_spa(
times, self.latitude, self.longitude, **kwargs)
elif method == 'geometric':
sr, ss, tr = solarposition.sun_rise_set_transit_geometric(
times, self.latitude, self.longitude, **kwargs)
result = pd.DataFrame(index=times,
data={'sunrise': sr,
'sunset': ss,
'transit': tr})
else:
raise ValueError('{} is not a valid method. Must be '
'one of pyephem, spa, geometric'
.format(method))
return result