NemReader 0.1.1
dotnet add package NemReader --version 0.1.1
NuGet\Install-Package NemReader -Version 0.1.1
<PackageReference Include="NemReader" Version="0.1.1" />
<PackageVersion Include="NemReader" Version="0.1.1" />
<PackageReference Include="NemReader" />
paket add NemReader --version 0.1.1
#r "nuget: NemReader, 0.1.1"
#:package NemReader@0.1.1
#addin nuget:?package=NemReader&version=0.1.1
#tool nuget:?package=NemReader&version=0.1.1
nemreader-dotnet
An F# library for reading the Australian Energy Market Operator (AEMO) meter data file formats:
- NEM12 for interval data, such as smart meters
- NEM13 for accumulated data, such as older manually read meters
This is a port of the Python nem-reader library. The parsing rules and the example test files come from that project. The F# version keeps the same behaviour, and adds a functional API with immutable data and results instead of exceptions.
The library has no dependencies beyond FSharp.Core.
Supported frameworks
The library targets netstandard2.0, so it works on .NET Framework 4.6.1 and
later, and on .NET 6, 8, 10 and newer. The command line project and the tests
target .NET 8 (LTS).
Install
dotnet add package NemReader
Reading a file
NemFile.read accepts a path to a CSV file or a single entry zip archive. Zip
archives are detected from their contents, so file names do not matter.
open System
open NemReader
// Plain CSV files and single entry zip archives both work.
let path = "NEM12.zip"
match NemFile.read path with
| Ok data ->
printfn $"{data.Header.VersionHeader} file created {data.Header.CreationDate}"
for nmi in NemData.nmis data do
let channels = String.concat ", " (NemData.channels nmi data)
printfn $"{nmi} has channels {channels}"
for reading in data.Readings["VABD000163"]["E1"] |> List.truncate 3 do
printfn $"{reading.TStart} to {reading.TEnd}: {reading.ReadValue} {reading.Uom}"
| Error error ->
printfn $"Could not read {path}: {NemError.describe error}"
NemData holds the header, the readings (nested by NMI and channel) and the
B2B transactions. Anything the parser could not use, such as a skipped record
or a missing end of data row, is collected in Warnings rather than logged.
Missing header rows and other quirks of real world files are tolerated by
default. Use NemFile.readWith { Strict = true } to require a header row, and
NemFile.readStream to read from an open stream.
Using NemReader from C#
Most .NET code is written in C#, and the library is just an assembly, so you can call it from a C# project without any wrappers. The package works the same way from either language:
dotnet add package NemReader
F# modules become static classes, so NemFile.read is called as written, while
the companion modules come through with a Module suffix: NemData.nmis is
NemDataModule.nmis and NemError.describe is NemErrorModule.describe.
using System;
using System.Linq;
using Microsoft.FSharp.Core;
using NemReader;
var path = "Example_NEM12_actual_interval.csv";
var result = NemFile.read(path);
if (result.IsOk)
{
var data = result.ResultValue;
Console.WriteLine($"{data.Header.VersionHeader}, created {OptionModule.ToNullable(data.Header.CreationDate):yyyy-MM-dd HH:mm}");
foreach (var nmi in NemDataModule.nmis(data))
{
var channels = NemDataModule.channels(nmi, data);
Console.WriteLine($"{nmi} has channels {string.Join(", ", channels)}");
foreach (var channel in channels)
{
if (!data.Readings.TryGetValue(nmi, out var byChannel)) continue;
if (!byChannel.TryGetValue(channel, out var readings)) continue;
foreach (var reading in readings.Take(3))
{
double? value = OptionModule.ToNullable(reading.ReadValue);
Console.WriteLine($" {channel} {reading.TStart:yyyy-MM-dd HH:mm} {value:F3} {reading.Uom}");
}
}
}
}
else
{
Console.WriteLine($"Could not read {path}: {NemErrorModule.describe(result.ErrorValue)}");
}
Against tests/NemReader.Tests/examples/unzipped/Example_NEM12_actual_interval.csv
this prints:
NEM12, created 2004-05-01 11:35
VABD000163 has channels E1, Q1
E1 2004-02-01 00:00 1.111 kWh
E1 2004-02-01 00:30 1.111 kWh
E1 2004-02-01 01:00 1.111 kWh
Q1 2004-02-01 00:00 2.222 kVArh
Q1 2004-02-01 00:30 2.222 kVArh
Q1 2004-02-01 01:00 2.222 kVArh
A few notes on the types you will meet:
NemFile.readreturnsFSharpResult<NemData, NemError>. CheckIsOkorIsError, then readResultValueorErrorValue. A bad file is a value, not an exception, so there is nothing to catch.Readingsis an F# map from NMI to a map of channel to readings. It implementsIReadOnlyDictionary, soTryGetValue,Keys,Valuesand the indexer all work;data.Readings["VABD000163"]["E1"]is fine as well.- F# lists are
IEnumerable<T>, so the readings for a channel,Warningsand the results ofNemDataModule.nmisandNemDataModule.channelsall work with LINQ. - Optional values are
FSharpOption<T>.OptionModule.ToNullableturnsReading.ReadValueinto adouble?and dates such asHeader.CreationDateinto aDateTime?; when you want the value itself,OptionModule.IsSomeandFSharpOption<T>.Valueare the pair to use. - The package brings
FSharp.Corewith it, soMicrosoft.FSharp.CoreandMicrosoft.FSharp.Collectionsare available without adding anything else.
Tables
Outputs.longFrame returns one row per reading with nmi, suffix, serno,
t_start, t_end, value, quality, evt_code and evt_desc columns.
Outputs.wideFrame returns one row per interval with one column per channel,
which is the shape you want for charting.
let options = { DataOptions.defaults with SetInterval = Some 30 }
match Outputs.wideFrame options data with
| Some frame ->
let columns = String.concat ", " frame.Columns
printfn $"Columns: {columns}"
printfn $"Rows: {Frame.count frame}"
let total =
frame
|> Frame.filter (fun row -> Frame.cellText "nmi" row = Some "VABD000163")
|> Frame.sumColumn "E1"
printfn $"Total E1: {total}"
| None ->
printfn "No readings in this file"
SplitDays splits readings that cover more than one day, and SetInterval
resamples to a fixed number of minutes. Longer intervals are split evenly and
shorter intervals are aggregated, with kWh values summed and everything else
averaged.
Frame is a small immutable table of named columns and rows of Cell values,
with helpers to read columns, filter rows, rename or drop columns, and write
CSV.
CSV output
Outputs.outputAsCsv "input.zip" "out" None
|> Result.iter (List.iter (fun path -> printfn $"Created {path}"))
Outputs.outputAsDailyCsv "input.zip" "out"
|> Result.iter (fun path -> printfn $"Created {path}")
outputAsCsv writes one transposed CSV per NMI, and outputAsDailyCsv writes
a daily totals file. Both take the input file and an output directory.
Command line
The src/NemReader.Cli project is a small console front end.
nemreader list-nmis <file>
nemreader output-csv <file> [--set-interval <minutes>] [--outdir <directory>]
nemreader output-csv-daily <file> [--outdir <directory>]
nemreader --version
Add --verbose to print parser warnings. From a clone:
dotnet run --project src/NemReader.Cli -- list-nmis "tests/NemReader.Tests/examples/unzipped/Example_NEM12_actual_interval.csv"
The following NMI[suffix] exist in this file:
VABD000163[E1,Q1]
Differences from the Python original
The file format handling and the test expectations are the same. The API is not, because F# leans on immutable records and results.
- The
NEMFileobject is replaced by functions that returnNemData. - Errors are returned as
Result<NemData, NemError>instead of raised. - Parser messages are returned in
NemData.Warningsinstead of being logged;--verboseprints them. - The polars data frames are replaced by the built in
Frametype, so there is no DataFrame dependency. The CSV outputs are written with a small built in writer. Reading.ReadValueis afloat option, since a missing value is not the same as zero. Quality methods are strings, empty when the file has none.read_nem_file(path, ignore_missing_header)in the original passes its flag into the parser'sstrictoption, which does the opposite of its name. Here the option is calledReadOptions.Strictand means what it says.- The original's daily CSV path for NEM13 channels passes the whole readings
map to the multi day splitter, which raises a
TypeError. This version splits each NEM13 channel's readings, and always flattens NEM13 readings even when the end of data row is missing. - Aggregated readings take their unit from the group being averaged rather than from the last reading in the file.
- The
include_sernooption of the wide data frame is gone. The original dropped the column during the pivot anyway, so it had no effect.
Development
dotnet build
dotnet test
The repository includes a global.json that selects the .NET 8 SDK, so the
build matches CI. The test project uses xunit and the example files from the
original repository, under tests/NemReader.Tests/examples.
Credits
This library is a port of nem-reader
by Alex Guinman. The example files in tests/NemReader.Tests/examples come
from that project.
License
MIT. See LICENSE. The original copyright notice is kept in full.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- FSharp.Core (>= 6.0.7)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.