INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Determine DNI from GHI and DHI.
When calculating the DNI from GHI and DHI the calculated DNI may be
unreasonably high or negative for zenith angles close to 90 degrees
(sunrise/sunset transitions). This function identifies unreasonable DNI
values and sets them to NaN. If the clearsky DNI is given unrea... | def dni(ghi, dhi, zenith, clearsky_dni=None, clearsky_tolerance=1.1,
zenith_threshold_for_zero_dni=88.0,
zenith_threshold_for_clearsky_limit=80.0):
"""
Determine DNI from GHI and DHI.
When calculating the DNI from GHI and DHI the calculated DNI may be
unreasonably high or negative for z... |
Determine clear sky GHI, DNI, and DHI from Ineichen/Perez model.
Implements the Ineichen and Perez clear sky model for global
horizontal irradiance (GHI), direct normal irradiance (DNI), and
calculates the clear-sky diffuse horizontal (DHI) component as the
difference between GHI and DNI*cos(zenith) as... | def ineichen(apparent_zenith, airmass_absolute, linke_turbidity,
altitude=0, dni_extra=1364., perez_enhancement=False):
'''
Determine clear sky GHI, DNI, and DHI from Ineichen/Perez model.
Implements the Ineichen and Perez clear sky model for global
horizontal irradiance (GHI), direct norm... |
Look up the Linke Turibidity from the ``LinkeTurbidities.h5``
data file supplied with pvlib.
Parameters
----------
time : pandas.DatetimeIndex
latitude : float
longitude : float
filepath : None or string, default None
The path to the ``.h5`` file.
interp_turbidity : bool, de... | def lookup_linke_turbidity(time, latitude, longitude, filepath=None,
interp_turbidity=True):
"""
Look up the Linke Turibidity from the ``LinkeTurbidities.h5``
data file supplied with pvlib.
Parameters
----------
time : pandas.DatetimeIndex
latitude : float
l... |
Determine if a year is leap year.
Parameters
----------
year : numeric
Returns
-------
isleap : array of bools | def _is_leap_year(year):
"""Determine if a year is leap year.
Parameters
----------
year : numeric
Returns
-------
isleap : array of bools
"""
isleap = ((np.mod(year, 4) == 0) &
((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))
return isleap |
Interpolated monthly Linke turbidity onto daily values.
Parameters
----------
lts : np.array
Monthly Linke turbidity values.
time : pd.DatetimeIndex
Times to be interpolated onto.
Returns
-------
linke_turbidity : pd.Series
The interpolated turbidity. | def _interpolate_turbidity(lts, time):
"""
Interpolated monthly Linke turbidity onto daily values.
Parameters
----------
lts : np.array
Monthly Linke turbidity values.
time : pd.DatetimeIndex
Times to be interpolated onto.
Returns
-------
linke_turbidity : pd.Series... |
List of middle day of each month, used by Linke turbidity lookup | def _calendar_month_middles(year):
"""List of middle day of each month, used by Linke turbidity lookup"""
# remove mdays[0] since January starts at mdays[1]
# make local copy of mdays since we need to change
# February for leap years
mdays = np.array(calendar.mdays[1:])
ydays = 365
# handle ... |
linearly scale input to output, used by Linke turbidity lookup | def _linearly_scale(inputmatrix, inputmin, inputmax, outputmin, outputmax):
"""linearly scale input to output, used by Linke turbidity lookup"""
inputrange = inputmax - inputmin
outputrange = outputmax - outputmin
delta = outputrange/inputrange # number of indices per input unit
inputmin = inputmin... |
Determine clear sky GHI using the Haurwitz model.
Implements the Haurwitz clear sky model for global horizontal
irradiance (GHI) as presented in [1, 2]. A report on clear
sky models found the Haurwitz model to have the best performance
in terms of average monthly error among models which require only
... | def haurwitz(apparent_zenith):
'''
Determine clear sky GHI using the Haurwitz model.
Implements the Haurwitz clear sky model for global horizontal
irradiance (GHI) as presented in [1, 2]. A report on clear
sky models found the Haurwitz model to have the best performance
in terms of average mont... |
Calculate the clear sky GHI, DNI, and DHI according to the
simplified Solis model [1]_.
Reference [1]_ describes the accuracy of the model as being 15, 20,
and 18 W/m^2 for the beam, global, and diffuse components. Reference
[2]_ provides comparisons with other clear sky models.
Parameters
---... | def simplified_solis(apparent_elevation, aod700=0.1, precipitable_water=1.,
pressure=101325., dni_extra=1364.):
"""
Calculate the clear sky GHI, DNI, and DHI according to the
simplified Solis model [1]_.
Reference [1]_ describes the accuracy of the model as being 15, 20,
and 18... |
Calculate the "enhanced extraterrestrial irradiance". | def _calc_i0p(i0, w, aod700, p):
"""Calculate the "enhanced extraterrestrial irradiance"."""
p0 = 101325.
io0 = 1.08 * w**0.0051
i01 = 0.97 * w**0.032
i02 = 0.12 * w**0.56
i0p = i0 * (i02*aod700**2 + i01*aod700 + io0 + 0.071*np.log(p/p0))
return i0p |
Calculate the taub coefficient | def _calc_taub(w, aod700, p):
"""Calculate the taub coefficient"""
p0 = 101325.
tb1 = 1.82 + 0.056*np.log(w) + 0.0071*np.log(w)**2
tb0 = 0.33 + 0.045*np.log(w) + 0.0096*np.log(w)**2
tbp = 0.0089*w + 0.13
taub = tb1*aod700 + tb0 + tbp*np.log(p/p0)
return taub |
Calculate the b coefficient. | def _calc_b(w, aod700):
"""Calculate the b coefficient."""
b1 = 0.00925*aod700**2 + 0.0148*aod700 - 0.0172
b0 = -0.7565*aod700**2 + 0.5057*aod700 + 0.4557
b = b1 * np.log(w) + b0
return b |
Calculate the taug coefficient | def _calc_taug(w, aod700, p):
"""Calculate the taug coefficient"""
p0 = 101325.
tg1 = 1.24 + 0.047*np.log(w) + 0.0061*np.log(w)**2
tg0 = 0.27 + 0.043*np.log(w) + 0.0090*np.log(w)**2
tgp = 0.0079*w + 0.1
taug = tg1*aod700 + tg0 + tgp*np.log(p/p0)
return taug |
Calculate the g coefficient. | def _calc_g(w, aod700):
"""Calculate the g coefficient."""
g = -0.0147*np.log(w) - 0.3079*aod700**2 + 0.2846*aod700 + 0.3798
return g |
Calculate the taud coefficient. | def _calc_taud(w, aod700, p):
"""Calculate the taud coefficient."""
# isscalar tests needed to ensure that the arrays will have the
# right shape in the tds calculation.
# there's probably a better way to do this.
if np.isscalar(w) and np.isscalar(aod700):
w = np.array([w])
aod700 ... |
Calculate the d coefficient. | def _calc_d(aod700, p):
"""Calculate the d coefficient."""
p0 = 101325.
dp = 1/(18 + 152*aod700)
d = -0.337*aod700**2 + 0.63*aod700 + 0.116 + dp*np.log(p/p0)
return d |
Detects clear sky times according to the algorithm developed by Reno
and Hansen for GHI measurements [1]. The algorithm was designed and
validated for analyzing GHI time series only. Users may attempt to
apply it to other types of time series data using different filter
settings, but should be skeptical... | def detect_clearsky(measured, clearsky, times, window_length,
mean_diff=75, max_diff=75,
lower_line_length=-5, upper_line_length=10,
var_diff=0.005, slope_dev=8, max_iterations=20,
return_components=False):
"""
Detects clear sky tim... |
Bird Simple Clear Sky Broadband Solar Radiation Model
Based on NREL Excel implementation by Daryl R. Myers [1, 2].
Bird and Hulstrom define the zenith as the "angle between a line to
the sun and the local zenith". There is no distinction in the paper
between solar zenith and apparent (or refracted) ze... | def bird(zenith, airmass_relative, aod380, aod500, precipitable_water,
ozone=0.3, pressure=101325., dni_extra=1364., asymmetry=0.85,
albedo=0.2):
"""
Bird Simple Clear Sky Broadband Solar Radiation Model
Based on NREL Excel implementation by Daryl R. Myers [1, 2].
Bird and Hulstrom d... |
Read in a daily NOAA SURFRAD[1] file.
Parameters
----------
filename: str
Filepath or url.
map_variables: bool
When true, renames columns of the Dataframe to pvlib variable names
where applicable. See variable SURFRAD_COLUMNS.
Returns
-------
Tuple of the form (data... | def read_surfrad(filename, map_variables=True):
"""Read in a daily NOAA SURFRAD[1] file.
Parameters
----------
filename: str
Filepath or url.
map_variables: bool
When true, renames columns of the Dataframe to pvlib variable names
where applicable. See variable SURFRAD_COLUMN... |
Create UTC localized DatetimeIndex for the dataframe.
Parameters
----------
data: Dataframe
Must contain columns 'year', 'jday', 'hour' and
'minute'.
Return
------
data: Dataframe
Dataframe with a DatetimeIndex localized to UTC. | def format_index(data):
"""Create UTC localized DatetimeIndex for the dataframe.
Parameters
----------
data: Dataframe
Must contain columns 'year', 'jday', 'hour' and
'minute'.
Return
------
data: Dataframe
Dataframe with a DatetimeIndex localized to UTC.
"""
... |
Used to display deprecation in a standard way.
Parameters
----------
since : str
The release at which this API became deprecated.
message : str, optional
Override the default deprecation message. The format
specifier `%(name)s` may be used for the name of the function,
a... | def warn_deprecated(
since, message='', name='', alternative='', pending=False,
obj_type='attribute', addendum='', removal=''):
"""
Used to display deprecation in a standard way.
Parameters
----------
since : str
The release at which this API became deprecated.
message : ... |
Decorator to mark a function or a class as deprecated.
Parameters
----------
since : str
The release at which this API became deprecated. This is
required.
message : str, optional
Override the default deprecation message. The format
specifier `%(name)s` may be used for ... | def deprecated(since, message='', name='', alternative='', pending=False,
addendum='', removal=''):
"""
Decorator to mark a function or a class as deprecated.
Parameters
----------
since : str
The release at which this API became deprecated. This is
required.
mess... |
A mapper function to rename Dataframe columns to their pvlib counterparts.
Parameters
----------
variable_map: Dictionary
A dictionary for mapping MIDC field name to pvlib name. See
VARIABLE_MAP for default value and description of how to construct
this argument.
field_name: str... | def map_midc_to_pvlib(variable_map, field_name):
"""A mapper function to rename Dataframe columns to their pvlib counterparts.
Parameters
----------
variable_map: Dictionary
A dictionary for mapping MIDC field name to pvlib name. See
VARIABLE_MAP for default value and description of how... |
Create DatetimeIndex for the Dataframe localized to the timezone provided
as the label of the second (time) column.
Parameters
----------
data: Dataframe
Must contain 'DATE (MM/DD/YYYY)' column, second column must be labeled
with the timezone and contain times in 'HH:MM' format.
Re... | def format_index(data):
"""Create DatetimeIndex for the Dataframe localized to the timezone provided
as the label of the second (time) column.
Parameters
----------
data: Dataframe
Must contain 'DATE (MM/DD/YYYY)' column, second column must be labeled
with the timezone and contain t... |
Create DatetimeIndex for the Dataframe localized to the timezone provided
as the label of the third column.
Parameters
----------
data: Dataframe
Must contain columns 'Year' and 'DOY'. Timezone must be found as the
label of the third (time) column.
Returns
-------
data: Dat... | def format_index_raw(data):
"""Create DatetimeIndex for the Dataframe localized to the timezone provided
as the label of the third column.
Parameters
----------
data: Dataframe
Must contain columns 'Year' and 'DOY'. Timezone must be found as the
label of the third (time) column.
... |
Read in National Renewable Energy Laboratory Measurement and
Instrumentation Data Center [1]_ weather data.
Parameters
----------
filename: string
Filename or url of data to read.
variable_map: dictionary
Dictionary for mapping MIDC field names to pvlib names. See variable
`... | def read_midc(filename, variable_map=VARIABLE_MAP, raw_data=False):
"""Read in National Renewable Energy Laboratory Measurement and
Instrumentation Data Center [1]_ weather data.
Parameters
----------
filename: string
Filename or url of data to read.
variable_map: dictionary
Dic... |
Request and read MIDC data directly from the raw data api.
Parameters
----------
site: string
The MIDC station id.
start: datetime
Start date for requested data.
end: datetime
End date for requested data.
Returns
-------
data:
Dataframe with DatetimeInde... | def read_midc_raw_data_from_nrel(site, start, end):
"""Request and read MIDC data directly from the raw data api.
Parameters
----------
site: string
The MIDC station id.
start: datetime
Start date for requested data.
end: datetime
End date for requested data.
Return... |
Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun zenith angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is not included or is
not valid, the default model is 'kastenyoung1989'.
... | def get_relative_airmass(zenith, model='kastenyoung1989'):
'''
Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun zenith angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is not i... |
r"""
Calculates precipitable water (cm) from ambient air temperature (C)
and relatively humidity (%) using an empirical model. The
accuracy of this method is approximately 20% for moderate PW (1-3
cm) and less accurate otherwise.
The model was developed by expanding Eq. 1 in [2]_:
.. math::
... | def gueymard94_pw(temp_air, relative_humidity):
r"""
Calculates precipitable water (cm) from ambient air temperature (C)
and relatively humidity (%) using an empirical model. The
accuracy of this method is approximately 20% for moderate PW (1-3
cm) and less accurate otherwise.
The model was dev... |
r"""
Spectral mismatch modifier based on precipitable water and absolute
(pressure corrected) airmass.
Estimates a spectral mismatch modifier M representing the effect on
module short circuit current of variation in the spectral
irradiance. M is estimated from absolute (pressure currected) air
... | def first_solar_spectral_correction(pw, airmass_absolute, module_type=None,
coefficients=None):
r"""
Spectral mismatch modifier based on precipitable water and absolute
(pressure corrected) airmass.
Estimates a spectral mismatch modifier M representing the effect on
... |
Calculate Linke turbidity factor using Kasten pyrheliometric formula.
Note that broadband aerosol optical depth (AOD) can be approximated by AOD
measured at 700 nm according to Molineaux [4] . Bird and Hulstrom offer an
alternate approximation using AOD measured at 380 nm and 500 nm.
Based on original... | def kasten96_lt(airmass_absolute, precipitable_water, aod_bb):
"""
Calculate Linke turbidity factor using Kasten pyrheliometric formula.
Note that broadband aerosol optical depth (AOD) can be approximated by AOD
measured at 700 nm according to Molineaux [4] . Bird and Hulstrom offer an
alternate ap... |
r"""
Calculate Angstrom alpha exponent.
Parameters
----------
aod1 : numeric
first aerosol optical depth
lambda1 : numeric
wavelength in nanometers corresponding to ``aod1``
aod2 : numeric
second aerosol optical depth
lambda2 : numeric
wavelength in nanometer... | def angstrom_alpha(aod1, lambda1, aod2, lambda2):
r"""
Calculate Angstrom alpha exponent.
Parameters
----------
aod1 : numeric
first aerosol optical depth
lambda1 : numeric
wavelength in nanometers corresponding to ``aod1``
aod2 : numeric
second aerosol optical depth... |
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. | 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 loca... |
Converts a datetime to the Dublin Julian Day
Parameters
----------
time : datetime.datetime
time to convert
Returns
-------
float
fractional days since 12/31/1899+0000 | 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.locali... |
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 t... | 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.datet... |
Convert a day of year scalar or array to a pd.DatetimeIndex.
Parameters
----------
doy : numeric
Contains days of the year
Returns
-------
pd.DatetimeIndex | 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.T... |
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 | 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_dic... |
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`. | 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 ... |
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
Lowe... | 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 repr... |
Determine the rotation angle of a single axis tracker using the
equations in [1] when given a particular sun zenith and azimuth
angle. backtracking may be specified, and if so, a ground coverage
ratio is required.
Rotation angle is determined in a panel-oriented coordinate system.
The tracker azimu... | def singleaxis(apparent_zenith, apparent_azimuth,
axis_tilt=0, axis_azimuth=0, max_angle=90,
backtrack=True, gcr=2.0/7.0):
"""
Determine the rotation angle of a single axis tracker using the
equations in [1] when given a particular sun zenith and azimuth
angle. backtracking... |
Get tracking data. See :py:func:`pvlib.tracking.singleaxis` more
detail.
Parameters
----------
apparent_zenith : float, 1d array, or Series
Solar apparent zenith angles in decimal degrees.
apparent_azimuth : float, 1d array, or Series
Solar apparent azim... | def singleaxis(self, apparent_zenith, apparent_azimuth):
"""
Get tracking data. See :py:func:`pvlib.tracking.singleaxis` more
detail.
Parameters
----------
apparent_zenith : float, 1d array, or Series
Solar apparent zenith angles in decimal degrees.
... |
Uses the :func:`irradiance.get_total_irradiance` function to
calculate the plane of array irradiance components on a tilted
surface defined by the input data and ``self.albedo``.
For a given set of solar zenith and azimuth angles, the
surface tilt and azimuth parameters are typically de... | def get_irradiance(self, surface_tilt, surface_azimuth,
solar_zenith, solar_azimuth, dni, ghi, dhi,
dni_extra=None, airmass=None, model='haydavies',
**kwargs):
"""
Uses the :func:`irradiance.get_total_irradiance` function to
ca... |
Read University of Oregon SRML[1] 1min .tsv file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the tsv file.
Returns
-------
data: Dataframe
A dataframe with datetime index and all of the variables listed
in the `VARIABLE_MAP` di... | def read_srml(filename):
"""
Read University of Oregon SRML[1] 1min .tsv file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the tsv file.
Returns
-------
data: Dataframe
A dataframe with datetime index and all of the variables li... |
Map data element numbers to pvlib names.
Parameters
----------
col: str
Column label to be mapped.
Returns
-------
str
The pvlib label if it was found in the mapping,
else the original label. | def map_columns(col):
"""Map data element numbers to pvlib names.
Parameters
----------
col: str
Column label to be mapped.
Returns
-------
str
The pvlib label if it was found in the mapping,
else the original label.
"""
if col.startswith('7'):
# spe... |
Create a datetime index from day of year, and time columns.
Parameters
----------
df: pd.Dataframe
The srml data to reindex.
Returns
-------
df: pd.Dataframe
The Dataframe with a DatetimeIndex localized to 'Etc/GMT+8'. | def format_index(df):
"""Create a datetime index from day of year, and time columns.
Parameters
----------
df: pd.Dataframe
The srml data to reindex.
Returns
-------
df: pd.Dataframe
The Dataframe with a DatetimeIndex localized to 'Etc/GMT+8'.
"""
# Name of the seco... |
Request a month of SRML[1] data from solardat and read it into
a Dataframe.
Parameters
----------
station: str
The name of the SRML station to request.
year: int
Year to request data for
month: int
Month to request data for.
filetype: string
SRML file type to... | def read_srml_month_from_solardat(station, year, month, filetype='PO'):
"""Request a month of SRML[1] data from solardat and read it into
a Dataframe.
Parameters
----------
station: str
The name of the SRML station to request.
year: int
Year to request data for
month: int
... |
Download data from ECMWF MACC Reanalysis API.
Parameters
----------
filename : str
full path of file where to save data, ``.nc`` appended if not given
params : str or sequence of str
keynames of parameter[s] to download
startdate : datetime.datetime or datetime.date
UTC date... | def get_ecmwf_macc(filename, params, startdate, stopdate, lookup_params=True,
server=None, target=_ecmwf):
"""
Download data from ECMWF MACC Reanalysis API.
Parameters
----------
filename : str
full path of file where to save data, ``.nc`` appended if not given
params... |
Read data from ECMWF MACC reanalysis netCDF4 file.
Parameters
----------
filename : string
full path to netCDF4 data file.
latitude : float
latitude in degrees
longitude : float
longitude in degrees
utc_time_range : sequence of datetime.datetime
pair of start and... | def read_ecmwf_macc(filename, latitude, longitude, utc_time_range=None):
"""
Read data from ECMWF MACC reanalysis netCDF4 file.
Parameters
----------
filename : string
full path to netCDF4 data file.
latitude : float
latitude in degrees
longitude : float
longitude in... |
Get nearest indices to (latitude, longitude).
Parmaeters
----------
latitude : float
Latitude in degrees
longitude : float
Longitude in degrees
Returns
-------
idx_lat : int
index of nearest latitude
idx_lon : int
... | def get_nearest_indices(self, latitude, longitude):
"""
Get nearest indices to (latitude, longitude).
Parmaeters
----------
latitude : float
Latitude in degrees
longitude : float
Longitude in degrees
Returns
-------
idx_la... |
Interpolate ``param`` values to ``utc_time`` using indices nearest to
(``latitude, longitude``).
Parmaeters
----------
latitude : float
Latitude in degrees
longitude : float
Longitude in degrees
utc_time : datetime.datetime or datetime.date
... | def interp_data(self, latitude, longitude, utc_time, param):
"""
Interpolate ``param`` values to ``utc_time`` using indices nearest to
(``latitude, longitude``).
Parmaeters
----------
latitude : float
Latitude in degrees
longitude : float
... |
Read NOAA SOLRAD [1]_ [2]_ fixed-width file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the fixed-width file.
Returns
-------
data: Dataframe
A dataframe with DatetimeIndex and all of the variables in the
file.
Notes
-... | def read_solrad(filename):
"""
Read NOAA SOLRAD [1]_ [2]_ fixed-width file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the fixed-width file.
Returns
-------
data: Dataframe
A dataframe with DatetimeIndex and all of the variable... |
Read NOAA USCRN [1]_ [2]_ fixed-width file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the fixed-width file.
Returns
-------
data: Dataframe
A dataframe with DatetimeIndex and all of the variables in the
file.
Notes
--... | def read_crn(filename):
"""
Read NOAA USCRN [1]_ [2]_ fixed-width file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the fixed-width file.
Returns
-------
data: Dataframe
A dataframe with DatetimeIndex and all of the variables in... |
Read an EPW file in to a pandas dataframe.
Note that values contained in the metadata dictionary are unchanged
from the EPW file.
EPW files are commonly used by building simulation professionals
and are widely available on the web. For example via:
https://energyplus.net/weather , http://climate.o... | def read_epw(filename, coerce_year=None):
'''
Read an EPW file in to a pandas dataframe.
Note that values contained in the metadata dictionary are unchanged
from the EPW file.
EPW files are commonly used by building simulation professionals
and are widely available on the web. For example via:... |
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.
... | 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 DataF... |
Uses the :py:func:`solarposition.get_solarposition` function
to calculate the solar zenith, azimuth, etc. at this location.
Parameters
----------
times : DatetimeIndex
pressure : None, float, or array-like, default None
If None, pressure will be calculated using
... | 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 : DatetimeIn... |
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_posi... | 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 'in... |
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... | 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 : N... |
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
solarposi... | 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',... |
This is the original way to calculate the julian day from the NREL paper.
However, it is much faster to convert to unix/epoch time and then convert
to julian day. Note that the date must be UTC. | def julian_day_dt(year, month, day, hour, minute, second, microsecond):
"""This is the original way to calculate the julian day from the NREL paper.
However, it is much faster to convert to unix/epoch time and then convert
to julian day. Note that the date must be UTC."""
if month <= 2:
year = y... |
Loop through the time array and calculate the solar position | def solar_position_loop(unixtime, loc_args, out):
"""Loop through the time array and calculate the solar position"""
lat = loc_args[0]
lon = loc_args[1]
elev = loc_args[2]
pressure = loc_args[3]
temp = loc_args[4]
delta_t = loc_args[5]
atmos_refract = loc_args[6]
sst = loc_args[7]
... |
Calculate the solar position using the numba compiled functions
and multiple threads. Very slow if functions are not numba compiled. | def solar_position_numba(unixtime, lat, lon, elev, pressure, temp, delta_t,
atmos_refract, numthreads, sst=False, esd=False):
"""Calculate the solar position using the numba compiled functions
and multiple threads. Very slow if functions are not numba compiled.
"""
# these args ... |
Calculates the distance from the earth to the sun using the
NREL SPA algorithm described in [1].
Parameters
----------
unixtime : numpy array
Array of unix/epoch timestamps to calculate solar position for.
Unixtime is the number of seconds since Jan. 1, 1970 00:00:00 UTC.
A pand... | def earthsun_distance(unixtime, delta_t, numthreads):
"""
Calculates the distance from the earth to the sun using the
NREL SPA algorithm described in [1].
Parameters
----------
unixtime : numpy array
Array of unix/epoch timestamps to calculate solar position for.
Unixtime is the... |
Calculate the difference between Terrestrial Dynamical Time (TD)
and Universal Time (UT).
Note: This function is not yet compatible for calculations using
Numba.
Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html | def calculate_deltat(year, month):
"""Calculate the difference between Terrestrial Dynamical Time (TD)
and Universal Time (UT).
Note: This function is not yet compatible for calculations using
Numba.
Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html
"""
plw = 'Delta... |
Calculate front and back surface plane-of-array irradiance on
a fixed tilt or single-axis tracker PV array configuration, and using
the open-source "pvfactors" package.
Please refer to pvfactors online documentation for more details:
https://sunpower.github.io/pvfactors/
Parameters
----------
... | def pvfactors_timeseries(
solar_azimuth, solar_zenith, surface_azimuth, surface_tilt,
timestamps, dni, dhi, gcr, pvrow_height, pvrow_width, albedo,
n_pvrows=3, index_observed_pvrow=1,
rho_front_pvrow=0.03, rho_back_pvrow=0.05,
horizon_band_angle=15.,
run_parallel_calculat... |
File based sample for the Google Assistant API.
Examples:
$ python -m audiofileinput -i <input file> -o <output file> | def main(api_endpoint, credentials,
device_model_id, device_id, lang, verbose,
input_audio_file, output_audio_file,
block_size, grpc_deadline, *args, **kwargs):
"""File based sample for the Google Assistant API.
Examples:
$ python -m audiofileinput -i <input file> -o <output fi... |
Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process. | def process_event(event):
"""Pretty prints events.
Prints all events that occur with two spaces between each new
conversation and a single space between turns of a conversation.
Args:
event(event.Event): The current event to process.
"""
if event.type == EventType.ON_CONVERSATION_TURN_... |
Build ClickException from a failed request. | def failed_request_exception(message, r):
"""Build ClickException from a failed request."""
try:
resp = json.loads(r.text)
message = '%s: %d\n%s' % (message, resp['error']['code'],
resp['error']['message'])
return click.ClickException(message)
except... |
Prints out a device model in the terminal by parsing dict. | def pretty_print_model(devicemodel):
"""Prints out a device model in the terminal by parsing dict."""
PRETTY_PRINT_MODEL = """Device Model ID: %(deviceModelId)s
Project ID: %(projectId)s
Device Type: %(deviceType)s"""
logging.info(PRETTY_PRINT_MODEL % devicemodel)
if 'traits' in devicemo... |
Prints out a device instance in the terminal by parsing dict. | def pretty_print_device(device):
"""Prints out a device instance in the terminal by parsing dict."""
logging.info('Device Instance ID: %s' % device['id'])
if 'nickname' in device:
logging.info(' Nickname: %s' % device['nickname'])
if 'modelId' in device:
logging.info(' Model: %s' %... |
Registers a device model and instance.
Device model fields can only contain letters, numbers, and the following
symbols: period (.), hyphen (-), underscore (_), space ( ) and plus (+).
The first character of a field must be a letter or number.
Device instance fields must start with a letter or number.... | def register(ctx, model, type, trait, manufacturer, product_name, description,
device, nickname, client_type):
"""Registers a device model and instance.
Device model fields can only contain letters, numbers, and the following
symbols: period (.), hyphen (-), underscore (_), space ( ) and plus ... |
Registers a device model.
Device model fields can only contain letters, numbers, and the following
symbols: period (.), hyphen (-), underscore (_), space ( ) and plus (+).
The first character of a field must be a letter or number. | def register_model(ctx, model, type, trait,
manufacturer, product_name, description):
"""Registers a device model.
Device model fields can only contain letters, numbers, and the following
symbols: period (.), hyphen (-), underscore (_), space ( ) and plus (+).
The first character of ... |
Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
hyphen (-), underscore (_), and plus (+). The device nickname can only
contain numbers, letters,... | def register_device(ctx, device, model, nickname, client_type):
"""Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
hyphen (-), underscore (_), a... |
Gets all of the information (fields) for a given device model or
instance. | def get(ctx, resource, id):
"""Gets all of the information (fields) for a given device model or
instance.
"""
session, api_url, project_id = build_client_from_context(ctx)
url = '/'.join([api_url, resource, id])
r = session.get(url)
if r.status_code != 200:
raise failed_request_excep... |
Delete given device model or instance. | def delete(ctx, resource, id):
"""Delete given device model or instance.
"""
session, api_url, project_id = build_client_from_context(ctx)
url = '/'.join([api_url, resource, id])
r = session.delete(url)
if r.status_code != 200:
raise failed_request_exception('failed to delete resource', ... |
Initiates or continues a conversation with the embedded assistant service.
Each call performs one round-trip, sending an audio request to the service
and receiving the audio response. Uses bidirectional streaming to receive
results, such as the `END_OF_UTTERANCE` event, while sending audio.
A conversat... | def Converse(self, request_iterator, context):
"""Initiates or continues a conversation with the embedded assistant service.
Each call performs one round-trip, sending an audio request to the service
and receiving the audio response. Uses bidirectional streaming to receive
results, such as the `END_OF_U... |
Log AssistRequest fields without audio data. | def log_assist_request_without_audio(assist_request):
"""Log AssistRequest fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistRequest()
resp_copy.CopyFrom(assist_request)
if len(resp_copy.audio_in) > 0:
s... |
Log AssistResponse fields without audio data. | def log_assist_response_without_audio(assist_response):
"""Log AssistResponse fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistResponse()
resp_copy.CopyFrom(assist_response)
has_audio_data = (resp_copy.HasField('au... |
Register a device action handlers. | def command(self, intent):
"""Register a device action handlers."""
def decorator(fn):
self.handlers[intent] = fn
return decorator |
Submit device command executions.
Returns: a list of concurrent.futures for scheduled executions. | def submit_commands(self, devices, execution):
"""Submit device command executions.
Returns: a list of concurrent.futures for scheduled executions.
"""
fs = []
for device in devices:
if device[key_id_] != self.device_id:
logging.warning('Ignoring comm... |
Dispatch device commands to the appropriate handler. | def dispatch_command(self, command, params=None):
"""Dispatch device commands to the appropriate handler."""
try:
if command in self.handlers:
self.handlers[command](**params)
else:
logging.warning('Unsupported command: %s: %s',
... |
Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplitude by a factor of 0.414,
and 75% volume scales the amplitude by a fact... | def normalize_audio_buffer(buf, volume_percentage, sample_width=2):
"""Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplit... |
In case of buffer size not aligned to sample_width pad it with 0s | def align_buf(buf, sample_width):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf |
Helper command to test audio stream processing.
- Record 5 seconds of 16-bit samples at 16khz.
- Playback the recorded samples. | def main(record_time, audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size):
"""Helper command to test audio stream processing.
- Record 5 seconds of 16-bit samples at 16khz.
- Playback the recorded samples.
"""
end_time = time.time() + record_time
... |
Read bytes from the stream and block until sample rate is achieved.
Args:
size: number of bytes to read from the stream. | def read(self, size):
"""Read bytes from the stream and block until sample rate is achieved.
Args:
size: number of bytes to read from the stream.
"""
now = time.time()
missing_dt = self._sleep_until - now
if missing_dt > 0:
time.sleep(missing_dt)
... |
Close the underlying stream. | def close(self):
"""Close the underlying stream."""
if self._wavep:
self._wavep.close()
self._fp.close() |
Read bytes from the stream. | def read(self, size):
"""Read bytes from the stream."""
buf, overflow = self._audio_stream.read(size)
if overflow:
logging.warning('SoundDeviceStream read overflow (%d, %d)',
size, len(buf))
return bytes(buf) |
Write bytes to the stream. | def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) |
Close the underlying stream and audio interface. | def close(self):
"""Close the underlying stream and audio interface."""
if self._audio_stream:
self.stop()
self._audio_stream.close()
self._audio_stream = None |
Start recording from the audio source. | def start_recording(self):
"""Start recording from the audio source."""
self._recording = True
self._stop_recording.clear()
self._source.start() |
Stop recording from the audio source. | def stop_recording(self):
"""Stop recording from the audio source."""
self._stop_recording.set()
with self._source_lock:
self._source.stop()
self._recording = False |
Stop playback from the audio sink. | def stop_playback(self):
"""Stop playback from the audio sink."""
self._sink.flush()
self._sink.stop()
self._playing = False |
Write bytes to the sink (if currently playing). | def write(self, buf):
"""Write bytes to the sink (if currently playing).
"""
buf = align_buf(buf, self._sample_width)
buf = normalize_audio_buffer(buf, self.volume_percentage)
return self._sink.write(buf) |
Send a text request to the Assistant and playback the response. | def assist(self, text_query):
"""Send a text request to the Assistant and playback the response.
"""
def iter_assist_requests():
config = embedded_assistant_pb2.AssistConfig(
audio_out_config=embedded_assistant_pb2.AudioOutConfig(
encoding='LINEAR1... |
Samples for the Google Assistant API.
Examples:
Run the sample with microphone input and speaker output:
$ python -m googlesamples.assistant
Run the sample with file input and speaker output:
$ python -m googlesamples.assistant -i <input file>
Run the sample with file input an... | def main(api_endpoint, credentials, project_id,
device_model_id, device_id, device_config,
lang, display, verbose,
input_audio_file, output_audio_file,
audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size,
grpc_deadline, once, *... |
Send a voice request to the Assistant and playback the response.
Returns: True if conversation should continue. | def assist(self):
"""Send a voice request to the Assistant and playback the response.
Returns: True if conversation should continue.
"""
continue_conversation = False
device_actions_futures = []
self.conversation_stream.start_recording()
logging.info('Recording ... |
Yields: AssistRequest messages to send to the API. | def gen_assist_requests(self):
"""Yields: AssistRequest messages to send to the API."""
config = embedded_assistant_pb2.AssistConfig(
audio_in_config=embedded_assistant_pb2.AudioInConfig(
encoding='LINEAR16',
sample_rate_hertz=self.conversation_stream.sample_... |
Returns reconstructed X from low-rank thresholded SVD and
the rank achieved. | def _svd_step(self, X, shrinkage_value, max_rank=None):
"""
Returns reconstructed X from low-rank thresholded SVD and
the rank achieved.
"""
if max_rank:
# if we have a max rank then perform the faster randomized SVD
(U, s, V) = randomized_svd(
... |
Parameters
----------
X : np.array
Data array containing NaN entries
missing_mask : np.array
Boolean array indicating where NaN entries are
fill_method : str
"zero": fill missing entries with zeros
"mean": fill with column means
... | def fill(
self,
X,
missing_mask,
fill_method=None,
inplace=False):
"""
Parameters
----------
X : np.array
Data array containing NaN entries
missing_mask : np.array
Boolean array indicating where ... |
Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask. | def prepare_input_data(self, X):
"""
Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask.
"""
X = check_array(X, force_all_finite=False)
if X.dtype != "f" and X.dtype != "d":
X = X.astype(float)
... |
Clip values to fall within any global or column-wise min/max constraints | def clip(self, X):
"""
Clip values to fall within any global or column-wise min/max constraints
"""
X = np.asarray(X)
if self.min_value is not None:
X[X < self.min_value] = self.min_value
if self.max_value is not None:
X[X > self.max_value] = self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.