Exemplo n.º 1
0
    def data_setter(self, data):
        self.lats = data['lats']
        self.longs = data['longs']
        self.tilt = data['tilt']
        self.surf_azi = data['surf_azi']  #since panel faces south
        self.altitude = data['altitude']
        self.name = data['name']
        self.timezone = data['timezone']
        self.albedo = data['albedo']
        self.mod_per_string = data['modules_per_string']
        self.str_per_inv = data['strings_per_inverter']

        try:
            self.panel_model = retrieve_sam('CECMod')
            self.panel_model = self.panel_model[data['module']]
        except:
            try:
                self.panel_model = retrieve_sam('SandiaMod')
                self.panel_model = self.panel_model[data['module']]
            except:
                return False, str('Module not found in the database!!')
        try:
            self.inverter_model = retrieve_sam('CECinverter')
            self.inverter_model = self.inverter_model[data['inverter']]
        except:
            try:
                self.inverter_model = retrieve_sam('SandiaInverter')
                self.inverter_model = self.inverter_model[data['inverter']]
            except:
                return False, str('Inverter model not found in the database!!')

        return True, str('Pass')
Exemplo n.º 2
0
def sam_data():
    data = {}
    data['cecmod'] = pvsystem.retrieve_sam('cecmod')
    data['sandiamod'] = pvsystem.retrieve_sam('sandiamod')
    data['cecinverter'] = pvsystem.retrieve_sam('cecinverter')
    data['adrinverter'] = pvsystem.retrieve_sam('adrinverter')
    return data
Exemplo n.º 3
0
def test_retrieve_sam_raise_no_parameters():
    """
    Raise an exception if no parameters are provided to `retrieve_sam()`.
    """
    with pytest.raises(ValueError) as error:
        pvsystem.retrieve_sam()
    assert 'A name or path must be provided!' == str(error.value)
Exemplo n.º 4
0
def sam_data():
    data = {}
    data['cecmod'] = pvsystem.retrieve_sam('cecmod')
    data['sandiamod'] = pvsystem.retrieve_sam('sandiamod')
    data['cecinverter'] = pvsystem.retrieve_sam('cecinverter')
    data['adrinverter'] = pvsystem.retrieve_sam('adrinverter')
    return data
Exemplo n.º 5
0
def download_forecasts(request):
    modules_per_string = request.session['modules_per_string']
    strings_per_inverter = request.session['strings_per_inverter']
    module = request.session['module']
    inverter = request.session['inverter']
    latitude = request.session['latitude']
    longitude = request.session['longitude']
    tz = request.session['timezone']

    sandia_modules = retrieve_sam('SandiaMod')
    cec_inverters = retrieve_sam('SandiaInverter')

    # Parametros de la granja solar
    surface_tilt = 30
    surface_azimuth = 180  # pvlib uses 0=North, 90=East, 180=South, 270=West convention
    albedo = 0.2
    # Rango de tiempo
    start = pd.Timestamp(date.today(), tz=tz)
    # Pronostico a 3 días en adelante
    end = start + pd.Timedelta(days=3)

    module = pd.Series(sandia_modules[module])
    inverter = cec_inverters[inverter]

    # model a big tracker for more fun
    system = SingleAxisTracker(module_parameters=module,
                               inverter_parameters=inverter,
                               modules_per_string=modules_per_string,
                               strings_per_inverter=strings_per_inverter)

    # fx is a common abbreviation for forecast
    fx_model = GFS()

    fx_data = fx_model.get_processed_data(latitude, longitude, start, end)

    # use a ModelChain object to calculate modeling intermediates
    mc = ModelChain(system, fx_model.location)

    # extract relevant data for model chain
    mc.run_model(fx_data.index, weather=fx_data)

    AC = mc.ac.fillna(0)

    response = HttpResponse(content_type='text/csv')
    response[
        'Content-Disposition'] = 'attachment; filename=AC_5days_forecasts.csv'

    AC.to_csv(path_or_buf=response,
              sep=';',
              float_format='%.2f',
              index=True,
              decimal=",")
    return response
Exemplo n.º 6
0
def system_parameters():
    """System parameters for generating simulated power data."""
    sandia_modules = pvsystem.retrieve_sam('SandiaMod')
    sapm_inverters = pvsystem.retrieve_sam('cecinverter')
    module = sandia_modules['Canadian_Solar_CS5P_220M___2009_']
    inverter = sapm_inverters['ABB__MICRO_0_25_I_OUTD_US_208__208V_']
    temperature_model_parameters = (
        TEMPERATURE_MODEL_PARAMETERS['sapm']['open_rack_glass_glass'])
    return {
        'module_parameters': module,
        'inverter_parameters': inverter,
        'temperature_model_parameters': temperature_model_parameters
    }
