Analysis: one selected period, one set of numbers, on every page
ci / build-test (push) Successful in 2m31s
ci / build-test (push) Successful in 2m31s
The dashboards told several stories at once. Overview asked for full calendar years, meter detail for a fixed 12-month window that was really 13, Trends for 24 months with an Apply button, and the energy pages for 60. Each page derived "today" from UTC, so the first hours of a local day belonged to yesterday. A missing tariff, a month nobody measured and a genuine zero all rendered as 0. And a virtual meter -- the one thing the spreadsheet leans on hardest -- was excluded from analysis outright: MeterPeriodService returned null for it and the page offered a flow diagram instead. docs/DASHBOARD_ANALYSIS_CHANGE_BRIEF.md is the work order. Every choice it left open is settled in docs/ANALYSIS_IMPLEMENTATION_NOTE.md as D-01..D-58 plus amendments A-01..A-30; code, tests and release notes cite those ids. The analysis layer Core/Analysis holds the pure rules: period presets resolved once in the instance zone into a local date range and a half-open UTC range, bucket plans, calendar-unit comparisons, coverage runs with a resolution class, normalized quantities and units, the totals policy, the virtual formula parser/validator/evaluator, and the cost calculator. "Now" comes from TimeProvider; services never read the clock. Normalization now writes, in the same transaction as consumption and by diff, per-meter rollups by local day and month plus coverage runs and a rollup state (AnalysisDataWriter). AnalysisReader answers a request from those tables -- month rollups for month and year buckets, day rollups otherwise, at most two partial edge days from consumption -- and CostReader prices the result month by month. Pages, /api/v1 and the CSV export read nothing else. The unused continuous aggregates are dropped. The reader's statement count per request is constant whether it covers one meter or a thousand. On a synthetic 1,000-meter, ten-year instance the brief's target request (100 meters, ten years, monthly) takes 374 ms against a two-second target, and the Overview went from 48,244 SQL statements per load to 205. Missing is not zero Every bucket carries a status -- available, partial, missing, unresolved, invalid, pending -- derived from coverage, never from the amount, with provenance and a reason code beside it. A true zero is a number and a bar on the baseline; an unknown bucket is a gap that says why; a month whose data only exists monthly says so instead of inventing daily detail; a scope with no tariff says "not priced" instead of 0. Rows whose interval closes after now are reported separately rather than counted. Virtual meters are analysis subjects A virtual meter stores a canonical definition -- expression over m<id> references, result kind, unit and cost rule -- validated on save and on read for syntax, unknown or self references, loops and unit/kind rules. It is evaluated on read from its sources' rollups over their joint coverage: a missing source makes the bucket missing, an observed zero is a valid input, a non-finite result is invalid with its dependency path, and the page lists each source's contribution. Topology links are topology only and never rewrite a saved calculation; expression-less meters from older installs are converted once at startup. The editor has Sum, Difference and Advanced modes with a live preview. Totals and the bill Per energy type the totals policy separates use, grid import, export, generation and runtime, marks breakdown meters as breakdowns and virtual meters as views, and never adds across units. The bill follows it: grid import where there is one, separately priced subsections at their own price, feed-in only on export meters, standing charges once per scope per local day, manual costs once on their start day, categories as non-overlapping covers whose composition reconciles to the bill. The seeded demo's yearly totals now match the spreadsheet. Pages and navigation The period lives in the URL and every page reads the same contract, so a link, a reload and the browser's Back button keep it. Shared components carry it: page header with breadcrumbs, period toolbar, theme-aware chart with an accessible table beside it, metric cards, comparison and availability states, attention items that each link to the one action that fixes them. Meter detail leads with an Analysis tab and resolves its tabs by key; the energy page has Overview, History, Flow and Meters; the old cost-only Trends page is a general Analysis page over portfolio, type, category, meter or a meter comparison. Records tabs are paged server-side instead of showing the latest 200. Everything is English and German, light and dark, down to 360px. Some figures change on purpose; docs/RELEASE_NOTES.md lists each one and what the first start after the update does (it rebuilds all analysis data before the web server listens). docs/SDD.md and CLAUDE.md describe the system as it now is. Tests: 1,733 Core and 746 integration, all green, plus an opt-in performance suite with a synthetic 1,000-meter generator.
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
using MeterVault.Core.Analysis.Virtual;
|
||||
|
||||
namespace MeterVault.Core.Tests.Analysis;
|
||||
|
||||
/// <summary>
|
||||
/// A parsed formula knows its own shape: which meters it reads, whether it is linear (additive, so buckets sum to
|
||||
/// the total and the quantity can be priced) or a pure sum (so costs can be the sources' own), and a canonical text
|
||||
/// that parses back to the same formula.
|
||||
/// </summary>
|
||||
public sealed class FormulaTests
|
||||
{
|
||||
[Fact]
|
||||
public void Meter_ids_are_distinct_and_ascending_and_references_keep_their_positions()
|
||||
{
|
||||
var formula = Formula.Parse("m12 + m3 - m12 * 2");
|
||||
|
||||
Assert.Equal([3, 12], formula.MeterIds);
|
||||
Assert.Equal(
|
||||
[new FormulaReference(12, 0, 3), new FormulaReference(3, 6, 2), new FormulaReference(12, 11, 3)],
|
||||
formula.References);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("m1 + m2", true, true)]
|
||||
[InlineData("(m1 + m2) * 1", true, true)]
|
||||
[InlineData("m1 - m2", true, false)]
|
||||
[InlineData("m1 + m1", true, false)]
|
||||
[InlineData("2 * (m1 + m2)", true, false)]
|
||||
[InlineData("0.5 * m1 + m2 / 4", true, false)]
|
||||
[InlineData("-(m1 - m2)", true, false)]
|
||||
[InlineData("m1 + 5 - 5", true, true)] // the constants cancel
|
||||
[InlineData("m1 + 5", false, false)] // a constant term: not additive across buckets
|
||||
[InlineData("m1 * m2", false, false)]
|
||||
[InlineData("m1 / m2", false, false)]
|
||||
[InlineData("1 / m1", false, false)]
|
||||
[InlineData("m1 / 0", false, false)]
|
||||
[InlineData("m1 * (1 / 0)", false, false)]
|
||||
[InlineData("(m1 - m1) * m2", false, false)] // decided by structure, not by the value that cancels
|
||||
public void Linearity_and_pure_sums_are_recognised(string text, bool linear, bool pureSum)
|
||||
{
|
||||
var formula = Formula.Parse(text);
|
||||
|
||||
Assert.Equal(linear, formula.IsLinear);
|
||||
Assert.Equal(pureSum, formula.IsPureSum);
|
||||
Assert.Equal(linear, formula.Coefficients is not null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Coefficients_are_each_meters_weight_in_a_linear_formula()
|
||||
{
|
||||
Assert.Equal(new Dictionary<int, double> { [1] = 1, [2] = -1 }, Formula.Parse("m1 - m2").Coefficients);
|
||||
Assert.Equal(new Dictionary<int, double> { [1] = 0.5, [2] = 0.25 }, Formula.Parse("0.5 * m1 + m2 / 4").Coefficients);
|
||||
Assert.Equal(new Dictionary<int, double> { [1] = -1, [2] = 1 }, Formula.Parse("-(m1 - m2)").Coefficients);
|
||||
Assert.Equal(new Dictionary<int, double> { [1] = 0, [2] = 1 }, Formula.Parse("m1 - m1 + m2").Coefficients);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("m1+m2", "m1 + m2")]
|
||||
[InlineData("((((m1))))", "m1")]
|
||||
[InlineData("(m1 + m2) * 2", "(m1 + m2) * 2")]
|
||||
[InlineData("(m1 - m2) - m3", "m1 - m2 - m3")]
|
||||
[InlineData("m1 - (m2 - m3)", "m1 - (m2 - m3)")]
|
||||
[InlineData("m1 - (m2 + m3)", "m1 - (m2 + m3)")]
|
||||
[InlineData("m1 + (m2 + m3)", "m1 + (m2 + m3)")]
|
||||
[InlineData("m1 / (m2 * m3)", "m1 / (m2 * m3)")]
|
||||
[InlineData("m1 * m2 + m3", "m1 * m2 + m3")]
|
||||
[InlineData("-(m1 + m2)", "-(m1 + m2)")]
|
||||
[InlineData("-m1 * m2", "-m1 * m2")]
|
||||
[InlineData("--m1", "--m1")]
|
||||
[InlineData("+m1", "m1")]
|
||||
[InlineData("m1 * -m2", "m1 * -m2")]
|
||||
[InlineData("m1 - -5", "m1 - -5")]
|
||||
[InlineData("0.50 * m1", "0.50 * m1")]
|
||||
public void The_canonical_text_has_minimal_parentheses_and_parses_back_to_an_equal_formula(string text, string canonical)
|
||||
{
|
||||
var formula = Formula.Parse(text);
|
||||
|
||||
Assert.Equal(canonical, formula.ToString());
|
||||
Assert.Equal(text, formula.Text);
|
||||
Assert.Equal(formula, Formula.Parse(formula.ToString()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equality_is_structural()
|
||||
{
|
||||
Assert.Equal(Formula.Parse("m1+m2"), Formula.Parse("(m1) + m2"));
|
||||
Assert.Equal(Formula.Parse("m1+m2").GetHashCode(), Formula.Parse("(m1) + m2").GetHashCode());
|
||||
Assert.Equal(Formula.Parse("1.0 * m1"), Formula.Parse("1 * m1"));
|
||||
Assert.NotEqual(Formula.Parse("m1 + m2"), Formula.Parse("m2 + m1"));
|
||||
Assert.NotEqual(Formula.Parse("m1 - m2 - m3"), Formula.Parse("m1 - (m2 - m3)"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_tree_mirrors_precedence()
|
||||
{
|
||||
var root = Assert.IsType<BinaryNode>(Formula.Parse("m1 - 2 * m2").Root);
|
||||
|
||||
Assert.Equal(FormulaOperator.Subtract, root.Operator);
|
||||
Assert.Equal(1, Assert.IsType<MeterReferenceNode>(root.Left).MeterId);
|
||||
var product = Assert.IsType<BinaryNode>(root.Right);
|
||||
Assert.Equal(FormulaOperator.Multiply, product.Operator);
|
||||
Assert.Equal(2, Assert.IsType<NumberNode>(product.Left).Value);
|
||||
Assert.Equal(2, Assert.IsType<MeterReferenceNode>(product.Right).MeterId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Division_by_zero_evaluates_to_a_non_finite_number_for_the_caller_to_judge()
|
||||
{
|
||||
var ratio = Formula.Parse("m1 / m2");
|
||||
|
||||
Assert.True(double.IsPositiveInfinity(ratio.Evaluate(id => id == 1 ? 80 : 0)));
|
||||
Assert.True(double.IsNaN(ratio.Evaluate(_ => 0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rewriting_ids_follows_meters_to_new_ids_and_keeps_the_users_text()
|
||||
{
|
||||
var map = new Dictionary<int, int> { [1] = 41, [2] = 42 };
|
||||
var formula = Formula.Parse("m1 + (m2*m1)");
|
||||
|
||||
var rewritten = formula.RewriteIds(id => map[id]);
|
||||
|
||||
Assert.Equal("m41 + (m42*m41)", rewritten.Text);
|
||||
Assert.Equal([41, 42], rewritten.MeterIds);
|
||||
Assert.Equal(Formula.Parse("m41 + m42 * m41"), rewritten);
|
||||
Assert.Equal(
|
||||
[new FormulaReference(41, 0, 3), new FormulaReference(42, 8, 3), new FormulaReference(41, 12, 3)],
|
||||
rewritten.References);
|
||||
Assert.Equal(Formula.Parse(rewritten.Text), rewritten);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rewriting_to_a_negative_id_is_refused()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => Formula.Parse("m1").RewriteIds(_ => -1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sum_and_difference_build_the_editors_simple_modes()
|
||||
{
|
||||
var sum = Formula.Sum([4, 5, 4]);
|
||||
Assert.Equal("m4 + m5", sum.ToString());
|
||||
Assert.True(sum.IsPureSum);
|
||||
|
||||
var difference = Formula.Difference(1, [2, 3]);
|
||||
Assert.Equal("m1 - m2 - m3", difference.ToString());
|
||||
Assert.Equal(new Dictionary<int, double> { [1] = 1, [2] = -1, [3] = -1 }, difference.Coefficients);
|
||||
|
||||
Assert.Throws<ArgumentException>(() => Formula.Sum([]));
|
||||
Assert.Throws<ArgumentException>(() => Formula.Difference(1, []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_throws_only_for_trusted_text_that_turns_out_invalid()
|
||||
{
|
||||
Assert.Throws<FormatException>(() => Formula.Parse("m1 +"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user