API Reference
Full documentation for all public classes and functions in sparta-solar, generated from the source docstrings.
Atmospheric data sources
MERRA-2 daily reanalysis
MERRA2DailyAtmosphere
Bases: BaseAtmosphere
MERRA-2 daily atmospheric data accessor.
Provides methods to load and interpolate MERRA-2 daily atmospheric data for specific locations or regular grids. Data is automatically cached locally and loaded from Zarr archives organized by year.
The class inherits from BaseAtmosphere and provides two main factory methods: - at_sites(): Extract data at specific point locations - on_regular_grid(): Extract data on a regular lat/lon mesh
Attributes:
-
database_path(Path) –Path to local MERRA-2 data storage directory.
Notes
Available variables include pressure, albedo, pwater,
ozone, beta, alpha and ssa.
Validates that the database path exists (if specified) and initializes the internal atmosphere dataset to None.
Raises:
-
AttributeError–If database_path is specified but does not exist
Methods:
-
__init_subclass__–Automatically sets the database path for subclasses.
-
at_sites–Load atmospheric data at specific geographic locations.
-
compute–Compute clear-sky solar radiation using a radiative transfer model.
-
on_regular_grid–Load atmospheric data on a regular lat/lon grid.
Source code in src/spartasolar/atmoslib/_base.py
__init_subclass__
__init_subclass__(database_path: str, **kwargs)
Automatically sets the database path for subclasses.
Parameters:
-
(database_pathstr or None) –The directory path where the specific atmosphere data is stored. Pass
Nonefor sources that do not use a file database (e.g.CustomAtmosphereor API-based retrievers).
Source code in src/spartasolar/atmoslib/_base.py
at_sites
classmethod
at_sites(
times: ndarray[tuple[int], dtype[datetime64]]
| DatetimeIndex,
latitude: Sequence[float] | float,
longitude: Sequence[float] | float,
site_names: Sequence[str] | None = None,
) -> Self
Load atmospheric data at specific geographic locations.
Extracts and interpolates MERRA-2 data for one or more point locations. Performs bilinear spatial interpolation and quadratic temporal interpolation.
Parameters:
-
(timesndarray or DatetimeIndex) –Time points for data extraction.
-
(latitudefloat or Sequence[float]) –Latitude coordinate(s) in decimal degrees.
-
(longitudefloat or Sequence[float]) –Longitude coordinate(s) in decimal degrees.
-
(site_namesSequence[str] or None, default:None) –Optional names for the sites.
Returns:
-
MERRA2DailyAtmosphere–Instance containing interpolated atmospheric data.
Raises:
-
ValueError–If latitude and longitude have different lengths or invalid values.
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>> # Single location
>>> times = pd.date_range("2020-01-01", periods=5, freq="D")
>>> atmos = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=40.4168,
... longitude=-3.7038,
... site_names="Madrid"
... )
>>> # Multiple locations
>>> lats = [40.4168, 41.3851, 36.7213] # Madrid, Barcelona, Málaga
>>> lons = [-3.7038, 2.1734, -4.4214]
>>> names = ["Madrid", "Barcelona", "Málaga"]
>>> atmos = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=lats,
... longitude=lons,
... site_names=names
... )
>>> # Access data
>>> pressure = atmos.dataset["pressure"]
>>> print(pressure.dims)
('time', 'site')
Source code in src/spartasolar/atmoslib/merra2_daily.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
compute
compute(
model: Model = "SPARTA",
include_atmosphere: bool = False,
model_kwargs: dict | None = None,
) -> Dataset
Compute clear-sky solar radiation using a radiative transfer model.
This method integrates solar position calculations with atmospheric constituent data to compute clear-sky irradiance components (GHI, DNI, DHI, etc.) using the specified radiative transfer model.
Parameters:
-
(modelModel, default:"SPARTA") –Name of the clear-sky model to use. Options: "SPARTA", "Bird"
-
(include_atmospherebool, default:False) –If True, include atmospheric constituents in the output dataset. If False, only radiation components are returned.
-
(model_kwargsdict, default:None) –Additional keyword arguments to pass to the model function
Returns:
-
Dataset–CF-compliant dataset containing computed irradiance components: - ghi: Global Horizontal Irradiance (W/m²) - dni: Direct Normal Irradiance (W/m²) - dhi or dif: Diffuse Horizontal Irradiance (W/m²) - csi: Circumsolar Irradiance (W/m², SPARTA only)
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42
... )
>>> result = atm.compute(model="SPARTA")
>>> print(result.ghi.values)
Use different model with custom parameters:
>>> result = atm.compute(
... model="Bird",
... model_kwargs={"scheme": "transmittance_parameterization"}
... )
Notes
The method automatically: - Calculates solar position (zenith angle, Earth-Sun distance) - Converts atmospheric units to model requirements - Handles both gridded and site-based data structures
See Also
spartasolar.modlib.sparta : SPARTA model implementation spartasolar.modlib.bird : Bird clear-sky model
Source code in src/spartasolar/atmoslib/_base.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
on_regular_grid
classmethod
on_regular_grid(
times: ndarray[tuple[int], dtype[datetime64]]
| DatetimeIndex,
latitude: Sequence[float] | float,
longitude: Sequence[float] | float,
) -> Self
Load atmospheric data on a regular lat/lon grid.
Extracts and interpolates MERRA-2 data onto a user-specified regular grid. The output has dimensions (time, lat, lon). NaN values in albedo are filled with zeros.
Parameters:
-
(timesndarray or DatetimeIndex) –Time points for data extraction.
-
(latitudefloat or Sequence[float]) –Latitude coordinates for the grid in decimal degrees.
-
(longitudefloat or Sequence[float]) –Longitude coordinates for the grid in decimal degrees.
Returns:
-
MERRA2DailyAtmosphere–Instance containing gridded atmospheric data.
Raises:
-
ValueError–If coordinates are out of valid range.
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>> # Define a regular grid over Iberian Peninsula
>>> times = pd.date_range("2020-06-01", periods=10, freq="D")
>>> lats = np.linspace(36, 44, 9) # 9 latitude points
>>> lons = np.linspace(-10, 4, 15) # 15 longitude points
>>> atmos = MERRA2DailyAtmosphere.on_regular_grid(
... times=times,
... latitude=lats,
... longitude=lons
... )
>>> # Access gridded data
>>> albedo = atmos.dataset["albedo"]
>>> print(albedo.dims)
('time', 'lat', 'lon')
>>> print(albedo.shape)
(10, 9, 15)
Source code in src/spartasolar/atmoslib/merra2_daily.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
MERRA-2 long-term averages
MERRA2LTAAtmosphere
Bases: BaseAtmosphere
MERRA-2 long-term monthly average atmospheric database.
Provides climatological monthly averages (1999-2018) of atmospheric constituents from NASA MERRA-2 reanalysis. Data is interpolated spatially and temporally to match requested coordinates and times.
See module documentation for examples.
Validates that the database path exists (if specified) and initializes the internal atmosphere dataset to None.
Raises:
-
AttributeError–If database_path is specified but does not exist
Methods:
-
__init_subclass__–Automatically sets the database path for subclasses.
-
at_sites–Retrieve monthly climatology at specific sites.
-
compute–Compute clear-sky solar radiation using a radiative transfer model.
-
on_regular_grid–Retrieve monthly climatology on a regular spatial grid.
Source code in src/spartasolar/atmoslib/_base.py
__init_subclass__
__init_subclass__(database_path: str, **kwargs)
Automatically sets the database path for subclasses.
Parameters:
-
(database_pathstr or None) –The directory path where the specific atmosphere data is stored. Pass
Nonefor sources that do not use a file database (e.g.CustomAtmosphereor API-based retrievers).
Source code in src/spartasolar/atmoslib/_base.py
at_sites
classmethod
at_sites(
times: ndarray[tuple[int], dtype[datetime64]]
| DatetimeIndex,
latitude: Sequence[float] | float,
longitude: Sequence[float] | float,
site_names: Sequence[str] | None = None,
) -> Self
Retrieve monthly climatology at specific sites.
Parameters:
-
(timesndarray or DatetimeIndex) –Time stamps for climatology retrieval. Monthly climatology is repeated for each year and interpolated to exact times.
-
(latitudeSequence[float]) –Latitude(s) in degrees North [-90, 90]
-
(longitudeSequence[float]) –Longitude(s) in degrees East [-180, 180]
-
(site_namesSequence[str], default:None) –Names for each site
Returns:
-
MERRA2LTAAtmosphere–Instance with interpolated climatological data
Examples:
>>> times = pd.date_range("2023-01-01", "2023-12-31", freq="D")
>>> atm = MERRA2LTAAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42,
... site_names="Málaga"
... )
Source code in src/spartasolar/atmoslib/merra2_lta.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
compute
compute(
model: Model = "SPARTA",
include_atmosphere: bool = False,
model_kwargs: dict | None = None,
) -> Dataset
Compute clear-sky solar radiation using a radiative transfer model.
This method integrates solar position calculations with atmospheric constituent data to compute clear-sky irradiance components (GHI, DNI, DHI, etc.) using the specified radiative transfer model.
Parameters:
-
(modelModel, default:"SPARTA") –Name of the clear-sky model to use. Options: "SPARTA", "Bird"
-
(include_atmospherebool, default:False) –If True, include atmospheric constituents in the output dataset. If False, only radiation components are returned.
-
(model_kwargsdict, default:None) –Additional keyword arguments to pass to the model function
Returns:
-
Dataset–CF-compliant dataset containing computed irradiance components: - ghi: Global Horizontal Irradiance (W/m²) - dni: Direct Normal Irradiance (W/m²) - dhi or dif: Diffuse Horizontal Irradiance (W/m²) - csi: Circumsolar Irradiance (W/m², SPARTA only)
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42
... )
>>> result = atm.compute(model="SPARTA")
>>> print(result.ghi.values)
Use different model with custom parameters:
>>> result = atm.compute(
... model="Bird",
... model_kwargs={"scheme": "transmittance_parameterization"}
... )
Notes
The method automatically: - Calculates solar position (zenith angle, Earth-Sun distance) - Converts atmospheric units to model requirements - Handles both gridded and site-based data structures
See Also
spartasolar.modlib.sparta : SPARTA model implementation spartasolar.modlib.bird : Bird clear-sky model
Source code in src/spartasolar/atmoslib/_base.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
on_regular_grid
classmethod
on_regular_grid(
times: ndarray[tuple[int], dtype[datetime64]]
| DatetimeIndex,
latitude: Sequence[float],
longitude: Sequence[float],
) -> Self
Retrieve monthly climatology on a regular spatial grid.
Parameters:
-
(timesndarray or DatetimeIndex) –Time stamps for climatology retrieval
-
(latitudeSequence[float]) –Latitude grid coordinates in degrees North
-
(longitudeSequence[float]) –Longitude grid coordinates in degrees East
Returns:
-
MERRA2LTAAtmosphere–Instance with gridded climatological data
Examples:
>>> import numpy as np
>>> lats = np.linspace(36.0, 41.0, 20)
>>> lons = np.linspace(-5.0, -3.0, 20)
>>> times = pd.date_range("2023-01-15", periods=12, freq="MS") + pd.Timedelta(14.5, "D")
>>> atm = MERRA2LTAAtmosphere.on_regular_grid(
... times=times,
... latitude=lats,
... longitude=lons
... )
Source code in src/spartasolar/atmoslib/merra2_lta.py
MERRA-2 via Google Earth Engine
MERRA2GEEAtmosphere
Bases: BaseAtmosphere
MERRA-2 atmospheric database via Google Earth Engine.
Provides access to NASA MERRA-2 reanalysis via GEE API. Automatically corrects for GEE's latitude grid offset and time stamp convention.
Requires GEE authentication and active project configuration.
See module documentation for setup instructions and examples.
Validates that the database path exists (if specified) and initializes the internal atmosphere dataset to None.
Raises:
-
AttributeError–If database_path is specified but does not exist
Methods:
-
__init_subclass__–Automatically sets the database path for subclasses.
-
at_site–Retrieve MERRA-2 data from GEE for a specific site.
-
compute–Compute clear-sky solar radiation using a radiative transfer model.
Source code in src/spartasolar/atmoslib/_base.py
__init_subclass__
__init_subclass__(database_path: str, **kwargs)
Automatically sets the database path for subclasses.
Parameters:
-
(database_pathstr or None) –The directory path where the specific atmosphere data is stored. Pass
Nonefor sources that do not use a file database (e.g.CustomAtmosphereor API-based retrievers).
Source code in src/spartasolar/atmoslib/_base.py
at_site
classmethod
at_site(
times: DatetimeIndex
| ndarray[tuple[int], dtype[datetime64]],
latitude: float,
longitude: float,
site_name: str | None = None,
) -> Self
Retrieve MERRA-2 data from GEE for a specific site.
Downloads data from GEE if not cached, applies spatial/temporal corrections, then interpolates to requested times.
Parameters:
-
(timespd.DatetimeIndex or np.ndarray of datetime64) –Time stamps for data retrieval (UTC)
-
(latitudefloat) –Latitude in degrees North [-90, 90]
-
(longitudefloat) –Longitude in degrees East [-180, 180]
-
(site_namestr, default:None) –Name identifier for the site
Returns:
-
MERRA2GEEAtmosphere–Instance with interpolated atmospheric data
Examples:
>>> import pandas as pd
>>> from spartasolar import config
>>> config.set_option('merra2_gee.project', 'my-gee-project')
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2GEEAtmosphere.at_site(
... times=times,
... latitude=36.72,
... longitude=-4.42,
... site_name="Málaga"
... )
>>> result = atm.compute(model="SPARTA")
Notes
- Requires
merra2_gee.projectconfiguration - Automatically corrects GEE's 0.25° latitude offset
- Adjusts time stamps from hour-start to hour-center
- Data is cached locally to minimize API calls
Source code in src/spartasolar/atmoslib/merra2_geeapi.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | |
compute
compute(
model: Model = "SPARTA",
include_atmosphere: bool = False,
model_kwargs: dict | None = None,
) -> Dataset
Compute clear-sky solar radiation using a radiative transfer model.
This method integrates solar position calculations with atmospheric constituent data to compute clear-sky irradiance components (GHI, DNI, DHI, etc.) using the specified radiative transfer model.
Parameters:
-
(modelModel, default:"SPARTA") –Name of the clear-sky model to use. Options: "SPARTA", "Bird"
-
(include_atmospherebool, default:False) –If True, include atmospheric constituents in the output dataset. If False, only radiation components are returned.
-
(model_kwargsdict, default:None) –Additional keyword arguments to pass to the model function
Returns:
-
Dataset–CF-compliant dataset containing computed irradiance components: - ghi: Global Horizontal Irradiance (W/m²) - dni: Direct Normal Irradiance (W/m²) - dhi or dif: Diffuse Horizontal Irradiance (W/m²) - csi: Circumsolar Irradiance (W/m², SPARTA only)
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42
... )
>>> result = atm.compute(model="SPARTA")
>>> print(result.ghi.values)
Use different model with custom parameters:
>>> result = atm.compute(
... model="Bird",
... model_kwargs={"scheme": "transmittance_parameterization"}
... )
Notes
The method automatically: - Calculates solar position (zenith angle, Earth-Sun distance) - Converts atmospheric units to model requirements - Handles both gridded and site-based data structures
See Also
spartasolar.modlib.sparta : SPARTA model implementation spartasolar.modlib.bird : Bird clear-sky model
Source code in src/spartasolar/atmoslib/_base.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
Copernicus CRS via SODA API
CRSSODAAtmosphere
Bases: BaseAtmosphere
CRS SODA (Copernicus Radiation Service) atmospheric database.
Provides access to atmospheric constituent data from the SODA McClear service via WPS API. Data is cached locally after first retrieval.
Requires user registration at https://www.soda-pro.com/ and email
configuration via crs_soda.user_email config option.
See module documentation for examples.
Validates that the database path exists (if specified) and initializes the internal atmosphere dataset to None.
Raises:
-
AttributeError–If database_path is specified but does not exist
Methods:
-
__init_subclass__–Automatically sets the database path for subclasses.
-
at_site–Retrieve CRS SODA atmospheric data for a specific site.
-
compute–Compute clear-sky solar radiation using a radiative transfer model.
Source code in src/spartasolar/atmoslib/_base.py
__init_subclass__
__init_subclass__(database_path: str, **kwargs)
Automatically sets the database path for subclasses.
Parameters:
-
(database_pathstr or None) –The directory path where the specific atmosphere data is stored. Pass
Nonefor sources that do not use a file database (e.g.CustomAtmosphereor API-based retrievers).
Source code in src/spartasolar/atmoslib/_base.py
at_site
classmethod
at_site(
times: DatetimeIndex
| ndarray[tuple[int], dtype[datetime64]],
latitude: float,
longitude: float,
site_name: str | None = None,
) -> Self
Retrieve CRS SODA atmospheric data for a specific site.
Downloads data from SODA API if not cached, then interpolates to requested times. Data is automatically resampled to hourly resolution.
Parameters:
-
(timesDatetimeIndex) –Time stamps for data retrieval
-
(latitudefloat) –Latitude in degrees North [-90, 90]
-
(longitudefloat) –Longitude in degrees East [-180, 180]
-
(site_namestr, default:None) –Name identifier for the site
Returns:
-
CRSSODAAtmosphere–Instance with interpolated atmospheric data
Examples:
>>> import pandas as pd
>>> from spartasolar import config
>>> config.set_option('crs_soda.user_email', 'user@example.com')
>>>
>>> times = pd.date_range("2020-01-01", "2020-01-31", freq="h")
>>> atm = CRSSODAAtmosphere.at_site(
... times=times,
... latitude=36.72,
... longitude=-4.42,
... site_name="Málaga"
... )
>>> result = atm.compute(model="SPARTA")
Notes
- Requires
crs_soda.user_emailconfiguration - Data is cached locally to minimize API calls
- Temporal interpolation uses quadratic splines
Source code in src/spartasolar/atmoslib/crs_sodaapi.py
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
compute
compute(
model: Model = "SPARTA",
include_atmosphere: bool = False,
model_kwargs: dict | None = None,
) -> Dataset
Compute clear-sky solar radiation using a radiative transfer model.
This method integrates solar position calculations with atmospheric constituent data to compute clear-sky irradiance components (GHI, DNI, DHI, etc.) using the specified radiative transfer model.
Parameters:
-
(modelModel, default:"SPARTA") –Name of the clear-sky model to use. Options: "SPARTA", "Bird"
-
(include_atmospherebool, default:False) –If True, include atmospheric constituents in the output dataset. If False, only radiation components are returned.
-
(model_kwargsdict, default:None) –Additional keyword arguments to pass to the model function
Returns:
-
Dataset–CF-compliant dataset containing computed irradiance components: - ghi: Global Horizontal Irradiance (W/m²) - dni: Direct Normal Irradiance (W/m²) - dhi or dif: Diffuse Horizontal Irradiance (W/m²) - csi: Circumsolar Irradiance (W/m², SPARTA only)
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42
... )
>>> result = atm.compute(model="SPARTA")
>>> print(result.ghi.values)
Use different model with custom parameters:
>>> result = atm.compute(
... model="Bird",
... model_kwargs={"scheme": "transmittance_parameterization"}
... )
Notes
The method automatically: - Calculates solar position (zenith angle, Earth-Sun distance) - Converts atmospheric units to model requirements - Handles both gridded and site-based data structures
See Also
spartasolar.modlib.sparta : SPARTA model implementation spartasolar.modlib.bird : Bird clear-sky model
Source code in src/spartasolar/atmoslib/_base.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
Custom atmosphere
CustomAtmosphere
Bases: BaseAtmosphere
Custom atmospheric data provider.
This class allows users to supply their own atmospheric constituent data from measurements, numerical weather prediction models, or other sources. Data can be provided for specific sites (time series) or regular grids.
See module documentation for examples.
Validates that the database path exists (if specified) and initializes the internal atmosphere dataset to None.
Raises:
-
AttributeError–If database_path is specified but does not exist
Methods:
-
__init_subclass__–Automatically sets the database path for subclasses.
-
at_sites–Create custom atmospheric data for specific sites.
-
compute–Compute clear-sky solar radiation using a radiative transfer model.
-
on_regular_grid–Create custom atmospheric data on a regular spatial grid.
Source code in src/spartasolar/atmoslib/_base.py
__init_subclass__
__init_subclass__(database_path: str, **kwargs)
Automatically sets the database path for subclasses.
Parameters:
-
(database_pathstr or None) –The directory path where the specific atmosphere data is stored. Pass
Nonefor sources that do not use a file database (e.g.CustomAtmosphereor API-based retrievers).
Source code in src/spartasolar/atmoslib/_base.py
at_sites
classmethod
at_sites(
times: ndarray[tuple[int], dtype[datetime64]]
| DatetimeIndex,
latitude: Sequence[float] | float,
longitude: Sequence[float] | float,
constituents: dict[
str, ndarray[tuple[int, int], float]
],
site_names: Sequence[str] | None = None,
var_attrs: dict | None = None,
global_attrs: dict | None = None,
) -> Self
Create custom atmospheric data for specific sites.
Parameters:
-
(timesndarray or DatetimeIndex) –Time stamps for the data (length n_times)
-
(latitudefloat or Sequence[float]) –Latitude(s) in degrees North [-90, 90] (length n_sites)
-
(longitudefloat or Sequence[float]) –Longitude(s) in degrees East [-180, 180] (length n_sites)
-
(constituentsdict[str, ndarray]) –Atmospheric variables as 2D arrays with shape (n_times, n_sites). Standard variable names: 'pressure' (Pa), 'pwater' (cm), 'ozone' (atm-cm), 'alpha', 'beta', 'ssa', 'albedo'
-
(site_namesSequence[str], default:None) –Names for each site
-
(var_attrsdict, default:None) –Custom attributes for variables (CF conventions)
-
(global_attrsdict, default:None) –Custom global attributes for the dataset
Returns:
-
CustomAtmosphere–Instance with atmospheric data loaded
Examples:
>>> times = pd.date_range("2020-01-01", periods=24, freq="h")
>>> atm = CustomAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42,
... constituents={
... "pressure": np.full((24, 1), 101325.0),
... "pwater": np.linspace(1.0, 2.0, 24).reshape(24, 1),
... "ozone": np.full((24, 1), 0.3)
... }
... )
Source code in src/spartasolar/atmoslib/custom.py
compute
compute(
model: Model = "SPARTA",
include_atmosphere: bool = False,
model_kwargs: dict | None = None,
) -> Dataset
Compute clear-sky solar radiation using a radiative transfer model.
This method integrates solar position calculations with atmospheric constituent data to compute clear-sky irradiance components (GHI, DNI, DHI, etc.) using the specified radiative transfer model.
Parameters:
-
(modelModel, default:"SPARTA") –Name of the clear-sky model to use. Options: "SPARTA", "Bird"
-
(include_atmospherebool, default:False) –If True, include atmospheric constituents in the output dataset. If False, only radiation components are returned.
-
(model_kwargsdict, default:None) –Additional keyword arguments to pass to the model function
Returns:
-
Dataset–CF-compliant dataset containing computed irradiance components: - ghi: Global Horizontal Irradiance (W/m²) - dni: Direct Normal Irradiance (W/m²) - dhi or dif: Diffuse Horizontal Irradiance (W/m²) - csi: Circumsolar Irradiance (W/m², SPARTA only)
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42
... )
>>> result = atm.compute(model="SPARTA")
>>> print(result.ghi.values)
Use different model with custom parameters:
>>> result = atm.compute(
... model="Bird",
... model_kwargs={"scheme": "transmittance_parameterization"}
... )
Notes
The method automatically: - Calculates solar position (zenith angle, Earth-Sun distance) - Converts atmospheric units to model requirements - Handles both gridded and site-based data structures
See Also
spartasolar.modlib.sparta : SPARTA model implementation spartasolar.modlib.bird : Bird clear-sky model
Source code in src/spartasolar/atmoslib/_base.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
on_regular_grid
classmethod
on_regular_grid(
times: ndarray[tuple[int], datetime64] | DatetimeIndex,
latitude: Sequence[float],
longitude: Sequence[float],
constituents: dict[
str, ndarray[tuple[int, int, int], float]
],
var_attrs: dict | None = None,
global_attrs: dict | None = None,
) -> Self
Create custom atmospheric data on a regular spatial grid.
Parameters:
-
(timesndarray or DatetimeIndex) –Time stamps for the data (length n_times)
-
(latitudeSequence[float]) –Latitude coordinates in degrees North (length n_lats)
-
(longitudeSequence[float]) –Longitude coordinates in degrees East (length n_lons)
-
(constituentsdict[str, ndarray]) –Atmospheric variables as 3D arrays with shape (n_times, n_lats, n_lons). Standard names: 'pressure', 'pwater', 'ozone', 'alpha', 'beta', 'ssa', 'albedo'
-
(var_attrsdict, default:None) –Custom variable attributes
-
(global_attrsdict, default:None) –Custom global dataset attributes
Returns:
-
CustomAtmosphere–Instance with gridded atmospheric data
Examples:
>>> lats = np.linspace(36.0, 41.0, 20)
>>> lons = np.linspace(-5.0, -3.0, 20)
>>> times = pd.date_range("2020-06-15", periods=5, freq="h")
>>> atm = CustomAtmosphere.on_regular_grid(
... times=times,
... latitude=lats,
... longitude=lons,
... constituents={
... "pressure": np.full((5, 20, 20), 101325.0),
... "pwater": np.random.uniform(1.0, 3.0, (5, 20, 20)),
... }
... )
Source code in src/spartasolar/atmoslib/custom.py
Base class
BaseAtmosphere
Abstract base class for atmospheric database interfaces.
This class defines the common interface that all atmospheric data sources must implement. It provides methods for loading atmospheric constituent data and computing clear-sky solar radiation using various radiative transfer models.
Subclasses must implement methods to retrieve atmospheric data either at specific sites (time series) or on regular grids. The class handles: - Loading and validation of atmospheric datasets - Integration with solar position calculations - Execution of clear-sky radiation models (SPARTA, Bird, etc.) - CF-compliant metadata management
Attributes:
-
database_path(Path or None) –Directory containing the database files (set by subclass)
-
dataset(Dataset) –The loaded atmospheric dataset
Examples:
Subclasses should define database_path and implement data retrieval:
>>> class MyAtmosphere(BaseAtmosphere, database_path="/path/to/data"):
... @classmethod
... def at_sites(cls, times, latitude, longitude, **kwargs):
... # Implementation here
... pass
Notes
This is an abstract base class and cannot be instantiated directly. Use concrete implementations like MERRA2DailyAtmosphere or CustomAtmosphere.
See Also
MERRA2DailyAtmosphere : Most commonly used implementation CustomAtmosphere : For user-provided data
Validates that the database path exists (if specified) and initializes the internal atmosphere dataset to None.
Raises:
-
AttributeError–If database_path is specified but does not exist
Methods:
-
__init_subclass__–Automatically sets the database path for subclasses.
-
compute–Compute clear-sky solar radiation using a radiative transfer model.
Source code in src/spartasolar/atmoslib/_base.py
__init_subclass__
__init_subclass__(database_path: str, **kwargs)
Automatically sets the database path for subclasses.
Parameters:
-
(database_pathstr or None) –The directory path where the specific atmosphere data is stored. Pass
Nonefor sources that do not use a file database (e.g.CustomAtmosphereor API-based retrievers).
Source code in src/spartasolar/atmoslib/_base.py
compute
compute(
model: Model = "SPARTA",
include_atmosphere: bool = False,
model_kwargs: dict | None = None,
) -> Dataset
Compute clear-sky solar radiation using a radiative transfer model.
This method integrates solar position calculations with atmospheric constituent data to compute clear-sky irradiance components (GHI, DNI, DHI, etc.) using the specified radiative transfer model.
Parameters:
-
(modelModel, default:"SPARTA") –Name of the clear-sky model to use. Options: "SPARTA", "Bird"
-
(include_atmospherebool, default:False) –If True, include atmospheric constituents in the output dataset. If False, only radiation components are returned.
-
(model_kwargsdict, default:None) –Additional keyword arguments to pass to the model function
Returns:
-
Dataset–CF-compliant dataset containing computed irradiance components: - ghi: Global Horizontal Irradiance (W/m²) - dni: Direct Normal Irradiance (W/m²) - dhi or dif: Diffuse Horizontal Irradiance (W/m²) - csi: Circumsolar Irradiance (W/m², SPARTA only)
Examples:
>>> import pandas as pd
>>> from spartasolar.atmoslib import MERRA2DailyAtmosphere
>>>
>>> times = pd.date_range("2020-06-15", periods=24, freq="h")
>>> atm = MERRA2DailyAtmosphere.at_sites(
... times=times,
... latitude=36.72,
... longitude=-4.42
... )
>>> result = atm.compute(model="SPARTA")
>>> print(result.ghi.values)
Use different model with custom parameters:
>>> result = atm.compute(
... model="Bird",
... model_kwargs={"scheme": "transmittance_parameterization"}
... )
Notes
The method automatically: - Calculates solar position (zenith angle, Earth-Sun distance) - Converts atmospheric units to model requirements - Handles both gridded and site-based data structures
See Also
spartasolar.modlib.sparta : SPARTA model implementation spartasolar.modlib.bird : Bird clear-sky model
Source code in src/spartasolar/atmoslib/_base.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 | |
Clear-sky models
SPARTA
SPARTA
SPARTA(
cosz: float | ndarray = 0.5,
pressure: float | ndarray = 1013.25,
albedo: float | ndarray = 0.2,
pwater: float | ndarray = 1.4,
ozone: float | ndarray = 0.3,
beta: float | ndarray = 0.1,
alpha: float | ndarray = 1.3,
ssa: float | ndarray = 0.92,
asy: float | ndarray = 0.65,
ecf: float | ndarray = 1.0,
csi_param: str = "sparta",
csi_hfov: float = 2.5,
transmittance_scheme: str = "interdependent",
) -> dict[str, ndarray]
Compute clear-sky solar irradiance using the SPARTA model.
SPARTA (Solar PArameterization of the Radiative Transfer of the Atmosphere) is a high-accuracy 2-band broadband clear-sky model that computes direct, diffuse, global, and circumsolar irradiance. The model is fully vectorized and handles nighttime masking automatically.
Parameters:
-
(coszfloat or ndarray, default:0.5) –Cosine of the solar zenith angle [0, 1]. Values ≤ cos(90.5°) ≈ 0.00872 are treated as nighttime.
-
(pressurefloat or ndarray, default:1013.25) –Atmospheric surface pressure in hPa (or mb). Typical range: 800-1100 hPa.
-
(albedofloat or ndarray, default:0.2) –Ground surface albedo [0, 1]. Typical values: 0.1-0.3 (vegetation), 0.6-0.9 (snow), 0.05-0.15 (water).
-
(pwaterfloat or ndarray, default:1.4) –Precipitable water vapor in cm. Typical range: 0.5-6.0 cm.
-
(ozonefloat or ndarray, default:0.3) –Total column ozone in atm-cm. Note: 1 atm-cm = 1000 DU (Dobson Units). Typical range: 0.2-0.5 atm-cm (200-500 DU).
-
(betafloat or ndarray, default:0.1) –Ångström turbidity coefficient (aerosol optical depth at 1000 nm). Automatically clipped to [0, 2.2]. Typical range: 0.02-0.5.
-
(alphafloat or ndarray, default:1.3) –Ångström wavelength exponent. Automatically clipped to [0, 2.5]. Typical values: 0.5-1.0 (coarse aerosols), 1.5-2.0 (fine aerosols).
-
(ssafloat or ndarray, default:0.92) –Aerosol single-scattering albedo at ~700 nm [0, 1]. Typical values: 0.85-0.95 (urban), 0.95-0.99 (desert dust).
-
(asyfloat or ndarray, default:0.65) –Aerosol asymmetry parameter at ~700 nm [-1, 1]. Typical range: 0.6-0.8.
-
(ecffloat or ndarray, default:1.0) –Eccentricity correction factor for Sun-Earth distance. Range: ~0.967 (early July) to ~1.034 (early January).
-
(csi_paramstr, default:'sparta') –Circumsolar irradiance parameterization method: - 'none': Neglects circumsolar component - 'sparta': Uses SPARTA native parameterization (recommended)
-
(csi_hfovfloat, default:2.5) –Half field of view angle in degrees for circumsolar evaluation. Typical pyrheliometer values: 2.5° (standard), 2.9° (some instruments).
-
(transmittance_schemestr, default:'interdependent') –Method for computing atmospheric transmittances: - 'independent': Treats each constituent separately (faster, less accurate) - 'interdependent': Accounts for constituent interactions (more accurate)
Returns:
-
dict[str, float or ndarray]–Dictionary with the following irradiance components (all in W/m²):
- 'dni': Direct Normal Irradiance (beam on plane perpendicular to sun)
- 'dhi': Direct Horizontal Irradiance (beam on horizontal plane)
- 'dif': Diffuse Horizontal Irradiance (scattered radiation)
- 'ghi': Global Horizontal Irradiance (total on horizontal plane)
- 'csi': Circumsolar Normal Irradiance (forward-scattered aureole)
Examples:
Single location and time:
>>> from spartasolar.modlib import SPARTA
>>> result = SPARTA(
... cosz=0.866, # 30° solar zenith angle
... pressure=1013.25,
... pwater=2.0,
... ozone=0.3,
... beta=0.1,
... alpha=1.3
... )
>>> print(f"DNI: {result['dni']:.1f} W/m²")
>>> print(f"GHI: {result['ghi']:.1f} W/m²")
Vectorized computation for time series:
>>> import numpy as np
>>> # Simulate conditions at different solar elevations
>>> zenith_angles = np.linspace(0, 85, 20) # degrees
>>> cosz_values = np.cos(np.radians(zenith_angles))
>>>
>>> result = SPARTA(
... cosz=cosz_values,
... pressure=1013.25,
... pwater=np.linspace(1.0, 3.0, 20), # varying water vapor
... ozone=0.3,
... beta=0.08,
... alpha=1.4
... )
>>> print(result['ghi'].shape) # (20,)
High aerosol loading scenario:
>>> result = SPARTA(
... cosz=0.7,
... beta=0.5, # high turbidity
... alpha=0.8, # coarse particles
... ssa=0.88, # slightly absorbing
... csi_param='sparta'
... )
>>> csi_fraction = result['csi'] / result['dni']
>>> print(f"CSI fraction: {csi_fraction:.2%}")
Disable circumsolar correction:
Notes
- Solar constant used: 1361.1 W/m²
- Nighttime threshold: cosz ≤ cos(90.5°) ≈ 0.00872
- All input arrays are automatically broadcast to compatible shapes
- Invalid/missing values (-999, NaN) are handled gracefully
- The 'interdependent' scheme is recommended for highest accuracy
The model has been validated against radiative transfer simulations and ground measurements, showing typical errors < 2% for GHI and DNI under most atmospheric conditions.
See Also
spartasolar.modlib.bird : Alternative Bird clear-sky model
References
.. [1] Ruiz-Arias, J. A. (2023). SPARTA: Solar parameterization for the radiative transfer of the cloudless atmosphere. Renewable and Sustainable Energy Reviews*, 188, 113833. https://doi.org/10.1016/j.rser.2023.113833
Source code in src/spartasolar/modlib/sparta.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
Bird & Hulstrom
BIRD
BIRD(
cosz: float | ndarray = 0.5,
pressure: float | ndarray = 1013.25,
albedo: float | ndarray = 0.2,
pwater: float | ndarray = 1.4,
ozone: float | ndarray = 0.3,
beta: float | ndarray = 0.1,
alpha: float | ndarray = 1.3,
ssa: float | ndarray = 0.92,
asy: float | ndarray = 0.65,
ecf: float | ndarray = 1.0,
) -> dict[str, ndarray]
Calculate solar irradiance using the Bird & Hulstrom model.
The model estimates solar radiation through individual transmittance processes for Rayleigh scattering, ozone absorption, uniformly mixed gases, water vapor, and aerosol extinction. It also accounts for multiple reflections between the ground and the sky.
Parameters:
-
(coszfloat or ndarray, default:0.5) –Cosine of the solar zenith angle.
-
(pressurefloat or ndarray, default:1013.25) –Atmospheric surface pressure in hPa.
-
(albedofloat or ndarray, default:0.2) –Ground surface albedo in the range [0, 1].
-
(pwaterfloat or ndarray, default:1.4) –Precipitable water in cm.
-
(ozonefloat or ndarray, default:0.3) –Ozone vertical path length in atm-cm (1 atm-cm = 1000 DU).
-
(betafloat or ndarray, default:0.1) –Angstrom turbidity coefficient (AOD at 1000 nm).
-
(alphafloat or ndarray, default:1.3) –Angstrom wavelength exponent.
-
(ssafloat or ndarray, default:0.92) –Aerosol single-scattering albedo at approximately 700 nm.
-
(asyfloat or ndarray, default:0.65) –Aerosol asymmetry parameter.
-
(ecffloat or ndarray, default:1.0) –Eccentricity correction factor for the Sun-Earth orbit.
Returns:
Notes
- The model uses a fixed solar constant of 1353 W/m².
- Nighttime values are automatically masked (set to 0) for zenith
angles greater than 90.5°.
- The algorithm includes a 0.9662 correction factor for the
direct normal component as per the original publication.
References
- Bird, R. E., & Hulstrom, R. L. (1981). A simplified clear sky
model for direct and diffuse insolation on horizontal surfaces.
Solar Energy Research Institute (SERI).
Source code in src/spartasolar/modlib/bird.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
Configuration
config
Configuration management for SPARTA-Solar.
This module handles the persistent storage and retrieval of user settings using a TOML configuration file located in the standard user configuration directory.
The configuration system manages: - API credentials (e.g., SODA's user email) - Local storage paths for cached data - Algorithm preferences (e.g., solar position algorithm) - Service-specific settings
Configuration Flow: 1. On first import, checks if config file exists 2. If not found, creates it with default template 3. Loads configuration into memory (_GLOBAL_CONFIG) 4. Changes via set_option() are session-only 5. Persistent changes require manual editing of config.toml
Configuration File Location:
- Linux: ~/.config/spartasolar/config.toml
- macOS: ~/Library/Application Support/spartasolar/config.toml
- Windows: C:\Users\
Examples:
>>> from spartasolar.config import get_config_path, get_option, set_option
>>> # Get configuration file path
>>> config_path = get_config_path()
>>> print(config_path)
PosixPath('/home/user/.config/spartasolar/config.toml')
>>> # Retrieve an option
>>> email = get_option('crs_soda.user_email')
>>> # Set option for current session only
>>> set_option('sunwhere.algorithm', 'spa')
>>> # Get data directory (returns Path object)
>>> data_dir = get_option('merra2_daily.data_dir')
See Also
- get_config_path(): Get path to configuration file
- get_option(): Retrieve configuration value
- set_option(): Modify configuration (session only)
- show_config(): Display all current settings
Functions:
-
get_config_path–Get the path to the user's configuration file.
-
get_option–Retrieve the value of a specific configuration option.
-
set_option–Temporarily update a global option for the current session.
-
show_config–Print all current global options to the console.
get_config_path
get_config_path() -> Path
Get the path to the user's configuration file.
Returns:
-
Path–Absolute path to
config.tomlwithin the standard system-specific user configuration directory.
Source code in src/spartasolar/config.py
get_option
Retrieve the value of a specific configuration option.
Options are organized in tables (sections) within the TOML file. This function uses dot notation to access nested values.
Parameters:
-
(namestr) –Name of the option to retrieve using the format
<table-name>.<option-name>(for example,"crs_soda.user_email"). -
(defaultAny, default:None) –Value to return if the option is missing.
Returns:
-
Any–Option value. Returns
defaultif the option is missing. Options named"data_dir"are automatically converted toPathobjects.
Examples:
>>> from spartasolar.config import get_option
>>> # Get solar position algorithm
>>> algorithm = get_option('sunwhere.algorithm')
>>> print(algorithm)
'psa'
>>> # Get with default value
>>> email = get_option('crs_soda.user_email', default='user@example.com')
>>> # Data directories return Path objects
>>> from pathlib import Path
>>> data_dir = get_option('merra2_daily.data_dir')
>>> isinstance(data_dir, (Path, type(None)))
True
Source code in src/spartasolar/config.py
set_option
Temporarily update a global option for the current session.
Modifies configuration values in memory only. Changes are lost when the Python session ends. To make persistent changes, edit the config.toml file directly.
Parameters:
-
(namestr) –Name of the option to update in format
<table>.<option>. -
(valueAny) –New value to assign.
Pathobjects for"data_dir"options are automatically converted to strings.
Notes
Session-only changes are NOT saved to the config file. Restart
the Python session to revert to file values.
Examples:
>>> from spartasolar.config import set_option, get_option
>>> # Change solar position algorithm
>>> set_option('sunwhere.algorithm', 'spa')
>>> get_option('sunwhere.algorithm')
'spa'
>>> # Set data directory with Path object
>>> from pathlib import Path
>>> set_option('merra2_daily.data_dir', Path('/custom/path'))
Notes
To persist changes, manually edit the configuration file at the
path returned by ``get_config_path``.
Source code in src/spartasolar/config.py
show_config
Print all current global options to the console.
Notes
This function uses pprint for formatted output of the global
configuration state.