darwin-merger 0.1.0__tar.gz

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.
@@ -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,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,66 @@
1
+ # darwin-merger
2
+
3
+ [English](README.md) · [简体中文](README.cn.md)
4
+
5
+ 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.
6
+
7
+ **Status: v0.3 design frozen, implementation in progress.**
8
+
9
+ ## Scope
10
+
11
+ | In the library | Outside (caller's responsibility) |
12
+ |---|---|
13
+ | Two-phase merge: intra-source evidence reduction, then inter-source arbitration | Discovering files, reading parquet, time-slice caches |
14
+ | Optional `source_id` lineage tags; independent corroboration counting | Loading `selector.json` / `select.d` / `clean.d` |
15
+ | Frame weights, per-field per-lineage weight overrides, three conflict policies | Date filtering, trading calendars, symbol normalization |
16
+ | Configurable numeric tolerance and value comparator | Writing parquet/manifest/done, CLI, exit codes, scheduling |
17
+ | Data + confidence column + serializable report with content fingerprint | Derived fields, formulas, `expect_zero` (excluded by decision) |
18
+
19
+ 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.
20
+
21
+ ## Quick start
22
+
23
+ ```python
24
+ import pandas as pd
25
+ from darwin_merger import (
26
+ MergeEngine, MergeRequest, MergeContract, InputFrame,
27
+ MergePolicy, FieldPolicy, Tolerance, MergeOptions,
28
+ )
29
+
30
+ contract = MergeContract(
31
+ name="stk_ohlcv",
32
+ keys=("symbol", "trade_date"),
33
+ columns=("symbol", "trade_date", "close", "volume"),
34
+ )
35
+
36
+ a = pd.DataFrame({"symbol": ["A"], "trade_date": ["2026-01-02"], "close": [10.0], "volume": [100]})
37
+ b = pd.DataFrame({"symbol": ["A"], "trade_date": ["2026-01-02"], "close": [10.01], "volume": [120]})
38
+ c = pd.DataFrame({"symbol": ["A"], "trade_date": ["2026-01-02"], "close": [9.8], "volume": [110]})
39
+
40
+ result = MergeEngine().merge(MergeRequest(
41
+ frames=[
42
+ InputFrame("tushare_a", a, weight=1.0, source_id="tushare"),
43
+ InputFrame("tushare_b", b, weight=0.9, source_id="tushare"),
44
+ InputFrame("baostock_a", c, weight=0.8, source_id="baostock"),
45
+ ],
46
+ contract=contract,
47
+ policy=MergePolicy(
48
+ on_conflict="take_priority_and_flag",
49
+ tolerance=Tolerance(abs=0.01, rel=1e-4),
50
+ field_policies={"volume": FieldPolicy(weights={"baostock": 1.2})},
51
+ ),
52
+ options=MergeOptions(confidence_column="_confidence"),
53
+ ))
54
+
55
+ df = result.data # contract.columns + "_confidence"
56
+ report = result.report.to_dict()
57
+ ```
58
+
59
+ ## Documentation
60
+
61
+ - [Design document](docs/design.md) — boundaries, evidence semantics, confidence model, API sketch, confirmed decisions.
62
+ - [Select-stage code walkthrough](docs/select-stage-code-walkthrough.md) — source-level record of the code being generalized.
63
+
64
+ Chinese versions: [设计文档](docs/design.cn.md) · [Select 阶段代码梳理](docs/select-stage-code-walkthrough.cn.md).
65
+
66
+ Python >= 3.10.
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "darwin-merger"
7
+ version = "0.1.0"
8
+ description = "Business-free engine that merges cleaned DataFrames into one trustworthy dataset with confidence and audit report"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = [
14
+ "pandas>=2.0",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest>=8"]
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
22
+
23
+ [tool.pytest.ini_options]
24
+ testpaths = ["tests"]
25
+ pythonpath = ["src"]
26
+ addopts = "-q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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)