Exemplo n.º 7
0
def test_retrieve_sam_cecinverter():
    """
    Test the expected data is retrieved from the CEC inverter database. In
    particular, check for a known inverter in the database and check for the
    expected keys for that inverter.
    """
    data = pvsystem.retrieve_sam('cecinverter')
    keys = [
        'Vac',
        'Paco',
        'Pdco',
        'Vdco',
        'Pso',
        'C0',
        'C1',
        'C2',
        'C3',
        'Pnt',
        'Vdcmax',
        'Idcmax',
        'Mppt_low',
        'Mppt_high',
        'CEC_Date',
        'CEC_Type',
    ]
    inverter = 'Yaskawa_Solectria_Solar__PVI_5300_208__208V_'
    assert inverter in data
    assert set(data[inverter].keys()) == set(keys)
Exemplo n.º 8
0
def system_parameters():
    """PVSystem parameters for generating simulated power data."""
    sapm_inverters = pvsystem.retrieve_sam('cecinverter')
    inverter = sapm_inverters['ABB__MICRO_0_25_I_OUTD_US_208__208V_']
    return {
        'inverter_parameters': inverter,
    }
Exemplo n.º 9
0
def AC_out(p_dc):
    ## Get list of inverters
    sapm_inverters = pvsystem.retrieve_sam('sandiainverter')
    ## Choose inverter (e.g. ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014)
    sapm_inverter = sapm_inverters[
        'ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014_']
    ## Run SAPM model
    p_ac = pvsystem.snlinverter(p_dc.v_mp, p_dc.p_mp, sapm_inverter)
    return (p_ac)
Exemplo n.º 10
0
def array_parameters():
    """Array parameters for generating simulated power data."""
    sandia_modules = pvsystem.retrieve_sam('SandiaMod')
    module = sandia_modules['Canadian_Solar_CS5P_220M___2009_']
    temperature_model_parameters = (
        TEMPERATURE_MODEL_PARAMETERS['sapm']['open_rack_glass_glass'])
    return {
        'module_parameters': module,
        'temperature_model_parameters': temperature_model_parameters
    }
Exemplo n.º 11
0
def get_cast(start_date, end_date):
    from pvlib.pvsystem import PVSystem, retrieve_sam

    from pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS

    from pvlib.tracking import SingleAxisTracker

    from pvlib.modelchain import ModelChain

    sandia_modules = retrieve_sam('sandiamod')

    cec_inverters = retrieve_sam('cecinverter')

    module = sandia_modules['SolarWorld_Sunmodule_250_Poly__2013_']

    inverter = cec_inverters['ABB__TRIO_20_0_TL_OUTD_S1_US_480__480V_']

    temperature_model_parameters = TEMPERATURE_MODEL_PARAMETERS['sapm'][
        'open_rack_glass_glass']

    # model a single axis tracker
    system = SingleAxisTracker(
        module_parameters=module,
        inverter_parameters=inverter,
        temperature_model_parameters=temperature_model_parameters,
        modules_per_string=15,
        strings_per_inverter=4)

    # fx is a common abbreviation for forecast
    fx_model = GFS()

    forecast_mod = fx_model.get_processed_data(latitude, longitude, start_date,
                                               end_date)

    # use a ModelChain object to calculate modeling intermediates
    mchain = ModelChain(system, fx_model.location)

    # extract relevant data for model chain
    mchain.run_model(forecast_mod)
    acp = mchain.ac.fillna(0)
    return acp
Exemplo n.º 12
0
def DC_out(solpos, poa_irrad, aoi, pvtemps):
    ## First calculate airmass
    airmass = atmosphere.relativeairmass(solpos['apparent_zenith'])
    ## Get list of modules
    sandia_modules = pvsystem.retrieve_sam('SandiaMod')
    ## Choose model (e.g. CS5P_220M___2009)
    sandia_module = sandia_modules.Canadian_Solar_CS5P_220M___2009_
    ## Run SAPM model
    effective_irradiance = pvsystem.sapm_effective_irradiance(
        poa_irrad.poa_direct, poa_irrad.poa_diffuse, airmass, aoi,
        sandia_module)
    p_dc = pvsystem.sapm(effective_irradiance, pvtemps['temp_cell'],
                         sandia_module)
    return (p_dc)
Exemplo n.º 13
0
def prepare_data():
    print('preparing single diode data from clear sky ghi...')
    # adjust values to change length of test data
    times = pd.DatetimeIndex(start='20180101',
                             end='20190101',
                             freq='1min',
                             tz='America/Phoenix')
    location = pvlib.location.Location(32.2, -110.9, altitude=710)
    cs = location.get_clearsky(times)
    poa_data = cs['ghi']
    cec_modules = pvsystem.retrieve_sam('cecmod')
    cec_module_params = cec_modules['Example_Module']
    IL, I0, Rs, Rsh, nNsVth = pvsystem.calcparams_desoto(
        poa_data,
        temp_cell=25,
        alpha_isc=cec_module_params['alpha_sc'],
        module_parameters=cec_module_params,
        EgRef=1.121,
        dEgdT=-0.0002677)
    return IL, I0, Rs, Rsh, nNsVth
