diff --git a/docs/ax/catalog/CONTEXT.md b/docs/ax/catalog/CONTEXT.md index 05c6491d8..8eaa6a8ec 100644 --- a/docs/ax/catalog/CONTEXT.md +++ b/docs/ax/catalog/CONTEXT.md @@ -237,8 +237,8 @@ _Avoid_: PiFinder format (ambiguous in prose), JSON format (Stellarium is JSON t **Resolution**: The umbrella term for matching an observing list entry to a `CompositeObject` in the catalog collection. Two strategies are tried in a fixed order, then a coordinate fallback: -1. **Catalog-keyed resolution** — match by catalog code + sequence, with alias mapping (Messier→M, Caldwell→C, Collinder→Cr). Tried whenever the entry carries a catalog key. -2. **Name resolution** — exact, case-insensitive match of the entry's name against catalog object names, also trying a constellation-genitive–normalized variant ("VY Andromedae" → "VY And"). **Strictly a fallback**: attempted only when catalog-keyed resolution finds nothing. Names collide more readily than catalog keys, so a name never overrides a key match. +1. **Catalog-keyed resolution** — match by catalog code + sequence. A designation is read by `designations.parse_designation`, the same parser the import uses, so "Cr 399", "Collinder 399" and "Col 399" all name Collinder 399, and a designation the import refuses ("H 24", a double star; "M 2-9", a Minkowski nebula) names no listing. The native format's catalog key is PiFinder's own and is looked up as it is. Tried whenever the entry carries a catalog key. +2. **Name resolution** — case-, space- and hyphen-insensitive match of the entry's name against catalog object names (the digit groups must match, so "M 2-9" never matches "M 29"), also trying a constellation-genitive–normalized variant ("VY Andromedae" → "VY And"). **Strictly a fallback**: attempted only when catalog-keyed resolution finds nothing. Names collide more readily than catalog keys, so a name never overrides a key match. A designation with a bare "A", "B" or "H" prefix ("H 24", "B 33") is never matched by name: sources use those names for different objects. 3. If both fail, an entry carrying coordinates becomes a **coordinate object**; an entry with no key, no name match, and no coordinates is dropped. _Avoid_: lookup, import (import is the whole read-then-resolve flow). diff --git a/docs/ax/catalog/obslist-formats/README.md b/docs/ax/catalog/obslist-formats/README.md index 499340858..83031cfd7 100644 --- a/docs/ax/catalog/obslist-formats/README.md +++ b/docs/ax/catalog/obslist-formats/README.md @@ -173,9 +173,12 @@ decimal as hours instead. The hint only affects a bare decimal — the colon and sexagesimal forms are already in hours. **Resolution.** A CSV list carries no special flag; its entries resolve through -the normal path (`obslist.py`): a `Name` that matches a catalog designation -resolves to that catalog object, otherwise the row's own coordinates become an -OBS target. Name lookup runs through the shared `ui_utils.normalize` (case-, +the normal path (`obslist.py`): a `CatalogCode` + `Sequence` pair, or a `Name`, +that the designation parser reads (`designations.parse_designation`, shared +with the catalog import) resolves to that catalog object; then a `Name` that +matches a catalog object's name; otherwise the row's own coordinates become an +OBS target. A bare `H`, `h`, `A` or `B` designation (`H 24`) is a double star +in some sources, so it never resolves by catalog or by name. Name lookup runs through the shared `ui_utils.normalize` (case-, space- and hyphen-insensitive, plus constellation-genitive folding), so `M 3`, `M3` and `NGC 224` all match regardless of how the catalog stores them. To force coordinates for an otherwise-matchable name, use a non-designation label (e.g. diff --git a/python/PiFinder/catalog_imports/catalog_import_utils.py b/python/PiFinder/catalog_imports/catalog_import_utils.py index e435bedb7..cb7e41b10 100644 --- a/python/PiFinder/catalog_imports/catalog_import_utils.py +++ b/python/PiFinder/catalog_imports/catalog_import_utils.py @@ -13,6 +13,11 @@ from tqdm import tqdm from PiFinder.composite_object import MagnitudeObject, SizeObject +from PiFinder.designations import ( # noqa: F401 -- re-exported for the loaders + CATALOG_CODE_ALIASES, + listing_named, + parse_designation, +) from PiFinder import calc_utils from PiFinder.db.objects_db import ObjectsDatabase from PiFinder.db.observations_db import ObservationsDatabase @@ -584,97 +589,6 @@ def trim_string(s): return " ".join(s.split()) -# Designation prefixes that name a PiFinder catalog, keyed on the lowercase, -# whitespace-free prefix as source catalogs write it. A prefix must be listed -# here for an alias to link one object to another; every other designation is -# kept as a plain name. The same catalog is spelled several ways across -# sources, and SIMBAD writes Abell planetaries as "PN A66 nn". -# -# Deliberately absent: -# - A bare "h". Herschel 400 uses catalog code "H", but "H 1-1" and similar -# names are Haro planetary nebulae, and a bare "H 12" can also be Hubble. -# - A bare "a" or "b". Double-star sources use them for the discoverers -# Aitken and van den Bos ("A 58", "B 53"). A loader whose source means -# Abell or Barnard passes them as extra_aliases to parse_designation. -# - "wds" and "pk". Their designations end in digits that are not a sequence -# ("WDS 00001+7508", "PK 120+09.1"). -CATALOG_CODE_ALIASES: Dict[str, str] = { - "abell": "Abl", - "abl": "Abl", - "pna66": "Abl", - "arp": "Arp", - "barnard": "B", - "c": "C", - "caldwell": "C", - "col": "Col", - "collinder": "Col", - "cr": "Col", - "egc": "EGC", - "har": "Har", - "herschel": "H", - "ic": "IC", - "lyn": "Lyn", - "m": "M", - "messier": "M", - "ngc": "NGC", - "rds": "RDS", - "saa": "SaA", - "sam": "SaM", - "sar": "SaR", - "sh2": "Sh2", - "sharpless": "Sh2", - "str": "Str", - "ta2": "Ta2", - "tlk": "TLK", -} - -# A designation reads "": the sequence is the trailing run of -# digits, the prefix is everything before it. -_DESIGNATION_RE = re.compile(r"(.*?)\s*(\d+)") - - -def parse_designation( - raw: str, extra_aliases: Optional[Dict[str, str]] = None -) -> Optional[Tuple[str, int]]: - """Split a source designation into a PiFinder catalog code and sequence. - - "NGC 7008" -> ("NGC", 7008), "Sh 2-176" -> ("Sh2", 176), - "PN A66 80" -> ("Abl", 80). - - Returns None when the designation names no PiFinder catalog. That covers - the planetary-nebula families whose numeric part is compound: "M 1-92" - (Minkowski), "H 3-29" (Haro), "K 2-1" (Kohoutek), "NGC 650-1" (the two - halves of M76). Those leave a prefix of "m1", "h3", "k2" or "ngc650", - none of which is a catalog, so they are rejected instead of being read as - Messier 92, Herschel 29, "K 21" or NGC 6501. - - ``extra_aliases`` adds prefixes for one source, for example {"a": "Abl"} - for a source that writes Abell planetaries as "A 50". - """ - match = _DESIGNATION_RE.fullmatch(trim_string(raw).lower()) - if match is None: - return None - prefix, sequence = match.groups() - key = prefix.rstrip("-.").replace(" ", "") - catalog_code = CATALOG_CODE_ALIASES.get(key) - if catalog_code is None and extra_aliases: - catalog_code = extra_aliases.get(key) - if catalog_code is None: - return None - return catalog_code, int(sequence) - - -def listing_named(name: str) -> Optional[Tuple[str, int]]: - """The listing a name resolves to in the loaders' lookup, or None. - - parse_designation alone answers it, so its prefix allowlist governs every - lookup: "B53" and "h99" name no listing, though Barnard 53 and Herschel - 400 #99 exist. ObjectFinder and the correction pass's checks - (corrections.resolves_to) both ask this, so they cannot disagree. - """ - return parse_designation(name) - - def delete_catalog_from_database(catalog_code: str): """Delete a catalog and all its related records from the database""" if objects_db is None: diff --git a/python/PiFinder/designations.py b/python/PiFinder/designations.py new file mode 100644 index 000000000..b5e422ecb --- /dev/null +++ b/python/PiFinder/designations.py @@ -0,0 +1,146 @@ +""" +Designation parsing shared by the catalog import and the observing-list lookup. + +One parser answers "which PiFinder listing does this designation name?" for +both, so a name an observing list resolves is the listing the import would +link it to. This module has no import-time dependencies beyond the standard +library, so the running app can use it. +""" + +import re +from typing import Dict, Optional, Tuple + +# Designation prefixes that name a PiFinder catalog, keyed on the lowercase, +# whitespace-free prefix as source catalogs write it. A prefix must be listed +# here for an alias to link one object to another; every other designation is +# kept as a plain name. The same catalog is spelled several ways across +# sources, and SIMBAD writes Abell planetaries as "PN A66 nn". +# +# Deliberately absent: +# - A bare "h". Herschel 400 uses catalog code "H", but "H 1-1" and similar +# names are Haro planetary nebulae, and a bare "H 12" can also be Hubble. +# - A bare "a" or "b". Double-star sources use them for the discoverers +# Aitken and van den Bos ("A 58", "B 53"). A loader whose source means +# Abell or Barnard passes them as extra_aliases to parse_designation. +# - "wds" and "pk". Their designations end in digits that are not a sequence +# ("WDS 00001+7508", "PK 120+09.1"). +CATALOG_CODE_ALIASES: Dict[str, str] = { + "abell": "Abl", + "abl": "Abl", + "pna66": "Abl", + "arp": "Arp", + "barnard": "B", + "c": "C", + "caldwell": "C", + "col": "Col", + "collinder": "Col", + "cr": "Col", + "egc": "EGC", + "har": "Har", + "herschel": "H", + "ic": "IC", + "lyn": "Lyn", + "m": "M", + "messier": "M", + "ngc": "NGC", + "rds": "RDS", + "saa": "SaA", + "sam": "SaM", + "sar": "SaR", + "sh2": "Sh2", + "sharpless": "Sh2", + "str": "Str", + "ta2": "Ta2", + "tlk": "TLK", +} + +# A designation reads "": the sequence is the trailing run of +# digits, the prefix is everything before it. +_DESIGNATION_RE = re.compile(r"(.*?)\s*(\d+)") + +# The bare one-letter prefixes left out of CATALOG_CODE_ALIASES (see above). +# Each is a double-star discoverer in some sources and a PiFinder catalog in +# others, so "H 24", "h 99", "A 58" or "B 33" names no single object. +AMBIGUOUS_PREFIXES = frozenset({"a", "b", "h"}) + + +def _prefix_and_sequence(raw: str) -> Optional[Tuple[str, int]]: + """The lowercase, whitespace-free prefix and the sequence of ``raw``.""" + match = _DESIGNATION_RE.fullmatch(" ".join(raw.split()).lower()) + if match is None: + return None + prefix, sequence = match.groups() + return prefix.rstrip("-.").replace(" ", ""), int(sequence) + + +def parse_designation( + raw: str, extra_aliases: Optional[Dict[str, str]] = None +) -> Optional[Tuple[str, int]]: + """Split a source designation into a PiFinder catalog code and sequence. + + "NGC 7008" -> ("NGC", 7008), "Sh 2-176" -> ("Sh2", 176), + "PN A66 80" -> ("Abl", 80). + + Returns None when the designation names no PiFinder catalog. That covers + the planetary-nebula families whose numeric part is compound: "M 1-92" + (Minkowski), "H 3-29" (Haro), "K 2-1" (Kohoutek), "NGC 650-1" (the two + halves of M76). Those leave a prefix of "m1", "h3", "k2" or "ngc650", + none of which is a catalog, so they are rejected instead of being read as + Messier 92, Herschel 29, "K 21" or NGC 6501. + + ``extra_aliases`` adds prefixes for one source, for example {"a": "Abl"} + for a source that writes Abell planetaries as "A 50". + """ + parsed = _prefix_and_sequence(raw) + if parsed is None: + return None + key, sequence = parsed + catalog_code = CATALOG_CODE_ALIASES.get(key) + if catalog_code is None and extra_aliases: + catalog_code = extra_aliases.get(key) + if catalog_code is None: + return None + return catalog_code, sequence + + +def listing_named(name: str) -> Optional[Tuple[str, int]]: + """The listing a name resolves to in the loaders' lookup, or None. + + parse_designation alone answers it, so its prefix allowlist governs every + lookup: "B53" and "h99" name no listing, though Barnard 53 and Herschel + 400 #99 exist. ObjectFinder, the correction pass's checks + (corrections.resolves_to) and the observing-list lookup all ask this, so + they cannot disagree. + """ + return parse_designation(name) + + +def is_ambiguous_designation(raw: str) -> bool: + """True if ``raw`` is a designation with a bare "A", "B" or "H" prefix. + + "H 24" and "h 99" are double stars in SAC and WDS, and Herschel 400 + entries in PiFinder, so a name lookup must not answer them either. + Compound designations such as "H 1-1" (Haro) are not ambiguous. + """ + parsed = _prefix_and_sequence(raw) + return parsed is not None and parsed[0] in AMBIGUOUS_PREFIXES + + +def designation(catalog_code: str, sequence: int) -> Optional[str]: + """A designation of a listing that listing_named reads back, or None. + + ("Col", 399) -> "Col 399". The parser refuses a bare "H" or "B", so + Herschel 400 and Barnard listings get their long form: ("H", 24) -> + "Herschel 24", ("B", 33) -> "Barnard 33". A catalog with no readable + prefix (WDS) gives None. + """ + candidates = [catalog_code] + [ + prefix.capitalize() + for prefix, code in CATALOG_CODE_ALIASES.items() + if code == catalog_code + ] + for prefix in candidates: + text = f"{prefix} {sequence}" + if listing_named(text) == (catalog_code, sequence): + return text + return None diff --git a/python/PiFinder/obslist.py b/python/PiFinder/obslist.py index 4f11a452b..4d2f5b7c8 100644 --- a/python/PiFinder/obslist.py +++ b/python/PiFinder/obslist.py @@ -21,11 +21,11 @@ from PiFinder.catalog_base import VirtualIDManager from PiFinder.catalogs import Catalogs from PiFinder.composite_object import CompositeObject +from PiFinder.designations import is_ambiguous_designation, listing_named from PiFinder.ui.ui_utils import normalize from PiFinder.obslist_formats import ( ObsList, ObsListEntry, - SKYSAFARI_CATALOG_NAMES_INV, SUPPORTED_EXTENSIONS, read_file as formats_read_file, write_skylist, @@ -63,38 +63,44 @@ def _entry_from_composite(obj: CompositeObject) -> ObsListEntry: ) -CATALOG_ALIASES: dict = { - "Messier": "M", - "Caldwell": "C", - "Collinder": "Cr", -} - - def resolve_object(catalog_numbers, catalogs: Catalogs): """ Takes a list of catalog number strings (e.g. ["M 31", "NGC 224"]) and tries to find a matching object in the PiFinder DB. + Each string is read by listing_named, the parser the catalog import uses, + so "Cr 399" and "Collinder 399" both name Collinder 399, and "H 24" (a + double-star discoverer, not Herschel 400) names nothing. + Pure lookup: returns the shared catalog object (or None). Callers must not mutate its catalog description; per-list text goes in `list_descriptions`. """ for catalog_number in catalog_numbers: - parts = catalog_number.strip().split(" ", 1) - catalog = SKYSAFARI_CATALOG_NAMES_INV.get(parts[0], parts[0]) - catalog = CATALOG_ALIASES.get(catalog, catalog) - try: - sequence = int(parts[1].strip()) - except (ValueError, IndexError): - sequence = None - - if sequence is not None: - _object = catalogs.get_object(catalog, sequence) + listing = listing_named(catalog_number) + if listing: + _object = catalogs.get_object(*listing) if _object: return _object return None +def resolve_entry(entry: ObsListEntry, catalogs: Catalogs): + """ + Catalog-keyed resolution of one observing list entry, or None. + + A SkySafari entry's catalog numbers are source spellings, so each goes + through resolve_object. Every other entry's catalog code and sequence were + already parsed by its reader (see ObsListEntry), or are the native + format's own catalog key, so they are looked up as they are. + """ + if entry.catalog_names: + return resolve_object(entry.catalog_names, catalogs) + if entry.catalog_code and entry.sequence: + return catalogs.get_object(entry.catalog_code, entry.sequence) + return None + + def _coordinate_object(entry: ObsListEntry, index: int) -> CompositeObject: """ Creates a CompositeObject from an ObsListEntry's coordinates @@ -281,8 +287,13 @@ def resolve_by_name(name: str, name_index: dict): space- and hyphen-insensitive, but the digit groups must match), also trying a constellation-normalized variant ("VY Andromedae" -> "VY And"). Returns the shared catalog object or None. + + A designation with a bare "A", "B" or "H" prefix ("H 24", "B 33") is not + matched by name: catalogs use those names for different objects (a double + star in SAC, a Herschel 400 or Barnard object in PiFinder), and the + designation parser refuses them for the same reason. """ - if not name: + if not name or is_ambiguous_designation(name): return None keys = [_name_key(name)] designation = _normalize_designation(name) @@ -322,13 +333,7 @@ def read_list(catalogs: Catalogs, name): try: _object = None - # Try catalog resolution with catalog_names (skylist multi-name) - if entry.catalog_names: - _object = resolve_object(entry.catalog_names, catalogs) - elif entry.catalog_code and entry.sequence: - _object = resolve_object( - [f"{entry.catalog_code} {entry.sequence}"], catalogs - ) + _object = resolve_entry(entry, catalogs) # No catalog match: try resolving by object name (handles lists # that identify objects only by name, e.g. "VY Andromedae"). diff --git a/python/PiFinder/obslist_formats.py b/python/PiFinder/obslist_formats.py index 1ac8f1175..a6d43e171 100644 --- a/python/PiFinder/obslist_formats.py +++ b/python/PiFinder/obslist_formats.py @@ -31,6 +31,7 @@ ra_to_hms_exact, ) from PiFinder.composite_object import MagnitudeObject, SizeObject +from PiFinder.designations import designation, parse_designation # ── Data model ────────────────────────────────────────────────────────── @@ -45,6 +46,9 @@ class ObsListEntry: dec: float # Dec in degrees (-90 to +90), J2000 obj_type: str = "" mag: MagnitudeObject = field(default_factory=lambda: MagnitudeObject([])) + # The PiFinder listing (catalog code and sequence) the entry names, or "" + # and 0. Readers fill it through _parse_catalog_name, so it is always a + # PiFinder catalog code and never a source spelling such as "Cr". catalog_code: str = "" sequence: int = 0 description: str = "" @@ -181,17 +185,29 @@ def _parse_dec_flexible(s: str) -> float: def _parse_catalog_name(name: str) -> tuple[str, int]: - """Extract catalog code and sequence from 'NGC 224' or 'NGC224' or 'Sh2 155'.""" - name = name.strip() - # With space: "NGC 7640", "Sh2 155", "Messier 31" - match = re.match(r"([A-Za-z]+\d*[A-Za-z]*)\s+(\d+)$", name) - if match: - return match.group(1), int(match.group(2)) - # No space: "NGC7640", "M31" — split at letter/digit boundary - match = re.match(r"([A-Za-z]+)(\d+)$", name) - if match: - return match.group(1), int(match.group(2)) - return "", 0 + """The PiFinder listing a designation names, as (catalog code, sequence). + + "NGC 224", "NGC224", "Sh 2-155" and "Collinder 399" all parse. Returns + ("", 0) for a name that names no PiFinder listing: a common name, a + compound designation such as "M 2-9", or a bare double-star prefix such + as "H 24". It asks parse_designation, the parser the catalog import uses, + so an observing list and the import read a designation the same way. + """ + parsed = parse_designation(name) + return parsed if parsed else ("", 0) + + +def _parse_catalog_fields(code: str, sequence: int, name: str) -> tuple[str, int]: + """The listing named by a separate catalog and number field, else by name. + + A CSV "CatalogCode" column or a NexTour category is the source's own + spelling ("Messier", "Cr"), so it goes through the same parser as a name. + """ + if code and sequence: + parsed = _parse_catalog_name(f"{code} {sequence}") + if parsed[0]: + return parsed + return _parse_catalog_name(name) # ── Type mapping tables ───────────────────────────────────────────────── @@ -240,14 +256,6 @@ def _parse_catalog_name(name: str) -> tuple[str, int]: if _v not in CELESTRON_TYPE_MAP_INV: CELESTRON_TYPE_MAP_INV[_v] = _k -SKYSAFARI_CATALOG_NAMES: dict[str, str] = { - "CAL": "C", - "COL": "Cr", -} -SKYSAFARI_CATALOG_NAMES_INV: dict[str, str] = { - v: k for k, v in SKYSAFARI_CATALOG_NAMES.items() -} - def _skylist_object_id(obj_type: str) -> str: if obj_type in ("*", "D*", "***"): @@ -263,10 +271,13 @@ def _skylist_object_id(obj_type: str) -> str: def write_skylist(obs_list: ObsList) -> str: lines = ["SkySafariObservingListVersion=3.0"] for i, entry in enumerate(obs_list.entries): - cat = SKYSAFARI_CATALOG_NAMES.get(entry.catalog_code, entry.catalog_code) + # Write a designation the reader parses back to the same listing: + # "Herschel 24", not "H 24", which the parser reads as a double star. catalog_num = ( - f"{cat} {entry.sequence}" if cat and entry.sequence else entry.name - ) + designation(entry.catalog_code, entry.sequence) + if entry.catalog_code and entry.sequence + else None + ) or entry.name lines.extend( [ "SkyObject=BeginObject", @@ -448,6 +459,7 @@ def read_csv(text: str) -> ObsList: sequence = int(seq_str) except ValueError: sequence = 0 + catalog_code, sequence = _parse_catalog_fields(catalog_code, sequence, name) entries.append( ObsListEntry( @@ -879,7 +891,9 @@ def _read_nextour_catalog_first(text: str) -> ObsList: except ValueError: obj_num = 0 - catalog_code = category if category != "User" else "" + catalog_code, obj_num = _parse_catalog_fields( + category if category != "User" else "", obj_num, obj_name + ) entries.append( ObsListEntry( name=obj_name, diff --git a/python/tests/test_obslist_designations.py b/python/tests/test_obslist_designations.py new file mode 100644 index 000000000..bb02a9da2 --- /dev/null +++ b/python/tests/test_obslist_designations.py @@ -0,0 +1,269 @@ +""" +The observing-list lookup reads a designation the way the catalog import does. + +Fault 6 of the review on #670: the lookup had its own parser, so "H 24" (a +double star) resolved to Herschel 400 #24, "Cr 399" resolved to nothing and +"Collinder 399" resolved to a Lyngå object. Both now ask +PiFinder.designations, and the name lookup keeps #673's cases. + +The fake catalog below copies the relevant rows of the catalog database: the +names "H 24" and "h 99" come from the SAC double-star listings, and the Lyngå +object carries the name "Collinder 399". +""" + +import ast +import inspect +import json +from types import SimpleNamespace + +import pytest + +from PiFinder import designations, obslist +from PiFinder.catalog_imports import catalog_import_utils +from PiFinder.obslist_formats import ObsList, ObsListEntry, write_skylist + + +def _obj(label, *names): + return SimpleNamespace(label=label, names=list(names), list_descriptions={}) + + +COL_399 = _obj("Col 399", "Col 399", "Brocchi's Cluster", "Ta2 173") +LYN_847 = _obj("Lyn 847", "Collinder 399") +NGC_5676 = _obj("NGC 5676", "NGC 5676", "H I 189") +H400_99 = _obj("NGC 4027", "NGC 4027", "H II 296") +SAM_137 = _obj("SaM 137", "SaM 137", "107 Aqr", "H 24") +SAM_999 = _obj("SaM 999", "SaM 999", "h 99") +M_29 = _obj("M 29", "M 29", "NGC 6913") +MINKOWSKI_2_9 = _obj("M 2-9", "M 2-9", "Minkowski's Butterfly") +NGC_497 = _obj("NGC 497", "NGC 497") +ARP_8 = _obj("Arp 8", "Arp 8", "NGC 0497 group") +SH2_155 = _obj("Sh2 155", "Sh2 155", "Cave Nebula") +BARNARD_33 = _obj("B 33", "B 33", "Horsehead Nebula") +WDS_10423 = _obj("WDS 10423", "B 33") +C_14 = _obj("C 14", "C 14", "Double Cluster") +VY_AND = _obj("SaR 7", "VY And") + +LISTINGS = { + ("Col", 399): COL_399, + ("Ta2", 173): COL_399, + ("Lyn", 847): LYN_847, + ("NGC", 5676): NGC_5676, + ("H", 24): NGC_5676, + ("NGC", 4027): H400_99, + ("H", 99): H400_99, + ("SaM", 137): SAM_137, + ("SaM", 999): SAM_999, + ("M", 29): M_29, + ("NGC", 6913): M_29, + ("NGC", 497): NGC_497, + ("Arp", 8): ARP_8, + ("Sh2", 155): SH2_155, + ("B", 33): BARNARD_33, + ("WDS", 10423): WDS_10423, + ("C", 14): C_14, + ("SaR", 7): VY_AND, +} + + +class FakeCatalogs: + def get_object(self, catalog_code, sequence): + return LISTINGS.get((catalog_code, sequence)) + + def get_objects(self, only_selected=True, filtered=True): + # The Minkowski nebula has no PiFinder listing; it resolves by name only. + objects = [MINKOWSKI_2_9] + for obj in LISTINGS.values(): + if obj not in objects: + objects.append(obj) + return objects + + +def _resolve(tmp_path, monkeypatch, filename, text): + """Load one observing list file and return the labels it resolved to.""" + monkeypatch.setattr(obslist, "OBSLIST_DIR", str(tmp_path)) + (tmp_path / filename).write_text(text) + result = obslist.read_list(FakeCatalogs(), filename) + assert result["result"] == "success" + return [obj.label for obj in result["catalog_objects"]] + + +def _resolve_name(tmp_path, monkeypatch, name): + """The label one plain-text name resolves to, or None.""" + labels = _resolve(tmp_path, monkeypatch, "list.txt", name + "\n") + return labels[0] if labels else None + + +@pytest.mark.unit +@pytest.mark.parametrize( + "name, expected", + [ + # A bare "H" or "h" is a double-star discoverer, not Herschel 400. + ("H 24", None), + ("h 99", None), + ("H24", None), + # Every spelling of Collinder names the "Col" catalog. + ("Cr 399", "Col 399"), + ("Collinder 399", "Col 399"), + ("Col 399", "Col 399"), + ("Caldwell 14", "C 14"), + ("C 14", "C 14"), + # #673's cases: a compound number is not a Messier number, and a + # leading zero does not change the number. + ("M 2-9", "M 2-9"), + ("M 29", "M 29"), + ("NGC 0497", "NGC 497"), + ("Sh2-155", "Sh2 155"), + ("Sh 2-155", "Sh2 155"), + ("Sh2 155", "Sh2 155"), + # Common names still resolve by name. + ("Cave Nebula", "Sh2 155"), + ("VY Andromedae", "SaR 7"), + # "B 33" is Barnard 33 and van den Bos 33; "Barnard 33" is not. + ("B 33", None), + ("Barnard 33", "B 33"), + ], +) +def test_plain_text_names(tmp_path, monkeypatch, name, expected): + assert _resolve_name(tmp_path, monkeypatch, name) == expected + + +@pytest.mark.unit +def test_compound_designation_with_no_object_is_not_messier(tmp_path, monkeypatch): + # With no Minkowski object to match by name, "M 2-9" resolves to nothing, + # never to M 29. + monkeypatch.setattr(FakeCatalogs, "get_objects", lambda self, **kw: [M_29]) + assert _resolve_name(tmp_path, monkeypatch, "M 2-9") is None + + +@pytest.mark.unit +def test_skylist_catalog_numbers(tmp_path, monkeypatch): + text = ( + "SkySafariObservingListVersion=3.0\n" + "SkyObject=BeginObject\n CatalogNumber=Cr 399\nEndObject=SkyObject\n" + "SkyObject=BeginObject\n CatalogNumber=H 24\nEndObject=SkyObject\n" + # The first catalog number names nothing; the second resolves. + "SkyObject=BeginObject\n CatalogNumber=h 99\n CatalogNumber=NGC 4027\n" + "EndObject=SkyObject\n" + ) + assert _resolve(tmp_path, monkeypatch, "list.skylist", text) == [ + "Col 399", + "NGC 4027", + ] + + +@pytest.mark.unit +def test_csv_catalog_columns_use_the_same_parser(tmp_path, monkeypatch): + text = ( + "Name,RA,Dec,CatalogCode,Sequence\n" + "Coathanger,,,Collinder,399\n" + "Double star,,,H,24\n" + "Cr 399,,,,\n" + ) + assert _resolve(tmp_path, monkeypatch, "list.csv", text) == [ + "Col 399", + "Col 399", + ] + + +@pytest.mark.unit +def test_native_format_catalog_key_is_exact(tmp_path, monkeypatch): + # The native format stores PiFinder's own catalog key, so "H" here is + # Herschel 400 by definition. + text = json.dumps( + { + "version": 1, + "name": "native", + "objects": [ + {"catalog_code": "H", "sequence": 24}, + {"catalog_code": "Col", "sequence": 399}, + ], + } + ) + assert _resolve(tmp_path, monkeypatch, "list.pifinder", text) == [ + "NGC 5676", + "Col 399", + ] + + +@pytest.mark.unit +@pytest.mark.parametrize( + "name, expected", + [ + ("H 24", True), + ("h 99", True), + ("h99", True), + ("A 58", True), + ("B 33", True), + ("H 1-1", False), + ("H II 296", False), + ("Barnard 33", False), + ("NGC 224", False), + ("Andromeda", False), + ], +) +def test_is_ambiguous_designation(name, expected): + assert designations.is_ambiguous_designation(name) is expected + + +@pytest.mark.unit +def test_import_reexports_the_one_parser(): + assert catalog_import_utils.parse_designation is designations.parse_designation + assert catalog_import_utils.listing_named is designations.listing_named + assert ( + catalog_import_utils.CATALOG_CODE_ALIASES is designations.CATALOG_CODE_ALIASES + ) + + +@pytest.mark.unit +def test_designations_is_runtime_safe(): + # The running app imports it, so it must not pull in the catalog import + # (tqdm, the import databases) or anything else outside the standard library. + tree = ast.parse(inspect.getsource(designations)) + imported = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + imported.add(node.module) + assert imported <= {"re", "typing"} + + +@pytest.mark.unit +@pytest.mark.parametrize( + "code, sequence, expected", + [ + ("Col", 399, "Col 399"), + ("NGC", 224, "NGC 224"), + ("Sh2", 155, "Sh2 155"), + ("H", 24, "Herschel 24"), + ("B", 33, "Barnard 33"), + ("WDS", 50812, None), + ], +) +def test_designation_reads_back(code, sequence, expected): + assert designations.designation(code, sequence) == expected + if expected: + assert designations.listing_named(expected) == (code, sequence) + + +@pytest.mark.unit +def test_saved_skylist_round_trips_herschel_and_barnard(tmp_path, monkeypatch): + # PiFinder saves lists as SkySafari files. A Herschel 400 or Barnard + # object must come back as the same object, not as a double star. + entries = [ + ObsListEntry( + name="NGC 5676", ra=218.2, dec=49.5, catalog_code="H", sequence=24 + ), + ObsListEntry(name="B 33", ra=85.2, dec=-2.5, catalog_code="B", sequence=33), + ObsListEntry( + name="Col 399", ra=291.3, dec=20.2, catalog_code="Col", sequence=399 + ), + ] + text = write_skylist(ObsList(name="saved", entries=entries)) + assert "CatalogNumber=Herschel 24" in text + assert "CatalogNumber=Barnard 33" in text + assert _resolve(tmp_path, monkeypatch, "saved.skylist", text) == [ + "NGC 5676", + "B 33", + "Col 399", + ] diff --git a/python/tests/test_obslist_resolve.py b/python/tests/test_obslist_resolve.py index ff7436ce1..99d62771f 100644 --- a/python/tests/test_obslist_resolve.py +++ b/python/tests/test_obslist_resolve.py @@ -119,12 +119,12 @@ def test_per_entry_failure_skips_and_continues(self, monkeypatch): resolved = SimpleNamespace(list_descriptions={}) - def fake_resolve(catalog_numbers, catalogs): - if "NGC 224" in catalog_numbers: + def fake_resolve(entry, catalogs): + if entry.name == "NGC 224": raise RuntimeError("bad row") return resolved - monkeypatch.setattr(obslist, "resolve_object", fake_resolve) + monkeypatch.setattr(obslist, "resolve_entry", fake_resolve) result = obslist.read_list(catalogs=None, name="Mixed.skylist") @@ -143,10 +143,10 @@ def test_all_entries_fail_returns_error(self, monkeypatch): ) monkeypatch.setattr(obslist, "formats_read_file", lambda path: obs_list) - def fake_resolve(catalog_numbers, catalogs): + def fake_resolve(entry, catalogs): raise RuntimeError("catalog db gone") - monkeypatch.setattr(obslist, "resolve_object", fake_resolve) + monkeypatch.setattr(obslist, "resolve_entry", fake_resolve) result = obslist.read_list(catalogs=None, name="AllBad.skylist")