### Install and Setup BETTER-LBNL Package Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Demonstrates how to clone the BETTER-LBNL repository, set up a virtual environment using 'uv', and install the package in development mode. This is the initial step to start using the library. ```bash git clone https://github.com/LBNL-ETA/better-lbnl.git cd better-lbnl uv venv uv pip install -e ".[dev]" ``` -------------------------------- ### Development Installation of better-lbnl-os Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/getting_started.md Sets up the better-lbnl-os library for development. This involves cloning the repository, creating a virtual environment with uv, and installing the package in editable mode with development dependencies. ```bash git clone https://github.com/LBNL-ETA/better-lbnl-os.git cd better-lbnl-os uv venv uv pip install -e ".[dev]" ``` -------------------------------- ### Install better-lbnl-os using uv (recommended) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/getting_started.md Installs the better-lbnl-os library using the uv package manager, which is recommended for faster installations. This command adds the package to your project's dependencies. ```bash uv add better-lbnl-os ``` -------------------------------- ### Install BETTER-LBNL-OS Package (Bash) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/weather/README.md A bash command to install the BETTER-LBNL-OS package in editable mode from the project directory. This is a prerequisite for running the provided Python examples. ```bash # From the better-lbnl-os directory pip install -e . ``` -------------------------------- ### Run Python Weather Example (Bash) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/weather/README.md A bash command to execute a Python example script from the BETTER-LBNL-OS project. This demonstrates how to run the weather module examples after installation. ```bash python examples/weather/simple_weather_example.py ``` -------------------------------- ### Install BETTER-LBNL-OS using pip or uv Source: https://context7.com/lbnl-eta/better-lbnl-os/llms.txt Instructions for installing the BETTER-LBNL-OS library using either pip or uv package managers. uv is recommended for faster and more efficient dependency management. ```bash # Using pip pip install better-lbnl-os # Using uv (recommended) uv add better-lbnl-os ``` -------------------------------- ### Fit Change-Point Model to Building Energy Data (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/getting_started.md Demonstrates fitting a change-point model to building energy consumption data using the better-lbnl-os library. It prepares sample temperature and energy data, fits a model, and prints key results like model type, R-squared, and baseload. Requires numpy. ```python from better_lbnl_os import fit_changepoint_model import numpy as np # Prepare temperature and energy data (showing heating and cooling patterns) temperatures = np.array([30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85]) # degF energy_use = np.array([150, 140, 125, 110, 95, 85, 80, 80, 85, 95, 110, 125]) # kBtu/day # Fit change-point model model_result = fit_changepoint_model(temperatures, energy_use) # Check model quality if model_result.is_valid(): print(f"Model Type: {model_result.model_type}") # 5P (heating and cooling) print(f"R-squared: {model_result.r_squared:.3f}") # 0.995 print(f"Baseload: {model_result.baseload:.1f}") # 80.0 ``` -------------------------------- ### Clone Repository and Setup Environment (Bash) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/contributing.md Clones the BETTER-LBNL-OS repository and sets up a virtual environment with development dependencies using 'uv'. ```bash git clone https://github.com/YOUR-USERNAME/better-lbnl-os.git cd better-lbnl-os uv venv uv pip install -e ".[dev]" ``` -------------------------------- ### Basic Weather Data Retrieval and Degree Day Calculation (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/weather/README.md A minimal Python example demonstrating how to retrieve weather data for a specific location, calculate heating and cooling degree days (HDD/CDD), and display temperature information. This is ideal for users new to the module. ```python # Get weather aligned with utility bills weather = service.get_weather_data(location, year, month) hdd = weather.calculate_hdd() # For heating analysis cdd = weather.calculate_cdd() # For cooling analysis ``` -------------------------------- ### Verify BETTER-LBNL Package Installation Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb A simple Python script to confirm that the better-lbnl package has been successfully installed and can be imported. This script prints a confirmation message if the import is successful. ```python # Standard imports - package should be installed via: # git clone https://github.com/LBNL-ETA/better-lbnl.git # cd better-lbnl # uv venv # uv pip install -e ".[dev]" print("✅ Using properly installed better-lbnl package") ``` -------------------------------- ### Benchmark Building Against Reference Statistics in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Demonstrates benchmarking a building's energy model against available reference statistics. It includes functions to list, retrieve, and use reference data for comparison. ```python from better_lbnl_os import ( benchmark_building, get_reference_statistics, list_available_reference_statistics ) # See available reference datasets available = list_available_reference_statistics() print(available) # Get reference statistics for a space type ref_stats = get_reference_statistics("office") # Benchmark a building's model against reference benchmark_result = benchmark_building(model_result, ref_stats) print(f"Percentile rank: {benchmark_result.percentile:.1f}") ``` -------------------------------- ### Python Docstring Example for Sphinx Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/CONTRIBUTING.md An example of a Google-style docstring for the `calculate_eui` method, including type hints, arguments, return values, and an example. ```python def calculate_eui(self, annual_energy_kwh: float) -> float: """Calculate Energy Use Intensity (kBtu/sqft/year). Args: annual_energy_kwh: Annual energy consumption in kWh Returns: EUI in kBtu/sqft/year Example: >>> building = BuildingData(name="Office", floor_area=10000, ...) >>> eui = building.calculate_eui(34120) >>> print(f"EUI: {eui:.1f} kBtu/sqft/year") EUI: 11.6 kBtu/sqft/year """ ``` -------------------------------- ### Install better-lbnl-os using pip Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/getting_started.md Installs the better-lbnl-os library using the pip package manager. This is a standard way to install Python packages. ```bash pip install better-lbnl-os ``` -------------------------------- ### Python Unit Test Example Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/CONTRIBUTING.md An example of a unit test for the `BuildingData` class, demonstrating how to test the `calculate_eui` method. ```python def test_building_calculate_eui(): """Test EUI calculation for BuildingData.""" building = BuildingData( name="Test Building", floor_area=10000, space_type="Office", location="Berkeley, CA" ) # 34,120 kWh = 116,441.44 kBtu # 116,441.44 kBtu / 10,000 sqft = 11.64 kBtu/sqft eui = building.calculate_eui(annual_energy_kwh=34120) assert abs(eui - 11.64) < 0.01 ``` -------------------------------- ### Process Utility Bills with BETTER-LBNL Models (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Demonstrates how to create and process `UtilityBillData` objects using the better-lbnl package. The example shows how to calculate the number of days in a billing period, convert consumption to kWh, and compute daily averages. ```python from datetime import date from better_lbnl_os.models import UtilityBillData # Create utility bills with conversion methods bills = [ UtilityBillData( fuel_type="ELECTRICITY", start_date=date(2024, 1, 1), end_date=date(2024, 1, 31), consumption=45000.0, cost=5400.0, units="kWh" ), UtilityBillData( fuel_type="NATURAL_GAS", start_date=date(2024, 1, 1), end_date=date(2024, 1, 31), consumption=1200.0, cost=1800.0, units="therms" ) ] print("⚡ Utility Bills:") for i, bill in enumerate(bills, 1): print(f"\nBill {i}: {bill.fuel_type}") print(f" Period: {bill.start_date} to {bill.end_date}") print(f" Days: {bill.get_days()} days") print(f" Consumption: {bill.consumption:,.0f} {bill.units}") print(f" kWh equivalent: {bill.to_kwh():,.0f} kWh") print(f" Daily average: {bill.calculate_daily_average():.1f} {bill.units}/day") ``` -------------------------------- ### Placeholder for Geocoding Examples (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb This section outlines where geocoding examples would be implemented within the geography utilities. It notes that full functionality for geocoding typically requires API keys and suggests that these examples would demonstrate how to convert addresses to coordinates and vice versa. ```python # Geocoding examples (Note: requires API keys for full functionality) print("\n📍 Geocoding Examples:") # These examples show how geocoding would work with proper API setup ``` -------------------------------- ### Recommend Energy Efficiency Measures in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Shows how to detect inefficiency symptoms from benchmarking results and generate corresponding energy efficiency measure recommendations. It outlines the process of identifying and suggesting improvements. ```python from better_lbnl_os import detect_symptoms, recommend_ee_measures # Detect symptoms from benchmark results symptoms = detect_symptoms(benchmark_result) for symptom in symptoms: print(f"- {symptom.description}") # Get measure recommendations recommendations = recommend_ee_measures(symptoms) for rec in recommendations.measures: print(f"- {rec.measure_name}: {rec.description}") ``` -------------------------------- ### Create and Display Weather Data Model (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Demonstrates the creation and usage of WeatherData and WeatherStation models from the better_lbnl_os.models module. It shows how to initialize these objects with weather parameters and display their properties, including calculated temperatures and distances. ```python # Weather domain models with methods from better_lbnl_os.models import WeatherData, WeatherStation # Create weather data with basic temperature properties weather = WeatherData( station_id="KOAK", latitude=location_info.geo_lat, longitude=location_info.geo_lng, year=2024, month=1, avg_temp_c=monthly_avg_c, min_temp_c=min(daily_temps_c), max_temp_c=max(daily_temps_c), ) print("🌤️ Weather Domain Model:") print(f" Station: {weather.station_id}") print(f" Location: {weather.latitude}, {weather.longitude}") print(f" Period: {weather.year}-{weather.month:02d}") print(f" Avg Temp: {weather.avg_temp_c:.1f}°C ({weather.avg_temp_f:.1f}°F)") print(f" Min Temp: {weather.min_temp_c:.1f}°C ({weather.min_temp_f:.1f}°F)") print(f" Max Temp: {weather.max_temp_c:.1f}°C ({weather.max_temp_f:.1f}°F)") # Weather station example station = WeatherStation( station_id="KOAK", name="Oakland International Airport", latitude=37.7214, longitude=-122.2208, elevation=2.4 ) # Calculate distance to building location distance = station.distance_to(location_info.geo_lat, location_info.geo_lng) print("\n📍 Weather Station:") print(f" {station.name} ({station.station_id})") print(f" Elevation: {station.elevation}m") print(f" Distance: {distance:.1f} km from building") ``` -------------------------------- ### Install Pre-commit Hooks (Bash) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/contributing.md Installs pre-commit hooks to automatically run linting and formatting checks before each commit. ```bash pre-commit install ``` -------------------------------- ### Create and Use BETTER-LBNL Domain Models (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Illustrates the creation and usage of `BuildingData` and `LocationInfo` domain models from the better-lbnl package. It shows how to instantiate these models with data and utilize their built-in business logic methods for calculations and validation. ```python from datetime import date from better_lbnl_os.models import BuildingData, LocationInfo, UtilityBillData # Create a building with business logic methods building = BuildingData( name="LBNL Building 90", floor_area=50000.0, # sq ft space_type="Office", location="Berkeley, CA", climate_zone="3C" ) # Create separate location info for geographic operations location_info = LocationInfo( geo_lat=37.8765, geo_lng=-122.2463, zipcode="94720", state="CA" ) print("🏢 Building created:") print(f"Name: {building.name}") print(f"Floor Area: {building.floor_area:,.0f} sq ft") print(f"Space Type: {building.space_type}") print(f"Location: {building.location}") print(f"Climate Zone: {building.climate_zone}") print("\n📍 Location Info:") print(f"Coordinates: ({location_info.geo_lat}, {location_info.geo_lng})") print(f"ZIP Code: {location_info.zipcode}") # Use business logic methods benchmark_category = building.get_benchmark_category() print(f"\n📊 Benchmark Category: {benchmark_category}") # Check coordinate validity is_valid = location_info.is_valid_coordinates() print(f"✅ Valid coordinates: {is_valid}") ``` -------------------------------- ### Install Development Dependencies (Bash) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/CONTRIBUTING.md Installs the project's development dependencies using uv pip, enabling features required for development, testing, and linting. ```bash uv pip install -e ".[dev]" ``` -------------------------------- ### Geocoding with Dummy Data (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Demonstrates how to use the geography module for geocoding, including creating dummy location data and showing available functions. It highlights that actual geocoding requires API keys. ```python try: # Import available functions from unified geography module from better_lbnl_os.utils.geography import create_dummy_location_info # Show what functions are actually available print(" Available geocoding functions:") print(" • geocode(address, api_key) - Convert address to coordinates") print(" • find_closest_weather_station(lat, lng, stations)") print(" • create_dummy_location_info() - Test data") # Demo with dummy data since we don't have API keys dummy_location = create_dummy_location_info() print("\n 📍 Dummy Location Data (SF Airport):") print(f" Coordinates: ({dummy_location.geo_lat:.4f}, {dummy_location.geo_lng:.4f})") print(f" ZIP: {dummy_location.zipcode}") print(f" State: {dummy_location.state}") print(f" NOAA Station: {dummy_location.noaa_station_name}") print(f" eGrid Region: {dummy_location.egrid_sub_region}") # Note about actual geocoding (would require API keys) print("\n ⚠️ Actual geocoding example (requires Google API key):") print(" location = geocode('1600 Amphitheatre Parkway, CA', api_key)") except Exception as e: print(f" ⚠️ Geocoding module error: {str(e)[:60]}...") print("\n💡 Note: Geocoding requires Google Maps API key for full functionality") ``` -------------------------------- ### Custom Base Temperature for Degree Day Calculation (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/weather/README.md This Python example illustrates how to calculate heating degree days (HDD) using custom base temperatures, which is beneficial for specialized applications like analyzing energy consumption for commercial buildings or populations sensitive to temperature variations. ```python # Use different base temperatures for specialized applications hdd_60 = weather.calculate_hdd(base_temp_f=60.0) # Commercial buildings hdd_70 = weather.calculate_hdd(base_temp_f=70.0) # Sensitive populations ``` -------------------------------- ### Create Custom Benchmarking Statistics in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Explains how to generate custom reference statistics from a collection of fitted change-point models. This allows for benchmarking against a specific portfolio or dataset. ```python from better_lbnl_os import create_statistics_from_models # List of ChangePointModelResult objects from your buildings models = [model1, model2, model3, ...] custom_stats = create_statistics_from_models(models) ``` -------------------------------- ### Generate Synthetic Building Energy Data (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Generates synthetic monthly energy consumption data based on monthly temperatures. It simulates base load, heating, and cooling energy requirements using Python lists and conditional logic, then prints the results. ```python from better_lbnl_os.core.changepoint import fit_changepoint_model # Generate synthetic energy consumption data correlated with temperature # This simulates a building with heating and cooling loads # Monthly temperature data (Celsius) for a full year monthly_temps = [7, 9, 12, 16, 20, 25, 28, 27, 23, 18, 12, 8] # Jan-Dec # Synthetic monthly energy consumption (kWh/day) # Base load + heating when cold + cooling when hot base_load = 1000 # kWh/day heating_energy = [max(0, (18 - temp) * 150) for temp in monthly_temps] # Heat when < 18°C cooling_energy = [max(0, (temp - 22) * 200) for temp in monthly_temps] # Cool when > 22°C monthly_energy = [base_load + heat + cool for heat, cool in zip(heating_energy, cooling_energy, strict=False)] print("📊 Synthetic Building Energy Data:") for i, (temp, energy) in enumerate(zip(monthly_temps, monthly_energy, strict=False), 1): print(f" Month {i:2d}: {temp:4.1f}°C → {energy:5.0f} kWh/day") print(f"\nTemperature range: {min(monthly_temps):.1f}°C to {max(monthly_temps):.1f}°C") print(f"Energy range: {min(monthly_energy):.0f} to {max(monthly_energy):.0f} kWh/day") ``` -------------------------------- ### Fit Change-Point Model to Energy Data (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Prepares temperature and energy data as NumPy arrays for fitting a change-point model. This is a preparatory step for statistical energy modeling using the fit_changepoint_model function. ```python # Fit change-point model to the data using new generic interface temperature_array = np.array(monthly_temps) energy_array = np.array(monthly_energy) ``` -------------------------------- ### Perform Building Analysis with BuildingAnalyticsService (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Illustrates the usage of the `BuildingAnalyticsService` class for running a complete building analysis. This involves instantiating the service and calling its `analyze` method with building data and utility bills. Assumes `building_data` and `utility_bills` are defined. ```python from better_lbnl_os import BuildingAnalyticsService service = BuildingAnalyticsService() # Run complete analysis analysis = service.analyze(building_data, utility_bills) ``` -------------------------------- ### Estimate Energy and Cost Savings in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Demonstrates how to estimate potential energy and cost savings based on a building's model and benchmarking results. It requires inputs like fuel type and energy rates to calculate savings. ```python from better_lbnl_os import estimate_savings savings = estimate_savings( model_result=model_result, benchmark_result=benchmark_result, fuel_type="electricity", energy_rate=0.12 # $/kWh ) print(f"Annual energy savings: {savings.energy_savings:.0f} kWh") print(f"Annual cost savings: ${savings.cost_savings:.2f}") ``` -------------------------------- ### Subsystem Pattern for Evolving Modules Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/notes/refactoring-summary.md Illustrates the subsystem pattern for organizing core modules. This pattern allows modules to start as single files and evolve into subsystems with dedicated directories for calculations, providers, and orchestration as complexity increases. ```plaintext core/ ├── simple_module.py # Start simple (single file) └── complex_module/ # Convert to subsystem when needed ├── calculations.py # Core algorithms ├── providers.py # External integrations └── service.py # Orchestration ``` -------------------------------- ### PortfolioBenchmarkService - __init__ Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/api/pipeline.md Initializes the PortfolioBenchmarkService. ```APIDOC ## POST /lbnl-eta/better-lbnl-os/PortfolioBenchmarkService/__init__ ### Description Initializes the PortfolioBenchmarkService. ### Method POST ### Endpoint /lbnl-eta/better-lbnl-os/PortfolioBenchmarkService/__init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed for initialization." } ``` ### Response #### Success Response (200) - **None** (None) - Initialization successful. #### Response Example ```json { "example": "None" } ``` ``` -------------------------------- ### Pytest Fixture Usage Example Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/tests/README.md This Python snippet illustrates how to use shared fixtures provided by pytest in test functions. Fixtures like `sample_building` and `sample_electricity_bill` are automatically injected into the test function, simplifying test setup and data management. ```python def test_something(sample_building, sample_electricity_bill): # sample_building and sample_electricity_bill are automatically available assert sample_building.floor_area == 50000 ``` -------------------------------- ### Benchmark Building Performance with Python Source: https://context7.com/lbnl-eta/better-lbnl-os/llms.txt Demonstrates two methods for benchmarking building energy performance using the better-lbnl-os library: using built-in reference statistics or custom statistics derived from a portfolio of models. It also shows how to access and interpret the benchmark results. ```python from better_lbnl_os import benchmark_with_reference, create_statistics_from_models, benchmark_building # Option 1: Benchmark against built-in reference statistics result = benchmark_with_reference( change_point_results={"ELECTRICITY": electricity_model}, floor_area=5000.0, # square feet country_code="US", building_type="OFFICE", savings_target="NOMINAL", # "CONSERVATIVE", "NOMINAL", or "AGGRESSIVE" building_id="building_001", ) # Option 2: Create custom statistics from portfolio models portfolio_models = [electricity_model] # Add more models from your portfolio custom_stats = create_statistics_from_models(portfolio_models) result = benchmark_building( change_point_results={"ELECTRICITY": electricity_model}, benchmark_statistics=custom_stats, floor_area=5000.0, savings_target="NOMINAL", building_id="building_001", ) # Access benchmark results print(f"Overall Rating: {result.get_overall_rating('ELECTRICITY')}") print(f"Average Percentile: {result.get_average_percentile('ELECTRICITY'):.1f}%") if result.ELECTRICITY and result.ELECTRICITY.baseload: bl = result.ELECTRICITY.baseload print(f"Baseload Rating: {bl.rating}") print(f"Baseload Percentile: {bl.percentile:.1f}%") print(f"Target Baseload: {bl.target_value:.3f}") ``` -------------------------------- ### Integrate Weather Data with WeatherData (Python) Source: https://context7.com/lbnl-eta/better-lbnl-os/llms.txt Shows how to create and use the `WeatherData` model for monthly weather observations. It also demonstrates fetching weather data using `get_weather_for_bills` and resolving locations with `resolve_location`, which requires a Google Maps API key. ```python from better_lbnl_os import ( WeatherData, WeatherStation, get_weather_for_bills, resolve_location, UtilityBillData, ) from datetime import date weather = WeatherData( latitude=37.8716, longitude=-122.2727, year=2023, month=1, avg_temp_c=10.5, min_temp_c=5.0, max_temp_c=15.0, data_source="OpenMeteo", ) print(f"Average Temp: {weather.avg_temp_c:.1f}°C ({weather.avg_temp_f:.1f}°F)") location = resolve_location( address="1 Cyclotron Road, Berkeley, CA 94720", google_maps_api_key="YOUR_GOOGLE_MAPS_API_KEY", ) print(f"Latitude: {location.latitude}, Longitude: {location.longitude}") print(f"State: {location.state}, ZIP: {location.zipcode}") ``` -------------------------------- ### Conventional Commits PR Title Examples Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/CONTRIBUTING.md Examples of pull request titles following the conventional commits format, used for categorizing changes like features, fixes, and documentation updates. ```text - `feat:` New feature - `fix:` Bug fix - `docs:` Documentation only - `style:` Code style changes - `refactor:` Code refactoring - `test:` Test additions/changes - `chore:` Maintenance tasks Examples: - `feat: add portfolio benchmarking service` - `fix: correct EUI calculation for metric units` - `docs: add examples for change-point modeling` ``` -------------------------------- ### Build Documentation with Sphinx (Bash) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/CONTRIBUTING.md Commands to navigate to the docs directory and build the HTML documentation using Sphinx. The output can be viewed in a web browser. ```bash cd docs make html # Open _build/html/index.html in a browser ``` -------------------------------- ### Basic usage of BETTER-LBNL-OS for change-point model fitting Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/index.md Demonstrates basic usage of the BETTER-LBNL-OS library. It shows how to create a BuildingData object and fit a change-point model to temperature and energy use data. Requires numpy for array manipulation. ```python from better_lbnl_os import BuildingData, fit_changepoint_model import numpy as np # Create a building building = BuildingData( name="Office Building", floor_area=50000, space_type="Office", location="Berkeley, CA" ) # Fit change-point model temperatures = np.array([45, 50, 55, 60, 65, 70, 75, 80]) energy_use = np.array([120, 110, 95, 85, 80, 82, 95, 115]) model = fit_changepoint_model(temperatures, energy_use) print(f"R-squared: {model.r_squared:.3f}") ``` -------------------------------- ### Building Analytics and Portfolio Benchmarking Services Source: https://context7.com/lbnl-eta/better-lbnl-os/llms.txt Provides high-level orchestration for complex analysis workflows and portfolio-level benchmarking. `BuildingAnalyticsService` analyzes individual buildings using bill and weather data, while `PortfolioBenchmarkService` allows adding multiple buildings, calculating portfolio-wide metrics, identifying improvement targets, and generating reports. ```python from better_lbnl_os import ( BuildingAnalyticsService, PortfolioBenchmarkService, BuildingData, UtilityBillData, WeatherData, BenchmarkResult, ) from datetime import date # Create service instance service = BuildingAnalyticsService() # Create building and data building = BuildingData( name="Office Tower", floor_area=100000, space_type="Office", location="San Francisco, CA", ) bills = [ UtilityBillData( fuel_type="ELECTRICITY", start_date=date(2023, 1, 1), end_date=date(2023, 1, 31), consumption=50000, units="kWh", ) ] weather = [ WeatherData(latitude=37.77, longitude=-122.42, year=2023, month=1, avg_temp_c=12.0) ] # Analyze building analysis = service.analyze_building(building, bills, weather) print(f"Analysis Status: {analysis['status']}") # Portfolio benchmarking portfolio_service = PortfolioBenchmarkService() # Add buildings with their benchmark results for i in range(5): b = BuildingData( name=f"Building {i+1}", floor_area=50000 + i * 10000, space_type="Office", location="California", ) result = BenchmarkResult( building_id=f"building_{i+1}", floor_area=b.floor_area, percentile=50.0 + i * 10, z_score=0.0 + i * 0.2, rating=["Poor", "Typical", "Typical", "Good", "Good"][i], ) portfolio_service.add_building(b, result) # Calculate portfolio metrics metrics = portfolio_service.calculate_portfolio_metrics() print(f"Total Buildings: {metrics['total_buildings']}") print(f"Average Percentile: {metrics['average_percentile']:.1f}") print(f"Rating Distribution: {metrics['rating_distribution']}") # Identify improvement targets targets = portfolio_service.identify_improvement_targets(top_n=3) print(f"Top Improvement Targets: {targets}") # Generate portfolio report report = portfolio_service.generate_portfolio_report() print(f"Report: {report}") ``` -------------------------------- ### Get Target Coefficient Value Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/api/benchmarking.md Calculates the target coefficient value based on a specified savings target level. This helps in setting performance goals for buildings. ```APIDOC ## POST /lbnl-eta/better-lbnl-os/core/benchmarking/get_target_coefficient_value ### Description Calculate target coefficient value based on savings target level. ### Method POST ### Endpoint /lbnl-eta/better-lbnl-os/core/benchmarking/get_target_coefficient_value ### Parameters #### Request Body - **coefficient_name** (str) - Required - Name of the coefficient - **current_value** (float) - Required - Current coefficient value - **median** (float) - Required - Reference median - **stdev** (float) - Required - Reference standard deviation - **savings_target** (str) - Optional - Target level (“CONSERVATIVE”, “NOMINAL”, “AGGRESSIVE”). Defaults to "NOMINAL". ### Response #### Success Response (200) - **float** - Target coefficient value ``` -------------------------------- ### Define Utility Bill Data Model in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Shows how to instantiate a UtilityBillData object for recording utility bill information. It includes fields for dates, consumption, fuel type, and cost. ```python from better_lbnl_os import UtilityBillData from datetime import date bill = UtilityBillData( start_date=date(2023, 1, 1), end_date=date(2023, 1, 31), consumption=1500, # kWh fuel_type="electricity", cost=150.00 ) ``` -------------------------------- ### Generate Energy Efficiency Recommendations with Python Source: https://context7.com/lbnl-eta/better-lbnl-os/llms.txt This Python code snippet demonstrates how to use the better-lbnl-os library to detect energy inefficiency symptoms from benchmark results, map these symptoms to specific energy efficiency measures, and generate a comprehensive set of recommendations. It also shows how to view all available BETTER measures. ```python from better_lbnl_os import ( detect_symptoms, map_symptoms_to_measures, recommend_ee_measures, BETTER_MEASURES, BenchmarkResult, ) # Assuming you have benchmark results from benchmarking step benchmark_result = { "ELECTRICITY": { "baseload": {"coefficient_value": 2.5, "target_value": 1.8}, "cooling_change_point": {"coefficient_value": 20.0, "target_value": 22.0}, "cooling_slope": {"coefficient_value": 0.035, "target_value": 0.025}, }, "FOSSIL_FUEL": { "baseload": {"coefficient_value": 1.2, "target_value": 0.8}, "heating_change_point": {"coefficient_value": 18.0, "target_value": 16.0}, "heating_slope": {"coefficient_value": -0.010, "target_value": -0.015}, }, } # Detect inefficiency symptoms symptoms = detect_symptoms(benchmark_result) for symptom in symptoms: print(f"Detected: {symptom.symptom_id}") print(f" Description: {symptom.description}") print(f" Detected Value: {symptom.detected_value}") print(f" Threshold: {symptom.threshold_value}") print(f" Severity: {symptom.severity}") # Map symptoms to recommended measures measures = map_symptoms_to_measures(symptoms) for measure in measures: print(f"Recommended: {measure.name}") print(f" Measure ID: {measure.measure_id}") print(f" Triggered by: {measure.triggered_by}") # Or use the convenience function for full recommendation result ee_result = recommend_ee_measures(benchmark_result) print(f"Total symptoms detected: {ee_result.metadata['total_symptoms']}") print(f"Total recommendations: {ee_result.metadata['total_recommendations']}") # View all available BETTER measures for measure_id, measure_name in BETTER_MEASURES.items(): print(f"{measure_id}: {measure_name}") ``` -------------------------------- ### Fit Basic Change-Point Model in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Illustrates fitting a basic change-point regression model using temperature and energy consumption data. The function returns a result object with model performance metrics. ```python from better_lbnl_os import fit_changepoint_model import numpy as np # Temperature data (degF) temperatures = np.array([30, 40, 50, 60, 70, 80, 90]) # Energy consumption (kBtu/day) energy = np.array([120, 100, 85, 75, 80, 95, 115]) result = fit_changepoint_model(temperatures, energy) print(f"Model type: {result.model_type}") print(f"R-squared: {result.r_squared:.3f}") print(f"CV(RMSE): {result.cvrmse:.1f}%") ``` -------------------------------- ### PortfolioBenchmarkService - calculate_portfolio_metrics Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/api/pipeline.md Calculates metrics for the entire portfolio. ```APIDOC ## GET /lbnl-eta/better-lbnl-os/PortfolioBenchmarkService/calculate_portfolio_metrics ### Description Calculates metrics for the entire portfolio. ### Method GET ### Endpoint /lbnl-eta/better-lbnl-os/PortfolioBenchmarkService/calculate_portfolio_metrics ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **dict** (dict) - A dictionary containing portfolio metrics. #### Response Example ```json { "example_metric_1": "value1", "example_metric_2": "value2" } ``` ``` -------------------------------- ### Define Building Data Model in Python Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/user_guide.md Demonstrates how to create a BuildingData object to represent a building's metadata. This class stores information like name, floor area, space type, and location. ```python from better_lbnl_os import BuildingData building = BuildingData( name="Office Building", floor_area=5000, # square meters space_type="Office", location="Berkeley, CA" ) ``` -------------------------------- ### PortfolioBenchmarkService - add_building Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/docs/api/pipeline.md Adds a building and its benchmark result to the portfolio. ```APIDOC ## POST /lbnl-eta/better-lbnl-os/PortfolioBenchmarkService/add_building ### Description Adds a building and its benchmark result to the portfolio. ### Method POST ### Endpoint /lbnl-eta/better-lbnl-os/PortfolioBenchmarkService/add_building ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **building** (BuildingData) - Required - Data for the building to be added. - **benchmark_result** (BenchmarkResult) - Required - The benchmark result for the building. ### Request Example ```json { "building": { "example_building_data": "..." }, "benchmark_result": { "example_benchmark_result": "..." } } ``` ### Response #### Success Response (200) - **None** (None) - Building successfully added. #### Response Example ```json { "example": "None" } ``` ``` -------------------------------- ### Statistical Model Validation (Python) Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/examples/notebooks/explore.ipynb Calculates and displays statistical metrics like R-squared and CV-RMSE for a change-point energy model. It compares manual calculations with model results and provides a performance assessment. ```python from better_lbnl_os.utils.statistics import calculate_cvrmse, calculate_r_squared # Statistical analysis of our change-point model fit predicted_energy = [] # Use the model to predict energy for each temperature point for temp in monthly_temps: prediction = model_result.baseload or 0 if model_result.heating_slope and model_result.heating_change_point: if temp < model_result.heating_change_point: prediction += model_result.heating_slope * (model_result.heating_change_point - temp) if model_result.cooling_slope and model_result.cooling_change_point: if temp > model_result.cooling_change_point: prediction += model_result.cooling_slope * (temp - model_result.cooling_change_point) predicted_energy.append(prediction) # Calculate statistical metrics manually to verify model results manual_r_squared = calculate_r_squared(np.array(monthly_energy), np.array(predicted_energy)) manual_cvrmse = calculate_cvrmse(np.array(monthly_energy), np.array(predicted_energy)) print("📈 Statistical Analysis:") print(f" Model R²: {model_result.r_squared:.3f}") print(f" Manual R²: {manual_r_squared:.3f}") print(f" Model CV-RMSE: {model_result.cvrmse:.3f}") print(f" Manual CV-RMSE: {manual_cvrmse:.3f}") print("\n🎯 Model Performance:") if model_result.r_squared > 0.8: print(" ✅ Excellent fit (R² > 0.8)") elif model_result.r_squared > 0.6: print(" ✅ Good fit (R² > 0.6)") else: print(" ⚠️ Poor fit (R² < 0.6)") if model_result.cvrmse < 0.2: print(" ✅ Low prediction error (CV-RMSE < 20%)") elif model_result.cvrmse < 0.5: print(" ✅ Acceptable error (CV-RMSE < 50%)") else: print(" ⚠️ High prediction error (CV-RMSE > 50%)") ``` -------------------------------- ### Run Tests with Coverage for better-lbnl-os Source: https://github.com/lbnl-eta/better-lbnl-os/blob/main/README.md This command runs the better-lbnl-os test suite with code coverage enabled, generating an HTML report. This helps identify which parts of the code are being tested and which might need more attention. ```bash pytest --cov=better_lbnl_os --cov-report=html ```