Exemplo n.º 14
0
def test_retrieve_sam_cecmod():
    """
    Test the expected data is retrieved from the CEC module database. In
    particular, check for a known module in the database and check for the
    expected keys for that module.
    """
    data = pvsystem.retrieve_sam('cecmod')
    keys = [
        'BIPV',
        'Date',
        'T_NOCT',
        'A_c',
        'N_s',
        'I_sc_ref',
        'V_oc_ref',
        'I_mp_ref',
        'V_mp_ref',
        'alpha_sc',
        'beta_oc',
        'a_ref',
        'I_L_ref',
        'I_o_ref',
        'R_s',
        'R_sh_ref',
        'Adjust',
        'gamma_r',
        'Version',
        'STC',
        'PTC',
        'Technology',
        'Bifacial',
        'Length',
        'Width',
    ]
    module = 'Itek_Energy_LLC_iT_300_HE'
    assert module in data
    assert set(data[module].keys()) == set(keys)
Exemplo n.º 15
0
def chooseCECModuleCoeffs(file='sam-library-cec-modules-2015-6-30.csv',
                          module_model='1Soltech_1STH_245_WH'):
    '''
    This function helps choose a module from CEC module database and its output can be used to generate matrices for a 
    large collection of modules.
    
    Parameters
    ----------
    
    file:         String  
                  A path to file that contains the module database. Could be the original or a (shorter) copy of that 
    
    module_model: String 
                  A module name from the database  
    
    
    Returns
    -------
    
    module_params_stc:  A dictionary of the STC parameters of the modules needed for the one diode model
    
    Also see generateMatrix
    
    '''

    module_coeffs = pvsystem.retrieve_sam(name="CECMod", samfile=file)

    try:
        test_module = module_coeffs[module_model]
        module_params_stc = test_module.to_dict()

    except KeyError:
        raise KeyError(
            'The chosen model does not exist or is typed incorrectly')

    return module_params_stc
Exemplo n.º 16
0
import datetime as dt
import pandas as pd
import pvlib.atmosphere as atmosphere
import pvlib.irradiance as irradiance
import pvlib.pvsystem as pvsystem
import pvlib.solarposition as solarposition

from pvlib.location import Location

_sandia_modules = pvsystem.retrieve_sam('SandiaMod')
_cec_inverters = pvsystem.retrieve_sam('cecinverter')
_sandia_module = _sandia_modules['Silevo_Triex_U300_Black__2014_']
_cec_inverter = _cec_inverters['ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014_']
_munich_location = Location(48.3, 11.8, 'CET', 447, 'Munich')
_module_count = 20


def get_perfect_voltage_for_a_day(start, freq):
    """This method is used to build a pandas serie with voltage values.
    This serie has DateTime index and contains a value for every "freq"
    seconds during 24 hours starting from "start" date.
    There are several assumptions:
    1. Location is Munich
    2. A battery is pointing to the south, amount of blocks is 20
    3. Sandia Module database is used
    4. pvlib library is heavily used

    :param start: datetime. First timestamp in result series
    :param freq: str. How often voltage should be sampled
    :return: voltage : Series
    """
Exemplo n.º 17
0
"""
testing single-diode methods using JW Bishop 1988
"""

import numpy as np
from pvlib import pvsystem
from pvlib.singlediode import bishop88, estimate_voc, VOLTAGE_BUILTIN
import pytest
from conftest import requires_scipy

POA = 888
TCELL = 55
CECMOD = pvsystem.retrieve_sam('cecmod')


@requires_scipy
def test_newton_spr_e20_327():
    """test pvsystem.singlediode with Newton method on SPR-E20-327"""
    spr_e20_327 = CECMOD.SunPower_SPR_E20_327
    x = pvsystem.calcparams_desoto(
        effective_irradiance=POA, temp_cell=TCELL,
        alpha_sc=spr_e20_327.alpha_sc, a_ref=spr_e20_327.a_ref,
        I_L_ref=spr_e20_327.I_L_ref, I_o_ref=spr_e20_327.I_o_ref,
        R_sh_ref=spr_e20_327.R_sh_ref, R_s=spr_e20_327.R_s,
        EgRef=1.121, dEgdT=-0.0002677)
    il, io, rs, rsh, nnsvt = x
    pvs = pvsystem.singlediode(*x, method='lambertw')
    out = pvsystem.singlediode(*x, method='newton')
    isc, voc, imp, vmp, pmp, ix, ixx = out.values()
    assert np.isclose(pvs['i_sc'], isc)
    assert np.isclose(pvs['v_oc'], voc)
