Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
24 changes: 21 additions & 3 deletions src/csv2sef/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""
import argparse
import importlib.metadata
from email.utils import getaddresses
import os
import sys

Expand Down Expand Up @@ -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"),
Expand Down
62 changes: 51 additions & 11 deletions src/csv2sef/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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"):
Expand All @@ -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:
Expand Down
18 changes: 18 additions & 0 deletions src/csv2sef/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
49 changes: 42 additions & 7 deletions src/csv2sef/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand All @@ -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()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
21 changes: 14 additions & 7 deletions src/csv2sef/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand All @@ -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]):
Expand Down
7 changes: 7 additions & 0 deletions tests/known_values.csv
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading