npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@simuwatt/calculations-hub

v1.0.36

Published

Centralized hub for all mathematical calculations needed across the organization's repositories.

Readme

@simuwatt/calculations-hub

npm version License: 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

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

npm install @simuwatt/calculations-hub

or with yarn:

yarn add @simuwatt/calculations-hub

Usage

Basic Import

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

Calculate Energy Baseline

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

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

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

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

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

Supported Units

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:
    yarn install
  3. Ensure you're using the correct Node.js version:
    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:

# 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
    yarn build
  3. Test: Run the full test suite
    yarn test
  4. Publish: Publish to npm (requires appropriate permissions)
    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 file for details.