Exemplo n.º 18
0
    def __init__(self, panel=None, forecast_length=7, forecast_model=None):
        self.forecast_length = forecast_length
        if panel == None:
            self.panel = Panel()
        else:
            self.panel = panel

        if forecast_model == None:
            self.fm = GFS()
        else:
            self.fm = forecast_model

        self.start = pd.Timestamp(datetime.date.today(),
                                  tz=self.panel.tz)  # today's date
        self.end = self.start + pd.Timedelta(
            days=forecast_length)  # days from today

        print(
            "getting processed data with lat: %s, lng: %s, start:%s, end:%s" %
            (self.panel.latitude, self.panel.longitude, self.start, self.end))
        # get forecast data
        forecast_data = self.fm.get_processed_data(self.panel.latitude,
                                                   self.panel.longitude,
                                                   self.start, self.end)
        ghi = forecast_data['ghi']

        # get solar position
        time = forecast_data.index
        a_point = self.fm.location
        solpos = a_point.get_solarposition(time)

        # get PV(photovoltaic device) modules
        sandia_modules = pvsystem.retrieve_sam('SandiaMod')
        sandia_module = sandia_modules.Canadian_Solar_CS5P_220M___2009_

        dni_extra = irradiance.get_extra_radiation(
            self.fm.time)  # extra terrestrial radiation
        airmass = atmosphere.get_relative_airmass(solpos['apparent_zenith'])
        # POA: Plane Of Array: an image sensing device consisting of an array
        # (typically rectangular) of light-sensing pixels at the focal plane of a lens.
        # https://en.wikipedia.org/wiki/Staring_array

        # Diffuse sky radiation is solar radiation reaching the Earth's surface after
        # having been scattered from the direct solar beam by molecules or particulates
        # in the atmosphere.
        # https://en.wikipedia.org/wiki/Diffuse_sky_radiation
        poa_sky_diffuse = irradiance.haydavies(self.panel.surface_tilt,
                                               self.panel.surface_azimuth,
                                               forecast_data['dhi'],
                                               forecast_data['dni'], dni_extra,
                                               solpos['apparent_zenith'],
                                               solpos['azimuth'])

        # Diffuse reflection is the reflection of light or other waves or particles
        # from a surface such that a ray incident on the surface is scattered at many
        # angles rather than at just one angle as in the case of specular reflection.
        poa_ground_diffuse = irradiance.get_ground_diffuse(
            self.panel.surface_tilt, ghi, albedo=self.panel.albedo)

        # AOI: Angle Of Incidence
        aoi = irradiance.aoi(self.panel.surface_tilt,
                             self.panel.surface_azimuth,
                             solpos['apparent_zenith'], solpos['azimuth'])

        #  irradiance is the radiant flux (power) received by a surface per unit area
        # https://en.wikipedia.org/wiki/Irradiance
        poa_irrad = irradiance.poa_components(aoi, forecast_data['dni'],
                                              poa_sky_diffuse,
                                              poa_ground_diffuse)

        temperature = forecast_data['temp_air']
        wnd_spd = forecast_data['wind_speed']

        # pvtemps: pv temperature
        pvtemps = pvsystem.sapm_celltemp(poa_irrad['poa_global'], wnd_spd,
                                         temperature)

        # irradiance actually used by PV
        effective_irradiance = pvsystem.sapm_effective_irradiance(
            poa_irrad.poa_direct, poa_irrad.poa_diffuse, airmass, aoi,
            sandia_module)

        # SAPM: Sandia PV Array Performance Model
        # https://pvpmc.sandia.gov/modeling-steps/2-dc-module-iv/point-value-models/sandia-pv-array-performance-model/

        self.sapm_out = pvsystem.sapm(effective_irradiance,
                                      pvtemps['temp_cell'], sandia_module)

        sapm_inverters = pvsystem.retrieve_sam('sandiainverter')
        sapm_inverter = sapm_inverters[
            'ABB__MICRO_0_25_I_OUTD_US_208_208V__CEC_2014_']
        self.ac_power = pvsystem.snlinverter(self.sapm_out.v_mp,
                                             self.sapm_out.p_mp, sapm_inverter)
Exemplo n.º 19
0
def test_retrieve_sam_network():
    sam_data["cecmod"] = pvsystem.retrieve_sam("cecmod")
    sam_data["sandiamod"] = pvsystem.retrieve_sam("sandiamod")
    sam_data["cecinverter"] = pvsystem.retrieve_sam("cecinverter")
Exemplo n.º 20
0
tz = 'Etc/GMT+5'
times = pd.date_range('2021-06-21', '2021-6-22', freq='1T', tz=tz)

# create site system characteristics
axis_tilt = 0
axis_azimuth = 180
gcr = 0.35
max_angle = 60
pvrow_height = 3
pvrow_width = 4
albedo = 0.2
bifaciality = 0.75

# load temperature parameters and module/inverter specifications
temp_model_parameters = PARAMS['sapm']['open_rack_glass_glass']
cec_modules = pvsystem.retrieve_sam('CECMod')
cec_module = cec_modules['Trina_Solar_TSM_300DEG5C_07_II_']
cec_inverters = pvsystem.retrieve_sam('cecinverter')
cec_inverter = cec_inverters['ABB__MICRO_0_25_I_OUTD_US_208__208V_']

# create a location for site, and get solar position and clearsky data
site_location = location.Location(lat, lon, tz=tz, name='Greensboro, NC')
solar_position = site_location.get_solarposition(times)
cs = site_location.get_clearsky(times)

# load solar position and tracker orientation for use in pvsystem object
sat_mount = pvsystem.SingleAxisTrackerMount(axis_tilt=axis_tilt,
                                            axis_azimuth=axis_azimuth,
                                            max_angle=max_angle,
                                            backtrack=True,
                                            gcr=gcr)
Exemplo n.º 21
0
"""
Retrieve standard sets of parameters
"""
from typing import List

from fastapi import APIRouter, HTTPException, Path
from pvlib.pvsystem import retrieve_sam  # type: ignore

