-
Notifications
You must be signed in to change notification settings - Fork 947
/
tools.py
427 lines (341 loc) · 10.8 KB
/
tools.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
"""
Collection of functions used in pvlib_python
"""
from collections import namedtuple
import datetime as dt
import warnings
import numpy as np
import pandas as pd
import pytz
def cosd(angle):
"""
Cosine with angle input in degrees
Parameters
----------
angle : float or array-like
Angle in degrees
Returns
-------
result : float or array-like
Cosine of the angle
"""
res = np.cos(np.radians(angle))
return res
def sind(angle):
"""
Sine with angle input in degrees
Parameters
----------
angle : float
Angle in degrees
Returns
-------
result : float
Sin of the angle
"""
res = np.sin(np.radians(angle))
return res
def tand(angle):
"""
Tan with angle input in degrees
Parameters
----------
angle : float
Angle in degrees
Returns
-------
result : float
Tan of the angle
"""
res = np.tan(np.radians(angle))
return res
def asind(number):
"""
Inverse Sine returning an angle in degrees
Parameters
----------
number : float
Input number
Returns
-------
result : float
arcsin result
"""
res = np.degrees(np.arcsin(number))
return res
def localize_to_utc(time, location):
"""
Converts or localizes a time series to UTC.
Parameters
----------
time : datetime.datetime, pandas.DatetimeIndex,
or pandas.Series/DataFrame with a DatetimeIndex.
location : pvlib.Location object
Returns
-------
pandas object localized to UTC.
"""
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = pytz.timezone(location.tz).localize(time)
time_utc = time.astimezone(pytz.utc)
else:
try:
time_utc = time.tz_convert('UTC')
except TypeError:
time_utc = time.tz_localize(location.tz).tz_convert('UTC')
return time_utc
def datetime_to_djd(time):
"""
Converts a datetime to the Dublin Julian Day
Parameters
----------
time : datetime.datetime
time to convert
Returns
-------
float
fractional days since 12/31/1899+0000
"""
if time.tzinfo is None:
time_utc = pytz.utc.localize(time)
else:
time_utc = time.astimezone(pytz.utc)
djd_start = pytz.utc.localize(dt.datetime(1899, 12, 31, 12))
djd = (time_utc - djd_start).total_seconds() * 1.0/(60 * 60 * 24)
return djd
def djd_to_datetime(djd, tz='UTC'):
"""
Converts a Dublin Julian Day float to a datetime.datetime object
Parameters
----------
djd : float
fractional days since 12/31/1899+0000
tz : str, default 'UTC'
timezone to localize the result to
Returns
-------
datetime.datetime
The resultant datetime localized to tz
"""
djd_start = pytz.utc.localize(dt.datetime(1899, 12, 31, 12))
utc_time = djd_start + dt.timedelta(days=djd)
return utc_time.astimezone(pytz.timezone(tz))
def _pandas_to_doy(pd_object):
"""
Finds the day of year for a pandas datetime-like object.
Useful for delayed evaluation of the dayofyear attribute.
Parameters
----------
pd_object : DatetimeIndex or Timestamp
Returns
-------
dayofyear
"""
return pd_object.dayofyear
def _doy_to_datetimeindex(doy, epoch_year=2014):
"""
Convert a day of year scalar or array to a pd.DatetimeIndex.
Parameters
----------
doy : numeric
Contains days of the year
Returns
-------
pd.DatetimeIndex
"""
doy = np.atleast_1d(doy).astype('float')
epoch = pd.Timestamp('{}-12-31'.format(epoch_year - 1))
timestamps = [epoch + dt.timedelta(days=adoy) for adoy in doy]
return pd.DatetimeIndex(timestamps)
def _datetimelike_scalar_to_doy(time):
return pd.DatetimeIndex([pd.Timestamp(time)]).dayofyear
def _datetimelike_scalar_to_datetimeindex(time):
return pd.DatetimeIndex([pd.Timestamp(time)])
def _scalar_out(arg):
if np.isscalar(arg):
output = arg
else: #
# works if it's a 1 length array and
# will throw a ValueError otherwise
output = np.asarray(arg).item()
return output
def _array_out(arg):
if isinstance(arg, pd.Series):
output = arg.values
else:
output = arg
return output
def _build_kwargs(keys, input_dict):
"""
Parameters
----------
keys : iterable
Typically a list of strings.
adict : dict-like
A dictionary from which to attempt to pull each key.
Returns
-------
kwargs : dict
A dictionary with only the keys that were in input_dict
"""
kwargs = {}
for key in keys:
try:
kwargs[key] = input_dict[key]
except KeyError:
pass
return kwargs
# FIXME: remove _array_newton when SciPy-1.2.0 is released
# pvlib.singlediode.bishop88_i_from_v(..., method='newton') and other
# functions in singlediode call scipy.optimize.newton with a vector
# unfortunately wrapping the functions with np.vectorize() was too slow
# a vectorized newton method was merged into SciPy but isn't released yet, so
# in the meantime, we just copied the relevant code: "_array_newton" for more
# info see: https://github.com/scipy/scipy/pull/8357
def _array_newton(func, x0, fprime, args, tol, maxiter, fprime2,
converged=False):
"""
A vectorized version of Newton, Halley, and secant methods for arrays. Do
not use this method directly. This method is called from :func:`newton`
when ``np.isscalar(x0)`` is true. For docstring, see :func:`newton`.
"""
try:
p = np.asarray(x0, dtype=float)
except TypeError: # can't convert complex to float
p = np.asarray(x0)
failures = np.ones_like(p, dtype=bool) # at start, nothing converged
nz_der = np.copy(failures)
if fprime is not None:
# Newton-Raphson method
for iteration in range(maxiter):
# first evaluate fval
fval = np.asarray(func(p, *args))
# If all fval are 0, all roots have been found, then terminate
if not fval.any():
failures = fval.astype(bool)
break
fder = np.asarray(fprime(p, *args))
nz_der = (fder != 0)
# stop iterating if all derivatives are zero
if not nz_der.any():
break
# Newton step
dp = fval[nz_der] / fder[nz_der]
if fprime2 is not None:
fder2 = np.asarray(fprime2(p, *args))
dp = dp / (1.0 - 0.5 * dp * fder2[nz_der] / fder[nz_der])
# only update nonzero derivatives
p[nz_der] -= dp
failures[nz_der] = np.abs(dp) >= tol # items not yet converged
# stop iterating if there aren't any failures, not incl zero der
if not failures[nz_der].any():
break
else:
# Secant method
dx = np.finfo(float).eps**0.33
p1 = p * (1 + dx) + np.where(p >= 0, dx, -dx)
q0 = np.asarray(func(p, *args))
q1 = np.asarray(func(p1, *args))
active = np.ones_like(p, dtype=bool)
for iteration in range(maxiter):
nz_der = (q1 != q0)
# stop iterating if all derivatives are zero
if not nz_der.any():
p = (p1 + p) / 2.0
break
# Secant Step
dp = (q1 * (p1 - p))[nz_der] / (q1 - q0)[nz_der]
# only update nonzero derivatives
p[nz_der] = p1[nz_der] - dp
active_zero_der = ~nz_der & active
p[active_zero_der] = (p1 + p)[active_zero_der] / 2.0
active &= nz_der # don't assign zero derivatives again
failures[nz_der] = np.abs(dp) >= tol # not yet converged
# stop iterating if there aren't any failures, not incl zero der
if not failures[nz_der].any():
break
p1, p = p, p1
q0 = q1
q1 = np.asarray(func(p1, *args))
zero_der = ~nz_der & failures # don't include converged with zero-ders
if zero_der.any():
# secant warnings
if fprime is None:
nonzero_dp = (p1 != p)
# non-zero dp, but infinite newton step
zero_der_nz_dp = (zero_der & nonzero_dp)
if zero_der_nz_dp.any():
rms = np.sqrt(
sum((p1[zero_der_nz_dp] - p[zero_der_nz_dp]) ** 2)
)
warnings.warn('RMS of {:g} reached'.format(rms),
RuntimeWarning)
# newton or halley warnings
else:
all_or_some = 'all' if zero_der.all() else 'some'
msg = '{:s} derivatives were zero'.format(all_or_some)
warnings.warn(msg, RuntimeWarning)
elif failures.any():
all_or_some = 'all' if failures.all() else 'some'
msg = '{0:s} failed to converge after {1:d} iterations'.format(
all_or_some, maxiter
)
if failures.all():
raise RuntimeError(msg)
warnings.warn(msg, RuntimeWarning)
if converged:
result = namedtuple('result', ('root', 'converged', 'zero_der'))
p = result(p, ~failures, zero_der)
return p
# Created April,2014
# Author: Rob Andrews, Calama Consulting
def _golden_sect_DataFrame(params, VL, VH, func):
"""
Vectorized golden section search for finding MPP from a dataframe
timeseries.
Parameters
----------
params : dict
Dictionary containing scalars or arrays
of inputs to the function to be optimized.
Each row should represent an independent optimization.
VL: float
Lower bound of the optimization
VH: float
Upper bound of the optimization
func: function
Function to be optimized must be in the form f(array-like, x)
Returns
-------
func(df,'V1') : DataFrame
function evaluated at the optimal point
df['V1']: Dataframe
Dataframe of optimal points
Notes
-----
This function will find the MAXIMUM of a function
"""
df = params
df['VH'] = VH
df['VL'] = VL
errflag = True
iterations = 0
while errflag:
phi = (np.sqrt(5)-1)/2*(df['VH']-df['VL'])
df['V1'] = df['VL'] + phi
df['V2'] = df['VH'] - phi
df['f1'] = func(df, 'V1')
df['f2'] = func(df, 'V2')
df['SW_Flag'] = df['f1'] > df['f2']
df['VL'] = df['V2']*df['SW_Flag'] + df['VL']*(~df['SW_Flag'])
df['VH'] = df['V1']*~df['SW_Flag'] + df['VH']*(df['SW_Flag'])
err = df['V1'] - df['V2']
try:
errflag = (abs(err) > .01).any()
except ValueError:
errflag = (abs(err) > .01)
iterations += 1
if iterations > 50:
raise Exception("EXCEPTION:iterations exceeded maximum (50)")
return func(df, 'V1'), df['V1']