npm package: @simuwatt/calculations-hub
Description: Centralized hub for all mathematical calculations needed across the organization's repositories.
Latest version: 1.0.45

# @simuwatt/calculations-hub

[![npm version](https://badge.fury.io/js/@simuwatt/calculations-hub.svg)](https://www.npmjs.com/package/@simuwatt/calculations-hub)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A centralized TypeScript library that serves as the mathematical calculation hub for energy efficiency and utility analysis across Simuwatt's repositories. This package provides standardized calculations for energy baselines, utility measurements, cash flow analysis, unit conversions, and energy efficiency metrics.

## Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Usage](#usage)
- [API Reference](#api-reference)
- [Development](#development)
- [Testing](#testing)
- [Publishing](#publishing)
- [Contributing](#contributing)
- [License](#license)

## Overview

The calculations-hub consolidates complex mathematical operations for:

- **Energy Baseline Calculations**: Analyze building energy consumption patterns and establish baseline metrics
- **Utility Analytics**: Process and analyze utility data across multiple energy types (electricity, gas, water, etc.)
- **Energy Efficiency Measures**: Calculate savings, costs, and financial metrics for energy conservation measures
- **Unit Conversions**: Convert between different energy units (kWh, BTU, therms, etc.)
- **Cash Flow Analysis**: Perform financial analysis including ROI, NPV, payback periods
- **Last Twelve Month Trends**: Analyze recent energy usage patterns and trends
- **GHG Emissions**: Calculate greenhouse gas emissions and carbon footprint metrics

## Features

- ✅ **Comprehensive Utility Support**: Handles 20+ utility types including electricity, natural gas, water, solar, wind, and various fuel oils
- ✅ **Multi-Unit Conversions**: Supports 40+ energy and volume units with automatic conversion factors
- ✅ **Financial Calculations**: ROI, NPV, SIR, simple payback, and cash flow projections
- ✅ **TypeScript Support**: Full type definitions with IntelliSense support
- ✅ **Tree-shakeable**: Modular exports for optimal bundle sizes
- ✅ **Well Tested**: Comprehensive test suite with Jest
- ✅ **Zero Dependencies**: Lightweight with minimal external dependencies

## Prerequisites

- **Node.js**: Version 20.12.2 or higher (as specified in `.nvmrc`)
- **Package Manager**: npm or yarn

## Installation

```bash
npm install @simuwatt/calculations-hub
```

or with yarn:

```bash
yarn add @simuwatt/calculations-hub
```

## Usage

### Basic Import

```typescript
import {
  calculateBaseline,
  calculateMeasuresMetrics,
  convertValueFromUnitAToUnitB,
  calculateCashflow,
  UNITS,
  UTILITIES
} from '@simuwatt/calculations-hub'
```

### Calculate Energy Baseline

```typescript
import { calculateBaseline } from '@simuwatt/calculations-hub'

const baselineResult = calculateBaseline(
  building,        // Building object with configuration
  organization,    // Organization settings
  monthUtilities,  // Historical utility data
  customRange?     // Optional custom date range
)

if (baselineResult) {
  console.log('Baseline Summary:', baselineResult.summary)
  console.log('Monthly Utilities:', baselineResult.monthUtilities)
}
```

### Unit Conversions

```typescript
import { convertValueFromUnitAToUnitB, UTILITIES, UNITS } from '@simuwatt/calculations-hub'

// Convert 1000 kWh to MBtu for electricity
const convertedValue = convertValueFromUnitAToUnitB(
  1000,
  UTILITIES.ELECTRICITY,
  UNITS.KWH,
  UNITS.MBTU
)

console.log(`1000 kWh = ${convertedValue} MBtu`)
```

### Cash Flow Analysis

```typescript
import { calculateCashflow } from '@simuwatt/calculations-hub'

const cashflowResult = calculateCashflow({
  electricitySavings: 5000,    // Annual electricity savings ($)
  gasSavings: 2000,            // Annual gas savings ($)
  measureCost: 50000,          // Total measure cost ($)
  incentives: 10000,           // Available incentives ($)
  electricityRate: 3,          // Annual electricity rate increase (%)
  gasRate: 2,                  // Annual gas rate increase (%)
  discountRate: 6,             // Discount rate (%)
  inflationRate: 2,            // Inflation rate (%)
  period: 15                   // Analysis period (years)
})

console.log('ROI:', cashflowResult.roi + '%')
console.log('NPV:', cashflowResult.npv)
console.log('Payback:', cashflowResult.payback + ' years')
```

### Calculate Energy Efficiency Measures

```typescript
import { calculateMeasuresMetrics } from '@simuwatt/calculations-hub'

const measuresMetrics = calculateMeasuresMetrics(
  measures,        // Array of energy efficiency measures
  building,        // Building object
  organization,    // Organization settings
  monthUtilities   // Historical utility data
)

if (measuresMetrics) {
  console.log('Total Energy Savings:', measuresMetrics.energy.saving)
  console.log('GHG Emissions Reduction:', measuresMetrics.ghgSaving)
  console.log('Financial Metrics:', measuresMetrics.generalData)
}
```

## API Reference

### Core Functions

#### `calculateBaseline(building, organization, dbMonthUtilities, customRange?)`
Calculates energy baseline metrics for a building based on historical utility data.

**Parameters:**
- `building: Building` - Building configuration and properties
- `organization: Organization` - Organization settings and preferences
- `dbMonthUtilities: MonthUtilityDB[]` - Historical monthly utility data
- `customRange?: MomentDateRange` - Optional custom date range for baseline calculation

**Returns:** `CalculateBaselineResponse | null`

#### `calculateMeasuresMetrics(measures, building, organization, dbMonthUtilities)`
Calculates comprehensive metrics for energy efficiency measures.

**Parameters:**
- `measures: any[]` - Array of energy efficiency measures
- `building: Building` - Building object
- `organization: Organization` - Organization settings
- `dbMonthUtilities: MonthUtilityDB[] | null` - Historical utility data

**Returns:** `MeasureMetric | null`

#### `convertValueFromUnitAToUnitB(value, type, unitA, unitB)`
Converts energy values between different units.

**Parameters:**
- `value: number` - The numeric value to convert
- `type: UtilityType` - Type of utility (electricity, gas, etc.)
- `unitA: UnitType` - Source unit
- `unitB: UnitType` - Target unit

**Returns:** `number | null`

#### `calculateCashflow(params)`
Performs comprehensive cash flow analysis for energy projects.

**Parameters:**
- `params: CalculateCashflow` - Cash flow calculation parameters

**Returns:** `CashflowResult`

### Constants

#### Supported Utilities
```typescript
UTILITIES = {
  ELECTRICITY: 'electric',
  NATURAL_GAS: 'naturalgas',
  WATER: 'water',
  SOLAR: 'solar',
  WIND: 'wind',
  // ... and 15+ more utility types
}
```

#### Supported Units
```typescript
UNITS = {
  KWH: 'kWh',
  MBTU: 'MBtu',
  THERMS: 'therms',
  CCF: 'ccf',
  GAL: 'Gal',
  // ... and 35+ more unit types
}
```

## Development

### Setup

1. Clone the repository
2. Install dependencies:
   ```bash
   yarn install
   ```
3. Ensure you're using the correct Node.js version:
   ```bash
   nvm use  # Uses Node.js 20.12.2 from .nvmrc
   ```

### Available Scripts

- **Build**: `yarn build` - Compiles TypeScript and generates distribution files
- **Development**: `yarn start` - Runs the development server with ts-node
- **Test**: `yarn test` - Runs the Jest test suite
- **Lint**: `yarn lint:check` - Checks code with ESLint
- **Lint Fix**: `yarn lint:fix` - Fixes linting issues automatically
- **Format**: `yarn format:check` - Checks code formatting with Prettier
- **Format Fix**: `yarn format:write` - Formats code with Prettier

### Project Structure

```
src/
├── baseline.ts           # Energy baseline calculations
├── cashflow.ts          # Financial cash flow analysis
├── converter.ts         # Unit conversion utilities
├── lastTwelveMonthTrend.ts # Recent usage trend analysis
├── measures.ts          # Energy efficiency measures calculations
├── monthUtilities.ts    # Monthly utility data processing
└── index.ts            # Main export file

static/
├── utilities.ts        # Utility type definitions and mappings
├── units.ts           # Unit definitions and conversion factors
├── conversions.ts     # Conversion factor constants
└── ...               # Additional static data files

types/
├── building.d.ts      # Building type definitions
├── measures.d.ts      # Energy measures types
├── utilities.d.ts     # Utility-related types
└── ...               # Additional type definitions
```

## Testing

The project uses Jest for testing with TypeScript support:

```bash
# Run all tests
yarn test

# Run tests in watch mode
yarn test --watch

# Run tests with coverage
yarn test --coverage
```

Tests are located in the `tests/` directory and include:
- Unit tests for all calculation functions
- Integration tests for complex workflows
- Mock data for consistent testing

## Publishing

### Publishing a New Version

1. **Update Version**: Update the version in `package.json` following semantic versioning
2. **Build**: Ensure the project builds successfully
   ```bash
   yarn build
   ```
3. **Test**: Run the full test suite
   ```bash
   yarn test
   ```
4. **Publish**: Publish to npm (requires appropriate permissions)
   ```bash
   npm publish
   ```

### Post-Publication Updates

After publishing a new version, the following repositories should be updated to use the latest version:

1. **node-api**: Update the `@simuwatt/calculations-hub` dependency
2. **buildee-modeling**: Update the `@simuwatt/calculations-hub` dependency

### Version Management Best Practices

- **Patch** (1.0.1): Bug fixes and minor improvements
- **Minor** (1.1.0): New features that don't break existing functionality
- **Major** (2.0.0): Breaking changes that require user code updates

## Contributing

1. Create a feature branch from `main`
2. Make your changes with appropriate tests
3. Ensure all tests pass and code is properly formatted
4. Submit a pull request with a clear description of changes
5. Ensure CI/CD pipeline passes before merging

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.