def pvl_snlinverter(**kwargs): Expect = { 'DataFrame': 'df', 'Inverter': (''), 'Vmp': ('matelement', 'num'), 'Pmp': ('matelement', 'num') } var = pvl_tools.Parse(kwargs, Expect) Paco = var.Inverter['Paco'] Pdco = var.Inverter['Pdco'] Vdco = var.Inverter['Vdco'] Pso = var.Inverter['Pso'] C0 = var.Inverter['C0'] C1 = var.Inverter['C1'] C2 = var.Inverter['C2'] C3 = var.Inverter['C3'] Pnt = var.Inverter['Pnt'] A = Pdco * ((1 + C1 * ((var.DataFrame.Vmp - Vdco)))) B = Pso * ((1 + C2 * ((var.DataFrame.Vmp - Vdco)))) C = C0 * ((1 + C3 * ((var.DataFrame.Vmp - Vdco)))) ACPower = ((Paco / (A - B)) - C * ((A - B))) * ( (var.DataFrame.Pmp - B)) + C * ((var.DataFrame.Pmp - B)**2) ACPower[ACPower > Paco] = Paco ACPower[ACPower < Pso] = -1.0 * abs(Pnt) var.DataFrame['ACPower'] = ACPower return var.DataFrame
def pvl_systemdef(**kwargs): Expect = { 'TMYmeta': '', 'SurfTilt': ('num', 'x>=0'), 'SurfAz': ('num'), 'Albedo': ('num', 'x>=0'), 'SeriesModules': ('default', 'default=1', 'num', 'x>=0'), 'ParallelModules': ('default', 'default=1', 'num', 'x>=0') } var = pvl_tools.Parse(kwargs, Expect) system = { 'SurfTilt': var.SurfTilt, 'SurfAz': var.SurfAz, 'Albedo': var.Albedo, 'SeriesModules': var.SeriesModules, 'ParallelModules': var.ParallelModules, 'Lat': var.TMYmeta.latitude, 'Long': var.TMYmeta.longitude, 'TZ': var.TMYmeta.TZ, 'name': var.TMYmeta.Name, 'altitude': var.TMYmeta.altitude } return system
def pvl_readtmy2(**kwargs): Expect = {'FileName': ('open')} var = [] if len(kwargs.keys()) == 0: Tkinter.Tk().withdraw() kwargs = {'FileName': askopenfilename()} var = pvl_tools.Parse(kwargs, Expect) else: var = pvl_tools.Parse(kwargs, Expect) string = '%2d%2d%2d%2d%4d%4d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%4d%1s%1d%2d%1s%1d%2d%1s%1d%4d%1s%1d%4d%1s%1d%3d%1s%1d%4d%1s%1d%3d%1s%1d%3d%1s%1d%4d%1s%1d%5d%1s%1d%10d%3d%1s%1d%3d%1s%1d%3d%1s%1d%2d%1s%1d' columns = 'year,month,day,hour,ETR,ETRN,GHI,GHISource,GHIUncertainty,DNI,DNISource,DNIUncertainty,DHI,DHISource,DHIUncertainty,GHillum,GHillumSource,GHillumUncertainty,DNillum,DNillumSource,DNillumUncertainty,DHillum,DHillumSource,DHillumUncertainty,Zenithlum,ZenithlumSource,ZenithlumUncertainty,TotCld,TotCldSource,TotCldUnertainty,OpqCld,OpqCldSource,OpqCldUncertainty,DryBulb,DryBulbSource,DryBulbUncertainty,DewPoint,DewPointSource,DewPointUncertainty,RHum,RHumSource,RHumUncertainty,Pressure,PressureSource,PressureUncertainty,Wdir,WdirSource,WdirUncertainty,Wspd,WspdSource,WspdUncertainty,Hvis,HvisSource,HvisUncertainty,CeilHgt,CeilHgtSource,CeilHgtUncertainty,PresentWeather,Pwat,PwatSource,PwatUncertainty,AOD,AODSource,AODUncertainty,SnowDepth,SnowDepthSource,SnowDepthUncertainty,LastSnowfall,LastSnowfallSource,LastSnowfallUncertaint' hdr_columns = 'WBAN,City,State,TimeZone,Latitude,Longitude,Elevation' TMY2, TMY2_meta = readTMY(string, columns, hdr_columns, var.FileName) return TMY2, TMY2_meta
def pvl_leapyear(**kwargs): Expect = {'Year': ('num', 'x>0')} v = pvt.Parse(kwargs, Expect) v.Year = np.floor(v.Year) LY = (((np.mod(v.Year, 4) == 0) & (np.mod(v.Year, 100) != 0)) | (np.mod(v.Year, 400) == 0)) return LY
def pvl_clearsky_haurwitz(ApparentZenith): ''' Determine clear sky GHI from 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 of models which require only zenith angle [3]. Parameters ---------- ApparentZenith : DataFrame The apparent (refraction corrected) sun zenith angle in degrees. Returns ------- ClearSkyGHI : DataFrame the modeled global horizonal irradiance in W/m^2 provided by the Haurwitz clear-sky model. Initial implementation of this algorithm by Matthew Reno. References ---------- [1] B. Haurwitz, "Insolation in Relation to Cloudiness and Cloud Density," Journal of Meteorology, vol. 2, pp. 154-166, 1945. [2] B. Haurwitz, "Insolation in Relation to Cloud Type," Journal of Meteorology, vol. 3, pp. 123-124, 1946. [3] M. Reno, C. Hansen, and J. Stein, "Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis", Sandia National Laboratories, SAND2012-2389, 2012. See Also --------- pvl_maketimestruct pvl_makelocationstruct pvl_ephemeris pvl_spa pvl_ineichen ''' Vars = locals() Expect = {'ApparentZenith': ('x<=180', 'x>=0')} var = pvl_tools.Parse(Vars, Expect) ClearSkyGHI = 1098.0 * pvl_tools.cosd(ApparentZenith) * (np.exp( -0.059 / pvl_tools.cosd(ApparentZenith))) ClearSkyGHI[ClearSkyGHI < 0] = 0 return ClearSkyGHI
def pvl_makelocationstruct(**kwargs): Expect = { 'latitude': ('num', 'x>=-90', 'x<=90'), 'longitude': ('num', 'x<=180', 'x>=-180'), 'altitude': ('num', 'default=100'), } Location = pvt.Parse(kwargs, Expect) return Location
def pvl_extraradiation(**kwargs): Expect = {'doy': ('array', 'num', 'x>=1', 'x<367')} var = pvt.Parse(kwargs, Expect) B = 2 * np.pi * var.doy / 365 Rfact2 = 1.00011 + 0.034221 * (np.cos(B)) + 0.00128 * ( np.sin(B)) + 0.000719 * (np.cos(2 * B)) + 7.7e-05 * (np.sin(2 * B)) Ea = 1367 * Rfact2 return Ea
def pvl_makelocationstruct(latitude, longitude, TZ, altitude=100): ''' Create a struct to define a site location Parameters ---------- Latitude : float Positive north of equator, decimal notation Longitude : float Positive east of prime meridian, decimal notation TZ : int Timezone in GMT offset Other Parameters ---------------- altitude : float (optional, default=100) Altitude from sea level. Set to 100m if none input Returns ------- Location : struct *Location.latitude* *Location.longitude* *Location.TZ* *Location.altitude* See Also -------- pvl_ephemeris pvl_alt2pres pvl_pres2alt ''' Vars = locals() Expect = { 'latitude': ('num', 'x>=-90', 'x<=90'), 'longitude': ('num', 'x<=180', 'x>=-180'), 'altitude': ('num', 'default', 'default=100'), 'TZ': ('num') } Location = pvt.Parse(Vars, Expect) return Location
def pvl_readtmy3(**kwargs): Expect = {'FileName': ('open')} #Set file expectation var = [] if len(kwargs.keys()) == 0: #If no filename is input Tkinter.Tk().withdraw() #Start interactive file input kwargs = {'FileName': askopenfilename()} #read in file name var = pvl_tools.Parse(kwargs, Expect) #Parse filename else: var = pvl_tools.Parse(kwargs, Expect) #Parse filename head = ['USAF', 'Name', 'State', 'TZ', 'latitude', 'longitude', 'altitude'] headerfile = open(var.FileName, 'r') meta = dict(zip( head, headerfile.readline().rstrip('\n').split(","))) #Read in file metadata meta['altitude'] = float(meta['altitude']) meta['latitude'] = float(meta['latitude']) meta['longitude'] = float(meta['longitude']) meta['TZ'] = float(meta['TZ']) meta['USAF'] = int(meta['USAF']) meta = pvl_tools.repack(meta) #repack dict as a struct TMYData = pd.read_csv( var.FileName, header=1, parse_dates={'datetime': ['Date (MM/DD/YYYY)', 'Time (HH:MM)']}, date_parser=parsedate, index_col='datetime') TMYData = recolumn(TMYData) #rename to standard column names #retreive Timezone for pandas NOTE: TMY3 is currently given in local standard time. Pandas and pytz can only handle DST timezones, and so to keep consistency, the time index will be input as TZ unaware for the moment #TZ=parsetz(float(meta['TZ'])) #pdb.set_trace() #TMY3.index=TMY3.index.tz_localize(TZ) return TMYData, meta
def pvl_retreiveSAM(**kwargs): Expect = {'name': ('str', ('CECMod', 'SandiaMod', 'SandiaInverter'))} var = pvl_tools.Parse(kwargs, Expect) if var.name == 'CECMod': url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/content/component_libraries/sam-database-cec-modules.csv' elif var.name == 'SandiaMod': url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/content/component_libraries/sam-database-sandia-modules.csv' elif var.name == 'SandiaInverter': url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/content/component_libraries/sam-database-sandia-inverters.csv' return read_url_to_pandas(url)
def pvl_pres2alt(pressure): ''' Determine altitude from site pressure Parameters ---------- Pressure : scalar, vector or DataFrame Atomspheric pressure (Pascals) Returns ------- altitude: scalar, vector or DataFrame Altitude in meters above sea level Notes ------ The following assumptions are made ============================ ================ Parameter Value ============================ ================ Base pressure 101325 Pa Temperature at zero altitude 288.15 K Gravitational acceleration 9.80665 m/s^2 Lapse rate -6.5E-3 K/m Gas constant for air 287.053 J/(kgK) Relative Humidity 0% ============================ ================ References ----------- "A Quick Derivation relating altitude to air pressure" from Portland State Aerospace Society, Version 1.03, 12/22/2004. See also -------- pvl_alt2pres ,pvl_makelocationstruct ''' Vars=locals() Expect={'pressure': ('array', 'num', 'x>0')} var=pvt.Parse(Vars,Expect) Alt=44331.5 - 4946.62 * var.pressure ** (0.190263) return Alt
def pvl_grounddiffuse(**kwargs): Expect = { 'DataFrame': 'df', 'SurfTilt': ('num'), 'GHI': ('matelement', 'num', 'array', 'x>=0'), 'Albedo': ('num', 'array', 'x>=0', 'x<=1'), } var = pvl_tools.Parse(kwargs, Expect) GR = var.DataFrame.GHI * (var.Albedo) * ( (1 - np.cos(np.radians(var.SurfTilt))) * (0.5)) var.DataFrame['GR'] = GR return var.DataFrame
def pvl_alt2pres(altitude): ''' Determine site pressure from altitude Parameters ---------- Altitude: scalar, vector or DataFrame Altitude in meters above sea level Returns ------- Pressure : scalar, vector or DataFrame Atomspheric pressure (Pascals) Notes ------ The following assumptions are made ============================ ================ Parameter Value ============================ ================ Base pressure 101325 Pa Temperature at zero altitude 288.15 K Gravitational acceleration 9.80665 m/s^2 Lapse rate -6.5E-3 K/m Gas constant for air 287.053 J/(kgK) Relative Humidity 0% ============================ ================ References ----------- "A Quick Derivation relating altitude to air pressure" from Portland State Aerospace Society, Version 1.03, 12/22/2004. See also -------- pvl_alt2pres ,pvl_makelocationstruct ''' Vars=locals() Expect={'altitude': 'num'} var=pvt.Parse(Vars,Expect) Press=100 * ((44331.514 - var.altitude) / 11880.516) ** (1 / 0.1902632) return Press
def pvl_extraradiation(doy): ''' Determine extraterrestrial radiation from day of year Parameters ---------- doy : int or pandas.index.dayofyear Day of the year Returns ------- Ea : float or DataFrame the extraterrestrial radiation present in watts per square meter on a surface which is normal to the sun. Ea is of the same size as the input doy. References ---------- <http://solardat.uoregon.edu/SolarRadiationBasics.html>, Eqs. SR1 and SR2 SR1 Partridge, G. W. and Platt, C. M. R. 1976. Radiative Processes in Meteorology and Climatology. SR2 Duffie, J. A. and Beckman, W. A. 1991. Solar Engineering of Thermal Processes, 2nd edn. J. Wiley and Sons, New York. See Also -------- pvl_disc ''' Vars=locals() Expect={'doy': ('array','num','x>=1','x<367')} var=pvt.Parse(Vars,Expect) B=2 * np.pi * var.doy / 365 Rfact2=1.00011 + 0.034221*(np.cos(B)) + 0.00128*(np.sin(B)) + 0.000719*(np.cos(2 * B)) + 7.7e-05*(np.sin(2 * B)) Ea=1367 * Rfact2 return Ea
def pvl_sapmcelltemp(**kwargs): Expect = { 'DataFrame': 'df', 'a': ('optional', 'num'), 'b': ('optional', 'num'), 'deltaT': ('optional', 'num'), 'E': ('matelement', 'num', 'array', 'x>=0'), 'Wspd': ('matelement', 'num', 'array', 'x>=0'), 'DryBulb': ('matelement', 'num', 'array', 'x>=0'), 'modelt': ('default', 'default=Open_rack_cell_glassback') } var = pvl_tools.Parse(kwargs, Expect) TempModel = { 'Open_rack_cell_glassback': [-3.47, -.0594, 3], 'Roof_mount_cell_glassback': [-2.98, -.0471, 1], 'Open_rack_cell_polymerback': [-3.56, -.0750, 3], 'Insulated_back_polumerback': [-2.81, -.0455, 0], 'Open_rack_Polymer_thinfilm_steel': [-3.58, -.113, 3], '22X_Concentrator_tracker': [-3.23, -.130, 13] } try: a = var.a b = var.b deltaT = var.deltaT except: a = TempModel[var.modelt][0] b = TempModel[var.modelt][1] deltaT = TempModel[var.modelt][2] E0 = 1000 # Reference irradiance Tmodule = var.DataFrame.E * ( (np.exp(a + b * var.DataFrame.Wspd))) + var.DataFrame.DryBulb Tcell = Tmodule + var.DataFrame.E / E0 * (deltaT) var.DataFrame['Tcell'] = Tcell var.DataFrame['Tmodule'] = Tmodule return var.DataFrame
def pvl_globalinplane(**kwargs): Expect={'DataFrame':'df', 'SurfTilt':('num','x>=0'), 'SurfAz':('num','x>=0'), 'AOI':('matelement','num','array','x>=0'), 'DNI':('matelement','num','array','x>=0'), 'In_Plane_SkyDiffuse':('matelement','num','array','x>=0'), 'GR':('matelement','num','array','x>=0'), } var=pvl_tools.Parse(kwargs,Expect) Eb = var.DataFrame.DNI*np.cos(np.radians(var.DataFrame.AOI)) E = Eb + var.DataFrame.In_Plane_SkyDiffuse + var.DataFrame.GR Ediff = var.DataFrame.In_Plane_SkyDiffuse + var.DataFrame.GR var.DataFrame['E']=E var.DataFrame['Eb']=Eb var.DataFrame['Ediff']=Ediff return var.DataFrame
def pvl_sapm(**kwargs): Expect={'DataFrame':'df', 'Module':(''), 'Eb':('matelement','num'), 'Ediff':('matelement','num'), 'Tcell':('matelement','num'), } var=pvl_tools.Parse(kwargs,Expect) T0=25 q=1.60218e-19 k=1.38066e-23 E0=1000 AMcoeff=[var.Module['A4'],var.Module['A3'],var.Module['A2'],var.Module['A1'],var.Module['A0']] AOIcoeff=[var.Module['B5'],var.Module['B4'],var.Module['B3'],var.Module['B2'],var.Module['B1'],var.Module['B0']] F1 = Np.polyval(AMcoeff,var.DataFrame.AM) F2 = Np.polyval(AOIcoeff,var.DataFrame.AOI) var.DataFrame['Ee'] = F1*((var.DataFrame.Eb*F2+var.Module['FD']*var.DataFrame.Ediff)/E0) var.DataFrame.Ee.fillna(0) var.DataFrame.Ee[var.DataFrame.Ee < 0]=0 Filt=var.DataFrame.Ee[var.DataFrame.Ee >= 0.001] var.DataFrame['Isc']=var.Module.ix['Isco']*(var.DataFrame.Ee)*((1 + var.Module.ix['Aisc']*((var.DataFrame.Tcell - T0)))) var.DataFrame['Imp']=var.Module.ix['Impo']*((var.Module.ix['C0']*(var.DataFrame.Ee) + var.Module.ix['C1'] * (var.DataFrame.Ee ** 2)))*((1 + var.Module.ix['Aimp']*((var.DataFrame.Tcell - T0)))) Bvoco=var.Module.ix['Bvoco'] + var.Module.ix['Mbvoc']*((1 - var.DataFrame.Ee)) delta=var.Module.ix['N']*(k)*((var.DataFrame.Tcell + 273.15)) / q var.DataFrame['Voc']=(var.Module.ix['Voco'] + var.Module.ix['#Series']*(delta)*(Np.log(var.DataFrame.Ee)) + Bvoco*((var.DataFrame.Tcell - T0))) Bvmpo=var.Module.ix['Bvmpo'] + var.Module.ix['Mbvmp']*((1 - var.DataFrame.Ee)) var.DataFrame['Vmp']=(var.Module.ix['Vmpo'] + var.Module.ix['C2']*(var.Module.ix['#Series'])*(delta)*(Np.log(var.DataFrame.Ee)) + var.Module.ix['C3']*(var.Module.ix['#Series'])*((delta*(Np.log(var.DataFrame.Ee))) ** 2) + Bvmpo*((var.DataFrame.Tcell - T0))) var.DataFrame['Pmp']=var.DataFrame.Imp*var.DataFrame.Vmp var.DataFrame['Ix']=var.Module.ix['IXO'] * (var.Module.ix['C4']*(var.DataFrame.Ee) + var.Module.ix['C5']*((var.DataFrame.Ee) ** 2))*((1 + var.Module.ix['Aisc']*((var.DataFrame.Tcell - T0)))) var.DataFrame['Ixx']=var.Module.ix['IXXO'] * (var.Module.ix['C6']*(var.DataFrame.Ee) + var.Module.ix['C7']*((var.DataFrame.Ee) ** 2))*((1 + var.Module.ix['Aisc']*((var.DataFrame.Tcell - T0)))) return var.DataFrame
def pvl_snlinverter(Inverter, Vmp, Pmp): ''' Converts DC power and voltage to AC power using Sandia's Grid-Connected PV Inverter model Determine the AC power output of an inverter given the DC voltage, DC power, and appropriate Sandia Grid-Connected Photovoltaic Inverter Model parameters. The output, ACPower, is clipped at the maximum power output, and gives a negative power during low-input power conditions, but does NOT account for maximum power point tracking voltage windows nor maximum current or voltage limits on the inverter. Parameters ---------- Inverter : DataFrame A DataFrame defining the inverter to be used, giving the inverter performance parameters according to the Sandia Grid-Connected Photovoltaic Inverter Model (SAND 2007-5036) [1]. A set of inverter performance parameters are provided with PV_LIB, or may be generated from a System Advisor Model (SAM) [2] library using pvl_retreivesam. Required DataFrame components are: ============= ============================================================================================================================================================================================== Field DataFrame ============= ============================================================================================================================================================================================== Inverter.Pac0 AC-power output from inverter based on input power and voltage, (W) Inverter.Pdc0 DC-power input to inverter, typically assumed to be equal to the PV array maximum power, (W) Inverter.Vdc0 DC-voltage level at which the AC-power rating is achieved at the reference operating condition, (V) Inverter.Ps0 DC-power required to start the inversion process, or self-consumption by inverter, strongly influences inverter efficiency at low power levels, (W) Inverter.C0 Parameter defining the curvature (parabolic) of the relationship between ac-power and dc-power at the reference operating condition, default value of zero gives a linear relationship, (1/W) Inverter.C1 Empirical coefficient allowing Pdco to vary linearly with dc-voltage input, default value is zero, (1/V) Inverter.C2 empirical coefficient allowing Pso to vary linearly with dc-voltage input, default value is zero, (1/V) Inverter.C3 empirical coefficient allowing Co to vary linearly with dc-voltage input, default value is zero, (1/V) Inverter.Pnt ac-power consumed by inverter at night (night tare) to maintain circuitry required to sense PV array voltage, (W) ============= ============================================================================================================================================================================================== Vdc : float or DataFrame DC voltages, in volts, which are provided as input to the inverter. Vdc must be >= 0. Pdc : float or DataFrame A scalar or DataFrame of DC powers, in watts, which are provided as input to the inverter. Pdc must be >= 0. Returns ------- ACPower : float or DataFrame Mdeled AC power output given the input DC voltage, Vdc, and input DC power, Pdc. When ACPower would be greater than Pac0, it is set to Pac0 to represent inverter "clipping". When ACPower would be less than Ps0 (startup power required), then ACPower is set to -1*abs(Pnt) to represent nightly power losses. ACPower is not adjusted for maximum power point tracking (MPPT) voltage windows or maximum current limits of the inverter. References ---------- [1] (SAND2007-5036, "Performance Model for Grid-Connected Photovoltaic Inverters by D. King, S. Gonzalez, G. Galbraith, W. Boyson) [2] System Advisor Model web page. https://sam.nrel.gov. See also -------- pvl_sapm pvl_samlibrary pvl_singlediode ''' Vars = locals() Expect = {'Inverter': (''), 'Vmp': '', 'Pmp': ''} var = pvl_tools.Parse(Vars, Expect) Paco = var.Inverter['Paco'] Pdco = var.Inverter['Pdco'] Vdco = var.Inverter['Vdco'] Pso = var.Inverter['Pso'] C0 = var.Inverter['C0'] C1 = var.Inverter['C1'] C2 = var.Inverter['C2'] C3 = var.Inverter['C3'] Pnt = var.Inverter['Pnt'] A = Pdco * ((1 + C1 * ((var.Vmp - Vdco)))) B = Pso * ((1 + C2 * ((var.Vmp - Vdco)))) C = C0 * ((1 + C3 * ((var.Vmp - Vdco)))) ACPower = ((Paco / (A - B)) - C * ((A - B))) * ((var.Pmp - B)) + C * ((var.Pmp - B)**2) ACPower[ACPower > Paco] = Paco ACPower[ACPower < Pso] = -1.0 * abs(Pnt) return ACPower
def pvl_haydavies1980(SurfTilt, SurfAz, DHI, DNI, HExtra, SunZen, SunAz): ''' Determine diffuse irradiance from the sky on a tilted surface using Hay & Davies' 1980 model Hay and Davies' 1980 model determines the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using the surface tilt angle, surface azimuth angle, diffuse horizontal irradiance, direct normal irradiance, extraterrestrial irradiance, sun zenith angle, and sun azimuth angle. Parameters ---------- SurfTilt : float or DataFrame Surface tilt angles in decimal degrees. SurfTilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90) SurfAz : float or DataFrame Surface azimuth angles in decimal degrees. SurfAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, South=180 East = 90, West = 270). DHI : float or DataFrame diffuse horizontal irradiance in W/m^2. DHI must be >=0. DNI : float or DataFrame direct normal irradiance in W/m^2. DNI must be >=0. HExtra : float or DataFrame extraterrestrial normal irradiance in W/m^2. HExtra must be >=0. SunZen : float or DataFrame apparent (refraction-corrected) zenith angles in decimal degrees. SunZen must be >=0 and <=180. SunAz : float or DataFrame Sun azimuth angles in decimal degrees. SunAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, East = 90, West = 270). Returns -------- SkyDiffuse : float or DataFrame the diffuse component of the solar radiation on an arbitrarily tilted surface defined by the Perez model as given in reference [3]. SkyDiffuse is the diffuse component ONLY and does not include the ground reflected irradiance or the irradiance due to the beam. References ----------- [1] Loutzenhiser P.G. et. al. "Empirical validation of models to compute solar irradiance on inclined surfaces for building energy simulation" 2007, Solar Energy vol. 81. pp. 254-267 [2] Hay, J.E., Davies, J.A., 1980. Calculations of the solar radiation incident on an inclined surface. In: Hay, J.E., Won, T.K. (Eds.), Proc. of First Canadian Solar Radiation Data Workshop, 59. Ministry of Supply and Services, Canada. See Also -------- pvl_ephemeris pvl_extraradiation pvl_isotropicsky pvl_reindl1990 pvl_perez pvl_klucher1979 pvl_kingdiffuse pvl_spa ''' Vars = locals() Expect = { 'SurfTilt': ('num', 'x>=0'), 'SurfAz': ('x>=-180'), 'DHI': ('x>=0'), 'DNI': ('x>=0'), 'HExtra': ('x>=0'), 'SunZen': ('x>=0'), 'SunAz': ('x>=-180'), } var = pvl_tools.Parse(Vars, Expect) COSTT = pvl_tools.cosd(SurfTilt) * pvl_tools.cosd(SunZen) + pvl_tools.sind( SurfTilt) * pvl_tools.sind(SunZen) * pvl_tools.cosd(SunAz - SurfAz) RB = np.max(COSTT, 0) / np.max(pvl_tools.cosd(SunZen), 0.01745) AI = DNI / HExtra SkyDiffuse = DHI * ((AI * (RB) + (1 - AI) * (0.5) * ((1 + pvl_tools.cosd(SurfTilt))))) return SkyDiffuse
def pvl_perez(SurfTilt, SurfAz, DHI, DNI, HExtra, SunZen, SunAz, AM, modelt='allsitescomposite1990'): ''' Determine diffuse irradiance from the sky on a tilted surface using one of the Perez models Perez models determine the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using the surface tilt angle, surface azimuth angle, diffuse horizontal irradiance, direct normal irradiance, extraterrestrial irradiance, sun zenith angle, sun azimuth angle, and relative (not pressure-corrected) airmass. Optionally a selector may be used to use any of Perez's model coefficient sets. Parameters ---------- SurfTilt : float or DataFrame Surface tilt angles in decimal degrees. SurfTilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90) SurfAz : float or DataFrame Surface azimuth angles in decimal degrees. SurfAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, South=180 East = 90, West = 270). DHI : float or DataFrame diffuse horizontal irradiance in W/m^2. DHI must be >=0. DNI : float or DataFrame direct normal irradiance in W/m^2. DNI must be >=0. HExtra : float or DataFrame extraterrestrial normal irradiance in W/m^2. HExtra must be >=0. SunZen : float or DataFrame apparent (refraction-corrected) zenith angles in decimal degrees. SunZen must be >=0 and <=180. SunAz : float or DataFrame Sun azimuth angles in decimal degrees. SunAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, East = 90, West = 270). AM : float or DataFrame relative (not pressure-corrected) airmass values. If AM is a DataFrame it must be of the same size as all other DataFrame inputs. AM must be >=0 (careful using the 1/sec(z) model of AM generation) Other Parameters ---------------- model : string (optional, default='allsitescomposite1990') a character string which selects the desired set of Perez coefficients. If model is not provided as an input, the default, '1990' will be used. All possible model selections are: * '1990' * 'allsitescomposite1990' (same as '1990') * 'allsitescomposite1988' * 'sandiacomposite1988' * 'usacomposite1988' * 'france1988' * 'phoenix1988' * 'elmonte1988' * 'osage1988' * 'albuquerque1988' * 'capecanaveral1988' * 'albany1988' Returns -------- SkyDiffuse : float or DataFrame the diffuse component of the solar radiation on an arbitrarily tilted surface defined by the Perez model as given in reference [3]. SkyDiffuse is the diffuse component ONLY and does not include the ground reflected irradiance or the irradiance due to the beam. References ---------- [1] Loutzenhiser P.G. et. al. "Empirical validation of models to compute solar irradiance on inclined surfaces for building energy simulation" 2007, Solar Energy vol. 81. pp. 254-267 [2] Perez, R., Seals, R., Ineichen, P., Stewart, R., Menicucci, D., 1987. A new simplified version of the Perez diffuse irradiance model for tilted surfaces. Solar Energy 39(3), 221-232. [3] Perez, R., Ineichen, P., Seals, R., Michalsky, J., Stewart, R., 1990. Modeling daylight availability and irradiance components from direct and global irradiance. Solar Energy 44 (5), 271-289. [4] Perez, R. et. al 1988. "The Development and Verification of the Perez Diffuse Radiation Model". SAND88-7030 See also -------- pvl_ephemeris pvl_extraradiation pvl_isotropicsky pvl_haydavies1980 pvl_reindl1990 pvl_klucher1979 pvl_kingdiffuse pvl_relativeairmass ''' Vars = locals() Expect = { 'SurfTilt': ('num', 'x>=0'), 'SurfAz': ('x>=-180'), 'DHI': ('x>=0'), 'DNI': ('x>=0'), 'HExtra': ('x>=0'), 'SunZen': ('x>=0'), 'SunAz': ('x>=-180'), 'AM': ('x>=0'), 'modelt': ('default', 'default=allsitescomposite1990') } var = pvl_tools.Parse(Vars, Expect) kappa = 1.041 #for SunZen in radians z = var.SunZen * np.pi / 180 # # convert to radians Dhfilter = var.DHI > 0 e = ((var.DHI[Dhfilter] + var.DNI[Dhfilter]) / var.DHI[Dhfilter] + kappa * z[Dhfilter]**3) / (1 + kappa * z[Dhfilter]**3).reindex_like( var.SunZen) ebin = pd.Series(np.zeros(var.DHI.shape[0]), index=e.index) # Select which bin e falls into ebin[(e < 1.065)] = 1 ebin[(e >= 1.065) & (e < 1.23)] = 2 ebin[(e >= 1.23) & (e < 1.5)] = 3 ebin[(e >= 1.5) & (e < 1.95)] = 4 ebin[(e >= 1.95) & (e < 2.8)] = 5 ebin[(e >= 2.8) & (e < 4.5)] = 6 ebin[(e >= 4.5) & (e < 6.2)] = 7 ebin[e >= 6.2] = 8 ebinfilter = ebin > 0 ebin = ebin - 1 #correct for 0 indexing ebin[ebinfilter == False] = np.NaN ebin = ebin.dropna().astype(int) # This is added because in cases where the sun is below the horizon # (var.SunZen > 90) but there is still diffuse horizontal light (var.DHI>0), it is # possible that the airmass (var.AM) could be NaN, which messes up later # calculations. Instead, if the sun is down, and there is still var.DHI, we set # the airmass to the airmass value on the horizon (approximately 37-38). #var.AM(var.SunZen >=90 & var.DHI >0) = 37; var.HExtra[var.HExtra == 0] = .00000001 #very hacky, fix this delt = var.DHI * var.AM / var.HExtra # # The various possible sets of Perez coefficients are contained # in a subfunction to clean up the code. F1c, F2c = GetPerezCoefficients(var.modelt) F1 = F1c[ebin, 0] + F1c[ebin, 1] * delt[ebinfilter] + F1c[ebin, 2] * z[ebinfilter] F1[F1 < 0] = 0 F1 = F1.astype(float) F2 = F2c[ebin, 0] + F2c[ebin, 1] * delt[ebinfilter] + F2c[ebin, 2] * z[ebinfilter] F2[F2 < 0] = 0 F2 = F2.astype(float) A = pvl_tools.cosd(var.SurfTilt) * pvl_tools.cosd( var.SunZen) + pvl_tools.sind(var.SurfTilt) * pvl_tools.sind( var.SunZen) * pvl_tools.cosd(var.SunAz - var.SurfAz) #removed +180 from azimuth modifier: Rob Andrews October 19th 2012 A[A < 0] = 0 B = pvl_tools.cosd(var.SunZen) B[B < pvl_tools.cosd(85)] = pvl_tools.cosd(85) #Calculate Diffuse POA from sky dome #SkyDiffuse = pd.Series(np.zeros(var.DHI.shape[0]),index=data.index) SkyDiffuse = var.DHI[ebinfilter] * ( 0.5 * (1 - F1[ebinfilter]) * (1 + pvl_tools.cosd(var.SurfTilt)) + F1[ebinfilter] * A[ebinfilter] / B[ebinfilter] + F2[ebinfilter] * pvl_tools.sind(var.SurfTilt)) SkyDiffuse[SkyDiffuse <= 0] = 0 return pd.DataFrame({'In_Plane_SkyDiffuse': SkyDiffuse})
def pvl_ashraeiam(b, theta): ''' Determine the incidence angle modifier using the ASHRAE transmission model. pvl_ashraeiam calculates the incidence angle modifier as developed in [1], and adopted by ASHRAE (American Society of Heating, Refrigeration, and Air Conditioning Engineers) [2]. The model has been used by model programs such as PVSyst [3]. Note: For incident angles near 90 degrees, this model has a discontinuity which has been addressed in this function. Parameters ---------- b : float A parameter to adjust the modifier as a function of angle of incidence. Typical values are on the order of 0.05 [3]. theta : DataFrame The angle of incidence between the module normal vector and the sun-beam vector in degrees. Theta must be a numeric scalar or vector. For any values of theta where abs(theta)>90, IAM is set to 0. For any values of theta where -90 < theta < 0, theta is set to abs(theta) and evaluated. A warning will be generated if any(theta<0 or theta>90). For values of theta near 90 degrees, the ASHRAE model may be above 1 or less than 0 due to the discontinuity of secant(theta). IAM values outside of [0,1] are set to 0 and a warning is generated. Returns ------- IAM : DataFrame The incident angle modifier calculated as 1-b*(sec(theta)-1) as described in [2,3]. IAM is a column vector with the same number of elements as the largest input vector. References ---------- [1] Souka A.F., Safwat H.H., "Determindation of the optimum orientations for the double exposure flat-plate collector and its reflections". Solar Energy vol .10, pp 170-174. 1966. [2] ASHRAE standard 93-77 [3] PVsyst Contextual Help. http://files.pvsyst.com/help/index.html?iam_loss.htm retrieved on September 10, 2012 See Also -------- pvl_getaoi pvl_ephemeris pvl_spa pvl_physicaliam ''' Vars = locals() Expect = {'b': 'x >= 0', 'theta': 'num'} var = pvl_tools.Parse(Vars, Expect) if any((var.theta < 0) | (var.theta >= 90)): print( 'Input incident angles <0 or >=90 detected For input angles with absolute value greater than 90, the ' + 'modifier is set to 0. For input angles between -90 and 0, the ' + 'angle is changed to its absolute value and evaluated.') var.theta[(var.theta < 0) | (var.theta >= 90)] = abs((var.theta < 0) | (var.theta >= 90)) IAM = 1 - var.b * ((1 / np.cos(np.radians(var.theta)) - 1)) IAM[abs(var.theta) > 90] = 0 if any((IAM > 1) | (IAM < 0)): print( 'It seems that we have encountered a discontinuity. Any incident angle modifiers calculated to be less than 0 or ' + 'greather than 1 have been set to 0.') IAM[((IAM > 1) | (IAM < 0))] = 0 return IAM
def pvl_perez(**kwargs): Expect = { 'DataFrame': 'df', 'SurfTilt': ('num', 'x>=0'), 'SurfAz': ('num', 'x>=0'), 'DHI': ('matelement', 'num', 'array', 'x>=0'), 'DNI': ('matelement', 'num', 'array', 'x>=0'), 'HExtra': ('matelement', 'num', 'array', 'x>=0'), 'SunZen': ('matelement', 'num', 'array', 'x>=0'), 'SunAz': ('matelement', 'num', 'array', 'x>=0'), 'AM': ('matelement', 'num', 'array', 'x>=0'), 'modelt': ('default', 'default=allsitescomposite1990') } var = pvl_tools.Parse(kwargs, Expect) kappa = 1.041 #for SunZen in radians z = var.DataFrame.SunZen * np.pi / 180 # # convert to radians Dhfilter = var.DataFrame.DHI > 0 e = ((var.DataFrame.DHI[Dhfilter] + var.DataFrame.DNI[Dhfilter]) / var.DataFrame.DHI[Dhfilter] + kappa * z[Dhfilter]**3) / ( 1 + kappa * z[Dhfilter]**3).reindex_like(var.DataFrame.SunZen) #pdb.set_trace() ebin = pd.Series(np.zeros(var.DataFrame.DHI.shape[0]), index=var.DataFrame.index) # Select which bin e falls into ebin[(e < 1.065)] = 1 ebin[(e >= 1.065) & (e < 1.23)] = 2 ebin[(e >= 1.23) & (e < 1.5)] = 3 ebin[(e >= 1.5) & (e < 1.95)] = 4 ebin[(e >= 1.95) & (e < 2.8)] = 5 ebin[(e >= 2.8) & (e < 4.5)] = 6 ebin[(e >= 4.5) & (e < 6.2)] = 7 ebin[e >= 6.2] = 8 ebinfilter = ebin > 0 ebin = ebin - 1 #correct for 0 indexing ebin[ebinfilter == False] = np.NaN ebin = ebin.dropna().astype(int) # This is added because in cases where the sun is below the horizon # (var.DataFrame.SunZen > 90) but there is still diffuse horizontal light (var.DataFrame.DHI>0), it is # possible that the airmass (var.DataFrame.AM) could be NaN, which messes up later # calculations. Instead, if the sun is down, and there is still var.DataFrame.DHI, we set # the airmass to the airmass value on the horizon (approximately 37-38). #var.DataFrame.AM(var.DataFrame.SunZen >=90 & var.DataFrame.DHI >0) = 37; var.DataFrame.HExtra[var.DataFrame.HExtra == 0] = .00000001 #very hacky, fix this delt = var.DataFrame.DHI * var.DataFrame.AM / var.DataFrame.HExtra # # The various possible sets of Perez coefficients are contained # in a subfunction to clean up the code. F1c, F2c = GetPerezCoefficients(var.modelt) F1 = F1c[ebin, 0] + F1c[ebin, 1] * delt[ebinfilter] + F1c[ebin, 2] * z[ebinfilter] F1[F1 < 0] = 0 F1 = F1.astype(float) F2 = F2c[ebin, 0] + F2c[ebin, 1] * delt[ebinfilter] + F2c[ebin, 2] * z[ebinfilter] F2[F2 < 0] = 0 F2 = F2.astype(float) A = cosd(var.SurfTilt) * cosd(var.DataFrame.SunZen) + sind( var.SurfTilt) * sind( var.DataFrame.SunZen) * cosd(var.DataFrame.SunAz - var.SurfAz) #removed +180 from azimuth modifier: Rob Andrews October 19th 2012 A[A < 0] = 0 B = cosd(var.DataFrame.SunZen) B[B < cosd(85)] = cosd(85) #Calculate Diffuse POA from sky dome #SkyDiffuse = pd.Series(np.zeros(var.DataFrame.DHI.shape[0]),index=data.index) SkyDiffuse = var.DataFrame.DHI[ebinfilter] * ( 0.5 * (1 - F1[ebinfilter]) * (1 + cosd(var.SurfTilt)) + F1[ebinfilter] * A[ebinfilter] / B[ebinfilter] + F2[ebinfilter] * sind(var.SurfTilt)) SkyDiffuse[SkyDiffuse <= 0] = 0 var.DataFrame['In_Plane_SkyDiffuse'] = SkyDiffuse return var.DataFrame
def pvl_sapmcelltemp(E, Wspd, Tamb,modelt='Open_rack_cell_glassback',**kwargs): ''' Estimate cell temperature from irradiance, windspeed, ambient temperature, and module parameters (SAPM) Estimate cell and module temperatures per the Sandia PV Array Performance model (SAPM, SAND2004-3535), when given the incident irradiance, wind speed, ambient temperature, and SAPM module parameters. Parameters ---------- E : float or DataFrame Total incident irradiance in W/m^2. Must be >=0. windspeed : float or DataFrame Wind speed in m/s at a height of 10 meters. Must be >=0 Tamb : float or DataFrame Ambient dry bulb temperature in degrees C. Must be >= -273.15. Other Parameters ---------------- modelt : string Model to be used for parameters, can be: * 'Open_rack_cell_glassback' (DEFAULT) * 'Roof_mount_cell_glassback' * 'Open_rack_cell_polymerback' * 'Insulated_back_polumerback' * 'Open_rack_Polymer_thinfilm_steel' * '22X_Concentrator_tracker' a : float (optional) SAPM module parameter for establishing the upper limit for module temperature at low wind speeds and high solar irradiance (see SAPM eqn. 11). Must be a scalar.If not input, this value will be taken from the chosen model b : float (optional) SAPM module parameter for establishing the rate at which the module temperature drops as wind speed increases (see SAPM eqn. 11). Must be a scalar.If not input, this value will be taken from the chosen model deltaT : float (optional) SAPM module parameter giving the temperature difference between the cell and module back surface at the reference irradiance, E0. Must be a numeric scalar >=0. If not input, this value will be taken from the chosen model Returns -------- Tcell : float or DataFrame Cell temperatures in degrees C. Tmodule : float or DataFrame Module back temperature in degrees C. References ---------- [1] King, D. et al, 2004, "Sandia Photovoltaic Array Performance Model", SAND Report 3535, Sandia National Laboratories, Albuquerque, NM See Also -------- pvl_sapm ''' Vars=locals() Expect={'a':('optional','num'), 'b':('optional','num'), 'deltaT':('optional','num'), 'E':('x>=0'), 'Wspd':('x>=0'), 'Tamb':('x>=0'), 'modelt': ('default','default=Open_rack_cell_glassback') } var=pvl_tools.Parse(Vars,Expect) TempModel={'Open_rack_cell_glassback':[-3.47, -.0594, 3], 'Roof_mount_cell_glassback':[-2.98, -.0471, 1], 'Open_rack_cell_polymerback': [-3.56, -.0750, 3], 'Insulated_back_polumerback': [-2.81, -.0455, 0 ], 'Open_rack_Polymer_thinfilm_steel':[-3.58, -.113, 3], '22X_Concentrator_tracker':[-3.23, -.130, 13] } try: a=var.a b=var.b deltaT=var.deltaT except: a=TempModel[var.modelt][0] b=TempModel[var.modelt][1] deltaT=TempModel[var.modelt][2] E0=1000 # Reference irradiance Tmodule=var.E*((np.exp(a + b*var.Wspd))) + var.Tamb Tcell=Tmodule + var.E / E0*(deltaT) return Tcell, Tmodule
def pvl_kingdiffuse(SurfTilt, DHI, GHI, SunZen): ''' Determine diffuse irradiance from the sky on a tilted surface using the King model King's model determines the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using the surface tilt angle, diffuse horizontal irradiance, global horizontal irradiance, and sun zenith angle. Note that this model is not well documented and has not been published in any fashion (as of January 2012). Parameters ---------- SurfTilt : float or DataFrame Surface tilt angles in decimal degrees. SurfTilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90) DHI : float or DataFrame diffuse horizontal irradiance in W/m^2. DHI must be >=0. GHI : float or DataFrame global horizontal irradiance in W/m^2. DHI must be >=0. SunZen : float or DataFrame apparent (refraction-corrected) zenith angles in decimal degrees. SunZen must be >=0 and <=180. Returns -------- SkyDiffuse : float or DataFrame the diffuse component of the solar radiation on an arbitrarily tilted surface as given by a model developed by David L. King at Sandia National Laboratories. See Also -------- pvl_ephemeris pvl_extraradiation pvl_isotropicsky pvl_haydavies1980 pvl_perez pvl_klucher1979 pvl_reindl1990 ''' Vars = locals() Expect = { 'SurfTilt': ('num', 'x>=0'), 'SunZen': ('x>=-180'), 'DHI': ('x>=0'), 'GHI': ('x>=0') } var = pvl_tools.Parse(Vars, Expect) SkyDiffuse = DHI * ((1 + pvl_tools.cosd(SurfTilt))) / 2 + GHI * ( (0.012 * SunZen - 0.04)) * ((1 - pvl_tools.cosd(SurfTilt))) / 2 return SkyDiffuse
def pvl_ephemeris(Time, Location, pressure=101325, temperature=12): ''' Calculates the position of the sun given time, location, and optionally pressure and temperature Parameters ---------- Time : `pandas.Index <http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.Index.html>`_ Location: struct *Location.latitude* - vector or scalar latitude in decimal degrees (positive is northern hemisphere) *Location.longitude* - vector or scalar longitude in decimal degrees (positive is east of prime meridian) *Location.altitude* - an optional component of the Location struct, not used in the ephemeris code directly, but it may be used to calculate standard site pressure (see pvl_alt2pres function) *location.TZ* - Time Zone offset from UTC Other Parameters ---------------- pressure : float or DataFrame Ambient pressure (Pascals) temperature: float or DataFrame Ambient temperature (C) Returns ------- SunAz : float of DataFrame Azimuth of the sun in decimal degrees from North. 0 = North to 270 = West SunEl : float of DataFrame Actual elevation (not accounting for refraction)of the sun in decimal degrees, 0 = on horizon. The complement of the True Zenith Angle. ApparentSunEl : float or DataFrame Apparent sun elevation accounting for atmospheric refraction. This is the complement of the Apparent Zenith Angle. SolarTime : fload or DataFrame Solar time in decimal hours (solar noon is 12.00). References ----------- Grover Hughes' class and related class materials on Engineering Astronomy at Sandia National Laboratories, 1985. See also -------- pvl_makelocationstruct pvl_alt2pres pvl_getaoi pvl_spa ''' Vars = locals() Expect = { 'pressure': ('default', 'default=101325', 'array', 'num', 'x>=0'), 'temperature': ('default', 'default=12', 'array', 'num', 'x>=-273.15'), 'Time': '', 'Location': '' } var = pvl_tools.Parse(Vars, Expect) Latitude = var.Location['latitude'] ''' the inversion of longitude is due to the fact that this code was originally written for the convention that positive longitude were for locations west of the prime meridian. However, the correct convention (as of 2009) is to use negative longitudes for locations west of the prime meridian. Therefore, the user should input longitude values under the correct convention (e.g. Albuquerque is at -106 longitude), but it needs to be inverted for use in the code. ''' Latitude = var.Location['latitude'] Longitude = 1 * var.Location['longitude'] Year = var.Time.year Month = var.Time.month Day = var.Time.day Hour = var.Time.hour Minute = var.Time.minute Second = var.Time.second DayOfYear = var.Time.dayofyear DecHours = Hour + Minute / float(60) + Second / float(3600) Abber = 20 / float(3600) LatR = np.radians(Latitude) UnivDate = DayOfYear UnivHr = DecHours + var.Location['TZ'] #-.5 #+60/float(60)/2 Yr = Year - 1900 YrBegin = 365 * Yr + np.floor((Yr - 1) / float(4)) - 0.5 Ezero = YrBegin + UnivDate T = Ezero / float(36525) GMST0 = 6 / float(24) + 38 / float(1440) + (45.836 + 8640184.542 * T + 0.0929 * T**2) / float(86400) GMST0 = 360 * (GMST0 - np.floor(GMST0)) GMSTi = np.mod(GMST0 + 360 * (1.0027379093 * UnivHr / float(24)), 360) LocAST = np.mod((360 + GMSTi - Longitude), 360) EpochDate = Ezero + UnivHr / float(24) T1 = EpochDate / float(36525) ObliquityR = np.radians(23.452294 - 0.0130125 * T1 - 1.64e-06 * T1**2 + 5.03e-07 * T1**3) MlPerigee = 281.22083 + 4.70684e-05 * EpochDate + 0.000453 * T1**2 + 3e-06 * T1**3 MeanAnom = np.mod((358.47583 + 0.985600267 * EpochDate - 0.00015 * T1**2 - 3e-06 * T1**3), 360) Eccen = 0.01675104 - 4.18e-05 * T1 - 1.26e-07 * T1**2 EccenAnom = MeanAnom E = 0 while np.max(abs(EccenAnom - E)) > 0.0001: E = EccenAnom EccenAnom = MeanAnom + np.degrees(Eccen) * (np.sin(np.radians(E))) #pdb.set_trace() TrueAnom = 2 * np.mod( np.degrees( np.arctan2(((1 + Eccen) / (1 - Eccen))**0.5 * np.tan(np.radians(EccenAnom) / float(2)), 1)), 360) EcLon = np.mod(MlPerigee + TrueAnom, 360) - Abber EcLonR = np.radians(EcLon) DecR = np.arcsin(np.sin(ObliquityR) * (np.sin(EcLonR))) Dec = np.degrees(DecR) #pdb.set_trace() RtAscen = np.degrees( np.arctan2(np.cos(ObliquityR) * ((np.sin(EcLonR))), np.cos(EcLonR))) HrAngle = LocAST - RtAscen HrAngleR = np.radians(HrAngle) HrAngle = HrAngle - (360 * ((abs(HrAngle) > 180))) SunAz = np.degrees( np.arctan2( -1 * np.sin(HrAngleR), np.cos(LatR) * (np.tan(DecR)) - np.sin(LatR) * (np.cos(HrAngleR)))) SunAz = SunAz + (SunAz < 0) * 360 SunEl = np.degrees( np.arcsin((np.cos(LatR) * (np.cos(DecR)) * (np.cos(HrAngleR)) + np.sin(LatR) * (np.sin(DecR))))) #potential error SolarTime = (180 + HrAngle) / float(15) Refract = [] for Elevation in SunEl: TanEl = np.tan(np.radians(Elevation)) if Elevation > 5 and Elevation <= 85: Refract.append((58.1 / float(TanEl) - 0.07 / float(TanEl**3) + 8.6e-05 / float(TanEl**5))) elif Elevation > -0.575 and Elevation <= 5: Refract.append( (Elevation * ((-518.2 + Elevation * ((103.4 + Elevation * ((-12.79 + Elevation * (0.711))))))) + 1735)) elif Elevation > -1 and Elevation <= -0.575: Refract.append(-20.774 / float(TanEl)) else: Refract.append(0) Refract = np.array(Refract) * ((283 / float(273 + var.temperature))) * ( var.pressure) / float(101325) / float(3600) SunZen = 90 - SunEl SunZen[SunZen >= 90] = 90 ApparentSunEl = SunEl + Refract DFOut = pd.DataFrame({'SunEl': SunEl}, index=var.Time) DFOut['SunAz'] = SunAz - 180 #Changed RA Feb 18,2014 to match Duffe DFOut['SunZen'] = SunZen DFOut['ApparentSunEl'] = ApparentSunEl DFOut['SolarTime'] = SolarTime return DFOut['SunAz'], DFOut['SunEl'], DFOut['ApparentSunEl'], DFOut[ 'SolarTime'], DFOut['SunZen']
def pvl_isotropicsky(SurfTilt, DHI): ''' Determine diffuse irradiance from the sky on a tilted surface using isotropic sky model Hottel and Woertz's model treats the sky as a uniform source of diffuse irradiance. Thus the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface can be found from the diffuse horizontal irradiance and the tilt angle of the surface. Parameters ---------- SurfTilt : float or DataFrame Surface tilt angles in decimal degrees. SurfTilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90) DHI : float or DataFrame Diffuse horizontal irradiance in W/m^2. DHI must be >=0. Returns ------- SkyDiffuse : float of DataFrame The diffuse component of the solar radiation on an arbitrarily tilted surface defined by the isotropic sky model as given in Loutzenhiser et. al (2007) equation 3. SkyDiffuse is the diffuse component ONLY and does not include the ground reflected irradiance or the irradiance due to the beam. SkyDiffuse is a column vector vector with a number of elements equal to the input vector(s). References ---------- [1] Loutzenhiser P.G. et. al. "Empirical validation of models to compute solar irradiance on inclined surfaces for building energy simulation" 2007, Solar Energy vol. 81. pp. 254-267 [2] Hottel, H.C., Woertz, B.B., 1942. Evaluation of flat-plate solar heat collector. Trans. ASME 64, 91. See also -------- pvl_reindl1990 pvl_haydavies1980 pvl_perez pvl_klucher1979 pvl_kingdiffuse ''' Vars = locals() Expect = {'SurfTilt': 'x <= 180 & x >= 0 ', 'DHI': 'x>=0'} var = pvl_tools.Parse(Vars, Expect) SkyDiffuse = DHI * (1 + pvl_tools.cosd(SurfTilt)) * 0.5 return SkyDiffuse
def pvl_getaoi(SurfTilt, SurfAz, SunZen, SunAz): ''' Determine angle of incidence from surface tilt/azimuth and apparent sun zenith/azimuth The surface is defined by its tilt angle from horizontal and its azimuth pointing angle. The sun position is defined by the apparent (refraction corrected)sun zenith angle and the sun azimuth angle. Parameters ---------- SurfTilt : scalar or DataFrame of surface tilt angles in decimal degrees If SurfTilt is a DataFrame it must be of the same size as all other DataFrame inputs. SurfTilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90) SurfAz : scalar or DataFrame of the surface azimuth angles in decimal degrees If SurfAz is a DataFrame it must be of the same size as all other DataFrame inputs. SurfAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, East = 90, West = 270). SunZen : scalar or DataFrame of apparent (refraction-corrected) zenith angles in decimal degrees. If SunZen is a DataFrame it must be of the same size as all other DataFrame inputs. SunZen must be >=0 and <=180. SunAz : scalar or DataFrame of sun azimuth angles in decimal degrees If SunAz is a DataFrame it must be of the same size as all other DataFrame inputs. SunAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, East = 90, West = 270). Returns ------- AOI : DataFrame The angle, in decimal degrees, between the surface normal DataFrame and the sun beam DataFrame. References ---------- D.L. King, J.A. Kratochvil, W.E. Boyson. "Spectral and Angle-of-Incidence Effects on Photovoltaic Modules and Solar Irradiance Sensors". 26th IEEE Photovoltaic Specialists Conference. Sept. 1997. See Also -------- PVL_EPHEMERIS ''' Vars = locals() Expect = { 'SurfTilt': ('num', 'x>=0'), 'SurfAz': ('num', 'x>=-180', 'x<=180'), 'SunZen': ('x>=0'), 'SunAz': ('x>=0') } var = pvl_tools.Parse(Vars, Expect) AOI = np.degrees( np.arccos( np.cos(np.radians(var.SunZen)) * (np.cos(np.radians(var.SurfTilt))) + np.sin(np.radians(var.SurfTilt)) * (np.sin(np.radians(var.SunZen))) * (np.cos(np.radians(var.SunAz) - np.radians(var.SurfAz)))) ) #Duffie and Beckmann 1.6.3 return pd.DataFrame({'AOI': AOI})
def pvl_clearsky_ineichen(Time, Location, LinkeTurbidity=-999): ''' 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 presented in [1, 2]. A report on clear sky models found the Ineichen/Perez model to have excellent performance with a minimal input data set [3]. Default values for Linke turbidity provided by SoDa [4, 5]. Parameters ---------- Time : Dataframe.index A timezone aware pandas dataframe index. Location : dict latitude vector or scalar latitude in decimal degrees (positive is northern hemisphere) longitude vector or scalar longitude in decimal degrees (positive is east of prime meridian) altitude an optional component of the Location struct, not used in the ephemeris code directly, but it may be used to calculate standard site pressure (see pvl_alt2pres function) TZ Time Zone offset from UTC Other Parameters ---------------- LinkeTurbidityInput : Optional, float or DataFrame An optional input to provide your own Linke turbidity. If this input is omitted, the default Linke turbidity maps will be used. LinkeTurbidityInput may be a float or dataframe of Linke turbidities. If dataframe is provided, the same turbidity will be used for all time/location sets. If a dataframe is provided, it must be of the same size as any time/location dataframes and each element of the dataframe corresponds to any time and location elements. Returns ------- ClearSkyGHI : Dataframe the modeled global horizonal irradiance in W/m^2 provided by the Ineichen clear-sky model. ClearSkyDNI : Dataframe the modeled direct normal irradiance in W/m^2 provided by the Ineichen clear-sky model. ClearSkyDHI : Dataframe the calculated diffuse horizonal irradiance in W/m^2 provided by the Ineichen clear-sky model. Notes ----- This implementation of the Ineichen model requires a number of other PV_LIB functions including pvl_ephemeris, pvl_date2doy, pvl_extraradiation, pvl_absoluteairmass, pvl_relativeairmass, and pvl_alt2pres. It also requires the file "LinkeTurbidities.mat" to be in the working directory. If you are using pvl_ineichen in a loop, it may be faster to load LinkeTurbidities.mat outside of the loop and feed it into pvl_ineichen as a variable, rather than having pvl_ineichen open the file each time it is called (or utilize column vectors of time/location instead of a loop). Initial implementation of this algorithm by Matthew Reno. References ---------- [1] P. Ineichen and R. Perez, "A New airmass independent formulation for the Linke turbidity coefficient", Solar Energy, vol 73, pp. 151-157, 2002. [2] R. Perez et. al., "A New Operational Model for Satellite-Derived Irradiances: Description and Validation", Solar Energy, vol 73, pp. 307-317, 2002. [3] M. Reno, C. Hansen, and J. Stein, "Global Horizontal Irradiance Clear Sky Models: Implementation and Analysis", Sandia National Laboratories, SAND2012-2389, 2012. [4] http://www.soda-is.com/eng/services/climat_free_eng.php#c5 (obtained July 17, 2012). [5] J. Remund, et. al., "Worldwide Linke Turbidity Information", Proc. ISES Solar World Congress, June 2003. Goteborg, Sweden. See Also -------- pvl_maketimestruct pvl_makelocationstruct pvl_ephemeris pvl_haurwitz ''' Vars = locals() Expect = {'Time': (''), 'Location': (''), 'LinkeTurbidity': ('optional')} var = pvl_tools.Parse(Vars, Expect) I0 = pvl_extraradiation.pvl_extraradiation(var.Time.dayofyear) __, __, ApparentSunElevation, __, __ = pvl_ephemeris.pvl_ephemeris( var.Time, var.Location, pvl_alt2pres.pvl_alt2pres(var.Location['altitude'])) # nargout=4 ApparentZenith = 90 - ApparentSunElevation ApparentZenith[ApparentZenith >= 90] = 90 if LinkeTurbidity == -999: # The .mat file 'LinkeTurbidities.mat' contains a single 2160 x 4320 x 12 # matrix of type uint8 called 'LinkeTurbidity'. The rows represent global # latitudes from 90 to -90 degrees; the columns represent global longitudes # from -180 to 180; and the depth (third dimension) represents months of # the year from January (1) to December (12). To determine the Linke # turbidity for a position on the Earth's surface for a given month do the # following: LT = LinkeTurbidity(LatitudeIndex, LongitudeIndex, month). Note that the numbers within the matrix are 20 * Linke # Turbidity, so divide the number from the file by 20 to get the # turbidity. mat = scipy.io.loadmat('LinkeTurbidities.mat') LinkeTurbidity = mat['LinkeTurbidity'] LatitudeIndex = np.round_( LinearlyScale(Location['latitude'], 90, -90, 1, 2160)) LongitudeIndex = np.round_( LinearlyScale(Location['longitude'], -180, 180, 1, 4320)) g = LinkeTurbidity[LatitudeIndex][LongitudeIndex] ApplyMonth = lambda x: g[x[0] - 1] LT = pd.DataFrame(Time.month) LT.index = Time LT = LT.apply(ApplyMonth, axis=1) TL = LT / float(20) else: TL = var.LinkeTurbidity # Get the absolute airmass assuming standard local pressure (per # pvl_alt2pres) using Kasten and Young's 1989 formula for airmass. AMabsolute = pvl_absoluteairmass.pvl_absoluteairmass( AMrelative=pvl_relativeairmass.pvl_relativeairmass( ApparentZenith, model='kastenyoung1989'), Pressure=pvl_alt2pres.pvl_alt2pres(var.Location['altitude'])) fh1 = np.exp(var.Location['altitude'] * ((-1 / 8000))) fh2 = np.exp(var.Location['altitude'] * ((-1 / 1250))) cg1 = (5.09e-05 * (var.Location['altitude']) + 0.868) cg2 = 3.92e-05 * (var.Location['altitude']) + 0.0387 # Dan's note on the TL correction: By my reading of the publication on # pages 151-157, Ineichen and Perez introduce (among other things) three # things. 1) Beam model in eqn. 8, 2) new turbidity factor in eqn 9 and # appendix A, and 3) Global horizontal model in eqn. 11. They do NOT appear # to use the new turbidity factor (item 2 above) in either the beam or GHI # models. The phrasing of appendix A seems as if there are two separate # corrections, the first correction is used to correct the beam/GHI models, # and the second correction is used to correct the revised turibidity # factor. In my estimation, there is no need to correct the turbidity # factor used in the beam/GHI models. # Create the corrected TL for TL < 2 # TLcorr = TL; # TLcorr(TL < 2) = TLcorr(TL < 2) - 0.25 .* (2-TLcorr(TL < 2)) .^ (0.5); # This equation is found in Solar Energy 73, pg 311. It is slightly # different than the equation given in Solar Energy 73, pg 156. We used the # equation from pg 311 because of the existence of known typos in the pg 156 # publication (notably the fh2-(TL-1) should be fh2 * (TL-1)). ClearSkyGHI = cg1 * (I0) * (pvl_tools.cosd(ApparentZenith)) * (np.exp( -cg2 * (AMabsolute) * ((fh1 + fh2 * ((TL - 1)))))) * (np.exp(0.01 * ((AMabsolute)**(1.8)))) ClearSkyGHI[ClearSkyGHI < 0] = 0 b = 0.664 + 0.163 / fh1 BncI = b * (I0) * (np.exp(-0.09 * (AMabsolute) * ((TL - 1)))) ClearSkyDNI = np.min( BncI, ClearSkyGHI * ((1 - (0.1 - 0.2 * (np.exp(-TL))) / (0.1 + 0.882 / fh1))) / pvl_tools.cosd(ApparentZenith)) #ClearSkyDNI=ClearSkyGHI*((1 - (0.1 - 0.2*(np.exp(- TL))) / (0.1 + 0.882 / fh1))) / pvl_tools.cosd(ApparentZenith) ClearSkyDHI = ClearSkyGHI - ClearSkyDNI * (pvl_tools.cosd(ApparentZenith)) return ClearSkyGHI, ClearSkyDNI, ClearSkyDHI, BncI
def pvl_retreiveSAM(name, FileLoc='none'): ''' Retreive lastest module and inverter info from SAM website PVL_RETREIVESAM Retreive lastest module and inverter info from SAM website. This function will retreive either: * CEC module database * Sandia Module database * Sandia Inverter database and export it as a pandas dataframe Parameters ---------- name: String Name can be one of: * 'CECMod'- returns the CEC module database * 'SandiaInverter- returns the Sandia Inverter database * 'SandiaMod'- returns the Sandia Module database FileLoc: String Absolute path to the location of local versions of the SAM file. If FileLoc is specified, the latest versions of the SAM database will not be downloaded. The selected file must be in .csv format. If set to 'select', a dialogue will open allowing the suer to navigate to the appropriate page. Returns ------- df: DataFrame A DataFrame containing all the elements of the desired database. Each column representa a module or inverter, and a specific dataset can be retreived by the command >>> df.module_or_inverter_name Examples -------- >>> Invdb=SAM.pvl_retreiveSAM(name='SandiaInverter') >>> inverter=Invdb.AE_Solar_Energy__AE6_0__277V__277V__CEC_2012_ >>> inverter Vac 277.000000 Paco 6000.000000 Pdco 6165.670000 Vdco 361.123000 Pso 36.792300 C0 -0.000002 C1 -0.000047 C2 -0.001861 C3 0.000721 Pnt 0.070000 Vdcmax 600.000000 Idcmax 32.000000 Mppt_low 200.000000 Mppt_high 500.000000 Name: AE_Solar_Energy__AE6_0__277V__277V__CEC_2012_, dtype: float64 ''' Vars = locals() Expect = { 'name': ('str', ('CECMod', 'SandiaMod', 'SandiaInverter')), 'FileLoc': ('optional') } var = pvl_tools.Parse(Vars, Expect) if var.name == 'CECMod': url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/sam-library-cec-modules-2014-1-14.csv' elif var.name == 'SandiaMod': url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/sam-library-sandia-modules-2014-1-14.csv' elif var.name == 'SandiaInverter': url = 'https://sam.nrel.gov/sites/sam.nrel.gov/files/sam-library-sandia-inverters-2014-1-14.csv' if FileLoc == 'none': return read_url_to_pandas(url) elif FileLoc == 'select': try: import Tkinter from tkFileDialog import askopenfilename Tkinter.Tk().withdraw() #Start interactive file input return read_relative_to_pandas(askopenfilename()) except: raise Exception( 'Python not configured for TKinter. Try installing XQuartz and rerunning' ) else: return read_relative_to_pandas(FileLoc)
def pvl_klucher1979(SurfTilt, SurfAz, DHI, GHI, SunZen, SunAz): ''' Determine diffuse irradiance from the sky on a tilted surface using Klucher's 1979 model Klucher's 1979 model determines the diffuse irradiance from the sky (ground reflected irradiance is not included in this algorithm) on a tilted surface using the surface tilt angle, surface azimuth angle, diffuse horizontal irradiance, direct normal irradiance, global horizontal irradiance, extraterrestrial irradiance, sun zenith angle, and sun azimuth angle. Parameters ---------- SurfTilt : float or DataFrame Surface tilt angles in decimal degrees. SurfTilt must be >=0 and <=180. The tilt angle is defined as degrees from horizontal (e.g. surface facing up = 0, surface facing horizon = 90) SurfAz : float or DataFrame Surface azimuth angles in decimal degrees. SurfAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, South=180 East = 90, West = 270). DHI : float or DataFrame diffuse horizontal irradiance in W/m^2. DHI must be >=0. GHI : float or DataFrame Global irradiance in W/m^2. DNI must be >=0. SunZen : float or DataFrame apparent (refraction-corrected) zenith angles in decimal degrees. SunZen must be >=0 and <=180. SunAz : float or DataFrame Sun azimuth angles in decimal degrees. SunAz must be >=0 and <=360. The Azimuth convention is defined as degrees east of north (e.g. North = 0, East = 90, West = 270). Returns ------- SkyDiffuse : float or DataFrame the diffuse component of the solar radiation on an arbitrarily tilted surface defined by the Klucher model as given in Loutzenhiser et. al (2007) equation 4. SkyDiffuse is the diffuse component ONLY and does not include the ground reflected irradiance or the irradiance due to the beam. SkyDiffuse is a column vector vector with a number of elements equal to the input vector(s). References ---------- [1] Loutzenhiser P.G. et. al. "Empirical validation of models to compute solar irradiance on inclined surfaces for building energy simulation" 2007, Solar Energy vol. 81. pp. 254-267 [2] Klucher, T.M., 1979. Evaluation of models to predict insolation on tilted surfaces. Solar Energy 23 (2), 111-114. See also -------- pvl_ephemeris pvl_extraradiation pvl_isotropicsky pvl_haydavies1980 pvl_perez pvl_reindl1990 pvl_kingdiffuse ''' Vars = locals() Expect = { 'SurfTilt': ('num', 'x>=0'), 'SurfAz': ('x>=-180'), 'DHI': ('x>=0'), 'GHI': ('x>=0'), 'SunZen': ('x>=0'), 'SunAz': ('x>=-180') } var = pvl_tools.Parse(Vars, Expect) GHI[GHI < DHI] = DHI GHI[GHI < 1e-06] = 1e-06 COSTT = pvl_tools.cosd(SurfTilt) * pvl_tools.cosd(SunZen) + pvl_tools.sind( SurfTilt) * pvl_tools.sind(SunZen) * pvl_tools.cosd(SunAz - SurfAz) F = 1 - ((DHI / GHI)**2) SkyDiffuse = DHI * ((0.5 * ((1 + pvl_tools.cosd(SurfTilt))))) * ((1 + F * ( ((pvl_tools.sind(SurfTilt / 2))**3)))) * ((1 + F * (((COSTT)**2)) * (( (pvl_tools.sind(SunZen))**3)))) return SkyDiffuse