darwin-merger 0.1.0__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.
- darwin_merger/__init__.py +32 -0
- darwin_merger/comparator.py +81 -0
- darwin_merger/contract.py +52 -0
- darwin_merger/engine.py +552 -0
- darwin_merger/exceptions.py +17 -0
- darwin_merger/frame.py +44 -0
- darwin_merger/policy.py +96 -0
- darwin_merger/request.py +66 -0
- darwin_merger/results.py +47 -0
- darwin_merger-0.1.0.dist-info/METADATA +79 -0
- darwin_merger-0.1.0.dist-info/RECORD +14 -0
- darwin_merger-0.1.0.dist-info/WHEEL +5 -0
- darwin_merger-0.1.0.dist-info/licenses/LICENSE +21 -0
- darwin_merger-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""darwin-merger: merge cleaned DataFrames into one trustworthy dataset."""
|
|
2
|
+
|
|
3
|
+
from .comparator import DefaultComparator, Tolerance, ValueComparator, is_missing
|
|
4
|
+
from .contract import MergeContract
|
|
5
|
+
from .engine import MergeEngine
|
|
6
|
+
from .exceptions import MergeConfigError, MergeDataError, MergeError, MergeInputError
|
|
7
|
+
from .frame import InputFrame
|
|
8
|
+
from .policy import FieldPolicy, MergePolicy
|
|
9
|
+
from .request import MergeOptions, MergeRequest
|
|
10
|
+
from .results import MergeReport, MergeResult
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"DefaultComparator",
|
|
14
|
+
"FieldPolicy",
|
|
15
|
+
"InputFrame",
|
|
16
|
+
"MergeConfigError",
|
|
17
|
+
"MergeContract",
|
|
18
|
+
"MergeDataError",
|
|
19
|
+
"MergeEngine",
|
|
20
|
+
"MergeError",
|
|
21
|
+
"MergeInputError",
|
|
22
|
+
"MergeOptions",
|
|
23
|
+
"MergePolicy",
|
|
24
|
+
"MergeReport",
|
|
25
|
+
"MergeRequest",
|
|
26
|
+
"MergeResult",
|
|
27
|
+
"Tolerance",
|
|
28
|
+
"ValueComparator",
|
|
29
|
+
"is_missing",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Value equality: missing-value handling, numeric tolerance and strict fallback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import numbers
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Protocol
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from .exceptions import MergeConfigError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _non_negative_number(value: Any, field: str) -> float:
|
|
17
|
+
try:
|
|
18
|
+
number = float(value)
|
|
19
|
+
except (TypeError, ValueError) as exc:
|
|
20
|
+
raise MergeConfigError(f"{field} must be a number, got {value!r}") from exc
|
|
21
|
+
if not math.isfinite(number) or number < 0:
|
|
22
|
+
raise MergeConfigError(f"{field} must be finite and non-negative, got {value!r}")
|
|
23
|
+
return number
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Tolerance:
|
|
28
|
+
"""Absolute and relative thresholds used when comparing numeric values."""
|
|
29
|
+
|
|
30
|
+
abs: float = 0.01
|
|
31
|
+
rel: float = 1e-4
|
|
32
|
+
|
|
33
|
+
def __post_init__(self) -> None:
|
|
34
|
+
object.__setattr__(self, "abs", _non_negative_number(self.abs, "Tolerance.abs"))
|
|
35
|
+
object.__setattr__(self, "rel", _non_negative_number(self.rel, "Tolerance.rel"))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ValueComparator(Protocol):
|
|
39
|
+
"""Strategy for deciding whether two cell values are the same."""
|
|
40
|
+
|
|
41
|
+
def equal(self, a: Any, b: Any, tolerance: Tolerance) -> bool:
|
|
42
|
+
"""Return True when ``a`` and ``b`` should be treated as equal."""
|
|
43
|
+
...
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def is_missing(value: Any) -> bool:
|
|
47
|
+
"""Return True for None, pandas/numpy missing scalars, but not for arrays."""
|
|
48
|
+
if value is None:
|
|
49
|
+
return True
|
|
50
|
+
try:
|
|
51
|
+
result = pd.isna(value)
|
|
52
|
+
except Exception:
|
|
53
|
+
return False
|
|
54
|
+
if isinstance(result, (bool, np.bool_)):
|
|
55
|
+
return bool(result)
|
|
56
|
+
return False
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DefaultComparator:
|
|
60
|
+
"""Comparator treating numbers with tolerance and everything else strictly."""
|
|
61
|
+
|
|
62
|
+
def equal(self, a: Any, b: Any, tolerance: Tolerance) -> bool:
|
|
63
|
+
"""Compare two values; missing values only match other missing values."""
|
|
64
|
+
a_missing, b_missing = is_missing(a), is_missing(b)
|
|
65
|
+
if a_missing or b_missing:
|
|
66
|
+
return a_missing and b_missing
|
|
67
|
+
if isinstance(a, bool) or isinstance(b, bool):
|
|
68
|
+
return isinstance(a, bool) and isinstance(b, bool) and a == b
|
|
69
|
+
if isinstance(a, numbers.Number) and isinstance(b, numbers.Number):
|
|
70
|
+
fa, fb = float(a), float(b)
|
|
71
|
+
if not (math.isfinite(fa) and math.isfinite(fb)):
|
|
72
|
+
return fa == fb
|
|
73
|
+
diff = abs(fa - fb)
|
|
74
|
+
if diff <= tolerance.abs:
|
|
75
|
+
return True
|
|
76
|
+
scale = max(abs(fa), abs(fb))
|
|
77
|
+
return scale > 0 and diff / scale <= tolerance.rel
|
|
78
|
+
try:
|
|
79
|
+
return bool(a == b)
|
|
80
|
+
except Exception:
|
|
81
|
+
return False
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Merge contract: the row key and output column set."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from .exceptions import MergeConfigError
|
|
8
|
+
|
|
9
|
+
RESERVED_PREFIX = "_dm_"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _as_names(value: object, field: str) -> tuple[str, ...]:
|
|
13
|
+
if isinstance(value, str) or not hasattr(value, "__iter__"):
|
|
14
|
+
raise MergeConfigError(f"{field} must be a sequence of column names")
|
|
15
|
+
names = tuple(value)
|
|
16
|
+
for name in names:
|
|
17
|
+
if not isinstance(name, str) or not name:
|
|
18
|
+
raise MergeConfigError(f"{field} contains an invalid column name: {name!r}")
|
|
19
|
+
if name.startswith(RESERVED_PREFIX):
|
|
20
|
+
raise MergeConfigError(
|
|
21
|
+
f"{field} column {name!r} uses reserved prefix {RESERVED_PREFIX!r}"
|
|
22
|
+
)
|
|
23
|
+
return names
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class MergeContract:
|
|
28
|
+
"""Declares the compound row key and the ordered set of output columns."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
keys: tuple[str, ...]
|
|
32
|
+
columns: tuple[str, ...]
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
object.__setattr__(self, "keys", _as_names(self.keys, "keys"))
|
|
36
|
+
object.__setattr__(self, "columns", _as_names(self.columns, "columns"))
|
|
37
|
+
if not isinstance(self.name, str) or not self.name:
|
|
38
|
+
raise MergeConfigError("contract name must be a non-empty string")
|
|
39
|
+
if not self.keys:
|
|
40
|
+
raise MergeConfigError("contract keys must not be empty")
|
|
41
|
+
if len(set(self.keys)) != len(self.keys):
|
|
42
|
+
raise MergeConfigError("contract keys contain duplicates")
|
|
43
|
+
if len(set(self.columns)) != len(self.columns):
|
|
44
|
+
raise MergeConfigError("contract columns contain duplicates")
|
|
45
|
+
unknown = [key for key in self.keys if key not in self.columns]
|
|
46
|
+
if unknown:
|
|
47
|
+
raise MergeConfigError(f"keys not present in columns: {unknown}")
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def value_columns(self) -> tuple[str, ...]:
|
|
51
|
+
"""Columns that are arbitrated rather than used as row keys."""
|
|
52
|
+
return tuple(column for column in self.columns if column not in self.keys)
|
darwin_merger/engine.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""Two-phase merge engine with a shared value-resolution primitive."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Sequence
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
from .comparator import DefaultComparator, ValueComparator, is_missing
|
|
14
|
+
from .contract import MergeContract
|
|
15
|
+
from .exceptions import MergeDataError, MergeInputError
|
|
16
|
+
from .policy import MergePolicy
|
|
17
|
+
from .request import MergeRequest
|
|
18
|
+
from .results import MergeReport, MergeResult
|
|
19
|
+
|
|
20
|
+
_CONFIDENCE_ORDER = {"missing": 0, "low": 1, "medium": 2, "high": 3}
|
|
21
|
+
_INDEPENDENT = "<independent>"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class _PreparedFrame:
|
|
26
|
+
order: int
|
|
27
|
+
name: str
|
|
28
|
+
lineage: str
|
|
29
|
+
weight: float
|
|
30
|
+
data: pd.DataFrame
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class _Candidate:
|
|
35
|
+
value: Any
|
|
36
|
+
weight: float
|
|
37
|
+
order: int
|
|
38
|
+
origin: str
|
|
39
|
+
lineage: str
|
|
40
|
+
intra_conflict: bool = False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class _Cell:
|
|
45
|
+
value: Any
|
|
46
|
+
confidence: str
|
|
47
|
+
chosen_lineage: str | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _display_lineage(lineage: str) -> str:
|
|
51
|
+
return _INDEPENDENT if lineage.startswith(f"{_INDEPENDENT}:") else lineage
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _hashable_key(values: Sequence[Any]) -> Any:
|
|
55
|
+
try:
|
|
56
|
+
hash(values)
|
|
57
|
+
return values
|
|
58
|
+
except TypeError:
|
|
59
|
+
return tuple(repr(value) for value in values)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _group_values(
|
|
63
|
+
values: Sequence[Any], comparator: ValueComparator, tolerance: Any
|
|
64
|
+
) -> list[list[int]]:
|
|
65
|
+
"""Partition candidate indices into groups of values the comparator calls equal."""
|
|
66
|
+
groups: list[list[int]] = []
|
|
67
|
+
for index, value in enumerate(values):
|
|
68
|
+
for group in groups:
|
|
69
|
+
if comparator.equal(value, values[group[0]], tolerance):
|
|
70
|
+
group.append(index)
|
|
71
|
+
break
|
|
72
|
+
else:
|
|
73
|
+
groups.append([index])
|
|
74
|
+
return groups
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class MergeEngine:
|
|
78
|
+
"""Align cleaned frames, reduce evidence per lineage, then arbitrate across lineages."""
|
|
79
|
+
|
|
80
|
+
def merge(self, request: MergeRequest) -> MergeResult:
|
|
81
|
+
"""Execute one merge and return the merged data with its audit report."""
|
|
82
|
+
prepared, frame_rows, duplicates, key_counter, warnings = self._prepare_frames(request)
|
|
83
|
+
row_keys = self._align_keys(prepared, request.contract)
|
|
84
|
+
if row_keys.empty:
|
|
85
|
+
raise MergeDataError("no usable rows in the input frames")
|
|
86
|
+
combined = self._join_frames(prepared, row_keys, request.contract)
|
|
87
|
+
comparator = request.policy.comparator or DefaultComparator()
|
|
88
|
+
|
|
89
|
+
view = self._reduce_within_lineages(
|
|
90
|
+
combined, request.contract, request.policy, comparator
|
|
91
|
+
)
|
|
92
|
+
cells, stats = self._arbitrate_between_lineages(
|
|
93
|
+
view, combined, len(row_keys), request.contract, request.policy, comparator
|
|
94
|
+
)
|
|
95
|
+
data = self._build_data(cells, row_keys, request)
|
|
96
|
+
report = self._build_report(
|
|
97
|
+
request=request,
|
|
98
|
+
prepared=prepared,
|
|
99
|
+
cells=cells,
|
|
100
|
+
row_keys=row_keys,
|
|
101
|
+
view=view,
|
|
102
|
+
stats=stats,
|
|
103
|
+
frame_rows=frame_rows,
|
|
104
|
+
duplicates=duplicates,
|
|
105
|
+
key_counter=key_counter,
|
|
106
|
+
warnings=warnings,
|
|
107
|
+
)
|
|
108
|
+
return MergeResult(data=data, report=report)
|
|
109
|
+
|
|
110
|
+
def _prepare_frames(
|
|
111
|
+
self, request: MergeRequest
|
|
112
|
+
) -> tuple[list[_PreparedFrame], dict[str, int], dict[str, int], Counter, list[str]]:
|
|
113
|
+
contract = request.contract
|
|
114
|
+
prepared: list[_PreparedFrame] = []
|
|
115
|
+
frame_rows: dict[str, int] = {}
|
|
116
|
+
duplicates: dict[str, int] = {}
|
|
117
|
+
key_counter: Counter = Counter()
|
|
118
|
+
warnings: list[str] = []
|
|
119
|
+
|
|
120
|
+
for frame in request.frames:
|
|
121
|
+
missing_keys = [key for key in contract.keys if key not in frame.data.columns]
|
|
122
|
+
if missing_keys:
|
|
123
|
+
raise MergeInputError(
|
|
124
|
+
f"frame {frame.name!r} is missing key columns: {missing_keys}"
|
|
125
|
+
)
|
|
126
|
+
missing_columns = [
|
|
127
|
+
column for column in contract.columns if column not in frame.data.columns
|
|
128
|
+
]
|
|
129
|
+
work = frame.data.reset_index(drop=True).copy()
|
|
130
|
+
for column in missing_columns:
|
|
131
|
+
work[column] = pd.NA
|
|
132
|
+
duplicate_mask = work.duplicated(subset=list(contract.keys), keep="first")
|
|
133
|
+
duplicates[frame.name] = int(duplicate_mask.sum())
|
|
134
|
+
clean = work.loc[~duplicate_mask, list(contract.columns)].copy()
|
|
135
|
+
frame_rows[frame.name] = int(len(clean))
|
|
136
|
+
|
|
137
|
+
if missing_columns and request.options.warn_on_missing_column:
|
|
138
|
+
warnings.append(
|
|
139
|
+
f"frame {frame.name!r}: filled missing columns {missing_columns}"
|
|
140
|
+
)
|
|
141
|
+
if clean.empty:
|
|
142
|
+
warnings.append(f"frame {frame.name!r} is empty after deduplication")
|
|
143
|
+
|
|
144
|
+
for key_tuple in clean[list(contract.keys)].itertuples(index=False, name=None):
|
|
145
|
+
key_counter[_hashable_key(key_tuple)] += 1
|
|
146
|
+
|
|
147
|
+
lineage = (
|
|
148
|
+
frame.source_id
|
|
149
|
+
if frame.source_id is not None
|
|
150
|
+
else f"{_INDEPENDENT}:{frame.name}"
|
|
151
|
+
)
|
|
152
|
+
prepared.append(
|
|
153
|
+
_PreparedFrame(
|
|
154
|
+
order=len(prepared),
|
|
155
|
+
name=frame.name,
|
|
156
|
+
lineage=lineage,
|
|
157
|
+
weight=frame.weight,
|
|
158
|
+
data=clean,
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
return prepared, frame_rows, duplicates, key_counter, warnings
|
|
162
|
+
|
|
163
|
+
def _align_keys(
|
|
164
|
+
self, prepared: Sequence[_PreparedFrame], contract: MergeContract
|
|
165
|
+
) -> pd.DataFrame:
|
|
166
|
+
"""Union of all keys in first-appearance order."""
|
|
167
|
+
frames = [frame.data[list(contract.keys)] for frame in prepared]
|
|
168
|
+
combined = pd.concat(frames, ignore_index=True, sort=False)
|
|
169
|
+
return combined.drop_duplicates(keep="first").reset_index(drop=True)
|
|
170
|
+
|
|
171
|
+
def _join_frames(
|
|
172
|
+
self,
|
|
173
|
+
prepared: Sequence[_PreparedFrame],
|
|
174
|
+
row_keys: pd.DataFrame,
|
|
175
|
+
contract: MergeContract,
|
|
176
|
+
) -> pd.DataFrame:
|
|
177
|
+
parts: list[pd.DataFrame] = []
|
|
178
|
+
for frame in prepared:
|
|
179
|
+
part = frame.data.copy()
|
|
180
|
+
part["_dm_order"] = frame.order
|
|
181
|
+
part["_dm_weight"] = frame.weight
|
|
182
|
+
part["_dm_name"] = frame.name
|
|
183
|
+
part["_dm_lineage"] = frame.lineage
|
|
184
|
+
parts.append(part)
|
|
185
|
+
combined = pd.concat(parts, ignore_index=True, sort=False)
|
|
186
|
+
indexed = row_keys.copy()
|
|
187
|
+
indexed["_dm_row"] = range(len(indexed))
|
|
188
|
+
return combined.merge(indexed, on=list(contract.keys), how="left", sort=False)
|
|
189
|
+
|
|
190
|
+
def _reduce_within_lineages(
|
|
191
|
+
self,
|
|
192
|
+
combined: pd.DataFrame,
|
|
193
|
+
contract: MergeContract,
|
|
194
|
+
policy: MergePolicy,
|
|
195
|
+
comparator: ValueComparator,
|
|
196
|
+
) -> dict[tuple[int, str, str], _Candidate]:
|
|
197
|
+
"""Phase 1: one value per (row, field, lineage), tagged with self-consistency."""
|
|
198
|
+
view: dict[tuple[int, str, str], _Candidate] = {}
|
|
199
|
+
for lineage, group in combined.groupby("_dm_lineage", sort=False):
|
|
200
|
+
for row_index, subset in group.groupby("_dm_row", sort=False):
|
|
201
|
+
columns = list(subset.columns)
|
|
202
|
+
value_pos = {name: columns.index(name) for name in contract.value_columns}
|
|
203
|
+
weight_pos = columns.index("_dm_weight")
|
|
204
|
+
order_pos = columns.index("_dm_order")
|
|
205
|
+
name_pos = columns.index("_dm_name")
|
|
206
|
+
records = list(subset.itertuples(index=False, name=None))
|
|
207
|
+
for field in contract.value_columns:
|
|
208
|
+
field_policy = policy.field_policies.get(field)
|
|
209
|
+
tolerance = (
|
|
210
|
+
field_policy.tolerance
|
|
211
|
+
if field_policy is not None and field_policy.tolerance is not None
|
|
212
|
+
else policy.tolerance
|
|
213
|
+
)
|
|
214
|
+
candidates = [
|
|
215
|
+
_Candidate(
|
|
216
|
+
value=record[value_pos[field]],
|
|
217
|
+
weight=float(record[weight_pos]),
|
|
218
|
+
order=int(record[order_pos]),
|
|
219
|
+
origin=str(record[name_pos]),
|
|
220
|
+
lineage=str(lineage),
|
|
221
|
+
)
|
|
222
|
+
for record in records
|
|
223
|
+
if not is_missing(record[value_pos[field]])
|
|
224
|
+
]
|
|
225
|
+
if not candidates:
|
|
226
|
+
continue
|
|
227
|
+
groups = _group_values(
|
|
228
|
+
[candidate.value for candidate in candidates], comparator, tolerance
|
|
229
|
+
)
|
|
230
|
+
best = min(candidates, key=lambda item: (-item.weight, item.order))
|
|
231
|
+
view[(int(row_index), field, str(lineage))] = _Candidate(
|
|
232
|
+
value=best.value,
|
|
233
|
+
weight=best.weight,
|
|
234
|
+
order=best.order,
|
|
235
|
+
origin=best.origin,
|
|
236
|
+
lineage=best.lineage,
|
|
237
|
+
intra_conflict=len(groups) > 1,
|
|
238
|
+
)
|
|
239
|
+
return view
|
|
240
|
+
|
|
241
|
+
def _arbitrate_between_lineages(
|
|
242
|
+
self,
|
|
243
|
+
view: dict[tuple[int, str, str], _Candidate],
|
|
244
|
+
combined: pd.DataFrame,
|
|
245
|
+
n_rows: int,
|
|
246
|
+
contract: MergeContract,
|
|
247
|
+
policy: MergePolicy,
|
|
248
|
+
comparator: ValueComparator,
|
|
249
|
+
) -> tuple[dict[tuple[int, str], _Cell], dict[str, Any]]:
|
|
250
|
+
"""Phase 2: rank value groups by independent lineage support and effective weight."""
|
|
251
|
+
lineages = sorted(str(value) for value in combined["_dm_lineage"].unique())
|
|
252
|
+
cells: dict[tuple[int, str], _Cell] = {}
|
|
253
|
+
stats: dict[str, Any] = {
|
|
254
|
+
"consensus": Counter(),
|
|
255
|
+
"conflict_count": Counter(),
|
|
256
|
+
"conflict_sources": {},
|
|
257
|
+
"conflict_strategy": {},
|
|
258
|
+
"lineage_max": {},
|
|
259
|
+
"lineage_sum": {},
|
|
260
|
+
"lineage_n": {},
|
|
261
|
+
"usage": {},
|
|
262
|
+
"intra": {},
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
for row_index in range(n_rows):
|
|
266
|
+
for field in contract.value_columns:
|
|
267
|
+
field_policy = policy.field_policies.get(field)
|
|
268
|
+
tolerance = (
|
|
269
|
+
field_policy.tolerance
|
|
270
|
+
if field_policy is not None and field_policy.tolerance is not None
|
|
271
|
+
else policy.tolerance
|
|
272
|
+
)
|
|
273
|
+
on_conflict = (
|
|
274
|
+
field_policy.on_conflict
|
|
275
|
+
if field_policy is not None and field_policy.on_conflict is not None
|
|
276
|
+
else policy.on_conflict
|
|
277
|
+
)
|
|
278
|
+
field_weights = field_policy.weights if field_policy is not None else {}
|
|
279
|
+
|
|
280
|
+
candidates: list[_Candidate] = []
|
|
281
|
+
for lineage in lineages:
|
|
282
|
+
base = view.get((row_index, field, lineage))
|
|
283
|
+
if base is None:
|
|
284
|
+
continue
|
|
285
|
+
multiplier = field_weights.get(_display_lineage(base.lineage), 1.0)
|
|
286
|
+
effective = base.weight * multiplier
|
|
287
|
+
if base.intra_conflict:
|
|
288
|
+
effective *= policy.intra_penalty
|
|
289
|
+
candidates.append(
|
|
290
|
+
_Candidate(
|
|
291
|
+
value=base.value,
|
|
292
|
+
weight=effective,
|
|
293
|
+
order=base.order,
|
|
294
|
+
origin=base.origin,
|
|
295
|
+
lineage=lineage,
|
|
296
|
+
intra_conflict=base.intra_conflict,
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
if not candidates:
|
|
301
|
+
cells[(row_index, field)] = _Cell(pd.NA, "missing")
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
groups = _group_values(
|
|
305
|
+
[candidate.value for candidate in candidates], comparator, tolerance
|
|
306
|
+
)
|
|
307
|
+
ranked: list[dict[str, Any]] = []
|
|
308
|
+
for group in groups:
|
|
309
|
+
members = [candidates[index] for index in group]
|
|
310
|
+
best = min(members, key=lambda item: (-item.weight, item.order))
|
|
311
|
+
ranked.append(
|
|
312
|
+
{
|
|
313
|
+
"sum": sum(member.weight for member in members),
|
|
314
|
+
"best": best,
|
|
315
|
+
"members": members,
|
|
316
|
+
"lineages": {member.lineage for member in members},
|
|
317
|
+
}
|
|
318
|
+
)
|
|
319
|
+
ranked.sort(
|
|
320
|
+
key=lambda item: (
|
|
321
|
+
-item["sum"],
|
|
322
|
+
-item["best"].weight,
|
|
323
|
+
item["best"].order,
|
|
324
|
+
)
|
|
325
|
+
)
|
|
326
|
+
winner = ranked[0]
|
|
327
|
+
inter_conflict = len(groups) > 1
|
|
328
|
+
tie = len(ranked) > 1 and (
|
|
329
|
+
ranked[0]["sum"],
|
|
330
|
+
ranked[0]["best"].weight,
|
|
331
|
+
ranked[0]["best"].order,
|
|
332
|
+
) == (
|
|
333
|
+
ranked[1]["sum"],
|
|
334
|
+
ranked[1]["best"].weight,
|
|
335
|
+
ranked[1]["best"].order,
|
|
336
|
+
)
|
|
337
|
+
support = len(winner["lineages"])
|
|
338
|
+
has_intra = any(member.intra_conflict for member in winner["members"])
|
|
339
|
+
lineage_total = len({candidate.lineage for candidate in candidates})
|
|
340
|
+
|
|
341
|
+
stats["lineage_max"][field] = max(
|
|
342
|
+
stats["lineage_max"].get(field, 0), lineage_total
|
|
343
|
+
)
|
|
344
|
+
stats["lineage_sum"][field] = stats["lineage_sum"].get(field, 0) + lineage_total
|
|
345
|
+
stats["lineage_n"][field] = stats["lineage_n"].get(field, 0) + 1
|
|
346
|
+
|
|
347
|
+
if inter_conflict:
|
|
348
|
+
stats["conflict_count"][field] += 1
|
|
349
|
+
stats["conflict_sources"].setdefault(field, set()).update(
|
|
350
|
+
candidate.lineage for candidate in candidates
|
|
351
|
+
)
|
|
352
|
+
stats["conflict_strategy"][field] = on_conflict
|
|
353
|
+
elif support >= policy.min_lineages_for_consensus:
|
|
354
|
+
stats["consensus"][field] += 1
|
|
355
|
+
|
|
356
|
+
if inter_conflict and on_conflict == "null_if_conflict":
|
|
357
|
+
cells[(row_index, field)] = _Cell(pd.NA, "missing")
|
|
358
|
+
continue
|
|
359
|
+
|
|
360
|
+
if inter_conflict or has_intra or tie:
|
|
361
|
+
confidence = "low"
|
|
362
|
+
elif support >= policy.min_lineages_for_consensus:
|
|
363
|
+
confidence = "high"
|
|
364
|
+
else:
|
|
365
|
+
confidence = "medium"
|
|
366
|
+
chosen = winner["best"]
|
|
367
|
+
cells[(row_index, field)] = _Cell(chosen.value, confidence, chosen.lineage)
|
|
368
|
+
stats["usage"].setdefault(field, Counter())[chosen.lineage] += 1
|
|
369
|
+
|
|
370
|
+
for (row_index, field, lineage), candidate in view.items():
|
|
371
|
+
if candidate.intra_conflict:
|
|
372
|
+
stats["intra"].setdefault(field, Counter())[lineage] += 1
|
|
373
|
+
return cells, stats
|
|
374
|
+
|
|
375
|
+
def _build_data(
|
|
376
|
+
self, cells: dict[tuple[int, str], _Cell], row_keys: pd.DataFrame, request: MergeRequest
|
|
377
|
+
) -> pd.DataFrame:
|
|
378
|
+
contract = request.contract
|
|
379
|
+
confidence_column = request.options.confidence_column
|
|
380
|
+
records: list[dict[str, Any]] = []
|
|
381
|
+
for row_index in range(len(row_keys)):
|
|
382
|
+
record: dict[str, Any] = {
|
|
383
|
+
key: row_keys.iloc[row_index][key] for key in contract.keys
|
|
384
|
+
}
|
|
385
|
+
confidences: list[str] = []
|
|
386
|
+
for field in contract.value_columns:
|
|
387
|
+
cell = cells[(row_index, field)]
|
|
388
|
+
record[field] = cell.value
|
|
389
|
+
confidences.append(cell.confidence)
|
|
390
|
+
if confidence_column is not None:
|
|
391
|
+
record[confidence_column] = (
|
|
392
|
+
min(confidences, key=lambda item: _CONFIDENCE_ORDER[item])
|
|
393
|
+
if confidences
|
|
394
|
+
else "missing"
|
|
395
|
+
)
|
|
396
|
+
records.append(record)
|
|
397
|
+
|
|
398
|
+
columns = list(contract.columns)
|
|
399
|
+
if confidence_column is not None:
|
|
400
|
+
columns.append(confidence_column)
|
|
401
|
+
data = pd.DataFrame.from_records(records, columns=columns)
|
|
402
|
+
if request.options.sort_by_keys:
|
|
403
|
+
data = data.sort_values(list(contract.keys), kind="stable")
|
|
404
|
+
return data.reset_index(drop=True)
|
|
405
|
+
|
|
406
|
+
def _fingerprint(self, prepared: Sequence[_PreparedFrame], request: MergeRequest) -> str:
|
|
407
|
+
policy = request.policy
|
|
408
|
+
config = {
|
|
409
|
+
"contract": {
|
|
410
|
+
"name": request.contract.name,
|
|
411
|
+
"keys": list(request.contract.keys),
|
|
412
|
+
"columns": list(request.contract.columns),
|
|
413
|
+
},
|
|
414
|
+
"policy": {
|
|
415
|
+
"on_conflict": policy.on_conflict,
|
|
416
|
+
"tolerance": [policy.tolerance.abs, policy.tolerance.rel],
|
|
417
|
+
"comparator": type(policy.comparator or DefaultComparator()).__name__,
|
|
418
|
+
"intra_penalty": policy.intra_penalty,
|
|
419
|
+
"min_lineages_for_consensus": policy.min_lineages_for_consensus,
|
|
420
|
+
"field_policies": {
|
|
421
|
+
name: {
|
|
422
|
+
"weights": dict(item.weights),
|
|
423
|
+
"tolerance": (
|
|
424
|
+
[item.tolerance.abs, item.tolerance.rel]
|
|
425
|
+
if item.tolerance is not None
|
|
426
|
+
else None
|
|
427
|
+
),
|
|
428
|
+
"on_conflict": item.on_conflict,
|
|
429
|
+
}
|
|
430
|
+
for name, item in policy.field_policies.items()
|
|
431
|
+
},
|
|
432
|
+
},
|
|
433
|
+
"options": {
|
|
434
|
+
"confidence_column": request.options.confidence_column,
|
|
435
|
+
"warn_on_missing_column": request.options.warn_on_missing_column,
|
|
436
|
+
"sort_by_keys": request.options.sort_by_keys,
|
|
437
|
+
},
|
|
438
|
+
}
|
|
439
|
+
digest = hashlib.sha256()
|
|
440
|
+
config_bytes = json.dumps(
|
|
441
|
+
config, sort_keys=True, ensure_ascii=False, default=str
|
|
442
|
+
).encode("utf-8")
|
|
443
|
+
digest.update(config_bytes)
|
|
444
|
+
contributions = []
|
|
445
|
+
for frame in prepared:
|
|
446
|
+
content = frame.data.sort_values(
|
|
447
|
+
list(request.contract.keys), kind="stable"
|
|
448
|
+
).to_csv(index=False, na_rep="", float_format="%.17g")
|
|
449
|
+
contributions.append((frame.lineage, frame.name, frame.weight, content))
|
|
450
|
+
for lineage, name, weight, content in sorted(
|
|
451
|
+
contributions, key=lambda item: (item[0], item[1], item[2])
|
|
452
|
+
):
|
|
453
|
+
digest.update(f"\n--{lineage}|{name}|{weight}--\n".encode("utf-8"))
|
|
454
|
+
digest.update(content.encode("utf-8"))
|
|
455
|
+
return digest.hexdigest()
|
|
456
|
+
|
|
457
|
+
def _build_report(
|
|
458
|
+
self,
|
|
459
|
+
request: MergeRequest,
|
|
460
|
+
prepared: Sequence[_PreparedFrame],
|
|
461
|
+
cells: dict[tuple[int, str], _Cell],
|
|
462
|
+
row_keys: pd.DataFrame,
|
|
463
|
+
view: dict[tuple[int, str, str], _Candidate],
|
|
464
|
+
stats: dict[str, Any],
|
|
465
|
+
frame_rows: dict[str, int],
|
|
466
|
+
duplicates: dict[str, int],
|
|
467
|
+
key_counter: Counter,
|
|
468
|
+
warnings: list[str],
|
|
469
|
+
) -> MergeReport:
|
|
470
|
+
contract = request.contract
|
|
471
|
+
frame_unique_rows = {
|
|
472
|
+
frame.name: sum(
|
|
473
|
+
1
|
|
474
|
+
for key_tuple in frame.data[list(contract.keys)].itertuples(
|
|
475
|
+
index=False, name=None
|
|
476
|
+
)
|
|
477
|
+
if key_counter[_hashable_key(key_tuple)] == 1
|
|
478
|
+
)
|
|
479
|
+
for frame in prepared
|
|
480
|
+
}
|
|
481
|
+
lineage_count = {
|
|
482
|
+
field: {
|
|
483
|
+
"max": stats["lineage_max"].get(field, 0),
|
|
484
|
+
"average": (
|
|
485
|
+
stats["lineage_sum"].get(field, 0) / stats["lineage_n"][field]
|
|
486
|
+
if stats["lineage_n"].get(field)
|
|
487
|
+
else 0.0
|
|
488
|
+
),
|
|
489
|
+
}
|
|
490
|
+
for field in contract.value_columns
|
|
491
|
+
}
|
|
492
|
+
intra_conflicts: dict[str, dict[str, int]] = {}
|
|
493
|
+
for field, counter in stats["intra"].items():
|
|
494
|
+
for lineage, count in counter.items():
|
|
495
|
+
intra_conflicts.setdefault(_display_lineage(lineage), {})[field] = count
|
|
496
|
+
field_source_usage = {
|
|
497
|
+
field: {
|
|
498
|
+
_display_lineage(lineage): count
|
|
499
|
+
for lineage, count in counter.items()
|
|
500
|
+
}
|
|
501
|
+
for field, counter in stats["usage"].items()
|
|
502
|
+
}
|
|
503
|
+
conflicts = {
|
|
504
|
+
field: {
|
|
505
|
+
"count": stats["conflict_count"][field],
|
|
506
|
+
"sources": sorted(
|
|
507
|
+
_display_lineage(lineage)
|
|
508
|
+
for lineage in stats["conflict_sources"].get(field, set())
|
|
509
|
+
),
|
|
510
|
+
"strategy": stats["conflict_strategy"].get(field),
|
|
511
|
+
"kind": "inter",
|
|
512
|
+
}
|
|
513
|
+
for field in stats["conflict_count"]
|
|
514
|
+
}
|
|
515
|
+
row_confidences = [
|
|
516
|
+
min(
|
|
517
|
+
(cells[(index, field)].confidence for field in contract.value_columns),
|
|
518
|
+
key=lambda item: _CONFIDENCE_ORDER[item],
|
|
519
|
+
default="missing",
|
|
520
|
+
)
|
|
521
|
+
for index in range(len(row_keys))
|
|
522
|
+
]
|
|
523
|
+
confidence_counts = Counter(row_confidences)
|
|
524
|
+
row_warnings = list(warnings)
|
|
525
|
+
total_conflicts = sum(stats["conflict_count"].values())
|
|
526
|
+
total_intra = sum(sum(counter.values()) for counter in stats["intra"].values())
|
|
527
|
+
if total_conflicts:
|
|
528
|
+
row_warnings.append(f"{total_conflicts} inter-source conflict cells")
|
|
529
|
+
if total_intra:
|
|
530
|
+
row_warnings.append(f"{total_intra} intra-source conflict cells")
|
|
531
|
+
|
|
532
|
+
sources = sorted(
|
|
533
|
+
{_display_lineage(frame.lineage) for frame in prepared},
|
|
534
|
+
key=lambda item: (item == _INDEPENDENT, item),
|
|
535
|
+
)
|
|
536
|
+
return MergeReport(
|
|
537
|
+
rows=len(row_confidences),
|
|
538
|
+
frame_rows=frame_rows,
|
|
539
|
+
frame_unique_rows=frame_unique_rows,
|
|
540
|
+
duplicates_removed=duplicates,
|
|
541
|
+
sources=tuple(sources),
|
|
542
|
+
lineage_count=lineage_count,
|
|
543
|
+
intra_conflicts=intra_conflicts,
|
|
544
|
+
field_source_usage=field_source_usage,
|
|
545
|
+
conflicts=conflicts,
|
|
546
|
+
consensus=dict(stats["consensus"]),
|
|
547
|
+
confidence_counts={
|
|
548
|
+
name: confidence_counts.get(name, 0) for name in _CONFIDENCE_ORDER
|
|
549
|
+
},
|
|
550
|
+
warnings=tuple(row_warnings),
|
|
551
|
+
fingerprint=self._fingerprint(prepared, request),
|
|
552
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Exception hierarchy for darwin-merger."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MergeError(Exception):
|
|
5
|
+
"""Base class for all errors raised by this library."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MergeConfigError(MergeError):
|
|
9
|
+
"""Invalid contract, policy, options or frame declaration."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MergeInputError(MergeError):
|
|
13
|
+
"""Invalid input frame contents, such as a missing key column."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MergeDataError(MergeError):
|
|
17
|
+
"""Input data cannot produce a usable merged result."""
|
darwin_merger/frame.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Input frame: one cleaned DataFrame, its priority and its evidence lineage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from .exceptions import MergeConfigError, MergeInputError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class InputFrame:
|
|
16
|
+
"""A cleaned DataFrame with a priority weight and an optional lineage tag."""
|
|
17
|
+
|
|
18
|
+
name: str
|
|
19
|
+
data: pd.DataFrame
|
|
20
|
+
weight: float = 1.0
|
|
21
|
+
source_id: str | None = None
|
|
22
|
+
|
|
23
|
+
def __post_init__(self) -> None:
|
|
24
|
+
if not isinstance(self.name, str) or not self.name:
|
|
25
|
+
raise MergeConfigError("frame name must be a non-empty string")
|
|
26
|
+
if not isinstance(self.data, pd.DataFrame):
|
|
27
|
+
raise MergeInputError(f"frame {self.name!r} data must be a pandas DataFrame")
|
|
28
|
+
try:
|
|
29
|
+
weight = float(self.weight)
|
|
30
|
+
except (TypeError, ValueError) as exc:
|
|
31
|
+
raise MergeConfigError(f"frame {self.name!r} weight must be a number") from exc
|
|
32
|
+
if not math.isfinite(weight) or weight < 0:
|
|
33
|
+
raise MergeConfigError(
|
|
34
|
+
f"frame {self.name!r} weight must be finite and non-negative"
|
|
35
|
+
)
|
|
36
|
+
object.__setattr__(self, "weight", weight)
|
|
37
|
+
source_id: Any = self.source_id
|
|
38
|
+
if source_id is not None:
|
|
39
|
+
if not isinstance(source_id, str) or not source_id.strip():
|
|
40
|
+
raise MergeConfigError(
|
|
41
|
+
f"frame {self.name!r} source_id must be a non-empty string or None"
|
|
42
|
+
)
|
|
43
|
+
source_id = source_id.strip()
|
|
44
|
+
object.__setattr__(self, "source_id", source_id)
|
darwin_merger/policy.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Merge policies: global conflict handling plus per-field overrides."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from types import MappingProxyType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .comparator import Tolerance, ValueComparator
|
|
12
|
+
from .exceptions import MergeConfigError
|
|
13
|
+
|
|
14
|
+
CONFLICT_POLICIES = frozenset(
|
|
15
|
+
{"take_priority", "take_priority_and_flag", "null_if_conflict"}
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _weight(value: Any, field: str) -> float:
|
|
20
|
+
try:
|
|
21
|
+
number = float(value)
|
|
22
|
+
except (TypeError, ValueError) as exc:
|
|
23
|
+
raise MergeConfigError(f"{field} must be a number, got {value!r}") from exc
|
|
24
|
+
if not math.isfinite(number) or number < 0:
|
|
25
|
+
raise MergeConfigError(f"{field} must be finite and non-negative, got {value!r}")
|
|
26
|
+
return number
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class FieldPolicy:
|
|
31
|
+
"""Per-column overrides composed on top of the global merge policy."""
|
|
32
|
+
|
|
33
|
+
weights: Mapping[str, float] = field(default_factory=dict)
|
|
34
|
+
tolerance: Tolerance | None = None
|
|
35
|
+
on_conflict: str | None = None
|
|
36
|
+
|
|
37
|
+
def __post_init__(self) -> None:
|
|
38
|
+
if not isinstance(self.weights, Mapping):
|
|
39
|
+
raise MergeConfigError("FieldPolicy.weights must be a mapping")
|
|
40
|
+
normalized = {}
|
|
41
|
+
for lineage, weight in self.weights.items():
|
|
42
|
+
if not isinstance(lineage, str) or not lineage:
|
|
43
|
+
raise MergeConfigError(f"invalid lineage key in weights: {lineage!r}")
|
|
44
|
+
normalized[lineage] = _weight(weight, f"weights[{lineage!r}]")
|
|
45
|
+
object.__setattr__(self, "weights", MappingProxyType(normalized))
|
|
46
|
+
if self.tolerance is not None and not isinstance(self.tolerance, Tolerance):
|
|
47
|
+
raise MergeConfigError("FieldPolicy.tolerance must be a Tolerance instance")
|
|
48
|
+
if self.on_conflict is not None and self.on_conflict not in CONFLICT_POLICIES:
|
|
49
|
+
raise MergeConfigError(
|
|
50
|
+
f"unknown conflict policy {self.on_conflict!r}; "
|
|
51
|
+
f"expected one of {sorted(CONFLICT_POLICIES)}"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class MergePolicy:
|
|
57
|
+
"""Conflict strategy, comparator, tolerance and lineage reliability settings."""
|
|
58
|
+
|
|
59
|
+
on_conflict: str = "take_priority_and_flag"
|
|
60
|
+
tolerance: Tolerance = field(default_factory=Tolerance)
|
|
61
|
+
comparator: ValueComparator | None = None
|
|
62
|
+
field_policies: Mapping[str, FieldPolicy] = field(default_factory=dict)
|
|
63
|
+
intra_penalty: float = 0.5
|
|
64
|
+
min_lineages_for_consensus: int = 2
|
|
65
|
+
|
|
66
|
+
def __post_init__(self) -> None:
|
|
67
|
+
if self.on_conflict not in CONFLICT_POLICIES:
|
|
68
|
+
raise MergeConfigError(
|
|
69
|
+
f"unknown conflict policy {self.on_conflict!r}; "
|
|
70
|
+
f"expected one of {sorted(CONFLICT_POLICIES)}"
|
|
71
|
+
)
|
|
72
|
+
if not isinstance(self.tolerance, Tolerance):
|
|
73
|
+
raise MergeConfigError("policy.tolerance must be a Tolerance instance")
|
|
74
|
+
if self.comparator is not None and not callable(
|
|
75
|
+
getattr(self.comparator, "equal", None)
|
|
76
|
+
):
|
|
77
|
+
raise MergeConfigError("comparator must provide an equal(a, b, tolerance) method")
|
|
78
|
+
if not isinstance(self.field_policies, Mapping):
|
|
79
|
+
raise MergeConfigError("field_policies must be a mapping")
|
|
80
|
+
for name, policy in self.field_policies.items():
|
|
81
|
+
if not isinstance(name, str) or not name:
|
|
82
|
+
raise MergeConfigError(f"invalid field policy column name: {name!r}")
|
|
83
|
+
if not isinstance(policy, FieldPolicy):
|
|
84
|
+
raise MergeConfigError(f"field policy for {name!r} must be a FieldPolicy")
|
|
85
|
+
object.__setattr__(self, "field_policies", MappingProxyType(dict(self.field_policies)))
|
|
86
|
+
object.__setattr__(
|
|
87
|
+
self, "intra_penalty", _weight(self.intra_penalty, "intra_penalty")
|
|
88
|
+
)
|
|
89
|
+
if not 0 < self.intra_penalty <= 1:
|
|
90
|
+
raise MergeConfigError("intra_penalty must be in (0, 1]")
|
|
91
|
+
if (
|
|
92
|
+
not isinstance(self.min_lineages_for_consensus, int)
|
|
93
|
+
or isinstance(self.min_lineages_for_consensus, bool)
|
|
94
|
+
or self.min_lineages_for_consensus < 2
|
|
95
|
+
):
|
|
96
|
+
raise MergeConfigError("min_lineages_for_consensus must be an integer >= 2")
|
darwin_merger/request.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Request and options value objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from .contract import MergeContract
|
|
8
|
+
from .exceptions import MergeConfigError
|
|
9
|
+
from .frame import InputFrame
|
|
10
|
+
from .policy import MergePolicy
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class MergeOptions:
|
|
15
|
+
"""Output-shaping options that do not change value arbitration."""
|
|
16
|
+
|
|
17
|
+
confidence_column: str | None = "_confidence"
|
|
18
|
+
warn_on_missing_column: bool = True
|
|
19
|
+
sort_by_keys: bool = True
|
|
20
|
+
|
|
21
|
+
def __post_init__(self) -> None:
|
|
22
|
+
if self.confidence_column is not None and (
|
|
23
|
+
not isinstance(self.confidence_column, str) or not self.confidence_column
|
|
24
|
+
):
|
|
25
|
+
raise MergeConfigError(
|
|
26
|
+
"confidence_column must be a non-empty string or None"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class MergeRequest:
|
|
32
|
+
"""All inputs and policies needed for one merge call."""
|
|
33
|
+
|
|
34
|
+
frames: tuple[InputFrame, ...]
|
|
35
|
+
contract: MergeContract
|
|
36
|
+
policy: MergePolicy = field(default_factory=MergePolicy)
|
|
37
|
+
options: MergeOptions = field(default_factory=MergeOptions)
|
|
38
|
+
|
|
39
|
+
def __post_init__(self) -> None:
|
|
40
|
+
object.__setattr__(self, "frames", tuple(self.frames))
|
|
41
|
+
if not self.frames:
|
|
42
|
+
raise MergeConfigError("at least one input frame is required")
|
|
43
|
+
if not isinstance(self.contract, MergeContract):
|
|
44
|
+
raise MergeConfigError("contract must be a MergeContract")
|
|
45
|
+
if not isinstance(self.policy, MergePolicy):
|
|
46
|
+
raise MergeConfigError("policy must be a MergePolicy")
|
|
47
|
+
if not isinstance(self.options, MergeOptions):
|
|
48
|
+
raise MergeConfigError("options must be a MergeOptions")
|
|
49
|
+
|
|
50
|
+
names = [frame.name for frame in self.frames]
|
|
51
|
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
|
52
|
+
if duplicates:
|
|
53
|
+
raise MergeConfigError(f"duplicate frame names: {duplicates}")
|
|
54
|
+
|
|
55
|
+
confidence_column = self.options.confidence_column
|
|
56
|
+
if confidence_column and confidence_column in self.contract.columns:
|
|
57
|
+
raise MergeConfigError(
|
|
58
|
+
f"confidence column {confidence_column!r} collides with contract columns"
|
|
59
|
+
)
|
|
60
|
+
unknown_fields = [
|
|
61
|
+
name
|
|
62
|
+
for name in self.policy.field_policies
|
|
63
|
+
if name not in self.contract.value_columns
|
|
64
|
+
]
|
|
65
|
+
if unknown_fields:
|
|
66
|
+
raise MergeConfigError(f"field policies target unknown columns: {unknown_fields}")
|
darwin_merger/results.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Merge output and auditable report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass
|
|
6
|
+
from typing import Any, Mapping
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _jsonable(value: Any) -> Any:
|
|
12
|
+
if isinstance(value, Mapping):
|
|
13
|
+
return {str(key): _jsonable(item) for key, item in value.items()}
|
|
14
|
+
if isinstance(value, (list, tuple)):
|
|
15
|
+
return [_jsonable(item) for item in value]
|
|
16
|
+
return value
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class MergeReport:
|
|
21
|
+
"""Serializable audit record for one merge call."""
|
|
22
|
+
|
|
23
|
+
rows: int
|
|
24
|
+
frame_rows: Mapping[str, int]
|
|
25
|
+
frame_unique_rows: Mapping[str, int]
|
|
26
|
+
duplicates_removed: Mapping[str, int]
|
|
27
|
+
sources: tuple[str, ...]
|
|
28
|
+
lineage_count: Mapping[str, Mapping[str, float]]
|
|
29
|
+
intra_conflicts: Mapping[str, Mapping[str, int]]
|
|
30
|
+
field_source_usage: Mapping[str, Mapping[str, int]]
|
|
31
|
+
conflicts: Mapping[str, Mapping[str, Any]]
|
|
32
|
+
consensus: Mapping[str, int]
|
|
33
|
+
confidence_counts: Mapping[str, int]
|
|
34
|
+
warnings: tuple[str, ...]
|
|
35
|
+
fingerprint: str
|
|
36
|
+
|
|
37
|
+
def to_dict(self) -> dict[str, Any]:
|
|
38
|
+
"""Return a JSON-friendly nested dictionary."""
|
|
39
|
+
return _jsonable(asdict(self))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class MergeResult:
|
|
44
|
+
"""Merged DataFrame plus its audit report."""
|
|
45
|
+
|
|
46
|
+
data: pd.DataFrame
|
|
47
|
+
report: MergeReport
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: darwin-merger
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Business-free engine that merges cleaned DataFrames into one trustworthy dataset with confidence and audit report
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: pandas>=2.0
|
|
10
|
+
Provides-Extra: test
|
|
11
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# darwin-merger
|
|
15
|
+
|
|
16
|
+
[English](README.md) · [简体中文](README.cn.md)
|
|
17
|
+
|
|
18
|
+
An in-memory engine that merges multiple already-cleaned DataFrames into one more trustworthy dataset. It is the business-free core extracted from the `select` stage of darwin-fetch: align rows on a declared key, complement missing rows and columns, reduce evidence within each source lineage, arbitrate across lineages with an explicit policy, and attach a confidence field.
|
|
19
|
+
|
|
20
|
+
**Status: v0.3 design frozen, implementation in progress.**
|
|
21
|
+
|
|
22
|
+
## Scope
|
|
23
|
+
|
|
24
|
+
| In the library | Outside (caller's responsibility) |
|
|
25
|
+
|---|---|
|
|
26
|
+
| Two-phase merge: intra-source evidence reduction, then inter-source arbitration | Discovering files, reading parquet, time-slice caches |
|
|
27
|
+
| Optional `source_id` lineage tags; independent corroboration counting | Loading `selector.json` / `select.d` / `clean.d` |
|
|
28
|
+
| Frame weights, per-field per-lineage weight overrides, three conflict policies | Date filtering, trading calendars, symbol normalization |
|
|
29
|
+
| Configurable numeric tolerance and value comparator | Writing parquet/manifest/done, CLI, exit codes, scheduling |
|
|
30
|
+
| Data + confidence column + serializable report with content fingerprint | Derived fields, formulas, `expect_zero` (excluded by decision) |
|
|
31
|
+
|
|
32
|
+
Frames carry an optional `source_id`. Frames sharing a lineage are merged first and their internal disagreement downweights that source for the field; frames from distinct lineages are independent witnesses, and at least two are required for a high-confidence consensus. Duplicate rows inside one frame keep the first row and are counted in the report.
|
|
33
|
+
|
|
34
|
+
## Quick start
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import pandas as pd
|
|
38
|
+
from darwin_merger import (
|
|
39
|
+
MergeEngine, MergeRequest, MergeContract, InputFrame,
|
|
40
|
+
MergePolicy, FieldPolicy, Tolerance, MergeOptions,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
contract = MergeContract(
|
|
44
|
+
name="stk_ohlcv",
|
|
45
|
+
keys=("symbol", "trade_date"),
|
|
46
|
+
columns=("symbol", "trade_date", "close", "volume"),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
a = pd.DataFrame({"symbol": ["A"], "trade_date": ["2026-01-02"], "close": [10.0], "volume": [100]})
|
|
50
|
+
b = pd.DataFrame({"symbol": ["A"], "trade_date": ["2026-01-02"], "close": [10.01], "volume": [120]})
|
|
51
|
+
c = pd.DataFrame({"symbol": ["A"], "trade_date": ["2026-01-02"], "close": [9.8], "volume": [110]})
|
|
52
|
+
|
|
53
|
+
result = MergeEngine().merge(MergeRequest(
|
|
54
|
+
frames=[
|
|
55
|
+
InputFrame("tushare_a", a, weight=1.0, source_id="tushare"),
|
|
56
|
+
InputFrame("tushare_b", b, weight=0.9, source_id="tushare"),
|
|
57
|
+
InputFrame("baostock_a", c, weight=0.8, source_id="baostock"),
|
|
58
|
+
],
|
|
59
|
+
contract=contract,
|
|
60
|
+
policy=MergePolicy(
|
|
61
|
+
on_conflict="take_priority_and_flag",
|
|
62
|
+
tolerance=Tolerance(abs=0.01, rel=1e-4),
|
|
63
|
+
field_policies={"volume": FieldPolicy(weights={"baostock": 1.2})},
|
|
64
|
+
),
|
|
65
|
+
options=MergeOptions(confidence_column="_confidence"),
|
|
66
|
+
))
|
|
67
|
+
|
|
68
|
+
df = result.data # contract.columns + "_confidence"
|
|
69
|
+
report = result.report.to_dict()
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Documentation
|
|
73
|
+
|
|
74
|
+
- [Design document](docs/design.md) — boundaries, evidence semantics, confidence model, API sketch, confirmed decisions.
|
|
75
|
+
- [Select-stage code walkthrough](docs/select-stage-code-walkthrough.md) — source-level record of the code being generalized.
|
|
76
|
+
|
|
77
|
+
Chinese versions: [设计文档](docs/design.cn.md) · [Select 阶段代码梳理](docs/select-stage-code-walkthrough.cn.md).
|
|
78
|
+
|
|
79
|
+
Python >= 3.10.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
darwin_merger/__init__.py,sha256=qKP82EYzv3vHCrovf4_DdCr7beb-Um1Xw4UFVWDoxXI,864
|
|
2
|
+
darwin_merger/comparator.py,sha256=aydiD_n79KuNfgr1AM1uMX9VruCYPAbCFDVE1Sfl-Xc,2696
|
|
3
|
+
darwin_merger/contract.py,sha256=xhVchdfuyxgZMirHdTj9ZBInaAxj2lge-1TEajtcqJo,2044
|
|
4
|
+
darwin_merger/engine.py,sha256=E2NJB8WmcHLSO3K8rl36Sq2RspoMlOc4OkPQaAFnzAw,22369
|
|
5
|
+
darwin_merger/exceptions.py,sha256=jXK7MP23gyd1FDEBJ2I7R24ITLM8FuGvV3NOk9BRK2w,443
|
|
6
|
+
darwin_merger/frame.py,sha256=GaW0RylRJW6zr6mMQb_0f6MZZOs1LXwBNRFAh90SU64,1618
|
|
7
|
+
darwin_merger/policy.py,sha256=6L9MaTHCvYP8AV-cX63LFsfRiAvaQS95lNWsKzOv6-E,4203
|
|
8
|
+
darwin_merger/request.py,sha256=czSop5IjAJ3Z7i1p8HFHHQg5tbPhZa5t8myq38dEcQ8,2468
|
|
9
|
+
darwin_merger/results.py,sha256=79M1lXIOWwYHUw5s0uZnL14sNDNIbIenhhNbjtKQHvI,1303
|
|
10
|
+
darwin_merger-0.1.0.dist-info/licenses/LICENSE,sha256=Jv2rYe7HuP4ueMkCFHFFWd9J4Cp6zKPZAi9VQWomW74,1068
|
|
11
|
+
darwin_merger-0.1.0.dist-info/METADATA,sha256=O2uuN7Uqja3k8Sh8y0ZQdZXQIKFiS6ZD4unbD1NaGuE,3790
|
|
12
|
+
darwin_merger-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
darwin_merger-0.1.0.dist-info/top_level.txt,sha256=RWa_K7O4CTPhOMTj35_qFug_GfXmBq8YzUCkmM_5IIs,14
|
|
14
|
+
darwin_merger-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 darwinalpha
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
darwin_merger
|