Ejemplo n.º 1
0
def load_GFS_data(latitude=33.8688,
                  longitude=151.2093,
                  tz='Australia/Sydney',
                  days=7):

    # latitude, longitude, tz = 32.2, -110.9, 'US/Arizona'
    # latitude, longitude, tz = 32.2, -110.9, 'US/Arizona'
    # latitude = 33.8688
    # longitude=151.2093
    # tz='Australia/Sydney'
    start = pd.Timestamp(datetime.date.today(), tz=tz)
    end = start + pd.Timedelta(days=7)
    irrad_vars = ['ghi', 'dni', 'dhi']

    model = GFS()
    raw_data = model.get_data(latitude, longitude, start, end)
    print(raw_data.head())

    data = raw_data
    data = model.rename(data)
    data['temp_air'] = model.kelvin_to_celsius(data['temp_air'])
    data['wind_speed'] = model.uv_to_speed(data)
    irrad_data = model.cloud_cover_to_irradiance(data['total_clouds'])
    data = data.join(irrad_data, how='outer')
    data = data[model.output_variables]
    print(data.head())

    data = model.process_data(raw_data)
    print(data.head())

    data = model.get_processed_data(latitude, longitude, start, end)

    print(data.head())

    return (data)
Ejemplo n.º 2
0
 def __get_weather(self, start: pd.Timestamp, end: pd.Timestamp) -> pd.DataFrame:
     """
     Get weather data for period.
     :param start: - pd.Timestamp, begin of period
     :param end: - pd.Timestamp, end of period
     :return: pd.DataFrame,
         Column names are: ``ghi, dni, dhi``
     """
     fx_model = GFS()
     return fx_model.get_processed_data(self.geo["latitude"], self.geo["longitude"], start, end)
Ejemplo n.º 3
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
Ejemplo n.º 4
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
Ejemplo n.º 5
0
import pandas as pd
import datetime
from pvlib.forecast import GFS

# specify location (Tucson, AZ)
latitude, longitude, tz = 32.2, -110.9, 'US/Arizona'

# specify time range.
start = pd.Timestamp(datetime.date.today(), tz=tz)

end = start + pd.Timedelta(days=7)

irrad_vars = ['ghi', 'dni', 'dhi']

model = GFS()

processed_data = model.get_processed_data(latitude=latitude,
                                          longitude=longitude,
                                          start=start,
                                          end=end,
                                          headers={
                                              'User-Agent': 'UserNoAuth',
                                              'Front-End-Https': 'on'
                                          },
                                          verify=False)
Ejemplo n.º 6
0
    'SMA_America__SC630CP_US__with_ABB_EcoDry_Ultra_transformer_']

temperature_model_parameters = TEMPERATURE_MODEL_PARAMETERS['sapm'][
    'open_rack_glass_polymer']

system = PVSystem(surface_tilt=20,
                  surface_azimuth=180,
                  module_parameters=myModule,
                  inverter_parameters=inverter,
                  temperature_model_parameters=temperature_model_parameters,
                  modules_per_string=25,
                  strings_per_inverter=8)

fx_model = GFS()

fx_data = fx_model.get_processed_data(latitudeEsfahan, longitudeEsfahan, start,
                                      end)
fx_data = fx_data.resample('60min').interpolate()

mc = ModelChain(system, fx_model.location)
mc.run_model(fx_data)

data = (mc.results.ac.fillna(0) / 200 / 274)
data = list(zip(data, data.index))

conn = psycopg2.connect(
    user="******",
    password="******",
    host="ec2-63-34-97-163.eu-west-1.compute.amazonaws.com",
    port="5432",
    database="d94t9tih4i30sp")
cur = conn.cursor()
Ejemplo n.º 7
0
latitude = -28.893597
longitude = 31.468293
tz = 'Africa/Johannesburg'
surface_tilt = 30
surface_azimuth = 180
albedo = 0.2

#Set beginning and end date
end = pd.Timestamp(datetime.date.today(), tz=tz)
start = end - timedelta(12)

# Define forecast model
fm = GFS()

# Retrieve data from forecast API and perform data preparation
previous_forecast = fm.get_processed_data(latitude, longitude, start, end)
previous_forecast.index = previous_forecast.index.strftime('%Y-%m-%d %H:%M:%S')
previous_forecast.index = pd.to_datetime(previous_forecast.index)

#resample to three hours to match weather data sampling rate
data_res = physical_asset.resample('3H').mean()

#set datetime limits of solar farm data to match weather data
forecast_dates = previous_forecast.index
start_datetime = forecast_dates[0]

list_r = data_res.index
stop_datetime = list_r[-5]

date_ranges = [start_datetime, stop_datetime]
data_res = data_res[start_datetime:stop_datetime]
Ejemplo n.º 8
0
start = pd.Timestamp(datetime.date.today(), tz=tz) # today's date
end = start + pd.Timedelta(days=7) # 7 days from today



# 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,
Ejemplo n.º 9
0
start_time = timeit.default_timer()
radiationForecast = RadiationFrameHandler.forecast(location)
elapsed = timeit.default_timer() - start_time
print("Solcast Radiation Forecast Location: %s Time: %s (seconds)" %
      (location.name, '%.6f' % elapsed))

# specify time range with timezone
start = pd.Timestamp(datetime.date.today(), tz=location.timezone)
end = start + pd.Timedelta(days=7)

start_time = timeit.default_timer()
# fx is a common abbreviation for forecast
fx_model = GFS(
)  # From Forecast models http://pvlib-python.readthedocs.io/en/latest/api.html#forecast-models
fx_data = fx_model.get_processed_data(location.lat, location.lng, start, end)
elapsed = timeit.default_timer() - start_time
print("pvlib (GFS) Radiation Forecast Location: %s Time: %s (seconds)" %
      (location.name, '%.6f' % elapsed))

plt.plot(fx_data.ghi, label="ghi - PVLIB (GFS)")
plt.plot(radiationForecast.ghi, label="ghi - Solcast", linestyle='dashdot')

plt.plot(fx_data.dhi, label="dhi - PVLIB (GFS)")
plt.plot(radiationForecast.dhi, label="dhi - Solcast", linestyle='dashdot')

plt.plot(fx_data.dni, label="dni - PVLIB (GFS)")
plt.plot(radiationForecast.dni, label="dni - Solcast", linestyle='dashdot')

plt.legend()
plt.show()
Ejemplo n.º 10
0
class Forecast():
    # forecast_models = [GFS(), NAM(), NDFD(), RAP(), HRRR()]

    def get_avg_daily_dc_power(self):
        total = self.sapm_out.p_mp.values.sum()
        avg = total / self.forecast_length
        return np.format_float_positional(avg, precision=3)

    def get_avg_daily_ac_power(self):
        total = self.ac_power.values.sum()
        avg = total / self.forecast_length
        return np.format_float_positional(avg, precision=3)

    # forecast_length in days
    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)
Ejemplo n.º 11
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})