File size: 4,734 Bytes
6cbe918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""Unified 7+1-class taxonomy for cross-domain benchmark.

Canonical classes (in benchmark order; integer ID = index):
    0 unknown
    1 cargo            (ITU 70-79 + DMA text 'cargo', 'bulk', 'container', 'ro-ro cargo')
    2 tanker           (ITU 80-89 + DMA 'tanker')
    3 passenger        (ITU 60-69 + DMA 'passenger', 'ferry', 'cruise')
    4 fishing          (ITU 30          + DMA 'fishing')
    5 tug              (ITU 31, 32, 52  + DMA 'tug', 'tow')
    6 service          (ITU 33, 34, 50, 51, 53-59 + DMA 'pilot', 'service', 'port tender', 'sar', 'law enforcement', 'anti-pollution')
    7 sailing_leisure  (ITU 35, 36, 37  + DMA 'sailing', 'pleasure', 'yacht')

Differs from the original DMA enum (which had `ferry` as a separate class and merged
`sailing_leisure` into `unknown`) — unified to give cross-dataset evaluations a
single class axis to score against.
"""
from __future__ import annotations

import re

CLASSES = ("unknown","cargo","tanker","passenger","fishing","tug","service","sailing_leisure")
CLASS_TO_ID = {c: i for i, c in enumerate(CLASSES)}


def _normalize(text: object) -> str:
    if text is None:
        return ""
    s = str(text).strip().lower()
    return re.sub(r"\s+", " ", s)


def from_itu_code(value: object) -> str | None:
    """Map an ITU AIS ship-type code (0–99) to a unified class."""
    if value is None:
        return None
    try:
        code = int(float(str(value).strip()))
    except (ValueError, TypeError):
        return None
    if not (0 <= code <= 99):
        return None
    if 70 <= code <= 79: return "cargo"
    if 80 <= code <= 89: return "tanker"
    if 60 <= code <= 69: return "passenger"
    if code == 30: return "fishing"
    if code in (31, 32, 52): return "tug"
    if code in (33, 34, 50, 51, 53, 54, 55, 56, 57, 58, 59): return "service"
    if code in (35, 36, 37): return "sailing_leisure"
    return "unknown"


_TEXT_RULES = (
    # (token-set, class) — first match wins
    (("ro-ro cargo", "container", "containership", "bulk carrier", "bulk cargo",
      "general cargo", "refrigerated cargo", "cargo,", "cargo "), "cargo"),
    (("oil tanker", "products tanker", "chemical tanker", "lng tanker", "lpg tanker",
      "shuttle tanker", "tanker"), "tanker"),
    (("passenger/ro-ro", "passenger/cruise", "cruise ship", "ferry", "passenger ship",
      "passenger,", "passenger "), "passenger"),
    (("fishing vessel", "fishing", "trawler", "fish factory"), "fishing"),
    (("tug,", "tug ", "tug/supply", "towing", "pusher"), "tug"),
    (("pilot", "search and rescue", "sar", "anti-pollution", "law enforcement",
      "port tender", "diving", "buoy/lighthouse", "research", "supply", "service",
      "offshore", "well stimulation", "crew boat", "icebreaker"), "service"),
    (("yacht", "sailing vessel", "sailing", "pleasure craft", "leisure"), "sailing_leisure"),
)


def from_text(value: object) -> str | None:
    """Map a free-text vessel-type string (DMA / VesselFinder / MarineTraffic style)
    to a unified class."""
    text = _normalize(value)
    if not text:
        return None
    for tokens, cls in _TEXT_RULES:
        for tok in tokens:
            if tok in text:
                return cls
    if text in ("unknown", "undefined", "not defined", "unknown value", "other"):
        return "unknown"
    return None


def unify(value: object) -> str:
    """Return one of the 8 canonical class names. Accepts ITU code, text label,
    or already-unified class. Falls back to 'unknown'."""
    if value is None:
        return "unknown"
    s = str(value).strip().lower()
    if not s:
        return "unknown"
    # Direct hit?
    if s in CLASS_TO_ID:
        return s
    # ITU code?
    try:
        code = int(float(s))
        cls = from_itu_code(code)
        if cls:
            return cls
    except (ValueError, TypeError):
        pass
    # Text rule?
    cls = from_text(s)
    if cls:
        return cls
    return "unknown"


def unify_id(value: object) -> int:
    return CLASS_TO_ID[unify(value)]


if __name__ == "__main__":
    # quick self-test
    cases = [
        (70, "cargo"), ("80", "tanker"), ("60.0", "passenger"), (30, "fishing"),
        (52, "tug"), (50, "service"), (35, "sailing_leisure"), (0, "unknown"),
        ("Oil Products Tanker", "tanker"), ("Container Ship", "cargo"),
        ("Cargo, hazard B (X)", "cargo"), ("Passenger", "passenger"),
        ("Pleasure Craft", "sailing_leisure"), ("Pilot Vessel", "service"),
        ("Fishing", "fishing"), ("Tug", "tug"), (None, "unknown"), ("", "unknown"),
    ]
    for v, expected in cases:
        got = unify(v)
        ok = "✓" if got == expected else "✗"
        print(f"  {ok} unify({v!r}) -> {got}  (expected {expected})")