diff --git a/README.md b/README.md index 16de8f2..b80aecb 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ csv2sef - convert transcribed historical weather observations (csv / Excel) into the Station Exchange Format (SEF 1.0.0). -Authors: Hervé Hacot, Victoria Slonosky (Open Data Rescue) +Authors: Hervé Hacot, Victoria Slonosky, Henry Balen (Open Data Rescue) Please cite: Slonosky, V., Black, R., Podolsky, L., Wang, X. & Cheng, V. (2026). diff --git a/pyproject.toml b/pyproject.toml index 8b44bab..8cf28dd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,8 @@ description = "convert transcribed historical weather observations (csv / Excel) readme = "README.md" authors = [ { name = "Vicky Slonosky", email = "VickyS08@users.noreply.github.com" }, - { name = "Hervé Hacot", email = "hhacot@users.noreply.github.com" } + { name = "Hervé Hacot", email = "hhacot@users.noreply.github.com" }, + { name = "Henry Balen", email = "balen@users.noreply.github.com" } ] requires-python = ">=3.10" classifiers = [ diff --git a/src/csv2sef/cli.py b/src/csv2sef/cli.py index 38a95b0..834b646 100644 --- a/src/csv2sef/cli.py +++ b/src/csv2sef/cli.py @@ -10,6 +10,7 @@ """ import argparse import importlib.metadata +from email.utils import getaddresses import os import sys @@ -128,13 +129,30 @@ def cmd_variables(a): print(f" {u:13} {desc}") +def _version(): + try: + return importlib.metadata.version(__package__) + except importlib.metadata.PackageNotFoundError: # run from the source folder, not installed + return "(not installed)" + + +def _authors(): + """Author names from the package metadata: 'Vicky Slonosky, Hervé Hacot'.""" + try: + raw = importlib.metadata.metadata(__package__).get("Author-email") or "" + except importlib.metadata.PackageNotFoundError: + return "" + names = [name or addr for name, addr in getaddresses([raw]) if name or addr] + return ", ".join(names) + + def main(argv=None): p = argparse.ArgumentParser( prog="csv2sef", - description=f"csv2sef {importlib.metadata.metadata(__package__)['Version']}: historical weather csv/Excel -> SEF 1.0.0. " - f"Authors: {', '.join(importlib.metadata.metadata(__package__)['Author-email'])}.", + description=f"csv2sef {_version()}: historical weather csv/Excel -> SEF 1.0.0. " + f"Authors: {_authors()}.", epilog="Please cite: " + CITATION) - p.add_argument("--version", action="version", version=f"csv2sef {importlib.metadata.metadata(__package__)['Version']}") + p.add_argument("--version", action="version", version=f"csv2sef {_version()}") sub = p.add_subparsers(dest="cmd") for name, fn, hlp in (("check", cmd_check, "dry run: show how each column will be read"), diff --git a/src/csv2sef/convert.py b/src/csv2sef/convert.py index 3bf75a7..3139f9c 100644 --- a/src/csv2sef/convert.py +++ b/src/csv2sef/convert.py @@ -56,7 +56,9 @@ def close(self): # Missing / invalid values (Table 7) # -------------------------------------------------------------------------- MISSING_EXACT = {"", "-", "--", "m", "na", "n/a", "nan", "missing", "none"} -MISSING_TERMS = ["not.taken", "not taken", "unknown symbol", "retracted", "-999", +# cloud type, direction and amount: "none" means no clouds (Table 5), not missing +CLOUD_TYPE_DIR_VARS = {"c", "cl", "ch", "cd", "hd", "n", "nl", "nh", "hl"} +MISSING_TERMS = ["not.taken", "not taken", "unknown symbol", "retracted", "redacted", "-999", "no grass", "no place", "suspended", "abt on duty"] INSTRUMENT_ERROR_TERMS = ["out of order", "out.of.order", "broken", "unserviceable", "-888", "incorrect", "not reliable", "covered in snow", "covered with snow", @@ -78,7 +80,7 @@ def pre_screen(value, var, unit, ctx, log): if unit in EMPTY_TOKEN_VALUE and var != "eee": return "ok", EMPTY_TOKEN_VALUE[unit], "no entry" return "stop", None, "missing" - if vl in MISSING_EXACT: + if vl in MISSING_EXACT and not (vl == "none" and var in CLOUD_TYPE_DIR_VARS): return "stop", None, "missing" if unit == "text": return "ok", v, None # free text is kept verbatim @@ -341,30 +343,50 @@ def c_percent(v, var, ctx, log, opts): def _scale(v, ctx, log, top, name): + """Scale value -> (whole force, in range?, flag). Fractions ('1/2', '1 1/2') are rounded down.""" from fractions import Fraction as Fr - s = int(float(sum(Fr(x) for x in v.replace(",", " ").split()))) + total = sum(Fr(x) for x in v.replace(",", " ").split()) + s = int(total) + flag = None + if total != s: + flag = "fraction rounded down" + log.write(ctx, "NOTATION", f"{name} '{v}': no fractions on this scale, rounded down to {s}") if s < 0 or s > top: log.write(ctx, "RANGE", f"{name} {s}: out of range") - return s, False - return s, True + return s, False, flag + return s, True, flag + + +def _force_part(v, ctx, log): + """'south 1' or 'north-west 1/2' (direction and force in one cell, as in some registers): + the force part. Other values are returned unchanged.""" + m = re.fullmatch(r"\s*([A-Za-z][A-Za-z .-]*?)\s+(\d[\d\s/.,]*)\s*", v) + if m: + d = m.group(1).strip().lower().replace(".", "").replace(" by ", "by") + if d in ABBR_TO_DEG or d.replace(" ", "-") in ABBR_TO_DEG: + log.write(ctx, "NOTATION", f"'{v}': direction and force in one cell, force {m.group(2).strip()} used") + return m.group(2).strip() + return v def c_Sm(v, var, ctx, log, opts): + v = _force_part(v, ctx, log) if not re.search(r"\d", v): return c_words(v, var, ctx, log, opts) # descriptive term in a numeric column - s, ok = _scale(v, ctx, log, 10, "Smithsonian force") + s, ok, flag = _scale(v, ctx, log, 10, "Smithsonian force") if not ok: return "out of range", s, None - return None, s, _r(im.convertSmithsonian(s), 1) # Table 4: nominal mph -> m/s + return flag, s, _r(im.convertSmithsonian(s), 1) # Table 4: nominal mph -> m/s def c_Bf(v, var, ctx, log, opts): + v = _force_part(v, ctx, log) if not re.search(r"\d", v): return c_words(v, var, ctx, log, opts) - b, ok = _scale(v, ctx, log, 12, "Beaufort force") + b, ok, flag = _scale(v, ctx, log, 12, "Beaufort force") if not ok: return "out of range", b, None - return None, b, _r(im.convertBeaufort(b), 1) + return flag, b, _r(im.convertBeaufort(b), 1) def c_words(v, var, ctx, log, opts): @@ -428,7 +450,7 @@ def c_tenths(v, var, ctx, log, opts): vl = v.lower() if any(x in vl for x in OBSCURED): return None, v, 9 - if "clear" in vl or vl == "zero": + if "clear" in vl or vl in ("zero", "none"): return None, 0, 0 t = clean_number(v, ctx, log) if t < 0 or t > 10: @@ -439,6 +461,8 @@ def c_tenths(v, var, ctx, log, opts): def c_okta(v, var, ctx, log, opts): vl = v.lower() + if vl.strip() in ("none", "clear"): + return None, 0, 0 if any(x in vl for x in OBSCURED): return None, v, 9 t = clean_number(v, ctx, log) @@ -481,8 +505,22 @@ def c_cloudvel(v, var, ctx, log, opts): "nno": 337.5, "sso": 202.5}) +# Table 5: "hidden" - fog or thick lower clouds hide the higher clouds, so their direction can't be seen +HIDDEN_WORDS = {"hidden", "obscured", "haze", "hazy", "fog", "foggy", "smoke", "mist"} +NO_CLOUD_WORDS = {"clear", "none", "no clouds", "cloudless"} + + def c_dir(v, var, ctx, log, opts): - vl = v.strip().lower().replace(".", "").replace(" by ", "by") + raw = v.strip().lower() + if raw in ("-999", "-999.0", "-999.9", "-9999"): + return "missing", v, None # missing-value code in a direction column + if raw in ("-888", "-888.0", "-888.8"): + return "instrument error", v, None + vl = raw.replace(".", "").replace(" by ", "by") + if vl in HIDDEN_WORDS: + return "hidden", v, None # clouds hidden: direction can't be seen + if vl in NO_CLOUD_WORDS and var != "dd": + return "no clouds", v, "Calm" # no clouds: Calm, flagged if vl in ("calm", "c", "0", "none", "not perceptible", "imp", "calme"): return None, v, "Calm" if vl.startswith("var"): @@ -502,6 +540,8 @@ def c_dir(v, var, ctx, log, opts): def _cloudtype(v, var, ctx, log, opts, upper): + if v.strip().lower() in NO_CLOUD_WORDS: + return None, v, "Ch0" if upper else "Cl0" # Table 5: None; Clear = 0 if opts.get("keep_wind_cloud_type"): code = im.abbr_cloud.get(v.lower(), "-999") else: diff --git a/src/csv2sef/headers.py b/src/csv2sef/headers.py index 42bc3bc..0afe179 100644 --- a/src/csv2sef/headers.py +++ b/src/csv2sef/headers.py @@ -61,6 +61,24 @@ def parse_time(tok): return h, mi +def split_time_suffix(name): + """Field name ending in an observation time -> (name without it, (hour, minute), token). + + 'attached_thermometer_7am' -> ('attached_thermometer', (7, 0), '7am'). Only clock times + with am/pm or a colon, and named times (sunrise, noon ...), count: bare numbers such as + 'casual_phenomena_line_2', 'barometer_observed_117' or '..._9pm_1' are left alone. + Returns (name, None, None) when the name has no such ending. + """ + m = re.match(r"^(.*?)[ _]+([^ _]+)$", (name or "").strip()) + if not m or not m.group(1): + return name, None, None + tok = m.group(2).lower().replace(".", "") + if (tok in NAMED_TIMES or re.fullmatch(r"\d{1,2}(:\d{2})?(am|pm)", tok) + or re.fullmatch(r"\d{1,2}:\d{2}", tok)): + return m.group(1), parse_time(tok), m.group(2) + return name, None, None + + def parse_when(rest): """Text after the variable -> (time, label, problem). time None and label None = daily value; label = approximate time word.""" diff --git a/src/csv2sef/pipeline.py b/src/csv2sef/pipeline.py index b464f0a..0ed0474 100644 --- a/src/csv2sef/pipeline.py +++ b/src/csv2sef/pipeline.py @@ -12,7 +12,10 @@ from . import reader, sef, tables from .checks import cross_checks, range_check from .convert import Context, Logger, process_value -from .headers import normalise, parse_time, parse_when, split_unit +from .headers import normalise, parse_time, parse_when, split_time_suffix, split_unit + +# length units written on barometer / vapour-pressure columns: mercury (issue #9) +MERCURY = {"mm": "mmHg", "in": "inHg"} # columns that identify the record rather than holding observations: ignored quietly ID_COLUMNS = {"observer", "observer id", "observer_id", "station", "station id", "station_id", @@ -104,6 +107,11 @@ def resolve_column(index, raw_header, md): continue unit, source = u, src break + # a length unit on a barometer or vapour-pressure column means millimetres / inches of mercury + if unit in MERCURY and base.get("quantity") in ("pressure", "vapour"): + problems.append(f"unit '{unit}' read as {MERCURY[unit]} ({'millimetres' if unit == 'mm' else 'inches'} " + f"of mercury) for {base.get('quantity')}; write [{MERCURY[unit]}] to avoid this note") + unit = MERCURY[unit] if unit is None: return None, "; ".join(problems) or f"no unit for '{var}'" # a weather column marked [text] is still a weather description to be coded @@ -140,7 +148,10 @@ def unit_on(md, var, date, unit): f = dt.date.fromisoformat(ch["from"]) if ch["from"] else dt.date.min t = dt.date.fromisoformat(ch["to"]) if ch["to"] else dt.date.max if f <= date <= t: - return tables.canonical_unit(ch["unit"]) or ch["unit"] + u = tables.canonical_unit(ch["unit"]) or ch["unit"] + if u in MERCURY and tables.variables().get(var, {}).get("quantity") in ("pressure", "vapour"): + u = MERCURY[u] + return u return unit @@ -154,7 +165,11 @@ def observations(table, md, log): cols, julian = reader.date_columns(table.headers) issues, columns, skipped, ignored = [], [], [], [] if not ("date" in cols or {"year", "month", "day"} <= set(cols)): - raise SystemExit("ERROR: no date columns found (need Year, Month, Day or Date)") + found = ", ".join(repr(h) for h in table.headers[:8] if h) or "(none)" + raise SystemExit("ERROR: no date columns found (need Year, Month, Day or Date).\n" + f"Columns read: {found}.\n" + "If these look wrong, check the separators in the first line of the file " + "(commas, tabs or semicolons, the same as in the data lines).") def is_ignored(h): n = normalise(h).lower() @@ -213,12 +228,23 @@ def is_ignored(h): ignored.append(hd) continue t = row[lc["time"]].strip() if "time" in lc else (dtime or "") - if t and not (midnight_daily and t in ("00:00", "0:00", "00:00:00")): - hd += " " + t - if "unit" in lc and row[lc["unit"]].strip(): - hd += f" [{row[lc['unit']].strip()}]" + use_t = bool(t) and not (midnight_daily and t in ("00:00", "0:00", "00:00:00")) + unit_txt = row[lc["unit"]].strip() if "unit" in lc else "" + name = hd + hd = name + (" " + t if use_t else "") + (f" [{unit_txt}]" if unit_txt else "") if hd not in cache: c, err = resolve_column(-1, hd, md) + # field name that already ends in the hour ('attached_thermometer_7am') plus the + # time column ('07:00'): read the name without its hour, and use the time column + if c and use_t and any("could not read time" in p for p in c.problems): + base, ftime, tok = split_time_suffix(name) + if ftime is not None: + c2, _ = resolve_column(-1, base + " " + t + (f" [{unit_txt}]" if unit_txt else ""), md) + if c2 and not any("could not read time" in p for p in c2.problems): + if parse_time(t) not in (None, ftime): + c2.problems.append(f"field name {name} says {tok}, time column says {t}: " + f"time column used") + c = c2 cache[hd] = c if c: columns.append(c) @@ -470,6 +496,15 @@ def make_report(data_path, table, md, columns, skipped, ignored, issues, records f"{iu[:8]:8} {c.stat:8} {nval:6d} {nflag:7d}") for p in c.problems: L.append(f" ! {p}") + for ch in md.unit_changes: # unit_change lines that apply to this column + if ch["var"] != c.var: + continue + f = dt.date.fromisoformat(ch["from"]) if ch["from"] else dt.date.min + u = unit_on(md, c.var, f, c.unit) + t = dt.date.fromisoformat(ch["to"]) if ch["to"] else dt.date.max + n = sum(1 for r in rs if f <= r["date"] <= t and r["iso_value"] is not None) + L.append(f" > unit {u} from {ch['from'] or 'the start'} to {ch['to'] or 'the end'} " + f"(unit_change): {n} value(s)") for hd, err in skipped: L.append(f"{hd[:28]:28} SKIPPED: {err}") if ignored: diff --git a/src/csv2sef/reader.py b/src/csv2sef/reader.py index 70a1b3a..d24eacc 100644 --- a/src/csv2sef/reader.py +++ b/src/csv2sef/reader.py @@ -68,6 +68,19 @@ def unquote(v): return v +def guess_delimiter(text): + """Comma, semicolon or tab, judged from the first lines of the file (the header and up to + five data lines), so that a header typed with tabs after its commas doesn't decide alone.""" + lines = [ln for ln in text.splitlines() if ln.strip()][:6] + if not lines: + return "," + data = lines[1:] or lines + def count(d, ls): + return sum(ln.count(d) for ln in ls) + best = max((",", ";", "\t"), key=lambda d: (count(d, data), count(d, lines[:1]), d == ",")) + return best if count(best, data) or count(best, lines[:1]) else "," + + def read(path, sheet=None): ext = os.path.splitext(path)[1].lower() if ext in (".xlsx", ".xlsm"): @@ -87,13 +100,7 @@ def read(path, sheet=None): break except UnicodeDecodeError: continue - delim = "\t" if ext in (".tsv", ".tab") else "," - if ext not in (".tsv", ".tab"): - first = text.splitlines()[0] if text else "" - if first.count(";") > first.count(","): - delim = ";" - elif first.count("\t") > first.count(","): - delim = "\t" + delim = "\t" if ext in (".tsv", ".tab") else guess_delimiter(text) raw = list(csv.reader(text.splitlines(), delimiter=delim)) # drop leading empty lines while raw and not any(c.strip() for c in raw[0]): diff --git a/tests/known_values.csv b/tests/known_values.csv index 48c606d..683ab66 100644 --- a/tests/known_values.csv +++ b/tests/known_values.csv @@ -137,3 +137,10 @@ id,category,var,unit,input,expected,expected_flag,tolerance,opts,source,note,sta 136,cloud,n,tenths,8,6,,0,,tenths x 0.8 rounded to whole oktas,Victoria 2026-11-18,formula 137,cloud,n,tenths,9,7,,0,,tenths x 0.8 rounded to whole oktas,Victoria 2026-11-18,formula 138,precipitation,rr,in,trace,0.13,trace,0,,"0.005 in = 0.13 mm (Table 8, Slonosky et al. 2026); default when trace_mm is not set",,formula +139,direction,hd,dir,-999,NA,missing,,,missing-value code (issue #7),,formula +140,direction,hd,dir,hidden,NA,hidden,,,clouds hidden by fog or thick lower clouds (Table 5); issue #7,,formula +141,direction,cd,dir,clear,Calm,no clouds,,,"no clouds: same value as 'none', flagged (Victoria 2026-11-18); issue #7",,formula +142,cloud,hd,dir,none,Calm,no clouds,,,none in a cloud column = no clouds (Victoria 2026-11-18),,formula +143,cloud,cl,lct,none,Cl0,,,,Table 5: None; Clear = Cl0,,formula +144,direction,dd,dir,none,NA,missing,,,none in other columns = missing (Table 7),,formula +145,cloud,n,tenths,none,0,,0,,none in a cloud-amount column = no clouds = 0 (Victoria 2026-11-18),,formula diff --git a/tests/test_csv2sef.py b/tests/test_csv2sef.py index 39231a7..9533484 100644 --- a/tests/test_csv2sef.py +++ b/tests/test_csv2sef.py @@ -86,6 +86,36 @@ def test_historical_notation(self): self.assertEqual(conv("3", "fs", "in")[3], "cm") self.assertEqual(conv("point de vent", "w", "Sm")[2], 0.0) + def test_direction_values(self): + """Issue #7: missing codes, hidden and clear in direction columns.""" + self.assertEqual(conv("-999", "hd", "dir")[:3], ("missing", "-999", None)) + self.assertEqual(conv("-888", "dd", "dir")[0], "instrument error") + self.assertEqual(conv("hidden", "hd", "dir")[:3], ("hidden", "hidden", None)) + self.assertEqual(conv("Haze", "hd", "dir")[0], "hidden") + self.assertEqual(conv("clear", "cd", "dir")[:3], ("no clouds", "clear", "Calm")) + self.assertEqual(conv("none", "hd", "dir")[:3], ("no clouds", "none", "Calm")) # cloud columns + self.assertEqual(conv("none", "cl", "lct")[2], "Cl0") + self.assertEqual(conv("None", "ch", "uct")[2], "Ch0") + self.assertEqual(conv("none", "dd", "dir")[0], "missing") # other columns + self.assertEqual(conv("none", "ta", "F")[0], "missing") + self.assertEqual(conv("none", "n", "tenths")[:3], (None, 0, 0)) # cloud amount + self.assertEqual(conv("None", "nh", "okta")[2], 0) + self.assertEqual(conv("none", "skc", "tenths_clear")[0], "missing") # clearness: not 0 + self.assertEqual(conv("clear", "dd", "dir")[0], "unmapped") # wind: not a cloud + self.assertEqual(conv("north-west", "hd", "dir")[2], 315) + self.assertEqual(conv("calm", "dd", "dir")[2], "Calm") + def test_direction_and_force(self): + """Issue #6: direction and force in one cell ('south 1'), as in Red River 1844-45.""" + self.assertEqual(conv("south 1", "w", "Sm")[:2], (None, 1)) + self.assertEqual(conv("north-west 2", "w", "Sm")[1], 2) + self.assertEqual(conv("South-East 1/2", "w", "Sm")[:2], ("fraction rounded down", 0)) + self.assertEqual(conv("2 1/2", "w", "Bf")[:2], ("fraction rounded down", 2)) + self.assertEqual(conv("redacted", "cv", "cloudvel")[0], "missing") + self.assertEqual(conv("N 3", "w", "Bf")[1], 3) + self.assertEqual(conv("south 1", "dd", "dir")[2], 180) # the direction part, as before + self.assertEqual(conv("fresh 1", "w", "Sm")[0], "invalid") # not a direction: unchanged + self.assertEqual(conv("3", "w", "Sm")[1], 3) + def test_flags(self): self.assertEqual(conv("M", "ta", "F")[0], "missing") self.assertEqual(conv("37.?", "ta", "F")[:3], ("uncertain", 37.0, 2.78)) @@ -93,6 +123,20 @@ def test_flags(self): self.assertEqual(conv("[45]", "ta", "F")[1], 45.0) +class TestCommandLine(unittest.TestCase): + def test_help_authors(self): + """Issue #5: --help lists author names, not the letters of one string.""" + from csv2sef import cli + authors = cli._authors() + if not authors: + self.skipTest("csv2sef not installed (pip install -e .)") + self.assertIn("Vicky Slonosky", authors) + self.assertIn("Hervé Hacot", authors) + self.assertIn("Henry Balen", authors) + self.assertNotIn("V, i, c", authors) + self.assertNotIn("@", authors) + + class TestHalifax(unittest.TestCase): @classmethod def setUpClass(cls): @@ -191,6 +235,82 @@ def test_database_export(self): 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_hour_in_field_name(self): + """Issue #4: database field names that already end in the hour ('..._7am') plus a time + column: fixed-hour readings keep their hour (not read as daily values).""" + from csv2sef.headers import split_time_suffix + self.assertEqual(split_time_suffix("attached_thermometer_7am"), ("attached_thermometer", (7, 0), "7am")) + self.assertEqual(split_time_suffix("clearness_sky_sunrise")[1], (6, 0)) + for name in ("casual_phenomena_line_2", "barometer_observed_117", "attached_thermometer_9pm_1", + "open_air_thermometer_mean"): + self.assertEqual(split_time_suffix(name), (name, None, None)) # bare numbers: not times + data = os.path.join(self.d, "hour.csv") + with open(data, "w", newline="") as f: + csv.writer(f).writerows([ + ["StationName", "ObservationDate", "value", "unit", "field_key"], + ["X", "1876-01-01 07:00:00", "-30", "F", "air_temperature_7am"], + ["X", "1876-01-01 14:00:00", "-14.5", "F", "air_temperature_2pm"], + ["X", "1876-01-01 20:00:00", "-8", "F", "air_temperature_9pm"]]) # name and time disagree + out = os.path.join(self.d, "o5") + rep = pipeline.run(data, self.meta, outdir=out) + self.assertIn("all files valid", rep) + self.assertNotIn("could not read time", rep) + self.assertIn("says 9pm, time column says 20:00: time column used", rep) + ta = sef_rows(glob.glob(os.path.join(out, "SEF", "*_ta.tsv"))[0]) + self.assertEqual([r[3:6] for r in ta], [["12", "0", "0"], ["19", "0", "0"], ["1", "0", "0"]]) # UTC-5 + def test_separators(self): + """Issue #8: a header typed with tabs after its commas; semicolons; tabs.""" + from csv2sef import reader + for name, text in (("tabhead.csv", 'Date,\tta 08:00 [F],\tdd 08:00 [dir]\t\n1773-01-01,"-6","West",\n'), + ("semi.csv", "year;month;day;ta 08:00 [F]\n1773;1;1;-6\n"), + ("tabs.csv", "year\tmonth\tday\tta 08:00 [F]\n1773\t1\t1\t-6\n")): + p = os.path.join(self.d, name) + with open(p, "w", encoding="utf-8") as f: + f.write(text) + t = reader.read(p) + self.assertIn("ta 08:00 [F]", t.headers, name) + cols, _ = reader.date_columns(t.headers) + self.assertTrue("date" in cols or "year" in cols, name) + bad = os.path.join(self.d, "nodate.csv") + with open(bad, "w", encoding="utf-8") as f: + f.write("Datum,ta 08:00 [F]\n1773-01-01,-6\n") + with self.assertRaises(SystemExit) as e: + pipeline.run(bad, self.meta, check_only=True) + self.assertIn("Columns read: 'Datum'", str(e.exception)) + def test_mm_on_pressure(self): + """Issue #9: [mm] / [in] on a barometer column = millimetres / inches of mercury.""" + md = mdmod.Metadata() + c, _ = pipeline.resolve_column(0, "p 08:00 [mm]", md) + self.assertEqual(c.unit, "mmHg") + self.assertTrue(any("read as mmHg" in p for p in c.problems)) + c, _ = pipeline.resolve_column(0, "p 08:00 [in]", md) + self.assertEqual(c.unit, "inHg") + c, _ = pipeline.resolve_column(0, "p 08:00 [mmHg]", md) + self.assertEqual((c.unit, c.problems), ("mmHg", [])) # no note when written right + c, _ = pipeline.resolve_column(0, "rr [mm]", md) + self.assertEqual(c.unit, "mm") # rain: still millimetres + data = os.path.join(self.d, "mm.csv") + with open(data, "w", newline="") as f: + csv.writer(f).writerows([["year", "month", "day", "p 08:00 [mm]"], [1883, 9, 1, 761.3]]) + out = os.path.join(self.d, "o6") + pipeline.run(data, self.meta, outdir=out) + p = sef_rows(glob.glob(os.path.join(out, "SEF", "*_p.tsv"))[0]) + self.assertEqual(p[0][6], "1014.98") # hPa, not 761.3 + def test_unit_change_in_check(self): + """Issue #10: check lists the units set by unit_change.""" + data = os.path.join(self.d, "uc.csv") + with open(data, "w", newline="") as f: + csv.writer(f).writerows([["year", "month", "day", "ta 08:00 [F]"], + [1850, 1, 1, 32], [1851, 6, 1, 10], [1853, 1, 1, 50]]) + with open(self.meta, "a", newline="") as f: + csv.writer(f).writerow(["unit_change", "ta; R; 1850-06-01; 1852-12-31"]) + rep = pipeline.run(data, self.meta, check_only=True) + self.assertIn("> unit R from 1850-06-01 to 1852-12-31 (unit_change): 1 value(s)", rep) + out = os.path.join(self.d, "o7") + pipeline.run(data, self.meta, outdir=out) + ta = sef_rows(glob.glob(os.path.join(out, "SEF", "*_ta.tsv"))[0]) + self.assertEqual([r[6] for r in ta], ["0", "12.5", "10"]) # F, R (10 R), F + def test_template(self): p = os.path.join(self.d, "t.csv") mdmod.write_template(p, [("ta", "F", "Air temperature")])