from .. import models

router = APIRouter()
sandia_inverter_params = (
    retrieve_sam("CECInverter").loc[models.SandiaInverterParameters.schema()
                                    ["properties"].keys()].astype(float))

# Database does not provide the fields 'EgRef', 'dEgdT'
# which have defaults in the model.
cec_keys = [
    "alpha_sc",
    "a_ref",
    "I_L_ref",
    "I_o_ref",
    "R_sh_ref",
    "R_s",
    "gamma_r",
    "Adjust",
    "N_s",
]
cec_module_params = (retrieve_sam("CECMod").loc[cec_keys].astype(float).rename(
    index={"N_s": "cells_in_series"}))
Exemplo n.º 22
0
 def __init__(self):
     self.inverters = retrieve_sam(name='SandiaInverter')
     self.inverter = None
Exemplo n.º 23
0
def test_retrieve_sam_network():
    sam_data['cecmod'] = pvsystem.retrieve_sam('cecmod')
    sam_data['sandiamod'] = pvsystem.retrieve_sam('sandiamod')
    sam_data['sandiainverter'] = pvsystem.retrieve_sam('sandiainverter')
Exemplo n.º 24
0
def get_inv_list():
    inv_list = list([])
    avlb_invs = ['CECInverter', 'SandiaInverter', 'ADRInverter']
    for invs in avlb_invs:
        inv_list = inv_list + retrieve_sam(invs).columns.values.tolist()
    return inv_list
Exemplo n.º 25
0
def run_sim_on_tracker(tracker, tmy_data, sand_point, albedo,  n_epochs=10, n_steps=500,):
    '''
    Returns power, angle history

    '''
    # print("running {} \n".format(tracker.name))
    sandia_modules = retrieve_sam('sandiamod')
    cec_inverters = retrieve_sam('cecinverter')
    module = sandia_modules['Canadian_Solar_CS5P_220M___2009_']
    cap = float(module['Isco']*module['Voco']/(10**6)) #convert to MW
    #TODO: save previous state/reward
    for e in range(n_epochs):
        #returning results from most recent epoch
        #TODO: avoid successive concats
        total = pd.DataFrame()
        angles = np.zeros((n_steps,))
        energy_consumed_move = np.zeros((n_steps,))
        temps = pd.DataFrame()
        radiation_rows = []
        ac_all = np.zeros((n_steps,))
        surface_azimuth = tracker.get_azimuth()
        old_tilt = 0
        prev_reward = 0
        for i in range(n_steps):
            print(i)
            current_step_data = tmy_data[tmy_data.index[i]:tmy_data.index[i]]

            solpos = pvlib.solarposition.get_solarposition(current_step_data.index, sand_point.latitude, sand_point.longitude)


            state = tmy_step_to_OOMDP(current_step_data, tracker, solpos, old_tilt, albedo)

            surface_tilt = float(tracker.get_angle(state, prev_reward))
            angles[i] = surface_tilt

            sapm_out, ac, rad_timestep, pvtemps = calculate_energy(surface_tilt, surface_azimuth, albedo, current_step_data['Wspd'], current_step_data['DryBulb'], current_step_data.index, solpos,  current_step_data['DHI'],  current_step_data['DNI'],  current_step_data['GHI'], tracker.name)

            radiation_rows.append(rad_timestep)

            eng_consumed_move = energy_motion(old_tilt, surface_tilt, cap)
            old_tilt = surface_tilt
            prev_reward = float(ac) - eng_consumed_move*1000
            energy_consumed_move[i] = eng_consumed_move

            ac_all[i] = ac - eng_consumed_move*1000 #kwh to wh
            temps = temps.append(pvtemps)


    #convert angles to df
    angles_series = pd.Series(angles, index=tmy_data.index[0:n_steps])
    energy_consumed = pd.Series(energy_consumed_move, index=tmy_data.index[0:n_steps])

    radiation = pd.concat(radiation_rows, axis=0)
    #rename
    temps.rename(columns={'temp_cell': 'cell temp {}'.format(tracker.name)}, inplace=True)

    angles_df = pd.DataFrame(angles_series, columns=['angle {}'.format(tracker.name)])
    energy_consumed_df = pd.DataFrame(energy_consumed, columns=['energy consumed {}'.format(tracker.name)])

    ac_total = pd.Series(ac_all, index=tmy_data.index[0:n_steps])
    sum = ac_total.sum()

    ac_df = pd.DataFrame(ac_total, columns=['ac_step'])
    ac_df['p cumulative {}'.format(tracker.name)] = ac_df.cumsum()

    return ac_df, angles_df, temps, energy_consumed_df, radiation, sum
