### Install pvlib-python from Source Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Installs pvlib-python in development mode from the cloned source directory. ```bash pip install -e . ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst Installs the necessary dependencies for building the pvlib documentation locally. This command is run from the project's root directory. ```bash pip install pvlib[doc] # on Mac: pip install "pvlib[doc]" ``` -------------------------------- ### Install pvlib-python with All Optional Dependencies Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Installs pvlib-python in development mode, including all optional dependencies for testing and documentation. ```bash pip install -e .[all] ``` -------------------------------- ### Sphinx-Gallery Example Template Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst A starter template for creating new examples using sphinx-gallery. It includes the necessary docstring header and basic code structure for execution and output capture. ```python """ Page Title ========== A sentence describing the example. """ # %% # Explanatory text about the example, what it does, why it does it, etc. # Text in the comment block before the first line of code `import pvlib` # will be printed to the example's webpage. import pvlib import matplotlib.pyplot as plt plt.scatter([1, 2, 3], [4, 5, 6]) plt.show() ``` -------------------------------- ### Setup pvlib Environment Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/solarposition.ipynb Imports necessary libraries for scientific computing, data manipulation, and plotting, including pvlib. ```python import datetime # scientific python add-ons import numpy as np import pandas as pd # plotting stuff # first line makes the plots appear in the notebook %matplotlib inline import matplotlib.pyplot as plt ``` -------------------------------- ### Install pvlib-python using Pip (with Optional Dependencies) Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Installs pvlib-python along with all optional dependencies from the Python Package Index using pip. This is an alternative if you know what you are doing and need all features. ```bash pip install pvlib[optional] ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst Builds the HTML documentation locally after installing dependencies. Navigate to the docs/sphinx directory before running this command. ```bash make html ``` -------------------------------- ### Test pvlib-python Installation Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Verifies the pvlib-python installation by importing the library. No output indicates a successful import. ```python python -c 'import pvlib' ``` -------------------------------- ### SPA Calculation Example Source: https://github.com/pvlib/pvlib-python.git/blob/main/pvlib/spa_c_files/README.md This function demonstrates how to call the SPA calculation with various parameters and retrieve the results. It's useful for verifying the installation and consistency of the SPA module. ```python from spa_py_example import spa_calc_example r = spa_calc_example() print(r) ``` -------------------------------- ### Install pvlib-python using Pip (with Optional Dependencies on Mac) Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Installs pvlib-python along with all optional dependencies from the Python Package Index using pip, with specific syntax for macOS. This is an alternative if you know what you are doing and need all features. ```bash pip install "pvlib[optional]" ``` -------------------------------- ### Documenting Direct Normal Irradiance Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst Example of documenting a parameter with its units and a link to its glossary term using Sphinx roles. ```rst dni : numeric Direct normal irradiance, see :term:`dni`. [Wm⁻²] ``` -------------------------------- ### Install pvlib-python using pip Source: https://github.com/pvlib/pvlib-python.git/blob/main/README.md Install the latest release of pvlib-python using the pip package manager. ```bash pip install pvlib ``` -------------------------------- ### Preview ASV HTML report Source: https://github.com/pvlib/pvlib-python.git/blob/main/benchmarks/README.md Start an HTTP server to view the generated test results locally after running `asv publish`. ```bash $ asv preview ``` -------------------------------- ### Full Example: Calculate Irradiance for a Different Date Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tracking.ipynb A comprehensive example demonstrating the calculation of solar position, tracker data, irradiance components, and total plane-of-array irradiance for a summer date. This consolidates multiple steps into a single execution block. ```python times = pd.date_range(start=datetime.datetime(2014,6,23), end=datetime.datetime(2014,6,24), freq='5Min') ephem_tus = pvlib.solarposition.get_solarposition(times.tz_localize(tus.tz), tus.latitude, tus.longitude) ephem_joh = pvlib.solarposition.get_solarposition(times.tz_localize(johannesburg.tz), johannesburg.latitude, johannesburg.longitude) tracker_data = pvlib.tracking.singleaxis(ephem_tus['apparent_zenith'], ephem_tus['azimuth'], axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) tracker_data.plot() plt.ylim(-100,100) irrad_data = tus.get_clearsky(times.tz_localize(tus.tz)) dni_et = pvlib.irradiance.get_extra_radiation(irrad_data.index, method='asce') plt.figure() irrad_data.plot() dni_et.plot(label='DNI ET') ground_irrad = pvlib.irradiance.get_ground_diffuse(tracker_data['surface_tilt'], irrad_data['ghi'], albedo=.25) ground_irrad.plot() ephem_data = ephem_tus haydavies_diffuse = pvlib.irradiance.haydavies(tracker_data['surface_tilt'], tracker_data['surface_azimuth'], irrad_data['dhi'], irrad_data['dni'], dni_et, ephem_data['apparent_zenith'], ephem_data['azimuth']) haydavies_diffuse.plot(label='haydavies diffuse') global_in_plane = cosd(tracker_data['aoi'])*irrad_data['dni'] + haydavies_diffuse + ground_irrad global_in_plane.plot(label='global in plane') plt.legend(); ``` -------------------------------- ### spectrum.get_example_spectral_response Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst Retrieves an example spectral response curve for a PV device. ```APIDOC ## spectrum.get_example_spectral_response ### Description Retrieves an example spectral response curve for a PV device. ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters This function may take parameters to specify which example response to retrieve. Please refer to the full documentation for detailed parameter descriptions and types. ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Installs optional dependencies for pvlib-python, such as statsmodels, numba, and pyephem. ```bash pip install pvlib[optional] ``` ```bash pip install "pvlib[optional]" ``` -------------------------------- ### Import necessary libraries Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/clearsky.rst Imports required for the examples in this section. ```python import os import itertools import matplotlib.pyplot as plt import pandas as pd import pvlib from pvlib import clearsky, atmosphere, solarposition from pvlib.location import Location from pvlib.iotools import read_tmy3 ``` -------------------------------- ### Install pvlib-python using conda Source: https://github.com/pvlib/pvlib-python.git/blob/main/README.md Install the latest release of pvlib-python using the conda package manager from the conda-forge channel. ```bash conda install -c conda-forge pvlib ``` -------------------------------- ### Perez Algorithm Setup Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/irradiance.ipynb Prepares input variables for the Perez diffuse irradiance algorithm. This includes solar position, irradiance components, extraterrestrial radiation, relative airmass, and surface orientation. Note that sun_zen is expected in radians for kappa calculation. ```python sun_zen = ephem_data['apparent_zenith'] sun_az = ephem_data['azimuth'] DNI = irrad_data['dni'] DHI = irrad_data['dhi'] DNI_ET = pvlib.irradiance.get_extra_radiation(times_utc.dayofyear) AM = pvlib.atmosphere.get_relative_airmass(sun_zen) surf_tilt = 32 surf_az = 180 kappa = 1.041 #for sun_zen in radians z = np.radians(sun_zen) # convert to radians #Dhfilter = DHI > 0 ``` -------------------------------- ### Example Function Docstring Template Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst A template for Python function docstrings in pvlib, demonstrating various sections like summary, extended description, version information, parameters, and returns. ```python def example_function(poa_global, exponents, degree_symbol, time_ref='UT', optional_arg=None): r""" One-sentence summary of the function (no citations). A longer description of the function. This can include citations (references) to literature [1]_, websites [2]_, and other code elements such as functions (:py:func:`pvlib.location.lookup_altitude`) and classes (:py:class:`pvlib.location.Location`). .. versionadded:: 0.0.1 There are many more purpose-specific directives, admonitions and such available at `this link `_. E.g.: ``.. versionchanged::``, ``.. deprecated::``, ``.. note::`` and ``.. warning::``. .. _admonitions: https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#admonitions-messages-and-warnings Parameters ---------- poa_global : numeric Plane-of-array global irradiance, see :term:`poa_global`. [Wm⁻²]. exponents : array-like A list of exponents. [x⁰¹²³⁴⁵⁶⁷⁸⁹⁻]. degree_symbol : pandas.Series or pandas.DataFrame It's different from superscript zero. [°]. time_ref : ``'UT'`` or ``'TST'``, default: ``'UT'`` ``'UT'`` (universal time) or ``'TST'`` (True Solar Time). optional_arg : integer, optional A description of ``optional_arg``. [Unitless]. Specify a suitable datatype for each parameter. Other common data types include ``str``, ``bool``, ``float``, ``numeric`` and ``pandas.DatetimeIndex``. Returns ------- name : numeric ``` -------------------------------- ### Referencing pvlib-python Project Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst Example of citing the pvlib-python project and other reference types within a docstring using numerical citations. ```rst This is the recommended citation for the pvlib-python project [1]_. There are also some conference papers linked to pvlib, for example [2]_. Other types of reference you may find in the pvlib-python documentation include books [3]_, technical reports [4]_, and websites [5]_. References ---------- .. [1] K. Anderson, C. Hansen, W. Holmgren, A. Jensen, M. Mikofski, ``` -------------------------------- ### Generating a Clear Sky Time Series Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/clearsky.rst This example shows how to generate a clear sky time series by calculating solar position, airmass, and Linke turbidity for a given location and time range. It's a foundational step for clear sky irradiance modeling. ```python latitude, longitude, tz, altitude, name = 32.2, -111, 'US/Arizona', 700, 'Tucson' times = pd.date_range(start='2014-01-01', end='2014-01-02', freq='1Min', tz=tz) solpos = pvlib.solarposition.get_solarposition(times, latitude, longitude) apparent_zenith = solpos['apparent_zenith'] airmass = pvlib.atmosphere.get_relative_airmass(apparent_zenith) pressure = pvlib.atmosphere.alt2pres(altitude) airmass = pvlib.atmosphere.get_absolute_airmass(airmass, pressure) linke_turbidity = pvlib.clearsky.lookup_linke_turbidity(times, latitude, longitude) dni_extra = pvlib.irradiance.get_extra_radiation(times) ``` -------------------------------- ### Example Docstring Structure Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/style_guide.rst Illustrates the standard structure of a Python docstring for functions, including parameter descriptions, return values, raised exceptions, and notes. ```python """ A description of the return value. Raises ------ ValueError If ``poa_global`` is negative. KeyError If ``time_ref`` does not exist. Notes ----- This section can include additional information about the function. For example, an equation using LaTeX markup: .. math:: a = \left(\frac{b}{c}\right)^2 where :math:`a` is the result of the equation, and :math:`b` and :math:`c` are inputs. Or a figure with a caption: .. figure:: ../../_images/pvlib_logo_horiz.png :scale: 10% :alt: alternate text :align: center Figure caption. See Also -------- pvlib.location.lookup_altitude, pvlib.location.Location Examples -------- >>> example_function(1, 1, pd.Series([1]), "TST", 2) 'Something' References ---------- A IEEE citation to a relevant reference. You may use an automatic citation generator to format the citation correctly. .. [1] Anderson, K., Hansen, C., Holmgren, W., Jensen, A., Mikofski, M., and Driesse, A. "pvlib python: 2023 project update." Journal of Open Source Software, 8(92), 5994, (2023). :doi:`10.21105/joss.05994`. .. [2] J. Smith and J. Doe. "Obama inaugurated as President." CNN.com. Accessed: Feb. 1, 2009. [Online.] Available: http://www.cnn.com/POLITICS/01/21/obama_inaugurated/index.html """ a = "Some" b = "thing" return a + b ``` -------------------------------- ### Single Axis Tracking Example 1 Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tracking.ipynb Demonstrates single-axis tracking with backtrack enabled. Used for calculating tracker theta, AOI, surface azimuth, and surface tilt. ```python apparent_zenith = pd.Series([10]) apparent_azimuth = pd.Series([180]) tracker_data = pvlib.tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) tracker_data ``` -------------------------------- ### Comparing Historic and Calculated Linke Turbidity Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/clearsky.rst This example compares historic Linke turbidity data from a TMY3 file with values calculated using the Kasten96 formulation. It requires reading TMY3 data and calculating solar position and airmass. Use this to validate atmospheric models. ```python pvlib_data = os.path.join(os.path.dirname(pvlib.__file__), 'data') mbars = 100 # conversion factor from mbars to Pa tmy_file = os.path.join(pvlib_data, '703165TY.csv') # TMY file tmy_data, tmy_header = read_tmy3(tmy_file, coerce_year=1999, map_variables=True) tl_historic = clearsky.lookup_linke_turbidity(time=tmy_data.index, latitude=tmy_header['latitude'], longitude=tmy_header['longitude']) solpos = solarposition.get_solarposition(time=tmy_data.index, latitude=tmy_header['latitude'], longitude=tmy_header['longitude'], altitude=tmy_header['altitude'], pressure=tmy_data['pressure']*mbars, temperature=tmy_data['temp_air']) am_rel = atmosphere.get_relative_airmass(solpos.apparent_zenith) am_abs = atmosphere.get_absolute_airmass(am_rel, tmy_data['pressure']*mbars) airmass = pd.concat([am_rel, am_abs], axis=1).rename( columns={0: 'airmass_relative', 1: 'airmass_absolute'}) tl_calculated = atmosphere.kasten96_lt( airmass.airmass_absolute, tmy_data['precipitable_water'], tmy_data['AOD (unitless)']) tl = pd.concat([tl_historic, tl_calculated], axis=1).rename( columns={0:'Historic', 1:'Calculated'}) tl.index = tmy_data.index.tz_convert(None) # remove timezone tl.resample('W').mean().plot(); plt.grid() plt.title('Comparison of Historic Linke Turbidity Factors vs. \n'+ 'Kasten Pyrheliometric Formula at {name:s}, {state:s} ({usaf:d}TY)'.format( name=tmy_header['Name'], state=tmy_header['State'], usaf=tmy_header['USAF'])) plt.ylabel('Linke Turbidity Factor, TL'); ``` -------------------------------- ### Test PVSystem.ashraeiam method with pytest-mock Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/testing.rst Example of testing a PVSystem method by mocking a core function and asserting correct calls and reasonable output. Requires the pytest-mock library. ```python def test_PVSystem_ashraeiam(mocker): # mocker is a pytest-mock object. # mocker.spy adds code to a function to keep track of how it is called mocker.spy(pvsystem, 'ashraeiam') # set up inputs module_parameters = {'b': 0.05} system = pvsystem.PVSystem(module_parameters=module_parameters) thetas = 1 # call the method iam = system.ashraeiam(thetas) # did the method call the function as we expected? # mocker.spy added assert_called_once_with to the function pvsystem.ashraeiam.assert_called_once_with(thetas, b=module_parameters['b']) # check that the output is reasonable, but no need to duplicate # the rigorous tests of the function assert iam < 1. ``` -------------------------------- ### Single Axis Tracking Example 7 Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tracking.ipynb Demonstrates single-axis tracking with a tilted axis and backtrack enabled. Used for calculating tracker theta, AOI, surface azimuth, and surface tilt. ```python apparent_zenith = pd.Series([30]) apparent_azimuth = pd.Series([135]) tracker_data = pvlib.tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=30, axis_azimuth=180, max_angle=90, backtrack=True, gcr=2.0/7.0) tracker_data ``` -------------------------------- ### Example Release Announcement Email Source: https://github.com/pvlib/pvlib-python.git/wiki/Release-procedures A template for announcing a new pvlib-python release via email to various Google Groups and Python mailing lists. Customize placeholders like version numbers and highlights. ```email Subject: [ANN] pvlib-python : predicting power for solar energy From: Release Manager To: pvlib-python@googlegroups.com, numfocus@googlegroups.com, pydata@googlegroups.com, \ scipy-user@python.org, numpy-discussion@python.org, python-announce-list@python.org pvlib has a new release, Release Notes: https://pvlib-python.readthedocs.io/en//whatsnew.html PyPI: https://pypi.org/project/pvlib/ Read the Docs: https://pvlib-python.readthedocs.io/en/latest/ GitHub: https://github.com/pvlib/pvlib-python Highlights: - dropped support for - new - updated This is a release, so there are a few . Users are advised to read the release notes before updating. ``` -------------------------------- ### Get pvlib Installation Path Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tmy.ipynb Find the absolute file path to your pvlib installation. This is useful for accessing local data files. ```python import os import inspect import pvlib pvlib_abspath = os.path.dirname(os.path.abspath(inspect.getfile(pvlib))) ``` -------------------------------- ### Check pvlib Python Version Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/extras/faq.rst Run this code in a Python interpreter to check your installed pvlib version. This is useful if documentation examples do not seem to match your installation. ```python import pvlib print(pvlib.__version__) ``` -------------------------------- ### Test pre-release installation Source: https://github.com/pvlib/pvlib-python.git/wiki/Release-procedures Installs a pre-release version of pvlib in a new conda environment for testing. Verifies the installation and import. ```bash conda create -n pvlibreltest python=3.8 conda activate pvlibreltest pip install pvlib --pre python -c 'import pvlib' ``` -------------------------------- ### Test final release installation Source: https://github.com/pvlib/pvlib-python.git/wiki/Release-procedures Installs the latest released version of pvlib from PyPI in a new conda environment. Verifies the installation and import. ```bash conda create -n pvlibreltest python=3.8 pvlib -c conda-forge conda activate pvlibreltest python -c 'import pvlib' ``` -------------------------------- ### Build Source Distribution Source: https://github.com/pvlib/pvlib-python.git/wiki/Release-procedures Builds a source distribution of the pvlib-python package using setup.py. This is a step in the manual PyPI upload process. ```bash python setup.py sdist ``` -------------------------------- ### Create basic Location and PVSystem objects Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Instantiates minimal Location and PVSystem objects. ```python location = Location(32.2, -110.9) poorly_specified_system = PVSystem() print(location) print(poorly_specified_system) ``` -------------------------------- ### Install Additional Packages Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/installation.rst Installs Jupyter, IPython, Matplotlib, Pytest, and Flake8 into the active conda environment. ```bash conda install jupyter ipython matplotlib pytest flake8 ``` -------------------------------- ### Create ModelChain using with_sapm convenience method Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Creates a ModelChain instance pre-configured for SAPM models using the `with_sapm` class method. Requires a PVSystem and Location object. ```python mc = mc.with_sapm(sapm_system, location) print(mc) ``` -------------------------------- ### Create Location, PVSystem, and ModelChain objects Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Instantiates Location, PVSystem, and ModelChain objects with specific parameters for a PV system. ```python location = Location(latitude=32.2, longitude=-110.9) system = PVSystem(surface_tilt=20, surface_azimuth=200, module_parameters=sandia_module, inverter_parameters=cec_inverter, temperature_model_parameters=temperature_model_parameters) mc = ModelChain(system, location) ``` -------------------------------- ### Build Wheels Source: https://github.com/pvlib/pvlib-python.git/wiki/Release-procedures Builds universal wheels for the pvlib-python package using setup.py. This is part of the manual PyPI upload process. ```bash python setup.py bdist_wheel --universal ``` -------------------------------- ### Initialize ModelChain with SAPM models Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Initializes a ModelChain using SAPM (System Advisor Model) DC, AC, AOI, and spectral loss models. Requires PVSystem and Location objects. ```python sapm_system = PVSystem( module_parameters=sandia_module, inverter_parameters=cec_inverter, temperature_model_parameters=temperature_model_parameters) nc = ModelChain(sapm_system, location) print(mc) ``` -------------------------------- ### spectrum.get_reference_spectra Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/reference/effects_on_pv_system_output/spectrum.rst Gets standard reference spectral irradiance data. ```APIDOC ## spectrum.get_reference_spectra ### Description Gets standard reference spectral irradiance data. ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters This function may accept parameters to specify the type or conditions of the reference spectra. Please refer to the full documentation for detailed parameter descriptions and types. ``` -------------------------------- ### PV System Modeling with Location, PVSystem, and ModelChain Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/getting_started/introtutorial.rst This code demonstrates how to instantiate and use pvlib Location, PVSystem, and ModelChain objects to model a PV system's energy yield. It handles default model selections and fills missing weather data. Use this for end-to-end system modeling. ```python from pvlib.pvsystem import PVSystem, Array, FixedMount from pvlib.location import Location from pvlib.modelchain import ModelChain energies = {} for location, weather in zip(coordinates, tmys): latitude, longitude, name, altitude, timezone = location location = Location( latitude, longitude, name=name, altitude=altitude, tz=timezone, ) mount = FixedMount(surface_tilt=latitude, surface_azimuth=180) array = Array( mount=mount, module_parameters=module, temperature_model_parameters=temperature_model_parameters, ) system = PVSystem(arrays=[array], inverter_parameters=inverter) mc = ModelChain(system, location) mc.run_model(weather) annual_energy = mc.results.ac.sum() energies[name] = annual_energy energies = pd.Series(energies) # based on the parameters specified above, these are in W*hrs print(energies) energies.plot(kind='bar', rot=0) plt.ylabel('Yearly energy yield (W hr)') ``` -------------------------------- ### ModelChain Initialization with Custom Models Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Initializes a ModelChain object with custom DC, AC, and temperature models. Demonstrates how to integrate user-defined functions like pvusa_mc_wrapper and no_loss_temperature. ```python module_parameters = {'a': 0.2, 'b': 0.00001, 'c': 0.001, 'd': -0.00005} pvusa_system = PVSystem(module_parameters=module_parameters) mc = ModelChain(pvusa_system, location, dc_model=pvusa_mc_wrapper, ac_model=pvusa_ac_mc, temperature_model=no_loss_temperature, aoi_model='no_loss', spectral_model='no_loss') ``` -------------------------------- ### Initialize ModelChain with PVWatts models Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Initializes a ModelChain using PVWatts DC and AC models, explicitly specifying AOI and spectral loss models. Requires PVSystem and Location objects. ```python pvwatts_system = PVSystem( module_parameters={'pdc0': 240, 'gamma_pdc': -0.004}, inverter_parameters={'pdc0': 240}, temperature_model_parameters=temperature_model_parameters) nc = ModelChain(pvwatts_system, location, aoi_model='physical', spectral_model='no_loss') print(mc) ``` -------------------------------- ### Create and push pre-release tag Source: https://github.com/pvlib/pvlib-python.git/wiki/Release-procedures Tags a pre-release version (e.g., alpha, beta, rc) and pushes it to GitHub. This triggers CI to deploy to PyPI as a prerelease. ```bash git tag v0.6.0-alpha git push pvlib [the-tag-name] ``` -------------------------------- ### Create a PVSystem instance Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Instantiate a PVSystem object by providing dictionaries for module and inverter parameters. The created system object stores these parameters as attributes. ```python import pandas as pd from pvlib import pvsystem module_parameters = {'pdc0': 5000, 'gamma_pdc': -0.004} inverter_parameters = {'pdc0': 5000, 'eta_inv_nom': 0.96} system = pvsystem.PVSystem(inverter_parameters=inverter_parameters, module_parameters=module_parameters) print(system.inverter_parameters) ``` -------------------------------- ### Define Location Object Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/solarposition.ipynb Sets up a location object for use in solar position calculations. This example uses the 'berlin' predefined location. ```python loc = berlin ``` -------------------------------- ### Get AOI for a single Array Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Calculates the angle of incidence for a single array instance. Requires solar zenith and azimuth angles. ```python import pvlib.pvsystem as pvsystem # two arrays each at 30 deg tilt with different facing array_one = pvsystem.Array(pvsystem.FixedMount(surface_tilt=30, surface_azimuth=90)) array_one_aoi = array_one.get_aoi(solar_zenith=30, solar_azimuth=180) print(array_one_aoi) ``` -------------------------------- ### Create a naive DatetimeIndex Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/timetimezones.rst Generates a pandas DatetimeIndex with hourly frequency for 24 periods, starting from '1997-01-01 01:00'. This index is timezone-naive. ```python index = pd.date_range(start='1997-01-01 01:00', freq='1h', periods=24) index ``` -------------------------------- ### Import pvlib and Specific Tools Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tracking.ipynb Imports the pvlib library and specific tools like cosd, sind, and Location for solar calculations. ```python import pvlib from pvlib.tools import cosd, sind from pvlib.location import Location ``` -------------------------------- ### Displaying Package Versions Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/pvsystem.ipynb Prints the installed versions of various Python packages, including pandas and numpy, which is useful for debugging and ensuring compatibility. ```python pd.show_versions() ``` -------------------------------- ### Initialize Time and Solar Position for Winter Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tracking.ipynb Sets up time range and calculates solar position for a winter date. This is a precursor to further irradiance calculations. ```python times = pd.date_range(start=datetime.datetime(2014,12,23), end=datetime.datetime(2014,12,24), freq='5Min') ephem_tus = pvlib.solarposition.get_solarposition(times.tz_localize(tus.tz), tus.latitude, tus.longitude) ephem_joh = pvlib.solarposition.get_solarposition(times.tz_localize(johannesburg.tz), johannesburg.latitude, johannesburg.longitude) tracker_data = pvlib.tracking.singleaxis(ephem_tus['apparent_zenith'], ephem_tus['azimuth'], axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) tracker_data.plot() plt.ylim(-100,100) irrad_data = tus.get_clearsky(times.tz_localize(tus.tz)) dni_et = pvlib.irradiance.get_extra_radiation(irrad_data.index, method='asce') ``` -------------------------------- ### Calculate Solar Position Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tmy_to_power.ipynb Calculates the solar position for all times in the TMY data index. For faster computation, install numba and use method='nrel_numba'. ```python solpos = pvlib.solarposition.get_solarposition(tmy_data.index, sand_point.latitude, sand_point.longitude) solpos.plot(); ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/atmosphere.ipynb Imports essential Python modules for data manipulation, plotting, and pvlib functionalities. Ensure pvlib is installed and updated. ```python %matplotlib inline import matplotlib.pyplot as plt # built in python modules import datetime import logging import os import inspect # python add-ons import numpy as np import pandas as pd ``` ```python import pvlib from pvlib.location import Location ``` -------------------------------- ### PVSystem with Single Array Parameters Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Instantiate a PVSystem with module and inverter parameters for a single array. The parameters are directly assigned to the system. ```python module_parameters = {'pdc0': 5000, 'gamma_pdc': -0.004} inverter_parameters = {'pdc0': 5000, 'eta_inv_nom': 0.96} system = pvsystem.PVSystem(module_parameters=module_parameters, inverter_parameters=inverter_parameters) print(system.arrays[0].module_parameters) print(system.inverter_parameters) ``` -------------------------------- ### Get AOI and IAM for a PVSystem Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Demonstrates calling get_aoi and get_iam on a PVSystem object. The output of get_aoi is a tuple when the system has multiple arrays. ```python import pvlib.pvsystem as pvsystem aoi = system.get_aoi(solar_zenith=30, solar_azimuth=180) print(aoi) system_multiarray.get_iam(aoi) ``` -------------------------------- ### Display Sphinx Configuration File Source: https://github.com/pvlib/pvlib-python.git/wiki/readthedocs-troubleshooting This command displays the content of the Sphinx configuration file, which can be useful for diagnosing build environment issues. ```bash cat docs/sphinx/source/conf.py ``` -------------------------------- ### Get AOI for a PVSystem with multiple Arrays Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Calculates the angle of incidence for all arrays within a PVSystem. The output is a tuple of AOI values, one for each array. ```python import pvlib.pvsystem as pvsystem array_one = pvsystem.Array(pvsystem.FixedMount(surface_tilt=30, surface_azimuth=90)) array_two = pvsystem.Array(pvsystem.FixedMount(surface_tilt=30, surface_azimuth=220)) system_multiarray = pvsystem.PVSystem(arrays=[array_one, array_two]) print(system_multiarray.num_arrays) # call get_aoi with solar_zenith, solar_azimuth aoi = system_multiarray.get_aoi(solar_zenith=30, solar_azimuth=180) print(aoi) ``` -------------------------------- ### Complete irradiance data for ModelChain Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/modelchain.rst Demonstrates how to use the `complete_irradiance` method to calculate missing irradiance components (e.g., DNI) before running the ModelChain simulation. ```python # Assume weather contains 'ghi' and 'dhi' nc.complete_irradiance(weather) # Now weather can be used with mc.run_model() ``` -------------------------------- ### Single Axis Tracking Example 5 Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tracking.ipynb Illustrates single-axis tracking with backtrack disabled. Used for calculating tracker theta, AOI, surface azimuth, and surface tilt. ```python apparent_zenith = pd.Series([80]) apparent_azimuth = pd.Series([90]) tracker_data = pvlib.tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=False, gcr=2.0/7.0) tracker_data ``` -------------------------------- ### Compare SAPM Results Under Different Conditions Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/pvsystem.ipynb Compares the maximum power point (Pmp) of a PV system simulated with SAPM under two different weather scenarios: hot and calm versus cold and windy. ```python temps = pvlib.temperature.sapm_cell(total_irrad['poa_global'], 5, 10, **thermal_params) sapm_2 = pvlib.pvsystem.sapm(effective_irradiance, temps, module) plot_sapm(sapm_2, effective_irradiance) ``` ```python sapm_1['p_mp'].plot(label='30 C, 0 m/s') sapm_2['p_mp'].plot(label=' 5 C, 10 m/s') plt.legend() plt.ylabel('Pmp') plt.title('Comparison of a hot, calm day and a cold, windy day'); ``` -------------------------------- ### PVSystem with Multiple Arrays and Different Mounts Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Configure a PVSystem with multiple arrays, each having its own mount with specified tilt and azimuth. ```python array_one = pvsystem.Array(pvsystem.FixedMount(surface_tilt=30, surface_azimuth=90)) print(array_one.mount.surface_tilt, array_one.mount.surface_azimuth) array_two = pvsystem.Array(pvsystem.FixedMount(surface_tilt=30, surface_azimuth=220)) system = pvsystem.PVSystem(arrays=[array_one, array_two]) print(system.num_arrays) for array in system.arrays: print(array.mount) ``` -------------------------------- ### Calculate and Plot Solar Azimuth using pyephem and ephemeris Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/solarposition.ipynb Calculates and plots the solar azimuth using both pyephem and ephemeris methods. This snippet is a continuation of the elevation plot example. ```python loc = berlin times = pd.date_range(start=datetime.date(2015,3,28), end=datetime.date(2015,3,29), freq='5min') pyephemout = pvlib.solarposition.pyephem(times.tz_localize(loc.tz), loc.latitude, loc.longitude) ephemout = pvlib.solarposition.ephemeris(times.tz_localize(loc.tz), loc.latitude, loc.longitude) pyephemout['elevation'].plot(label='pyephem') pyephemout['apparent_elevation'].plot(label='pyephem apparent') ephemout['elevation'].plot(label='ephem') plt.legend(ncol=2) plt.title('elevation') plt.figure() pyephemout['azimuth'].plot(label='pyephem') ephemout['azimuth'].plot(label='ephem') plt.legend(ncol=2) plt.title('azimuth') print('pyephem') print(pyephemout.head()) print('ephem') print(ephemout.head()) ``` -------------------------------- ### PVSystem with Single Array Tilt and Azimuth Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/user_guide/modeling_topics/pvsystem.rst Instantiate a PVSystem with surface tilt and azimuth for a single array. This automatically creates a FixedMount for the array. ```python # single south-facing array at 20 deg tilt system_one_array = pvsystem.PVSystem(surface_tilt=20, surface_azimuth=180) print(system_one_array.arrays[0].mount) ``` -------------------------------- ### Calculate DC Power Parameters (Single Diode Model) Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/tmy_to_power.ipynb Calculates the parameters for the single-diode model using the DeSoto method. Requires irradiance, temperature, module parameters, and reference values. ```python photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth = ( pvlib.pvsystem.calcparams_desoto(poa_irrad.poa_global, pvtemps, cec_module['alpha_sc'], EgRef=1.121, dEgdT=-0.0002677, **d)) ``` -------------------------------- ### Import pvlib Library Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/tutorials/solarposition.ipynb Import the main pvlib library for use in your scripts. ```python import pvlib ``` -------------------------------- ### Test ModelChain DC Model with Mocking Source: https://github.com/pvlib/pvlib-python.git/blob/main/docs/sphinx/source/contributing/testing.rst Use pytest-mock to assert that the correct PVSystem method is called within ModelChain.run_model. This example spies on the 'sapm' method of a PVSystem instance. ```python def test_modelchain_dc_model(mocker): # set up location and system for model chain location = location.Location(32, -111) system = pvsystem.PVSystem(module_parameters=some_sandia_mod_params, inverter_parameters=some_cecinverter_params) # mocker.spy adds code to the system.sapm method to keep track of how # it is called. use returned mock object m to make assertion later, # but see example above for alternative m = mocker.spy(system, 'sapm') # make and run the model chain mc = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss') times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') mc.run_model(times) # assertion fails if PVSystem.sapm is not called once m.assert_called_once() # use `assert m.call_count == num` if function should be called # more than once # ensure that dc attribute now exists and is correct type assert isinstance(mc.dc, (pd.Series, pd.DataFrame)) ```