tgcn 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tgcn/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ from ._version import __version__
2
+ from ._version import __version_parser__
3
+ from .circulars import Circular
4
+ from .classifications import SciClass
5
+ from .config import Configuration
6
+ from .instruments import Instrument
7
+ from .normalized import Quantity
8
+ from .parser import Output
9
+ from .parser import Parser
10
+ from .parser import View
11
+
12
+ __all__ = [
13
+ "Circular",
14
+ "Configuration",
15
+ "Instrument",
16
+ "Output",
17
+ "Parser",
18
+ "View",
19
+ "Quantity",
20
+ "SciClass",
21
+ ]
tgcn/_repr.py ADDED
@@ -0,0 +1,42 @@
1
+ """Shell representations for parsed results and their nested models."""
2
+
3
+ from enum import Enum
4
+
5
+ from pydantic import BaseModel
6
+ from rich.pretty import pretty_repr
7
+
8
+
9
+ def enum_repr(value: Enum) -> str:
10
+ """Display an enum's class and member name."""
11
+ return f"{type(value).__name__}.{value.name}"
12
+
13
+
14
+ def model_repr(value: object) -> str:
15
+ """Lay out nested fields with indentation when they exceed one line."""
16
+ return pretty_repr(value)
17
+
18
+
19
+ def model_rich_repr(value: BaseModel):
20
+ """Show populated fields and hide the type discriminator."""
21
+ for name, item in value.__repr_args__():
22
+ if name != "type" and item is not None:
23
+ yield name, item
24
+
25
+
26
+ _QUANTITY_FIELD_ORDER = {
27
+ "value": 0,
28
+ "geometry": 0,
29
+ "unit": 1,
30
+ "instruments": 3,
31
+ "references": 4,
32
+ }
33
+
34
+
35
+ def quantity_rich_repr(value: BaseModel):
36
+ """Show the measurement first and its provenance last."""
37
+ yield from sorted(model_rich_repr(value), key=lambda field: _QUANTITY_FIELD_ORDER.get(field[0], 2))
38
+
39
+
40
+ def view_rich_repr(value):
41
+ """Display the claims selected by this parsed view."""
42
+ yield "selected", value.selected
tgcn/_version.py ADDED
@@ -0,0 +1,4 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version(__package__)
4
+ __version_parser__ = "accordion"
tgcn/circulars.py ADDED
@@ -0,0 +1,294 @@
1
+ """NASA GCN Circular models and utilities."""
2
+
3
+ from datetime import datetime
4
+ from datetime import timedelta
5
+ from datetime import UTC
6
+ import logging
7
+ from typing import Annotated, Any, Callable, Self
8
+ from urllib.request import urlopen
9
+
10
+ from pydantic import BaseModel
11
+ from pydantic import ConfigDict
12
+ from pydantic import Field
13
+ from pydantic import StrictInt
14
+
15
+ from . import llm
16
+ from . import reported
17
+ from .citations import extract_citations
18
+ from .claims import Claim
19
+ from .config import RequestSettings
20
+ from .link import extract_emails
21
+ from .link import extract_urls
22
+ from .segmenter import AnnotatedLine
23
+ from .segmenter import Line
24
+ from .segmenter import Segment
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ MAX_QUANTITY_TABLE_LINES = 25
30
+ GCN_CIRCULARS_URL = "https://gcn.nasa.gov/circulars"
31
+ GCN_DOWNLOAD_TIMEOUT = 10
32
+
33
+
34
+ class Circular(BaseModel):
35
+ """Data from a NASA GCN circular and methods to access it."""
36
+
37
+ model_config = ConfigDict(extra="allow")
38
+
39
+ circularId: Annotated[StrictInt, Field(ge=0)]
40
+ """The circular's GCN number."""
41
+
42
+ subject: str
43
+ """The circular's subject line."""
44
+
45
+ createdOn: StrictInt
46
+ """Publication time in milliseconds since the Unix epoch."""
47
+
48
+ submitter: str
49
+ """The person or team who submitted the circular."""
50
+
51
+ body: str
52
+ """The full body text of the circular."""
53
+
54
+ @property
55
+ def date(self) -> datetime:
56
+ """Return the publication time as a UTC datetime.
57
+
58
+ Raises:
59
+ OverflowError: The publication timestamp is outside the range of
60
+ `datetime`.
61
+ """
62
+ return datetime(1970, 1, 1, tzinfo=UTC) + timedelta(milliseconds=self.createdOn)
63
+
64
+ @property
65
+ def extras(self) -> dict[str, Any]:
66
+ """A dictionary of the circular's optional metadata."""
67
+ return dict(self.model_extra or {})
68
+
69
+ @property
70
+ def eventId(self) -> str | None:
71
+ """Return the event ID as a string, or `None` if absent or null."""
72
+ event_id = self.extras.get("eventId")
73
+ return str(event_id) if event_id is not None else None
74
+
75
+ @classmethod
76
+ def from_json(cls, payload: bytes) -> Self:
77
+ """Parse a NASA GCN circular JSON.
78
+
79
+ Args:
80
+ payload: Raw JSON bytes for one GCN circular.
81
+
82
+ Returns:
83
+ The parsed circular with its source metadata.
84
+
85
+ Raises:
86
+ pydantic.ValidationError: The payload is invalid JSON or fails
87
+ circular validation.
88
+
89
+ Examples:
90
+ Load a circular from a JSON file:
91
+
92
+ ```python
93
+ from pathlib import Path
94
+ from tgcn import Circular
95
+
96
+ circular = Circular.from_json(Path("circular.json").read_bytes())
97
+ ```
98
+ """
99
+ return cls.model_validate_json(payload)
100
+
101
+ def _to_json(self) -> str:
102
+ """Serialize this circular using the GCN JSON field names."""
103
+ return self.model_dump_json()
104
+
105
+ @classmethod
106
+ def from_web(cls, circular_id: int, timeout: float = GCN_DOWNLOAD_TIMEOUT) -> Self:
107
+ """Download and parse the GCN circular identified by `circular_id`.
108
+
109
+ Args:
110
+ circular_id: The GCN number of the circular to download.
111
+ timeout: Timeout in seconds for blocking network operations.
112
+
113
+ Returns:
114
+ The parsed circular with its source metadata.
115
+
116
+ Raises:
117
+ OSError: The download fails or times out, including HTTP status
118
+ errors reported by `urllib`.
119
+ http.client.HTTPException: The HTTP response is malformed or
120
+ incomplete.
121
+ pydantic.ValidationError: The response is invalid JSON or fails
122
+ circular validation.
123
+ """
124
+ with urlopen(f"{GCN_CIRCULARS_URL}/{circular_id}.json", timeout=timeout) as response:
125
+ return cls.from_json(response.read())
126
+
127
+ def citations(self) -> list[int]:
128
+ """Return unique cited GCN IDs from subject then body, in mention order."""
129
+ return list(dict.fromkeys(extract_citations(self.subject) + extract_citations(self.body)))
130
+
131
+ def urls(self) -> list[str]:
132
+ """Return unique normalized URLs from subject then body, in mention order."""
133
+ return list(dict.fromkeys(match.value for text in (self.subject, self.body) for match in extract_urls(text)))
134
+
135
+ def emails(self) -> list[str]:
136
+ """Return unique email addresses from subject then body, in mention order."""
137
+ return list(dict.fromkeys(match.value for text in (self.subject, self.body) for match in extract_emails(text)))
138
+
139
+
140
+ def annotate_lines_responses(
141
+ circular: Circular,
142
+ *,
143
+ client: llm.Client,
144
+ settings: RequestSettings,
145
+ on_call: Callable[[llm.Meta], None] | None = None,
146
+ ) -> list[AnnotatedLine]:
147
+ """Annotate the original body lines of a circular.
148
+
149
+ Args:
150
+ circular: Source circular.
151
+ client: Connection URL and API key.
152
+ settings: Model request parameters.
153
+ on_call: Optional call-summary callback. Exceptions propagate.
154
+
155
+ Returns:
156
+ Annotated lines preserving their original order, IDs, and text.
157
+
158
+ Raises:
159
+ openai.APIError: The model API request fails.
160
+ llm.ModelOutputError: The response is unusable or contains invalid
161
+ annotations.
162
+ """
163
+ lines = [Line(id=index, value=value) for index, value in enumerate(circular.body.splitlines())]
164
+ return llm.annotate_lines_responses(lines, client=client, settings=settings, on_call=on_call)
165
+
166
+
167
+ def annotate_lines_decisions(
168
+ circular: Circular,
169
+ *,
170
+ client: llm.Client,
171
+ settings: RequestSettings,
172
+ on_call: Callable[[llm.Meta], None] | None = None,
173
+ ) -> list[AnnotatedLine]:
174
+ """Annotate the original body lines through the Decisions API.
175
+
176
+ Args:
177
+ circular: Source circular.
178
+ client: Connection URL and API key.
179
+ settings: Model request parameters.
180
+ on_call: Optional call-summary callback. Exceptions propagate.
181
+
182
+ Returns:
183
+ Annotated lines preserving their original order, IDs, and text.
184
+
185
+ Raises:
186
+ openai.APIError: The model API request fails.
187
+ llm.ModelOutputError: The response is unusable or does not answer every
188
+ line question exactly once.
189
+ """
190
+ lines = [Line(id=index, value=value) for index, value in enumerate(circular.body.splitlines())]
191
+ return llm.annotate_lines_decisions(lines, client=client, settings=settings, on_call=on_call)
192
+
193
+
194
+ def extract_quantities(
195
+ circular: Circular,
196
+ segments: list[Segment],
197
+ *,
198
+ client: llm.Client,
199
+ settings: RequestSettings,
200
+ on_call: Callable[[llm.Meta], None] | None = None,
201
+ ) -> list[reported.Quantity]:
202
+ """Extract quantities using the circular header and supplied segments.
203
+
204
+ Tables longer than MAX_QUANTITY_TABLE_LINES are excluded from the
205
+ model input. The supplied segments and their IDs remain unchanged.
206
+
207
+ Args:
208
+ circular: Source circular supplying header context.
209
+ segments: Segments derived from this circular's annotated lines.
210
+ client: Connection URL and API key.
211
+ settings: Model request parameters.
212
+ on_call: Optional call-summary callback. Exceptions propagate.
213
+
214
+ Returns:
215
+ Validated quantities whose tokens reference the supplied segments.
216
+
217
+ Raises:
218
+ OverflowError: The publication timestamp is outside the range of
219
+ `datetime`.
220
+ pydantic.ValidationError: The extraction input is invalid, such as
221
+ when segments sent to the model have duplicate IDs.
222
+ openai.APIError: The model API request fails.
223
+ llm.ModelOutputError: The response is unusable or contains quantities
224
+ that do not match their source text.
225
+ """
226
+ # Exclude large tables without renumbering the remaining segments.
227
+ model_segments = []
228
+ for segment in segments:
229
+ if segment.kind == "table" and len(segment.value.splitlines()) > MAX_QUANTITY_TABLE_LINES:
230
+ logger.warning(
231
+ f"Circular {circular.circularId}: skipping quantity extraction "
232
+ f"from table {segment.id} with {len(segment.value.splitlines())} "
233
+ f"lines (limit: {MAX_QUANTITY_TABLE_LINES})."
234
+ )
235
+ else:
236
+ model_segments.append(segment)
237
+ return llm.extract_quantities(
238
+ model_segments,
239
+ circularId=circular.circularId,
240
+ subject=circular.subject,
241
+ date=circular.date,
242
+ submitter=circular.submitter,
243
+ client=client,
244
+ settings=settings,
245
+ on_call=on_call,
246
+ )
247
+
248
+
249
+ def extract_claims(
250
+ circular: Circular,
251
+ segments: list[Segment],
252
+ quantities: list[reported.Quantity],
253
+ *,
254
+ client: llm.Client,
255
+ settings: RequestSettings,
256
+ on_call: Callable[[llm.Meta], None] | None = None,
257
+ ) -> list[Claim[reported.Quantity]]:
258
+ """Extract claims using the circular header, segments, and quantities.
259
+
260
+ Args:
261
+ circular: Source circular supplying header context.
262
+ segments: Segments derived from this circular's annotated lines.
263
+ quantities: Quantities extracted from the circular.
264
+ client: Connection URL and API key.
265
+ settings: Model request parameters.
266
+ on_call: Optional call-summary callback. Exceptions propagate.
267
+
268
+ Returns:
269
+ Claims with validated measurement and subject references.
270
+
271
+ Raises:
272
+ OverflowError: The publication timestamp is outside the range of
273
+ `datetime`.
274
+ pydantic.ValidationError: The extraction input is invalid, such as
275
+ when segments have duplicate IDs.
276
+ openai.APIError: The model API request fails.
277
+ llm.ModelOutputError: The response is unusable or contains invalid
278
+ subject, measurement, or citation references.
279
+
280
+ Notes:
281
+ Does not support extraction from URLs.
282
+ """
283
+ return llm.extract_claims(
284
+ segments,
285
+ quantities,
286
+ citations=circular.citations(),
287
+ circularId=circular.circularId,
288
+ subject=circular.subject,
289
+ date=circular.date,
290
+ submitter=circular.submitter,
291
+ client=client,
292
+ settings=settings,
293
+ on_call=on_call,
294
+ )
tgcn/citations.py ADDED
@@ -0,0 +1,68 @@
1
+ """Deterministic citation extraction from NASA GCN Circulars."""
2
+
3
+ import re
4
+
5
+ # Match a GCN citation introducer and its first ID, allowing common spelling,
6
+ # spacing, and marker variations (for example, ``GCN Circ. #123``).
7
+ _CITATION_START = re.compile(
8
+ r"""
9
+ (?<!\w)
10
+ GCN
11
+ (?:s|C)?
12
+ (?:\s*(?:Circulars?|Circ\.?))?
13
+ \s*(?:\#\s*|=\s*)?
14
+ (?P<id>\d+)
15
+ (?!\w|\.\d)
16
+ """,
17
+ re.IGNORECASE | re.VERBOSE,
18
+ )
19
+
20
+ # Continue a citation through commas, semicolons or ``and`` (including
21
+ # comma-and lists), optionally repeating the GCN introducer.
22
+ _CITATION_LIST_ITEM = re.compile(
23
+ r"""
24
+ \s*(?:[,;]\s*(?:\band\b)?|\band\b)\s*
25
+ (?:
26
+ GCN
27
+ (?:s|C)?
28
+ (?:\s*(?:Circulars?|Circ\.?))?
29
+ \s*(?:\#\s*|=\s*)?
30
+ | [\#=]\s*
31
+ )?
32
+ (?P<id>\d+)
33
+ (?!\w|\.\d)
34
+ """,
35
+ re.IGNORECASE | re.VERBOSE,
36
+ )
37
+
38
+
39
+ def extract_citations(text: str) -> list[int]:
40
+ """Extract unique GCN Circular IDs cited in a circular text, deduplicated and in
41
+ mention order.
42
+
43
+ Args:
44
+ text: A string input.
45
+
46
+ Returns:
47
+ Cited Circular IDs, in first-mention order.
48
+ """
49
+ citations = []
50
+ seen = set()
51
+ for match in _CITATION_START.finditer(text):
52
+ # Start at each explicit GCN marker, then consume only directly linked
53
+ # list items so nearby, unrelated numbers are not treated as citations.
54
+ citation_ids = [match.group("id")]
55
+ position = match.end()
56
+
57
+ while list_item := _CITATION_LIST_ITEM.match(text, position):
58
+ citation_ids.append(list_item.group("id"))
59
+ position = list_item.end()
60
+
61
+ # Order-preserving deduplication.
62
+ for citation_id in citation_ids:
63
+ citation = int(citation_id)
64
+ if citation not in seen:
65
+ seen.add(citation)
66
+ citations.append(citation)
67
+
68
+ return citations
tgcn/claims.py ADDED
@@ -0,0 +1,248 @@
1
+ """Classification and relations models for astrophysical events and sources."""
2
+
3
+ from collections import defaultdict
4
+ from collections.abc import Iterable, Sequence
5
+ from enum import StrEnum
6
+ from typing import Annotated, Literal, NamedTuple
7
+
8
+ from pydantic import BaseModel
9
+ from pydantic import ConfigDict
10
+ from pydantic import Field
11
+ from pydantic import field_validator
12
+ from pydantic import StrictInt
13
+
14
+ from ._repr import enum_repr
15
+ from ._repr import model_repr
16
+ from ._repr import model_rich_repr
17
+ from .classifications import SciClass
18
+
19
+
20
+ class Qualifier(StrEnum):
21
+ """Whether a statement is asserted or uncertain."""
22
+
23
+ __repr__ = enum_repr
24
+
25
+ ASSERTED = "asserted"
26
+ """The authors present the proposition as fact."""
27
+
28
+ UNCERTAIN = "uncertain"
29
+ """The authors express uncertainty to some degree (e.g., using words like "very
30
+ likely", "likely", "tentatively", "may be")."""
31
+
32
+
33
+ class _Model(BaseModel):
34
+ __rich_repr__ = model_rich_repr
35
+ __repr__ = model_repr
36
+ __str__ = model_repr
37
+
38
+ model_config = ConfigDict(extra="forbid", frozen=True, use_attribute_docstrings=True)
39
+
40
+
41
+ class Classification(_Model):
42
+ """A statement classifying an astrophysical subject or event."""
43
+
44
+ kind: Literal["class"] = "class"
45
+ name: SciClass
46
+ """The scientific class assigned to the subject."""
47
+
48
+
49
+ class RelationKind(StrEnum):
50
+ """The relationship between two astrophysical subjects."""
51
+
52
+ __repr__ = enum_repr
53
+
54
+ COUNTERPART = "counterpart"
55
+ """The subject is a counterpart to the target."""
56
+
57
+ HOST = "host"
58
+ """The subject is the host of the target."""
59
+
60
+ LOCALIZATION_COMPATIBLE = "localization_compatible"
61
+ """The subject's position is consistent with the target's localization."""
62
+
63
+
64
+ class Relation(_Model):
65
+ """A directed relation from one subject to another."""
66
+
67
+ kind: RelationKind
68
+ """The type of the relation."""
69
+
70
+ to: str
71
+ """The relation target subject `id`."""
72
+
73
+
74
+ class Not(_Model):
75
+ """Negates a statement about an astrophysical subject or event. A negation
76
+ expresses rejection, rather than an absence of evidence."""
77
+
78
+ kind: Literal["not"] = "not"
79
+ statement: Classification | Relation
80
+ """The classification or relation being negated."""
81
+
82
+
83
+ type Statement = Classification | Relation | Not
84
+ """A positive or negative statement about what a subject is or how it relates to
85
+ another."""
86
+
87
+
88
+ class Proposition(_Model):
89
+ """A statement on an astrophysical subject or event, qualified by a degree of
90
+ certainty."""
91
+
92
+ statement: Statement
93
+ """A classification, relation, or negation statement concerning a subject."""
94
+
95
+ qualifier: Qualifier = Qualifier.ASSERTED
96
+ """Whether the source asserts the statement or presents it as uncertain."""
97
+
98
+
99
+ class Subject(_Model):
100
+ """An astrophysical source or event identified in a circular."""
101
+
102
+ id: str
103
+ """A unique identifier for the subject within the circular."""
104
+
105
+ aliases: tuple[str, ...] = Field(default_factory=tuple)
106
+ """Names and identifiers used in the circular for the subject. Empty when the
107
+ subject is unnamed."""
108
+
109
+ citations: tuple[Annotated[StrictInt, Field(gt=0)], ...] = Field(default_factory=tuple)
110
+ """GCN Circular IDs cited in the circular as reporting or discussing the subject."""
111
+
112
+ @field_validator("citations")
113
+ @classmethod
114
+ def deduplicate_citations(cls, citations: tuple[int, ...]) -> tuple[int, ...]:
115
+ """Remove duplicate citation IDs, preserving first-seen order."""
116
+ return tuple(dict.fromkeys(citations))
117
+
118
+
119
+ class Claim[T](_Model):
120
+ """Measurements, aliases, citations and propositions about one astrophysical
121
+ subject."""
122
+
123
+ # Normalized times contain native tzinfo objects.
124
+ model_config = ConfigDict(arbitrary_types_allowed=True)
125
+
126
+ subject: Subject
127
+ """The subject this claim is about."""
128
+
129
+ propositions: tuple[Proposition, ...]
130
+ """Propositions about what the subject is or how it relates to other subjects."""
131
+
132
+ quantities: tuple[T, ...] = Field(default_factory=tuple)
133
+ """Measurements or measurement references for the subject."""
134
+
135
+
136
+ def resolve_subject_ids[T](claims: Sequence[Claim[T]], identifier: str) -> set[str]:
137
+ """Resolve an ID or alias, preferring exact IDs over alias matches.
138
+
139
+ Args:
140
+ claims: Claims whose subjects are searched.
141
+ identifier: Subject ID or alias to look up.
142
+
143
+ Returns:
144
+ A set containing the exact ID if present, or the IDs of all subjects
145
+ with the alias. The set is empty if no subject matches.
146
+ """
147
+ subjects = [claim.subject for claim in claims]
148
+ matches = {subject.id for subject in subjects if subject.id == identifier}
149
+ if not matches:
150
+ matches = {subject.id for subject in subjects if identifier in subject.aliases}
151
+ return matches
152
+
153
+
154
+ class Edge(NamedTuple):
155
+ """A directed link between subject IDs in one circular.
156
+
157
+ Attributes:
158
+ source: Subject ID at the start of the edge.
159
+ target: Subject ID at the end of the edge.
160
+ kind: The type of the relation.
161
+ qualifier: Whether the relation is asserted or uncertain.
162
+ negated: Whether the relation is negated.
163
+ """
164
+
165
+ source: str
166
+ target: str
167
+ kind: RelationKind
168
+ qualifier: Qualifier
169
+ negated: bool
170
+
171
+ def matches(self, *, include_uncertain: bool, include_negated: bool) -> bool:
172
+ """Return whether this edge passes the certainty and polarity filters.
173
+
174
+ Args:
175
+ include_uncertain: Whether to accept uncertain relations.
176
+ include_negated: Whether to accept negated relations.
177
+
178
+ Returns:
179
+ True if both filters accept the edge.
180
+ """
181
+ return (include_uncertain or self.qualifier == Qualifier.ASSERTED) and (include_negated or not self.negated)
182
+
183
+
184
+ def as_graph[T](claims: Iterable[Claim[T]]) -> set[Edge]:
185
+ """Return relation edges.
186
+
187
+ Counterpart and host relations produce one directed edge. Localization
188
+ compatibility produces an edge in both direction.
189
+
190
+ Args:
191
+ claims: Claims containing the relation propositions.
192
+
193
+ Returns:
194
+ A set of edges retaining each relation's qualifier and negation.
195
+ """
196
+ edges = set()
197
+ for claim in claims:
198
+ for proposition in claim.propositions:
199
+ match proposition.statement:
200
+ case Relation() as relation:
201
+ negated = False
202
+ case Not(statement=Relation() as relation):
203
+ negated = True
204
+ case _:
205
+ continue
206
+
207
+ edge = Edge(claim.subject.id, relation.to, relation.kind, proposition.qualifier, negated)
208
+ edges.add(edge)
209
+ if edge.kind == RelationKind.LOCALIZATION_COMPATIBLE:
210
+ edges.add(edge._replace(source=edge.target, target=edge.source))
211
+ return edges
212
+
213
+
214
+ def connected_subject_ids(
215
+ edges: Iterable[Edge],
216
+ roots: set[str],
217
+ *,
218
+ include_uncertain: bool = True,
219
+ include_negated: bool = True,
220
+ ) -> set[str]:
221
+ """Return IDs reachable from roots through relations in either direction.
222
+
223
+ By default, uncertain and negated relations also connect subjects; set either
224
+ option to False to exclude them.
225
+
226
+ Args:
227
+ edges: Relation edges to traverse.
228
+ roots: Subject IDs to start from.
229
+ include_uncertain: Whether to follow uncertain relations.
230
+ include_negated: Whether to follow negated relations.
231
+
232
+ Returns:
233
+ A set of connected subject IDs. The roots themselves are included.
234
+ """
235
+ neighbors: defaultdict[str, set[str]] = defaultdict(set)
236
+ for edge in edges:
237
+ if edge.matches(include_uncertain=include_uncertain, include_negated=include_negated):
238
+ neighbors[edge.source].add(edge.target)
239
+ neighbors[edge.target].add(edge.source)
240
+
241
+ connected = set(roots)
242
+ pending = list(roots)
243
+ while pending:
244
+ current = pending.pop()
245
+ for neighbor in neighbors[current] - connected:
246
+ connected.add(neighbor)
247
+ pending.append(neighbor)
248
+ return connected