Exemplo n.º 26
0
def simulate_power_by_station(station_index, surface_tilt, surface_azimuth,
                              pv_module, tcell_model_parameters, ghi, tamb,
                              wspd, albedo, days, lead_times, air_mass,
                              dni_extra, zenith, apparent_zenith, azimuth):
    """
    This is the worker function for simulating power at a specified location. This function should be used inside
    of `simulate_power` and direct usage is discouraged.

    :param station_index: A station index
    :param ghi: See `simulate_power`
    :param tamb: See `simulate_power`
    :param wspd: See `simulate_power`
    :param albedo: See `simulate_power`
    :param days: See `simulate_power`
    :param lead_times: See `simulate_power`
    :param air_mass: See `simulate_power`
    :param dni_extra: See `simulate_power`
    :param zenith: See `simulate_power`
    :param apparent_zenith: See `simulate_power`
    :param azimuth: See `simulate_power`
    :param surface_tilt: See `simulate_power`
    :param surface_azimuth: See `simulate_power`
    :param pv_module: A PV module name
    :param tcell_model_parameters: A cell module name
    :return: A list with power, cell temperature, and the effective irradiance
    """

    # Sanity check
    assert 0 <= station_index < ghi.shape[3], 'Invalid station index'

    # Determine the dimensions
    num_analogs = ghi.shape[0]
    num_lead_times = ghi.shape[1]
    num_days = ghi.shape[2]

    # Initialization
    p_mp = np.zeros((num_analogs, num_lead_times, num_days))
    tcell = np.zeros((num_analogs, num_lead_times, num_days))
    effective_irradiance = np.zeros((num_analogs, num_lead_times, num_days))
    pv_module = pvsystem.retrieve_sam("SandiaMod")[pv_module]
    tcell_model_parameters = temperature.TEMPERATURE_MODEL_PARAMETERS["sapm"][
        tcell_model_parameters]

    for day_index in range(num_days):
        for lead_time_index in range(num_lead_times):

            # Determine the current time
            current_posix = days[day_index] + lead_times[lead_time_index]
            current_time = pd.Timestamp(current_posix, tz="UTC", unit='s')

            for analog_index in range(num_analogs):
                ghi_ = ghi[analog_index, lead_time_index, day_index,
                           station_index]

                if ghi_ == 0:
                    continue

                albedo_ = albedo[analog_index, lead_time_index, day_index,
                                 station_index]
                wspd_ = wspd[analog_index, lead_time_index, day_index,
                             station_index]
                tamb_ = tamb[analog_index, lead_time_index, day_index,
                             station_index]
                air_mass_ = air_mass[lead_time_index, day_index, station_index]
                dni_extra_ = dni_extra[lead_time_index, day_index,
                                       station_index]
                zenith_ = zenith[lead_time_index, day_index, station_index]
                apparent_zenith_ = apparent_zenith[lead_time_index, day_index,
                                                   station_index]
                azimuth_ = azimuth[lead_time_index, day_index, station_index]

                ##########################################################################################
                #                                                                                        #
                #                     Core procedures of simulating power at one location                #
                #                                                                                        #
                ##########################################################################################

                # Decompose DNI from GHI
                dni_dict = irradiance.disc(ghi_, zenith_, current_time)

                # Calculate POA sky diffuse
                poa_sky_diffuse = irradiance.haydavies(
                    surface_tilt, surface_azimuth, ghi_, dni_dict["dni"],
                    dni_extra_, apparent_zenith_, azimuth_)

                # Calculate POA ground diffuse
                poa_ground_diffuse = irradiance.get_ground_diffuse(
                    surface_tilt, ghi_, albedo_)

                # Calculate angle of incidence
                aoi = irradiance.aoi(surface_tilt, surface_azimuth,
                                     apparent_zenith_, azimuth_)

                # Calculate POA total
                poa_irradiance = irradiance.poa_components(
                    aoi, dni_dict["dni"], poa_sky_diffuse, poa_ground_diffuse)

                # Calculate cell temperature
                tcell[analog_index, lead_time_index,
                      day_index] = pvsystem.temperature.sapm_cell(
                          poa_irradiance['poa_global'], tamb_, wspd_,
                          tcell_model_parameters['a'],
                          tcell_model_parameters['b'],
                          tcell_model_parameters["deltaT"])

                # Calculate effective irradiance
                effective_irradiance[
                    analog_index, lead_time_index,
                    day_index] = pvsystem.sapm_effective_irradiance(
                        poa_irradiance['poa_direct'],
                        poa_irradiance['poa_diffuse'], air_mass_, aoi,
                        pv_module)

                # Calculate power
                sapm_out = pvsystem.sapm(
                    effective_irradiance[analog_index, lead_time_index,
                                         day_index],
                    tcell[analog_index, lead_time_index, day_index], pv_module)

                # Save output to numpy
                p_mp[analog_index, lead_time_index,
                     day_index] = sapm_out["p_mp"]

    return [p_mp, tcell, effective_irradiance]
Exemplo n.º 27
0
import os
import numpy as np
import pandas as pd
from pvlib import pvsystem
from pvlib.singlediode_methods import bishop88, estimate_voc

logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
TEST_DATA = 'bishop88_numerical_precision.csv'
TEST_PATH = os.path.dirname(os.path.abspath(__file__))
PVLIB_PATH = os.path.dirname(TEST_PATH)
DATA_PATH = os.path.join(PVLIB_PATH, 'data', TEST_DATA)
POA = 888
TCELL = 55
CECMOD = pvsystem.retrieve_sam('cecmod')
# get module from cecmod and apply temp/irrad desoto corrections
SPR_E20_327 = CECMOD.SunPower_SPR_E20_327
ARGS = pvsystem.calcparams_desoto(effective_irradiance=POA,
                                  temp_cell=TCELL,
                                  alpha_sc=SPR_E20_327.alpha_sc,
                                  a_ref=SPR_E20_327.a_ref,
                                  I_L_ref=SPR_E20_327.I_L_ref,
                                  I_o_ref=SPR_E20_327.I_o_ref,
                                  R_sh_ref=SPR_E20_327.R_sh_ref,
                                  R_s=SPR_E20_327.R_s,
                                  EgRef=1.121,
                                  dEgdT=-0.0002677)
IL, I0, RS, RSH, NNSVTH = ARGS
IVCURVE_NPTS = 100
Exemplo n.º 28
0
def get_panel_list():
    panel_list = list([])
    avlb_mods = ['SandiaMod', 'CECMod']
    for mods in avlb_mods:
        panel_list = panel_list + retrieve_sam(mods).columns.values.tolist()
    return panel_list
Exemplo n.º 29
0
#running PVLib simulation in steps

from pvlib.pvsystem import PVSystem, retrieve_sam
from pvlib.tracking import SingleAxisTracker
from pvlib.modelchain import ModelChain
from pvlib.forecast import GFS, NAM, NDFD, HRRR, RAP
import pandas as pd
import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

#set up system
sandia_modules = retrieve_sam('sandiamod')
cec_inverters = retrieve_sam('cecinverter')
module = sandia_modules['Canadian_Solar_CS5P_220M___2009_']
inverter = cec_inverters['SMA_America__SC630CP_US_315V__CEC_2012_']

system = PVSystem(surface_tilt=20,
                  surface_azimuth=200,
                  module_parameters=module,
                  inverter_parameters=inverter,
                  modules_per_string=15,
                  strings_per_inverter=300)

latitude, longitude, tz = 32.2, -110.9, 'US/Arizona'

start = pd.Timestamp(datetime.date.today() - pd.Timedelta(days=20), tz=tz)

end = start + pd.Timedelta(days=7)
# model = GFS()
Exemplo n.º 30
0
 def __init__(self):
     self.modules = retrieve_sam(name='SandiaMod')
     self.module = None
Exemplo n.º 31
0
def pvlib_location(request):
    if request.method == 'POST':
        formulario = location_pv(request.POST)
        if formulario.is_valid():
            params = formulario.cleaned_data

            #Creación del diccionario para las caracteristicas del modulo PV utilizado en Cutonalá
            #Canadian_Solar_CS6X_320P___2016_ = {"Vintage": 2016, "Area":1.91 , "Material": "Poly-crystalline", "Cells_in_Series": 72, "Parallel_Strings": 1,
            #       "Isco":9.26, "Voco":45.3, "Impo":8.69, "Vmpo":36.8, "Aisc":0.000397, "Aimp":0.000181, "C0":1.01284, "C1":-0.0128398, "Bvoco":-0.21696,
            #      "Mbvoc":0, "Bvmpo":-0.235488, "Mbvmp":0, "N":1.4032, "C2":0.279317, "C3":-7.24463, "A0":0.928385, "A1":0.068093, "A2":-0.0157738, "A3":0.0016605999999999997,
            #     "A4":-6.929999999999999e-05, "B0":1, "B1":-0.002438, "B2":0.0003103, "B3":-1.246e-05, "B4":2.1100000000000002e-07, "B5":-1.36e-09, "DTC":3.0, "FD":1, "A":-3.4064099999999997, "B":-0.0842075, "C4":0.9964459999999999,
            #    "C5":0.003554, "IXO":4.97599, "IXXO":3.18803, "C6":1.15535, "C7":-0.155353, "Notes":"caracteristicas del modulo instalado en CUT"}

            #module = pd.Series(Canadian_Solar_CS6X_320P___2016_, name="Canadian_Solar_CS6X_320P___2016_")

            #Modulo desde la librería de Sandia labs
            #cec_inverters = retrieve_sam('cecinverter')
            #inverter = cec_inverters['SMA_America__SC630CP_US_315V__CEC_2012_']

            modules_per_string = params['modules_per_string']
            strings_per_inverter = params['strings_per_inverter']
            module = params['module']
            inverter = params['inverter']

            request.session['modules_per_string'] = modules_per_string
            request.session['strings_per_inverter'] = strings_per_inverter
            request.session['module'] = module
            request.session['inverter'] = inverter

            #Calcular la potencia CD, aqui debemos tener el diccionario para el tipo de Modulo en CUTonalá
            sandia_modules = retrieve_sam('SandiaMod')

            #### Modulo desde la librería de Sandia labs
            cec_inverters = retrieve_sam('cecinverter')

            # Lugar Tonalá
            latitude, longitude = params['latitude'], params['longitude']

            request.session['latitude'] = latitude
            request.session['longitude'] = longitude

            tz = tzwhere.tzwhere().tzNameAt(latitude, longitude)

            request.session['timezone'] = tz

            # Parametros de la granja solar
            surface_tilt = 30
            surface_azimuth = 180  # pvlib uses 0=North, 90=East, 180=South, 270=West convention
            albedo = 0.2
            # Rango de tiempo
            start = pd.Timestamp(date.today(), tz=tz)
            # Pronostico a 3 días en adelante
            end = start + pd.Timedelta(days=5)

            module = pd.Series(sandia_modules[module])

            inverter = cec_inverters[inverter]

            # model a big tracker for more fun
            system = SingleAxisTracker(
                module_parameters=module,
                inverter_parameters=inverter,
                modules_per_string=modules_per_string,
                strings_per_inverter=strings_per_inverter)

            # fx is a common abbreviation for forecast
            fx_model = GFS()

            fx_data = fx_model.get_processed_data(latitude, longitude, start,
                                                  end)

            # use a ModelChain object to calculate modeling intermediates
            mc = ModelChain(system, fx_model.location)

            # extract relevant data for model chain
            mc.run_model(fx_data.index, weather=fx_data)
            #mc.run_model(fx_data)

            AC = mc.ac.fillna(0)
            #AC = pd.DataFrame(AC)

            #labeles = AC.keys()

            #valores = AC.values()

            #data = {
            #    "Dates": labeles,
            #    "Power (W)": valores,
            #}
            #here we print the data the correct thing would be to use them to graph them
            #print(AC.head())

            #return render(request, 'chart.html', {'forma': formulario})

            template = 'chart.html'
            #columns = [{'field': 'date', 'title': 'Date'}, {'field': 'value', 'title': 'Value'}]
            #Write the DataFrame to JSON (as easy as can be)
            #json = AC.to_json(orient='records')  # output just the records (no fieldnames) as a collection of tuples
            #Proceed to create your context object containing the columns and the data
            #context = {
            #          'data': json,
            #         'columns': columns
            #       }
            #And render it!
            #return render(request, template, context)
            AC = AC.reset_index()
            AC.rename(columns={
                'index': 'Time',
                0: 'AC Power (W)'
            },
                      inplace=True)
            figure = px.line(AC, x='Time', y='AC Power (W)')
            #figure.update_layout(title="Your 5 days AC power output forecast (W)", font=dict(size=20, color='black'))
            #figure.update_xaxes(title_font=dict(size=16, color='black'))
            #figure.update_yaxes(title_font=dict(size=16, color='black'))
            figure.update_xaxes(dtick=10800000)

            plot_div = plot(figure,
                            image_height='100%',
                            output_type='div',
                            include_plotlyjs=False)

            context = {'linechart': plot_div}

            return render(request, template, context)
    else:
        formulario = location_pv()

    return render(request, 'forecast_data.html', {'form': formulario})
