diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..73c4f64 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,39 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.14"] + + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # full history, so setuptools-scm can work out the version + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install csv2sef + run: pip install -e . + + - name: Run the tests + run: python -m unittest discover -s tests -v + + - name: Convert the examples + run: | + cd examples/YorkFactoryHBC + csv2sef convert YorkFactory-HBC_1773_wide.csv YorkFactoryHBC_metadata.csv -o /tmp/out1 + csv2sef convert YorkFactory-HBC_1773_long.csv YorkFactoryHBC_metadata.csv -o /tmp/out2 + cd ../Hebron + csv2sef convert Hebron_Pressure_1883-09_1883-12.csv Hebron_metadata.csv -o /tmp/out3 + cd ../HalifaxCitadel + csv2sef convert HalifaxCitadel_1863-1865.csv HalifaxCitadel_metadata.csv -o /tmp/out4 diff --git a/pyproject.toml b/pyproject.toml index ed82ed2..2b20fcf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,7 +13,7 @@ classifiers = [ "Operating System :: OS Independent", ] dependencies = [ - "cdrutilities>=1.0.1", + "cdrutilities>=1.0.2", ] license = "MIT" license-files = ["LICEN[CS]E*"] diff --git a/tests/known_values.csv b/tests/known_values.csv new file mode 100644 index 0000000..46724d6 --- /dev/null +++ b/tests/known_values.csv @@ -0,0 +1,135 @@ +id,category,var,unit,input,expected,expected_flag,tolerance,opts,source,note,status +001,temperature,ta,F,32,0.0,,0.01,,C = (F - 32) x 5/9,,formula +002,temperature,ta,F,212,100.0,,0.01,,C = (F - 32) x 5/9,,formula +003,temperature,ta,F,-40,-40.0,,0.01,,C = (F - 32) x 5/9,,formula +004,temperature,ta,F,58.2,14.56,,0.01,,C = (F - 32) x 5/9,,formula +005,temperature,ta,F,0,-17.78,,0.01,,C = (F - 32) x 5/9,,formula +006,temperature,ta,C,10,10.0,,0.01,,identity,,formula +007,temperature,ta,R,80,100.0,,0.01,,C = R x 5/4 (Reaumur: 80 = boiling),,formula +008,temperature,ta,R,10,12.5,,0.01,,C = R x 5/4 (Reaumur: 80 = boiling),,formula +009,temperature,ta,R,-10,-12.5,,0.01,,C = R x 5/4 (Reaumur: 80 = boiling),,formula +010,temperature,ta,De,150,0.0,,0.01,,"Delisle: 0 = boiling, 150 = freezing; C = 100 - De x 2/3",,formula +011,temperature,ta,De,0,100.0,,0.01,,"Delisle: 0 = boiling, 150 = freezing; C = 100 - De x 2/3",,formula +012,temperature,ta,De,165,-10.0,,0.01,,"Delisle: 0 = boiling, 150 = freezing; C = 100 - De x 2/3",,formula +013,temperature,ta,De_frz,15,10.0,,0.01,,Delisle degrees from freezing; C = x x 2/3 (Victoria 2026-10-16),,formula +014,temperature,ta,F,37 1/2,3.06,,0.01,,fraction 37 1/2 F,,formula +015,temperature,ta,F,37.?,2.78,uncertain,0.01,,"'?' removed, flagged (Table 8)",,formula +016,temperature,ta,F,-,NA,missing,0.01,,missing marker,,formula +017,temperature,ta,F,"""",NA,ditto,0.01,,ditto mark: not reconstructed,,formula +018,temperature,ta,F,16R,20.0,unit R,0.01,,unit letter overrides column unit (Victoria 2026-10-16),,formula +019,temperature_diff,ta_range,Fdiff,9,5.0,,0.01,,difference: x 5/9,,formula +020,temperature_diff,ta_range,Cdiff,5,5.0,,0.01,,identity,,formula +021,caves,ta,De_frz,9-0,6.8,caves notation,0.01,caves_temperature_c=12.8,12.8 - 9 x 2/3 (Gaultier lines 330/335),,formula +022,caves,ta,De_frz,15+c,22.8,caves notation,0.01,caves_temperature_c=12.8,12.8 + 15 x 2/3 (Gaultier line 2433),,formula +023,caves,ta,De_frz,24+c,28.8,caves notation,0.01,caves_temperature_c=12.8,12.8 + 24 x 2/3 (Gaultier line 2716),,formula +024,caves,ta,De_frz,16+0 R,32.8,caves notation,0.01,caves_temperature_c=12.8,12.8 + 16 x 5/4 (R letter),,formula +025,caves,ta,De_frz,14+,22.13,caves notation (assumed),0.01,caves_temperature_c=12.8,"no token: caves assumed, flagged",,formula +026,caves,ta,De_frz,co,12.8,caves notation,0.01,caves_temperature_c=12.8,caves = 12.8 C,,formula +027,caves,ta,De_frz,5=c,NA,"caves notation, sign unclear",0.01,caves_temperature_c=12.8,"x=c, x != 0: not converted",,formula +028,caves,ta,De_frz,-1R,-1.25,unit R,0.01,caves_temperature_c=12.8,Gaultier line 2596,,formula +029,below_scale,ta,F,<=-34,-34.0,at or below,0.01,below_scale_c=-34,mercury in bulb rule (Victoria 2026-10-16),,formula +030,below_scale,ta,F,mercury in bulb,-34.0,at or below; below scale,0.01,below_scale_c=-34,mercury in bulb = -34 C,,formula +031,below_scale,ta,F,<=-30,-34.44,at or below,0.01,,no below_scale_c: column unit used,,formula +032,pressure,p,inHg,29.9213,1013.25,,0.01,,1 inHg = 33.8639 hPa (List 1966; WMO 1966),,formula +033,pressure,p,inHg,30.00,1015.92,,0.01,,1 inHg = 33.8639 hPa (List 1966; WMO 1966),,formula +034,pressure,p,inHg,29.71,1006.1,,0.01,,1 inHg = 33.8639 hPa (List 1966; WMO 1966),,formula +035,pressure,p,mmHg,760,1013.25,,0.01,,1 mmHg = 1.333224 hPa (List 1966),,formula +036,pressure,p,mmHg,750,999.92,,0.01,,1 mmHg = 1.333224 hPa (List 1966),,formula +037,pressure,p,hPa,1013.2,1013.2,,0.01,,identity,,formula +038,pressure,p,ParisIn,28,1010.53,,0.01,,1 Paris inch = 12 lines = 27.07 mm (IMC 1890); then mm -> hPa,Not covered by any worked example; breaks in GitHub cdr-utilities,formula +039,pressure,p,ParisIn,27 11,1007.52,,0.01,,1 Paris inch = 12 lines = 27.07 mm (IMC 1890); then mm -> hPa,Not covered by any worked example; breaks in GitHub cdr-utilities,formula +040,pressure,p,ParisIn,27 11.5,1009.02,,0.01,,1 Paris inch = 12 lines = 27.07 mm (IMC 1890); then mm -> hPa,Not covered by any worked example; breaks in GitHub cdr-utilities,formula +041,pressure,p,ParisIn,27p 10l,1004.51,,0.01,,1 Paris inch = 12 lines = 27.07 mm (IMC 1890); then mm -> hPa,Not covered by any worked example; breaks in GitHub cdr-utilities,formula +042,pressure,p,ParisLine,336,1010.53,,0.01,,12 Paris lines = 1 Paris inch,,formula +043,pressure,p,ParisLine,330,992.48,,0.01,,12 Paris lines = 1 Paris inch,,formula +044,vapour_pressure,e,inHg,0.245,8.3,,0.01,,1 inHg = 33.8639 hPa,,formula +045,vapour_pressure,e,inHg,245,8.3,missing decimal,0.01,,vapour pressure written without decimal,,formula +046,precipitation,rr,in,1,25.4,,0.01,,1 in = 25.4 mm,,formula +047,precipitation,rr,in,0.5,12.7,,0.01,,1 in = 25.4 mm,,formula +048,precipitation,rr,mm,10,10.0,,0.01,,identity,,formula +049,precipitation,rr,cm,1,10.0,,0.01,,1 cm = 10 mm,,formula +050,precipitation,rr,in,inapp,0.2,trace,0.01,trace_mm=0.2,trace default 0.2 mm,,formula +051,precipitation,rr,in,a little,0.2,trace; qualitative,0.01,trace_mm=0.2,'a little' = trace (Victoria 2026-10-16),,formula +052,precipitation,rr,in,nil,0.0,no entry,0.01,,nil = 0,,formula +053,precipitation,rr,in,Rain,NA,qualitative,0.01,,"occurrence only, amount unknown",,formula +054,precipitation,rr,in,0.25 | 0.10,8.89,two values added,0.01,,two amounts in one cell are added,,formula +055,snow,sd,in,2,5.08,,0.01,,2 in = 5.08 cm (snow written in cm),,formula +056,snow,fs,in,4,10.16,,0.01,,snowfall in cm (Montreal Barr),,formula +057,snow,fs,cm,1,1.0,,0.01,,"identity, cm",,formula +058,distance,wr,mi,10,16093,,1,,1 mile = 1609.344 m,,formula +059,humidity,rh,%,85,85.0,,0.01,,identity,,formula +060,humidity,rh,%,0.85,85.0,multiply by 100,0.01,,fraction -> percent,,formula +061,wind,w,mph,10,4.47,,0.01,,1 mph = 0.44704 m/s,,formula +062,wind,w,kt,10,5.14,,0.01,,1 kt = 0.514444 m/s,,formula +063,wind,w,km/h,36,10.0,,0.01,,1 km/h = 1/3.6 m/s,,formula +064,wind,w,m/s,5,5.0,,0.01,,identity,,formula +065,wind,w,lbsft,1,8.84,,0.01,,"P = 0.00256 V^2 (lb/ft2, mph); '3 15' = 3 lb 15 oz",,formula +066,wind,w,lbsft,3 15,17.53,,0.01,,"P = 0.00256 V^2 (lb/ft2, mph); '3 15' = 3 lb 15 oz",,formula +067,wind_beaufort,w,Bf,0,0.0,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +068,wind_beaufort,w,Bf,1,0.9,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +069,wind_beaufort,w,Bf,2,2.4,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +070,wind_beaufort,w,Bf,3,4.4,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +071,wind_beaufort,w,Bf,4,6.7,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +072,wind_beaufort,w,Bf,5,9.3,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +073,wind_beaufort,w,Bf,6,12.3,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +074,wind_beaufort,w,Bf,7,15.5,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +075,wind_beaufort,w,Bf,8,18.9,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +076,wind_beaufort,w,Bf,9,22.6,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +077,wind_beaufort,w,Bf,10,26.4,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +078,wind_beaufort,w,Bf,11,30.5,,0.15,,"WMO code 1100, mid-point of m/s range",rounding of mid-points to check,to_check +079,wind_beaufort,w,Bf,12,,,0.15,,"WMO code 1100, mid-point of m/s range",Force 12 has no upper bound: fill in the value the paper uses,to_fill +080,wind_smithsonian,w,Sm,0,0.0,,0.05,,"Smithsonian scale 0 = 0 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +081,wind_smithsonian,w,Sm,1,0.9,,0.05,,"Smithsonian scale 1 = 2 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +082,wind_smithsonian,w,Sm,2,1.8,,0.05,,"Smithsonian scale 2 = 4 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +083,wind_smithsonian,w,Sm,3,5.4,,0.05,,"Smithsonian scale 3 = 12 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +084,wind_smithsonian,w,Sm,4,11.2,,0.05,,"Smithsonian scale 4 = 25 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +085,wind_smithsonian,w,Sm,5,15.6,,0.05,,"Smithsonian scale 5 = 35 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +086,wind_smithsonian,w,Sm,6,20.1,,0.05,,"Smithsonian scale 6 = 45 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +087,wind_smithsonian,w,Sm,7,26.8,,0.05,,"Smithsonian scale 7 = 60 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +088,wind_smithsonian,w,Sm,8,33.5,,0.05,,"Smithsonian scale 8 = 75 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +089,wind_smithsonian,w,Sm,9,40.2,,0.05,,"Smithsonian scale 9 = 90 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +090,wind_smithsonian,w,Sm,10,44.7,,0.05,,"Smithsonian scale 10 = 100 mph nominal (Table 4, Slonosky et al. 2026)",mph values written from memory of the Smithsonian instructions: check against Table 4,to_check +091,wind_words,w,words,calm,0.0,,0.01,,calm = 0,,formula +092,wind_words,w,words,fresh breeze,9.3,,0.15,,Beaufort 5,,formula +093,wind_words,w,words,bonne brise,9.3,,0.15,,French Beaufort 5,,formula +094,wind_words,w,words,word not in table,NA,unmapped,0.01,,"unknown term kept, NA",,formula +095,direction,dd,dir,N,0,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +096,direction,dd,dir,NNE,22.5,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +097,direction,dd,dir,E,90,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +098,direction,dd,dir,SW,225,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +099,direction,dd,dir,NW,315,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +100,direction,dd,dir,N by E,11.25,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +101,direction,dd,dir,200,200,,0.01,,"16/32-point compass, 11.25 degrees per point",,formula +102,direction,dd,dir,calm,Calm,,,,calm,,formula +103,direction,dd,dir,variable,Variable,,,,variable,,formula +104,cloud,n,tenths,5,4.0,,0.01,,oktas = tenths x 0.8,,formula +105,cloud,n,tenths,7,5.6,,0.01,,oktas = tenths x 0.8,"Inconsistent with tenths_clear, which uses the WMO integer table (7 tenths covered -> 6 oktas). Decide which to use.",to_check +106,cloud,n,tenths,10,8.0,,0.01,,oktas = tenths x 0.8,,formula +107,cloud,n,tenths,fog,9,,0.01,,obscured sky = 9,,formula +108,cloud,n,tenths,clear,0,,0.01,,clear = 0,,formula +109,cloud,n,okta,4,4.0,,0.01,,identity,,formula +110,cloud,n,tenths_clear,10,0,,0.01,,"tenths CLEAR -> tenths covered (10 - x) -> oktas, WMO code 2700 table (0,1,2,2,3,4,5,6,6,7,8)",Not covered by any worked example; breaks in GitHub cdr-utilities,formula +111,cloud,n,tenths_clear,0,8,,0.01,,"tenths CLEAR -> tenths covered (10 - x) -> oktas, WMO code 2700 table (0,1,2,2,3,4,5,6,6,7,8)",Not covered by any worked example; breaks in GitHub cdr-utilities,formula +112,cloud,n,tenths_clear,5,4,,0.01,,"tenths CLEAR -> tenths covered (10 - x) -> oktas, WMO code 2700 table (0,1,2,2,3,4,5,6,6,7,8)",Not covered by any worked example; breaks in GitHub cdr-utilities,formula +113,cloud,n,tenths_clear,3,6,,0.01,,"tenths CLEAR -> tenths covered (10 - x) -> oktas, WMO code 2700 table (0,1,2,2,3,4,5,6,6,7,8)",Not covered by any worked example; breaks in GitHub cdr-utilities,formula +114,cloud,cv,cloudvel,3,3,,0.01,,scale 0-10,,formula +115,cloud,cv,cloudvel,p,1,,0.01,,perceptible = 1,,formula +116,cloud_type,cl,lct,cumulus,,,,,WMO cloud atlas code,fill in the code you expect; the test run prints the current one,to_fill +117,cloud_type,cl,lct,stratus,,,,,WMO cloud atlas code,fill in the code you expect; the test run prints the current one,to_fill +118,cloud_type,cl,lct,cirrus,,,,,WMO cloud atlas code,fill in the code you expect; the test run prints the current one,to_fill +119,cloud_type,cl,lct,nimbus,,,,,WMO cloud atlas code,fill in the code you expect; the test run prints the current one,to_fill +120,cloud_type,cl,lct,cirro-stratus,,,,,WMO cloud atlas code,fill in the code you expect; the test run prints the current one,to_fill +121,cloud_type,cl,lct,cumulo-nimbus,,,,,WMO cloud atlas code,fill in the code you expect; the test run prints the current one,to_fill +122,cloud_type,ch,uct,cirrus,,,,,WMO cloud atlas code,fill in the code you expect,to_fill +123,cloud_type,ch,uct,cirro-cumulus,,,,,WMO cloud atlas code,fill in the code you expect,to_fill +124,weather,ww,mno,rain & fog all day,RA FG,,,,weather_terms.csv / Victoria 2026-10-16,,formula +125,weather,ww,mno,neige et poudrerie,BLSN SN,,,,weather_terms.csv / Victoria 2026-10-16,,formula +126,weather,ww,mno,beautiful,SKC,,,,weather_terms.csv / Victoria 2026-10-16,,formula +127,weather,ww,mno,sombre,OVC,,,,weather_terms.csv / Victoria 2026-10-16,,formula +128,weather,ww,mno,snow,SN,,,,weather_terms.csv / Victoria 2026-10-16,,formula +129,weather,ww,mno,thunder and lightning,,,,,synoptic code,fill in the code you expect,to_fill +130,weather,ww,mno,hazy,,,,,synoptic code,fill in the code you expect,to_fill +131,weather,ww,mno,overcast with drizzle,,,,,synoptic code,fill in the code you expect,to_fill +132,weather,ww,mno,aurora borealis,,,,,synoptic code,fill in the code you expect,to_fill +133,text,remarks,text,Ice broke up in the river,Ice broke up in the river,,,,free text kept verbatim,,formula +134,ozone,oz,oz,7,7,,,,"ozone scale, no conversion",,formula diff --git a/tests/test_csv2sef.py b/tests/test_csv2sef.py new file mode 100644 index 0000000..5ca94e2 --- /dev/null +++ b/tests/test_csv2sef.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +"""Tests: python -m unittest discover -s tests (from the csv2sef folder)""" +import csv +import datetime as dt +import glob +import os +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +sys.path.insert(0, os.path.join(ROOT, "src")) + +from csv2sef import pipeline, sef, tables # noqa: E402 +from csv2sef import metadata as mdmod # noqa: E402 +from csv2sef.convert import Context, Logger, process_value # noqa: E402 +from csv2sef.headers import parse_header # noqa: E402 + +EX = os.path.join(ROOT, "examples", "HalifaxCitadel") +OPTS = {"trace_mm": 0.2, "wind_words": tables.wind_words(), "weather_terms": tables.weather_terms()} + + +def conv(v, var, unit): + return process_value(v, var, unit, Context(1, "x", dt.date(1860, 1, 1), var), Logger(), OPTS) + + +def sef_rows(path): + with open(path, encoding="utf-8") as f: + lines = f.read().splitlines() + return [ln.split("\t") for ln in lines[13:]] + + +class TestHeaders(unittest.TestCase): + def test_forms(self): + h = parse_header("ta 07:00 [F]") + self.assertEqual((h.var, h.time, h.unit_token), ("ta", (7, 0), "F")) + h = parse_header("p 2 pm (inHg)") + self.assertEqual((h.var, h.time, h.unit_token), ("p", (14, 0), "inHg")) + self.assertIsNone(parse_header("Tn").time) + self.assertIsNone(parse_header("ww daily").time) + self.assertEqual(parse_header("tdb\xa0sunrise").time, (6, 0)) + + +class TestConversions(unittest.TestCase): + def test_values(self): + self.assertEqual(conv("58.2", "ta", "F")[2], 14.56) + self.assertEqual(conv("10", "ta", "R")[2], 12.5) + self.assertEqual(conv("29.71", "p", "inHg")[2], 1006.1) + self.assertAlmostEqual(conv("28", "p", "ParisIn")[2], 1010.6, delta=0.5) + self.assertAlmostEqual(conv("27 11", "p", "ParisIn")[2], 1008.0, delta=1.0) + self.assertEqual(conv("0.5", "rr", "in")[2], 12.7) + self.assertEqual(conv("inapp", "rr", "in")[0], "trace") + self.assertEqual(conv("2", "sd", "in")[3], "cm") + self.assertEqual(conv("fresh breeze", "w", "words")[2], 9.3) + self.assertEqual(conv("bonne brise", "w", "words")[2], 9.3) + self.assertEqual(conv("10", "w", "kt")[2], 5.14) + self.assertEqual(conv("NNE", "dd", "dir")[2], 22.5) + self.assertEqual(conv("rain & fog all day", "ww", "mno")[2], "RA FG") + self.assertEqual(conv("neige et poudrerie", "ww", "mno")[2], "BLSN SN") + self.assertEqual(conv("7", "n", "tenths")[2], 5.6) + + def test_historical_notation(self): + self.assertEqual(conv("10+c", "ta", "R")[:3], ("caves notation", "10+c", 25.3)) # 12.8 + 12.5 + self.assertEqual(conv("2-co", "ta", "R")[2], 10.3) + self.assertEqual(conv("=c", "ta", "R")[2], 12.8) + self.assertEqual(conv("0=0", "ta", "R")[2], 12.8) + self.assertEqual(conv("9-0", "ta", "De_frz")[2], 6.8) # 12.8 - 6 + self.assertEqual(conv("14+", "ta", "De_frz")[:3], ("caves notation (assumed)", "14+", 22.13)) + self.assertEqual(conv("16+0 R", "ta", "De_frz")[2], 32.8) # 12.8 + 20 + self.assertEqual(conv("9=0", "ta", "De_frz")[0], "caves notation, sign unclear") + self.assertEqual(conv("0", "ta", "De_frz")[2], 0.0) + self.assertEqual(conv("-5", "ta", "R")[2], -6.25) + self.assertEqual(conv("10+co", "ta", "De_frz")[2], 19.47) # 12.8 + 6.67 + self.assertEqual(conv("30", "ta", "De_frz")[2], 20.0) + self.assertEqual(conv("150", "ta", "De")[2], 0.0) + self.assertEqual(conv("16R", "ta", "De_frz")[:3], ("unit R", 16.0, 20.0)) + self.assertEqual(conv("<=-34", "ta", "R")[0], "at or below") + opts = dict(OPTS, below_scale_c="-34") + ctx = Context(1, "x", dt.date(1748, 1, 1), "ta") + self.assertEqual(process_value("<=-34", "ta", "De_frz", ctx, Logger(), opts)[2], -34.0) + self.assertEqual(process_value("mercury in bulb", "ta", "De_frz", ctx, Logger(), opts)[2], -34.0) + self.assertEqual(conv("mercury in bulb", "ta", "R")[0], "below scale") + self.assertEqual(conv("a little", "rr", "in")[:3], ("trace; qualitative", "a little", 0.2)) + self.assertEqual(conv("Rain", "rr", "in")[0], "qualitative") + self.assertEqual(conv("3", "fs", "in")[3], "cm") + self.assertEqual(conv("point de vent", "w", "Sm")[2], 0.0) + + def test_flags(self): + self.assertEqual(conv("M", "ta", "F")[0], "missing") + self.assertEqual(conv("37.?", "ta", "F")[:3], ("uncertain", 37.0, 2.78)) + self.assertEqual(conv("*", "ta", "F")[0], "instrument error") + self.assertEqual(conv("[45]", "ta", "F")[1], 45.0) + + +class TestHalifax(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.out = tempfile.mkdtemp() + cls.report = pipeline.run(os.path.join(EX, "HalifaxCitadel_1863-1865.csv"), + os.path.join(EX, "HalifaxCitadel_metadata.csv"), outdir=cls.out) + cls.files = {os.path.basename(p).split("_")[-1][:-4] if "daily" not in p else "ww_daily": p + for p in glob.glob(os.path.join(cls.out, "SEF", "*.tsv"))} + + def test_all_valid(self): + self.assertIn("all files valid", self.report) + for p in self.files.values(): + self.assertEqual(sef.validate(p), [], p) + + def test_values(self): + ta = sef_rows(self.files["ta"]) + self.assertEqual(ta[0][:7], ["1863", "11", "1", "11", "0", "0", "14.56"]) # 07:00 local = 11:00 UTC + w = {tuple(r[:3]): r for r in sef_rows(self.files["w"])} + self.assertEqual(w[("1865", "1", "1")][6], "12.3") # SB = strong breeze + self.assertIn("qc=unknown", w[("1865", "2", "14")][7]) # s/o + tn = sef_rows(self.files["Tn"]) + self.assertEqual(tn[0][:7], ["1863", "11", "2", "0", "0", "day", "2.22"]) # next midnight + ww = {tuple(r[:3]): r for r in sef_rows(self.files["ww"])} + self.assertEqual(ww[("1864", "3", "30")][6], "RA") # wet + + +class TestAliases(unittest.TestCase): + def test_descriptive_headers(self): + md = mdmod.Metadata() + c, err = pipeline.resolve_column(0, "Thermometer Air AM", md) + self.assertEqual((c.var, c.time, c.time_label), ("ta", None, "AM")) + c, err = pipeline.resolve_column(0, "'Weather'", md) + self.assertEqual((c.var, c.period, c.unit), ("ww", "day", "mno")) + c, err = pipeline.resolve_column(0, "Wind_Direction 08:00 [16-point compass]", md) + self.assertEqual((c.var, c.time, c.unit), ("dd", (8, 0), "dir")) + md.columns["Thermometer Air AM"] = {"time": "07:30"} + c, err = pipeline.resolve_column(0, "Thermometer Air AM", md) + self.assertEqual((c.time, c.time_label, c.period), ((7, 30), None, "0")) + + +class TestOtherInputs(unittest.TestCase): + def setUp(self): + self.d = tempfile.mkdtemp() + self.meta = os.path.join(self.d, "m.csv") + with open(self.meta, "w", newline="") as f: + csv.writer(f).writerows([["key", "value"], ["name", "Test Station"], ["lat", "46.8"], + ["lon", "-71.2"], ["source", "TEST"], ["unit.ta", "R"]]) + + def test_long_layout_and_offset(self): + data = os.path.join(self.d, "long.csv") + with open(data, "w", newline="") as f: + csv.writer(f).writerows([["Date", "Time", "Variable", "Value", "Unit"], + ["1790-01-01", "7am", "ta", "-10", "R"], + ["1790-01-01", "2pm", "p", "28 1", "ParisIn"], + ["1790-01-01", "", "ww", "neige", ""]]) + out = os.path.join(self.d, "out") + rep = pipeline.run(data, self.meta, outdir=out) + self.assertIn("all files valid", rep) + md = mdmod.load(self.meta) + self.assertEqual(md.site["utc_offset"], -5.0) # nearest time zone + ta = sef_rows(glob.glob(os.path.join(out, "SEF", "*_ta.tsv"))[0]) + self.assertEqual(ta[0][3:7], ["12", "0", "0", "-12.5"]) # 07:00 local = 12:00 UTC + + def test_xlsx_and_metadata_unit(self): + try: + import openpyxl + except ImportError: + self.skipTest("openpyxl not installed") + wb = openpyxl.Workbook() + ws = wb.active + ws.append(["Year", "Month", "Day", "ta 08:00"]) + ws.append([1800, 2, 1, 4.5]) + data = os.path.join(self.d, "x.xlsx") + wb.save(data) + rep = pipeline.run(data, self.meta, outdir=os.path.join(self.d, "o2")) + self.assertIn("R metadata", rep) + self.assertIn("all files valid", rep) + + def test_database_export(self): + data = os.path.join(self.d, "db.csv") + with open(data, "w", newline="") as f: + csv.writer(f).writerows([ + ["StationName", "ObservationDate", "value", "unit", "field_key", "fieldID"], + ["X", "1750-01-01 08:00:00", "10+c", "R", "Air_Temperature", "9"], + ["X", "1750-01-01 00:00:00", "NA", "free text", "Weather", "18"], + ["X", "1750-01-01 00:00:00", "neige", "free text", "Weather", "18"], + ["X", "1750-01-01 00:00:00", "-1.5", "C", "Minimum_Thermometer", "38"]]) + with open(self.meta, "a", newline="") as f: + csv.writer(f).writerow(["midnight_means_daily", "yes"]) + out = os.path.join(self.d, "o3") + rep = pipeline.run(data, self.meta, outdir=out) + self.assertIn("all files valid", rep) + self.assertNotIn("Date problems", rep) # empty duplicate dropped + ww = sef_rows(glob.glob(os.path.join(out, "SEF", "*_ww.tsv"))[0]) + self.assertEqual(ww[0][3:7], ["0", "0", "day", "SN"]) + ta = sef_rows(glob.glob(os.path.join(out, "SEF", "*_ta.tsv"))[0]) + self.assertEqual(ta[0][3:7], ["13", "0", "0", "25.3"]) + + def test_template(self): + p = os.path.join(self.d, "t.csv") + mdmod.write_template(p, [("ta", "F", "Air temperature")]) + with open(p) as f: + text = f.read() + self.assertIn("unit.ta,F", text) + self.assertIn("unit_change,", text) # blank line to fill in + self.assertNotIn("PTC", text) # no pressure: no line + + def test_template_pressure_and_unknown(self): + p = os.path.join(self.d, "t2.csv") + mdmod.write_template(p, [("foo", None, "UNKNOWN variable")], pressure=["p"]) + with open(p) as f: + text = f.read() + self.assertIn("variable.p,header_meta=PTC=|PGC=", text) + self.assertIn("alias.foo,", text) + # blank alias / unit_change / PTC lines must not break a conversion + data = os.path.join(self.d, "p.csv") + with open(data, "w", newline="") as f: + csv.writer(f).writerows([["year", "month", "day", "p 08:00 [mmHg]"], [1883, 9, 1, 761.3]]) + rows = list(csv.reader(open(p, encoding="utf-8"))) + fill = {"name": "T", "id": "T", "lat": "58.2", "lon": "-62.6", "utc_offset": "-4", "source": "TEST"} + rows = [[r[0], fill.get(r[0], r[1])] + r[2:] if r else r for r in rows] + with open(p, "w", newline="", encoding="utf-8") as f: + csv.writer(f).writerows(rows) + out = os.path.join(self.d, "o4") + rep = pipeline.run(data, p, outdir=out) + self.assertIn("PTC, PGC not filled in", rep) + self.assertIn("all files valid", rep) + with open(glob.glob(os.path.join(out, "SEF", "*_p.tsv"))[0], encoding="utf-8") as f: + self.assertNotIn("PTC=", f.read()) # blanks kept out of the header + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_known_values.py b/tests/test_known_values.py new file mode 100644 index 0000000..eb4ea0e --- /dev/null +++ b/tests/test_known_values.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +"""Known-value tests for every csv2sef conversion. + +Reads tests/known_values.csv (one row per test) and converts each input with csv2sef. +Expected values come from published factors and tables, NOT from csv2sef itself. + +Run from the csv2sef folder (local layout or GitHub layout with src/): + python -m unittest tests.test_known_values -v +or, to print a table of every row (also the rows still to fill in): + python tests/test_known_values.py --report + +Columns of known_values.csv + unit, var, input what csv2sef is given + expected value in SI units; NA = must be missing; blank = not filled in yet + expected_flag quality flag csv2sef must give (blank = no flag) + tolerance allowed difference for numbers (blank = exact match, for codes/text) + opts settings, e.g. caves_temperature_c=12.8;below_scale_c=-34 + status formula (standard factor, must pass) | to_check (expected value to be confirmed: + reported, not failed) | to_fill (no expected value yet) +""" +import csv +import datetime as dt +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +for p in (os.path.join(ROOT, "src"), ROOT): # GitHub layout (src/) or local layout + if os.path.isdir(os.path.join(p, "csv2sef")): + sys.path.insert(0, p) + break + +from csv2sef import tables # noqa: E402 +from csv2sef.convert import Context, Logger, process_value # noqa: E402 + +TABLE = os.path.join(HERE, "known_values.csv") +BASE_OPTS = {"trace_mm": 0.2, "wind_words": tables.wind_words(), + "weather_terms": tables.weather_terms()} + + +def load_rows(): + with open(TABLE, encoding="utf-8", newline="") as f: + return [r for r in csv.DictReader(f) if r["id"] and not r["id"].startswith("#")] + + +def run_row(r): + """Convert one test row -> (flag, iso_value, iso_unit), or ('ERROR: ...', None, None).""" + opts = dict(BASE_OPTS) + for item in filter(None, (r.get("opts") or "").split(";")): + k, v = item.split("=", 1) + opts[k.strip()] = v.strip() + ctx = Context(int(r["id"]), r["unit"], dt.date(1860, 1, 1), r["var"]) + try: + flag, _clean, iso, iu = process_value(r["input"], r["var"], r["unit"], ctx, Logger(), opts) + return flag, iso, iu + except Exception as e: # a crash is a result to report, not to hide + return f"ERROR: {type(e).__name__}: {e}", None, None + + +def check(r, flag, iso): + """Return a list of problems ([] = pass). Rows with status to_fill are never failures.""" + if r["status"] == "to_fill" or r["expected"] == "": + return [] + problems = [] + exp = r["expected"] + if flag and str(flag).startswith("ERROR"): + return [flag] + if exp == "NA": + if iso is not None: + problems.append(f"expected NA, got {iso!r}") + elif r["tolerance"] == "": + if str(iso) != exp: + problems.append(f"expected {exp!r}, got {iso!r}") + else: + try: + if iso is None or abs(float(iso) - float(exp)) > float(r["tolerance"]) + 1e-9: + problems.append(f"expected {exp} +/- {r['tolerance']}, got {iso!r}") + except (TypeError, ValueError): + problems.append(f"expected {exp}, got non-number {iso!r}") + if (flag or "") != r["expected_flag"]: + problems.append(f"flag: expected {r['expected_flag']!r}, got {flag!r}") + return problems + + +class TestKnownValues(unittest.TestCase): + def test_all_rows(self): + """Rows with status 'formula' must pass. Rows with status 'to_check' (expected value + still to be confirmed) are reported but do not fail; a crash always fails.""" + to_check = [] + for r in load_rows(): + flag, iso, _ = run_row(r) + problems = check(r, flag, iso) + crashed = any(p.startswith("ERROR") for p in problems) + if problems and r["status"] == "to_check" and not crashed: + to_check.append(f"{r['id']} {r['unit']} {r['input']!r}: {'; '.join(problems)}") + continue + with self.subTest(id=r["id"], unit=r["unit"], input=r["input"]): + self.assertFalse(problems, "; ".join(problems) + f" [source: {r['source']}]") + if to_check: + print(f"\n{len(to_check)} known value(s) still to be confirmed (status to_check):") + for line in to_check: + print(" ", line) + + +def report(out=None): + """Print (and optionally write to csv) every row with its result.""" + res = [] + for r in load_rows(): + flag, iso, iu = run_row(r) + p = check(r, flag, iso) + verdict = "TO FILL" if (r["status"] == "to_fill" or r["expected"] == "") else ("FAIL" if p else "ok") + res.append({**r, "got": "" if iso is None else iso, "got_flag": flag or "", "iso_unit": iu or "", + "result": verdict, "problem": "; ".join(p)}) + w = max(len(x["input"]) for x in res) + for x in res: + print(f"{x['id']} {x['result']:8s} {x['unit']:12s} {x['input']:<{w}} exp={x['expected']!s:<10} " + f"got={x['got']!s:<10} {x['got_flag']} {x['problem']}") + n = {k: sum(x["result"] == k for x in res) for k in ("ok", "FAIL", "TO FILL")} + print(f"\n{len(res)} rows: {n['ok']} ok, {n['FAIL']} fail, {n['TO FILL']} to fill") + if out: + with open(out, "w", newline="", encoding="utf-8") as f: + wr = csv.DictWriter(f, fieldnames=list(res[0])) + wr.writeheader() + wr.writerows(res) + print("written:", out) + return res + + +if __name__ == "__main__": + if "--report" in sys.argv: + i = sys.argv.index("--report") + report(sys.argv[i + 1] if len(sys.argv) > i + 1 else None) + else: + unittest.main() diff --git a/tools/coverage_report.py b/tools/coverage_report.py new file mode 100644 index 0000000..4a3b3c4 --- /dev/null +++ b/tools/coverage_report.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- +"""Which csv2sef conversions have no test? + +Lists: + 1. converters (units) in csv2sef with no row in tests/known_values.csv + 2. unit names/aliases in data/units.csv that point to a unit with no converter + 3. wind_words.csv terms whose lookup does not return the table's own Beaufort number + 4. weather_terms.csv terms that, written alone, do not come out as the table's own code + (usually an earlier, shorter term in the table catching it first) + +Run from the csv2sef folder: python tools/coverage_report.py +""" +import csv +import datetime as dt +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for p in (os.path.join(ROOT, "src"), ROOT): + if os.path.isdir(os.path.join(p, "csv2sef")): + sys.path.insert(0, p) + PKG = os.path.join(p, "csv2sef") + break + +from csv2sef import tables # noqa: E402 +from csv2sef.convert import CONVERTERS, Context, Logger, process_value # noqa: E402 + +DATA = os.path.join(PKG, "data") +KNOWN = os.path.join(ROOT, "tests", "known_values.csv") +OPTS = {"trace_mm": 0.2, "wind_words": tables.wind_words(), "weather_terms": tables.weather_terms()} +BF_MS = None + + +def conv(v, var, unit): + try: + return process_value(v, var, unit, Context(0, unit, dt.date(1860, 1, 1), var), Logger(), OPTS) + except Exception as e: + return f"ERROR: {type(e).__name__}: {e}", None, None, None + + +def rows(path): + with open(path, encoding="utf-8", newline="") as f: + return [r for r in csv.DictReader(f) if not next(iter(r.values()), "").startswith("#")] + + +def main(): + problems = 0 + known = rows(KNOWN) + tested = {} + for r in known: + tested.setdefault(r["unit"], []).append(r) + + print("1. Converters and their tests") + for unit in sorted(CONVERTERS): + rs = tested.get(unit, []) + filled = [r for r in rs if r["status"] != "to_fill" and r["expected"] != ""] + mark = "MISSING" if not filled else ("to check" if all(r["status"] == "to_check" for r in filled) else "ok") + if mark == "MISSING": + problems += 1 + print(f" {mark:9s} {unit:14s} {len(filled)} test(s)" + (f", {len(rs) - len(filled)} to fill" if len(rs) > len(filled) else "")) + extra = sorted(set(tested) - set(CONVERTERS)) + if extra: + print(" test rows for units csv2sef does not know:", ", ".join(extra)) + + print("\n2. Unit names in units.csv with no converter") + bad = [r for r in rows(os.path.join(DATA, "units.csv")) if r["unit"] not in CONVERTERS] + for r in bad: + print(f" {r['alias']!r} -> {r['unit']!r}") + print(" none" if not bad else "") + problems += len(bad) + + print("\n3. wind_words.csv: does each term give its own Beaufort number?") + bf_ms = {} + for b in range(13): + bf_ms[b] = conv(str(b), "w", "Bf")[2] + n_bad = 0 + for r in rows(os.path.join(DATA, "wind_words.csv")): + term, b = r["term"], r["beaufort"].strip().lower() + flag, _, iso, _ = conv(term, "w", "words") + if b in ("qualitative", "unknown"): + ok = flag == b + want = b + elif b == "": + ok, want = flag == "unmapped", "unmapped" + else: + want = bf_ms.get(int(float(b))) + ok = iso == want or (term == "calm" and iso == 0.0) + if not ok: + n_bad += 1 + print(f" {term!r}: table says {r['beaufort']} ({want}), csv2sef gives {iso!r} {flag or ''}") + print(f" {n_bad} problem(s)") + problems += n_bad + + print("\n4. weather_terms.csv: does each term, written alone, give its own code?") + n_bad = 0 + for term, code, match in OPTS["weather_terms"]: + flag, _, iso, _ = conv(term, "ww", "mno") + want = None if code.lower() == "unknown" else " ".join(c for c in code.split() if c.lower() != "unknown") + if iso != want: + n_bad += 1 + print(f" {term!r} ({match}): table code {code!r}, csv2sef gives {iso!r} {flag or ''}") + print(f" {n_bad} term(s) shadowed or changed by other rows - check whether that is intended") + + print(f"\n{problems} coverage problem(s) in sections 1-3") + return problems + + +if __name__ == "__main__": + sys.exit(1 if main() else 0) diff --git a/uv.lock b/uv.lock index 6af8087..2c9381e 100644 --- a/uv.lock +++ b/uv.lock @@ -29,7 +29,7 @@ dependencies = [ ] [package.metadata] -requires-dist = [{ name = "cdrutilities", specifier = ">=1.0.1" }] +requires-dist = [{ name = "cdrutilities", specifier = ">=1.0.2" }] [[package]] name = "numpy"