Exemplo n.º 32
0
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from pvlib import pvsystem

all_modules = pvsystem.retrieve_sam(name='SandiaMod')
module_names = list(all_modules.columns)

layout = html.Div([

    dbc.Nav(
            [
                dbc.NavItem(dbc.NavLink('Home Page', href='/', style= {'color': 'white'}, external_link=True)),
                dbc.NavItem(dbc.NavLink('Load Configuration', href='/dashapp_profile/', style= {'color': 'white'}, external_link=True)),
                dbc.NavItem(dbc.NavLink('Simulation', active=True, href='/dashapp_simulation/', style= {'color': 'white'}, external_link=True))
            ],
            className= 'navbar navbar-expand-lg navbar-dark bg-dark fixed-top'
        ),

    html.Div([
        html.Div([
            html.H5('Select Graph'),
            dcc.Dropdown(
                id='select_Graph',
                options=[
                    {'label': 'Costs', 'value': 'cost_graph'},
                    {'label': 'Energy Overview', 'value': 'power_graph'}
                ], value= 'cost_graph')
        ], className='col-3'),

    ], className='row', style={'paddingTop': '60px'}),
Exemplo n.º 33
0
def retrieve_sam_network():
    sam_data['cecmod'] = pvsystem.retrieve_sam('cecmod')
    sam_data['sandiamod'] = pvsystem.retrieve_sam('sandiamod')
    sam_data['cecinverter'] = pvsystem.retrieve_sam('cecinverter')
Exemplo n.º 34
0

# Define forecast model
fm = GFS()
#fm = NAM()
#fm = NDFD()
#fm = RAP()
#fm = HRRR()



# Retrieve data
forecast_data = fm.get_processed_data(latitude, longitude, start, end)
ghi = forecast_data['ghi']

sandia_modules = pvsystem.retrieve_sam('SandiaMod')
sandia_module = sandia_modules.Canadian_Solar_CS5P_220M___2009_



# retrieve time and location parameters
time = forecast_data.index
a_point = fm.location

solpos = a_point.get_solarposition(time)
dni_extra = irradiance.get_extra_radiation(fm.time)
airmass = atmosphere.get_relative_airmass(solpos['apparent_zenith'])
poa_sky_diffuse = irradiance.haydavies(surface_tilt, surface_azimuth,
                           forecast_data['dhi'], forecast_data['dni'], dni_extra,
                           solpos['apparent_zenith'], solpos['azimuth'])