Metadata-Version: 2.4
Name: dual-water-tank-mcp
Version: 0.1.1
Summary: Dual water tank lithium-ion full-cell model fitting tools and a lightweight MCP server.
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        "License" shall mean the terms and conditions for use, reproduction,
        and distribution as defined by Sections 1 through 9 of this document.
        
        "Licensor" shall mean the copyright owner or entity authorized by
        the copyright owner that is granting the License.
        
        "Legal Entity" shall mean the union of the acting entity and all
        other entities that control, are controlled by, or are under common
        control with that entity. For the purposes of this definition,
        "control" means (i) the power, direct or indirect, to cause the
        direction or management of such entity, whether by contract or
        otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.
        
        "You" (or "Your") shall mean an individual or Legal Entity
        exercising permissions granted by this License.
        
        "Source" form shall mean the preferred form for making modifications,
        including but not limited to software source code, documentation
        source, and configuration files.
        
        "Object" form shall mean any form resulting from mechanical
        transformation or translation of a Source form, including but
        not limited to compiled object code, generated documentation,
        and conversions to other media types.
        
        "Work" shall mean the work of authorship, whether in Source or
        Object form, made available under the License, as indicated by a
        copyright notice that is included in or attached to the work
        (an example is provided in the Appendix below).
        
        "Derivative Works" shall mean any work, whether in Source or Object
        form, that is based on (or derived from) the Work and for which the
        editorial revisions, annotations, elaborations, or other modifications
        represent, as a whole, an original work of authorship. For the purposes
        of this License, Derivative Works shall not include works that remain
        separable from, or merely link (or bind by name) to the interfaces of,
        the Work and Derivative Works thereof.
        
        "Contribution" shall mean any work of authorship, including
        the original version of the Work and any modifications or additions
        to that Work or Derivative Works thereof, that is intentionally
        submitted to Licensor for inclusion in the Work by the copyright owner
        or by an individual or Legal Entity authorized to submit on behalf of
        the copyright owner. For the purposes of this definition, "submitted"
        means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems,
        and issue tracking systems that are managed by, or on behalf of, the
        Licensor for the purpose of discussing and improving the Work, but
        excluding communication that is conspicuously marked or otherwise
        designated in writing by the copyright owner as "Not a Contribution."
        
        "Contributor" shall mean Licensor and any individual or Legal Entity
        on behalf of whom a Contribution has been received by Licensor and
        subsequently incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        copyright license to reproduce, prepare Derivative Works of,
        publicly display, publicly perform, sublicense, and distribute the
        Work and such Derivative Works in Source or Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        (except as stated in this section) patent license to make, have made,
        use, offer to sell, sell, import, and otherwise transfer the Work,
        where such license applies only to those patent claims licensable
        by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s)
        with the Work to which such Contribution(s) was submitted. If You
        institute patent litigation against any entity (including a
        cross-claim or counterclaim in a lawsuit) alleging that the Work
        or a Contribution incorporated within the Work constitutes direct
        or contributory patent infringement, then any patent licenses
        granted to You under this License for that Work shall terminate
        as of the date such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the
        Work or Derivative Works thereof in any medium, with or without
        modifications, and in Source or Object form, provided that You
        meet the following conditions:
        
        (a) You must give any other recipients of the Work or
            Derivative Works a copy of this License; and
        
        (b) You must cause any modified files to carry prominent notices
            stating that You changed the files; and
        
        (c) You must retain, in the Source form of any Derivative Works
            that You distribute, all copyright, patent, trademark, and
            attribution notices from the Source form of the Work,
            excluding those notices that do not pertain to any part of
            the Derivative Works; and
        
        (d) If the Work includes a "NOTICE" text file as part of its
            distribution, then any Derivative Works that You distribute must
            include a readable copy of the attribution notices contained
            within such NOTICE file, excluding those notices that do not
            pertain to any part of the Derivative Works, in at least one
            of the following places: within a NOTICE text file distributed
            as part of the Derivative Works; within the Source form or
            documentation, if provided along with the Derivative Works; or,
            within a display generated by the Derivative Works, if and
            wherever such third-party notices normally appear. The contents
            of the NOTICE file are for informational purposes only and
            do not modify the License. You may add Your own attribution
            notices within Derivative Works that You distribute, alongside
            or as an addendum to the NOTICE text from the Work, provided
            that such additional attribution notices cannot be construed
            as modifying the License.
        
        You may add Your own copyright statement to Your modifications and
        may provide additional or different license terms and conditions
        for use, reproduction, or distribution of Your modifications, or
        for any such Derivative Works as a whole, provided Your use,
        reproduction, and distribution of the Work otherwise complies with
        the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise,
        any Contribution intentionally submitted for inclusion in the Work
        by You to the Licensor shall be under the terms and conditions of
        this License, without any additional terms or conditions.
        Notwithstanding the above, nothing herein shall supersede or modify
        the terms of any separate license agreement you may have executed
        with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade
        names, trademarks, service marks, or product names of the Licensor,
        except as required for reasonable and customary use in describing the
        origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or
        agreed to in writing, Licensor provides the Work (and each
        Contributor provides its Contributions) on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        implied, including, without limitation, any warranties or conditions
        of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any
        risks associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory,
        whether in tort (including negligence), contract, or otherwise,
        unless required by applicable law (such as deliberate and grossly
        negligent acts) or agreed to in writing, shall any Contributor be
        liable to You for damages, including any direct, indirect, special,
        incidental, or consequential damages of any character arising as a
        result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill,
        work stoppage, computer failure or malfunction, or any and all
        other commercial damages or losses), even if such Contributor
        has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Additional Liability. While redistributing
        the Work or Derivative Works thereof, You may choose to offer,
        and charge a fee for, acceptance of support, warranty, indemnity,
        or other liability obligations and/or rights consistent with this
        License. However, in accepting such obligations, You may act only
        on Your own behalf and on Your sole responsibility, not on behalf
        of any other Contributor, and only if You agree to indemnify,
        defend, and hold each Contributor harmless for any liability
        incurred by, or claims asserted against, such Contributor by reason
        of your accepting any such warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
        To apply the Apache License to your work, attach the following
        boilerplate notice, with the fields enclosed by brackets "[]"
        replaced with your own identifying information. (Don't include
        the brackets!) The text should be enclosed in the appropriate
        comment syntax for the file format. We also recommend that a
        file or class name and description of purpose be included on the
        same "printed page" as the copyright notice for easier
        identification within third-party archives.
        
        Copyright [yyyy] [name of copyright owner]
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
            http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
        
Keywords: battery,lithium-ion,dual-water-tank,mcp,model-context-protocol
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy
Requires-Dist: pandas
Requires-Dist: openpyxl
Requires-Dist: xlrd
Dynamic: license-file

# Dual Water Tank MCP for Battery Aging Mechanism Identification

<!-- mcp-name: io.github.ZidingWang/dual-water-tank-aging-identification-mcp -->

[English](#dual-water-tank-mcp-for-battery-aging-mechanism-identification) | [中文](#dual-water-tank-mcp-for-battery-aging-mechanism-identification-中文)

This project is an MCP server for fitting a lithium-ion full-cell dual-water-tank model from charge/discharge voltage-capacity data. It is designed for battery aging mechanism identification, including parameter fitting, charge/discharge sign handling, capacity-bound adaptation, and batch processing.

The project keeps a two-layer structure:

- `dual_water_tank_mcp/`: core model code, including data loading, column detection, charge/discharge detection, model calculation, GA fitting, batch output, and CLI.
- `dual_water_tank_mcp/server.py`: a thin MCP interface layer that exposes the core functions as MCP tools.

If you need to fix or improve the model later, edit the core code under `dual_water_tank_mcp/`, then restart the MCP server.

## Dual-Water-Tank Model

<img src="references/figures/dual-water-tank-model.png" width="480" alt="Dual-water-tank model showing the positive and negative electrodes as connected tanks">

*Figure 3. Water-tank analogy for the positive and negative electrodes.*

<img src="references/figures/dual-water-tank-voltage-fit.png" width="700" alt="Measured and simulated voltage–capacity curves for a graphite/LFP cell when fresh and after 330, 690, and 1,020 cycles">

*Figure 10. Measured and simulated voltage–capacity curves for a graphite/LFP cell at (a) 0, (b) 330, (c) 690, and (d) 1,020 cycles.*

Both figures are from [Han et al., Journal of Power Sources 251 (2014), 38–54](https://doi.org/10.1016/j.jpowsour.2013.11.029).

## Features

- Reads `.xlsx`, `.xls`, `.csv`, `.txt`, and `.tsv` battery test data.
- Automatically detects voltage and capacity columns.
- Automatically detects charge or discharge from the voltage trend.
- Applies charge/discharge signs for electrode stoichiometry `y` and `x`.
- Automatically tests both `+I*R` and `-I*R`, then keeps the lower-RMSE result.
- Automatically adapts GA capacity bounds from the dataset capacity span.
- Supports single-file fitting and batch fitting.
- Writes final results to a desktop output folder by default.
- Runs as an MCP server with ready-to-call tools.

## Quick start without cloning

Install [uv](https://docs.astral.sh/uv/getting-started/installation/) once, then start the local STDIO MCP server:

```bash
uvx --from "git+https://github.com/ZidingWang/LIB-dual-water-tank-aging-identification-mcp.git" dual-water-tank-mcp
```

For a JSON-based MCP client (Windows/macOS/Linux), use:

```json
{
  "mcpServers": {
    "dual-water-tank-model": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/ZidingWang/LIB-dual-water-tank-aging-identification-mcp.git", "dual-water-tank-mcp"]
    }
  }
}
```

For Codex, use:

```toml
[mcp_servers.dual-water-tank-model]
command = "uvx"
args = ["--from", "git+https://github.com/ZidingWang/LIB-dual-water-tank-aging-identification-mcp.git", "dual-water-tank-mcp"]
startup_timeout_sec = 180
tool_timeout_sec = 3600
```

The first run installs dependencies; when started in a terminal, the STDIO server waits for MCP requests. The client needs access to `uvx` on its PATH. For reproducible use, append `@<commit-sha>` to the Git URL. For installed packages, provide absolute paths to your own full-cell data and both electrode OCV files (`anode_path`, `cathode_path`). The source checkout's test-case files are not included in distributed packages. The preview tool only needs the full-cell data.

## From GitHub To Installation (source checkout)

Clone the repository:

```powershell
git clone <your GitHub repository URL>
cd dual-water-tank-mcp
```

If you already have the source code locally, enter the project root directly, for example:

```powershell
cd "D:\desktop\PSG\1.1 github\dual-water-tank-mcp"
```

Python 3.10 or newer is required. Git is also recommended.

Check:

```powershell
python --version
git --version
```

You can use the bundled one-click MCP launcher. On first run, it creates `.venv` and installs dependencies:

```powershell
.\run_mcp.cmd
```

The same launcher is what MCP clients should call. Users do not need to edit model code, Python files, or MCP server code.

Command-line preview example:

```powershell
.\dual-water-tank.cmd preview "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

Command-line fitting example:

```powershell
.\dual-water-tank.cmd fit "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

## Start MCP

Add this project as an MCP server in Codex, Claude Desktop, Claude Code, or another MCP client.

Windows MCP configuration:

```json
{
  "mcpServers": {
    "dual-water-tank-model": {
      "command": "C:\\path\\to\\dual-water-tank-mcp\\run_mcp.cmd",
      "args": []
    }
  }
}
```

macOS/Linux MCP configuration:

```json
{
  "mcpServers": {
    "dual-water-tank-model": {
      "command": "/path/to/dual-water-tank-mcp/run_mcp.sh",
      "args": []
    }
  }
}
```

On macOS/Linux, make the scripts executable once:

```bash
chmod +x run_mcp.sh dual-water-tank.sh
```

Reusable config examples are also provided:

- `examples/mcp_config_windows.json`
- `examples/mcp_config_macos_linux.json`

After configuring the client, refresh or restart the MCP connection. If `dual-water-tank-model` appears as an available MCP server, the connection is ready.

## How To Use After MCP Is Connected

Once connected, you do not need to manually run Python or command-line scripts. Ask your MCP client to call the tools exposed by this project.

Recommended workflow:

1. If the input format is uncertain, call `preview_dual_water_tank_data` first.
2. For one file, call `fit_dual_water_tank`.
3. For many files, call `batch_fit_dual_water_tank`.
4. Open `result.json`, `fitted_curve.csv`, or `batch_summary.csv` in the desktop output folder.

By default, final results are written to the desktop:

```text
Desktop/dual water tank output/run_YYYYMMDD_HHMMSS/
```

On this author's Windows machine, the default desktop path is usually:

```text
D:\desktop\dual water tank output\
```

The MCP response also includes output paths such as `output_dir`, `curve_csv`, and `result_json`.

Example user requests:

```text
Use the dual-water-tank MCP to preview test_cases/25C_0.1C/25C_0.1C.xlsx.
```

```text
Use the dual-water-tank MCP to fit test_cases/25C_0.1C/25C_0.1C.xlsx and save the final result to the desktop.
```

```text
Use the dual-water-tank MCP to batch fit all Excel files in D:\my_battery_data.
Write the final results to the desktop dual water tank output folder.
```

```text
Use the dual-water-tank MCP to fit D:\data\cell.xlsx.
Use D:\data\anode.txt as anode_path and D:\data\cathode.txt as cathode_path.
Automatically detect charge/discharge direction and I*R sign.
```

## MCP Tools

The server exposes these tools:

- `preview_dual_water_tank_data`: preview one dataset and return inferred columns, charge/discharge direction, capacity span, voltage range, and current estimate.
- `fit_dual_water_tank`: fit one file or one workbook sheet and write `result.json` plus `fitted_curve.csv`.
- `batch_fit_dual_water_tank`: fit all supported files in a folder, or fit a supplied file list, and write per-file outputs plus batch summaries.

## Tool Examples

Example MCP call for `preview_dual_water_tank_data`:

```json
{
  "data_file": "test_cases/25C_0.1C/25C_0.1C.xlsx"
}
```

Example MCP call for `fit_dual_water_tank`:

```json
{
  "data_file": "test_cases/25C_0.1C/25C_0.1C.xlsx",
  "direction": "auto",
  "resistance_sign": "auto"
}
```

Optional inputs for `fit_dual_water_tank`:

```json
{
  "data_file": "D:/data/cell.xlsx",
  "anode_path": "D:/data/anode.txt",
  "cathode_path": "D:/data/cathode.txt",
  "current": 65,
  "direction": "auto",
  "resistance_sign": "auto",
  "voltage_col": "B",
  "capacity_col": "C",
  "output_dir": "D:/desktop/dual water tank output/my_run"
}
```

Example MCP call for `batch_fit_dual_water_tank`:

```json
{
  "input_dir": "D:/my_battery_data",
  "direction": "auto",
  "resistance_sign": "auto"
}
```

## Model Sign Convention

The model keeps the original five parameters:

```text
[y0, Cp, x0, Cn, R]
```

Charge:

```text
y = y0 - Q / Cp
x = x0 + Q / Cn
V = Upos(y) - Uneg(x) + I * R
```

Discharge:

```text
y = y0 + Q / Cp
x = x0 - Q / Cn
V = Upos(y) - Uneg(x) - I * R
```

`I` is treated as a positive current magnitude. By default, `resistance_sign` is `auto`, so the tool fits both `+I*R` and `-I*R` for the detected direction and keeps the lower full-data RMSE. The selected sign and both candidate RMSE values are written to `resistance_sign_selection` in `result.json`.

Available resistance-sign modes:

```text
auto | physics | positive | negative | matlab
```

- `auto`: fit both `+I*R` and `-I*R`, then choose the lower full-data RMSE.
- `physics`: charge uses `+I*R`; discharge uses `-I*R`.
- `positive`: force `+I*R`.
- `negative`: force `-I*R`.
- `matlab`: always use `+I*R`, matching the executed objective function in the original MATLAB file.

The original MATLAB target function uses `+I*R` for the provided charge example, while one MATLAB comment says charge should use `-I*R`. Because the code and comment conflict, the MCP default is data-driven sign selection.

## Input Data Rules

Recommended full-cell data columns:

| Voltage | Capacity |
| --- | --- |
| `voltage_V` | `capacity_Ah` |

Headerless files are supported. The program scores numeric columns by whether they look like voltage and capacity:

- voltage-like columns usually have median values in a common battery voltage range and a reasonable voltage span;
- capacity-like columns usually have a meaningful span and are mostly monotonic;
- adjacent voltage/capacity columns get a bonus because this is common in cycler exports.

Charge/discharge detection normalizes capacity to move forward from zero, then compares the median voltage near the end against the median voltage near the beginning:

- voltage rising means `charge`;
- voltage falling means `discharge`;
- near-flat data falls back to a linear voltage-capacity slope.

The current magnitude can be provided explicitly with `current`. If it is omitted, the tool tries to parse C-rate from the file name. For example, `25C_0.1C.xlsx` is interpreted as `0.1C`; the temperature-like `25C` is ignored when a more plausible C-rate is present.

## Electrode OCV Files

The bundled test case includes matching electrode OCV files:

```text
test_cases/25C_0.1C/anode.txt
test_cases/25C_0.1C/cathode.txt
```

When running from the source checkout with these files present, the MCP uses them by default. Installed packages do not include test-case or reference data; supply both `anode_path` and `cathode_path` explicitly. For real experiments, always use the appropriate half-cell OCV curves.

## Output Files

Each single-file fitting job outputs:

- `result.json`: fitted parameters, RMSE, sign selection, stoichiometry ranges, and derived values.
- `fitted_curve.csv`: capacity, measured voltage, modeled voltage, residual, electrode potentials, and `x/y` stoichiometry.

Batch jobs also output:

- `batch_summary.csv`: one-row summary for each fitted file.
- `batch_summary.json`: full batch summary with errors, if any.

If `output_dir` is not provided, final results are written to:

```text
Desktop/dual water tank output/run_YYYYMMDD_HHMMSS/
```

The input data folder stays clean by default.

## Test Case

The repository includes one test case:

```text
test_cases/25C_0.1C/
```

Files:

- `25C_0.1C.xlsx`: full-cell voltage-capacity test data.
- `anode.txt`: anode half-cell OCV curve.
- `cathode.txt`: cathode half-cell OCV curve.

Quick preview:

```powershell
.\dual-water-tank.cmd preview "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

Quick fit:

```powershell
.\dual-water-tank.cmd fit "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

## Repository Layout

```text
dual_water_tank_mcp/          Python package and MCP server
test_cases/25C_0.1C/          Example full-cell dataset plus anode/cathode OCV files
references/original_resource/ Original MATLAB scripts, notes, and source references
examples/                     MCP configuration examples
Desktop/dual water tank output/ Generated results outside the repository
```

## Local Debugging

Run a quick preview:

```powershell
.\dual-water-tank.cmd preview "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

Run a quick fit without saving files:

```powershell
.\dual-water-tank.cmd fit "test_cases\25C_0.1C\25C_0.1C.xlsx" --no-save --population-size 20 --generations 1 --max-points 100
```

Run the sign-diagnosis script:

```powershell
python scripts\diagnose_parameter_gap.py
```

Developer installation, only if you want to modify the code:

```powershell
python -m venv .venv
.\.venv\Scripts\activate
pip install -e .
```

## License

The Python code in this repository is released under the Apache License 2.0. See `LICENSE`. Project attribution is listed in `NOTICE`.

Apache License 2.0 includes an explicit patent license and patent termination language. Reference materials under `references/original_resource/` may have their own copyright, patent, or usage terms. The Apache License 2.0 for this repository code does not change the ownership or licensing of those external/reference files.

---

# Dual Water Tank MCP for Battery Aging Mechanism Identification 中文

[English](#dual-water-tank-mcp-for-battery-aging-mechanism-identification) | [中文](#dual-water-tank-mcp-for-battery-aging-mechanism-identification-中文)

这是一个用于锂离子电池双水箱模型参数辨识的 MCP 服务。输入为充电/放电电压-容量数据，输出为双水箱模型参数、拟合曲线、误差、符号选择结果和批量汇总。它主要面向电池老化机理识别，例如容量损失、锂库存变化、正负极容量变化等参数分析。

项目保持两层结构：

- `dual_water_tank_mcp/`：核心模型代码，包括数据读取、列识别、充放电识别、模型计算、遗传算法拟合、批量输出和 CLI。
- `dual_water_tank_mcp/server.py`：MCP 薄接口层，只负责把核心函数暴露成 MCP 工具。

后续如果需要修正或改进模型，直接改 `dual_water_tank_mcp/` 下的核心代码，然后重启 MCP 服务即可。

## 双水箱模型

<img src="references/figures/dual-water-tank-model.png" width="480" alt="双水箱模型示意图，相连的两个水箱分别代表正极和负极">

*图 3．用相连的两个水箱表示电池的正极和负极。*

<img src="references/figures/dual-water-tank-voltage-fit.png" width="700" alt="石墨/磷酸铁锂电池在初始状态及循环 330、690 和 1020 次后的实测与仿真电压–容量曲线">

*图 10．石墨/磷酸铁锂电池的实测与仿真电压–容量曲线，(a)–(d) 分别对应 0、330、690 和 1020 次循环。*

两图均引自 [Han 等，Journal of Power Sources 251 (2014), 38–54](https://doi.org/10.1016/j.jpowsour.2013.11.029)。

## 功能

- 读取 `.xlsx`、`.xls`、`.csv`、`.txt`、`.tsv` 电池测试数据。
- 自动识别电压列和容量列。
- 根据电压趋势自动识别充电或放电。
- 自动处理正负极化学计量比 `y/x` 的充放电符号。
- 自动分别尝试 `+I*R` 和 `-I*R`，选择全数据 RMSE 更低的结果。
- 根据数据容量范围自动适配遗传算法容量上下限。
- 支持单文件拟合和批量拟合。
- 默认把最终结果输出到桌面文件夹。
- 可以作为 MCP server 被 Codex、Claude 等 agent 调用。

## 无需克隆的一键启动

先安装 [uv](https://docs.astral.sh/uv/getting-started/installation/)，然后启动本地 STDIO MCP：

```bash
uvx --from "git+https://github.com/ZidingWang/LIB-dual-water-tank-aging-identification-mcp.git" dual-water-tank-mcp
```

Windows、macOS、Linux 的通用 JSON MCP 配置：

```json
{
  "mcpServers": {
    "dual-water-tank-model": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/ZidingWang/LIB-dual-water-tank-aging-identification-mcp.git", "dual-water-tank-mcp"]
    }
  }
}
```

Codex 配置：

```toml
[mcp_servers.dual-water-tank-model]
command = "uvx"
args = ["--from", "git+https://github.com/ZidingWang/LIB-dual-water-tank-aging-identification-mcp.git", "dual-water-tank-mcp"]
startup_timeout_sec = 180
tool_timeout_sec = 3600
```

首次启动会安装依赖；在终端启动后等待 STDIO 请求属正常现象。MCP 客户端需能从 PATH 找到 `uvx`。`@<commit-sha>` 可附加在 Git URL 后以固定版本。安装包不包含源码仓库里的示例及参考资料；使用拟合工具时请传入自己的全电池数据、`anode_path` 与 `cathode_path` 绝对路径。预览工具只需要全电池数据。

## 从 GitHub 到安装（源码克隆方式）

如果项目已经上传到 GitHub，先克隆仓库：

```powershell
git clone <你的 GitHub 仓库地址>
cd dual-water-tank-mcp
```

如果已经有本地源码，直接进入项目根目录，例如：

```powershell
cd "D:\desktop\PSG\1.1 github\dual-water-tank-mcp"
```

需要 Python 3.10 或更高版本，建议同时安装 Git。

检查版本：

```powershell
python --version
git --version
```

可以直接使用仓库自带的一键 MCP 启动脚本。第一次运行会自动创建 `.venv` 并安装依赖：

```powershell
.\run_mcp.cmd
```

MCP 客户端也应该调用这个脚本。用户不需要修改模型代码、Python 文件或 MCP server 文件。

命令行预览示例：

```powershell
.\dual-water-tank.cmd preview "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

命令行拟合示例：

```powershell
.\dual-water-tank.cmd fit "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

## 启动 MCP

在 Codex、Claude Desktop、Claude Code 或其他 MCP 客户端中添加这个 MCP server。

Windows MCP 配置示例：

```json
{
  "mcpServers": {
    "dual-water-tank-model": {
      "command": "C:\\path\\to\\dual-water-tank-mcp\\run_mcp.cmd",
      "args": []
    }
  }
}
```

macOS/Linux MCP 配置示例：

```json
{
  "mcpServers": {
    "dual-water-tank-model": {
      "command": "/path/to/dual-water-tank-mcp/run_mcp.sh",
      "args": []
    }
  }
}
```

macOS/Linux 需要先给脚本执行权限：

```bash
chmod +x run_mcp.sh dual-water-tank.sh
```

仓库里也提供了可复制修改的配置文件：

- `examples/mcp_config_windows.json`
- `examples/mcp_config_macos_linux.json`

配置完成后，在 MCP 客户端中刷新或重启连接。看到 `dual-water-tank-model` 可用，就说明已经连上。

## MCP 已连接后怎么用

连接成功以后，不需要手动运行 Python 或命令行脚本。你只需要在支持 MCP 的客户端里提出需求，客户端会调用本项目暴露的 MCP 工具。

推荐流程：

1. 如果不确定输入数据格式，先调用 `preview_dual_water_tank_data`。
2. 单文件拟合调用 `fit_dual_water_tank`。
3. 批量拟合调用 `batch_fit_dual_water_tank`。
4. 打开桌面输出目录里的 `result.json`、`fitted_curve.csv` 或 `batch_summary.csv` 查看结果。

最终结果默认输出到桌面：

```text
Desktop/dual water tank output/run_YYYYMMDD_HHMMSS/
```

在作者的 Windows 电脑上，通常是：

```text
D:\desktop\dual water tank output\
```

MCP 返回结果里也会包含 `output_dir`、`curve_csv`、`result_json` 等路径。

用户可以这样对 MCP 客户端说：

```text
请使用 dual-water-tank MCP 预览 test_cases/25C_0.1C/25C_0.1C.xlsx。
```

```text
请使用 dual-water-tank MCP 拟合 test_cases/25C_0.1C/25C_0.1C.xlsx，并把最终结果保存到桌面。
```

```text
请使用 dual-water-tank MCP 批量拟合 D:\my_battery_data 里面的所有 Excel 文件。
最终结果输出到桌面的 dual water tank output 文件夹。
```

```text
请使用 dual-water-tank MCP 拟合 D:\data\cell.xlsx。
anode_path 使用 D:\data\anode.txt，cathode_path 使用 D:\data\cathode.txt。
自动判断充放电方向和 I*R 符号。
```

## MCP 工具

MCP server 暴露这些工具：

- `preview_dual_water_tank_data`：预览一个数据集，返回自动识别到的列、充放电方向、容量范围、电压范围和电流估计。
- `fit_dual_water_tank`：拟合一个文件或一个工作表，输出 `result.json` 和 `fitted_curve.csv`。
- `batch_fit_dual_water_tank`：拟合一个文件夹或文件列表，输出每个文件的结果和批量汇总。

## 工具调用示例

`preview_dual_water_tank_data` 示例：

```json
{
  "data_file": "test_cases/25C_0.1C/25C_0.1C.xlsx"
}
```

`fit_dual_water_tank` 示例：

```json
{
  "data_file": "test_cases/25C_0.1C/25C_0.1C.xlsx",
  "direction": "auto",
  "resistance_sign": "auto"
}
```

`fit_dual_water_tank` 可选参数示例：

```json
{
  "data_file": "D:/data/cell.xlsx",
  "anode_path": "D:/data/anode.txt",
  "cathode_path": "D:/data/cathode.txt",
  "current": 65,
  "direction": "auto",
  "resistance_sign": "auto",
  "voltage_col": "B",
  "capacity_col": "C",
  "output_dir": "D:/desktop/dual water tank output/my_run"
}
```

`batch_fit_dual_water_tank` 示例：

```json
{
  "input_dir": "D:/my_battery_data",
  "direction": "auto",
  "resistance_sign": "auto"
}
```

## 模型符号约定

模型保留原始五个参数：

```text
[y0, Cp, x0, Cn, R]
```

充电：

```text
y = y0 - Q / Cp
x = x0 + Q / Cn
V = Upos(y) - Uneg(x) + I * R
```

放电：

```text
y = y0 + Q / Cp
x = x0 - Q / Cn
V = Upos(y) - Uneg(x) - I * R
```

`I` 按正的电流大小输入。默认 `resistance_sign` 为 `auto`，工具会对检测到的方向分别拟合 `+I*R` 和 `-I*R`，选择全数据 RMSE 更低的结果。最终选择的符号和两个候选的 RMSE 会写入 `result.json` 的 `resistance_sign_selection` 字段。

可选的电阻符号模式：

```text
auto | physics | positive | negative | matlab
```

- `auto`：同时拟合 `+I*R` 和 `-I*R`，选择全数据 RMSE 更低的结果。
- `physics`：充电用 `+I*R`，放电用 `-I*R`。
- `positive`：强制 `+I*R`。
- `negative`：强制 `-I*R`。
- `matlab`：始终使用 `+I*R`，对应原 MATLAB 目标函数实际执行的公式。

原 MATLAB 目标函数在给定充电示例中实际使用 `+I*R`，但脚本注释中有一处写成充电 `-I*R`。因为代码和注释冲突，所以本 MCP 默认使用数据驱动的符号选择。

## 输入数据规则

推荐全电池数据至少包含两列：

| 电压 | 容量 |
| --- | --- |
| `voltage_V` | `capacity_Ah` |

没有表头也可以。程序会根据数值特征识别电压列和容量列：

- 电压列通常在常见电池电压范围内，并且有合理电压跨度。
- 容量列通常有明显跨度，并且大体单调。
- 相邻的电压/容量列会获得额外评分，因为这符合常见测试设备导出格式。

充放电识别会先把容量归一化为从零向前增加，再比较末端电压和起始电压：

- 电压整体上升：`charge`
- 电压整体下降：`discharge`
- 近似平坦：退回到线性电压-容量斜率判断

电流大小可以通过 `current` 显式传入。如果不传，工具会尝试从文件名解析 C-rate。例如 `25C_0.1C.xlsx` 会识别为 `0.1C`，温度含义的 `25C` 不会被当成倍率。

## 半电池 OCV 文件

自带测试案例包含匹配的半电池 OCV 文件：

```text
test_cases/25C_0.1C/anode.txt
test_cases/25C_0.1C/cathode.txt
```

在源码仓库中运行时，只要文件存在，MCP 默认可以使用这套测试案例里的电极文件。通过安装包运行时不包含示例和参考资料，必须显式传入 `anode_path` 与 `cathode_path`。真实实验中请使用对应的半电池 OCV 曲线。

## 输出文件

单文件拟合会输出：

- `result.json`：拟合参数、RMSE、符号选择、化学计量比范围和派生参数。
- `fitted_curve.csv`：容量、实测电压、模型电压、残差、正负极电势和 `x/y`。

批量任务额外输出：

- `batch_summary.csv`：每个拟合文件一行摘要。
- `batch_summary.json`：完整批量结果和错误信息。

如果不传 `output_dir`，最终结果会写到：

```text
Desktop/dual water tank output/run_YYYYMMDD_HHMMSS/
```

默认不会污染输入数据文件夹。

## 测试案例

仓库包含一个测试案例：

```text
test_cases/25C_0.1C/
```

文件：

- `25C_0.1C.xlsx`：全电池电压-容量测试数据。
- `anode.txt`：负极半电池 OCV 曲线。
- `cathode.txt`：正极半电池 OCV 曲线。

快速预览：

```powershell
.\dual-water-tank.cmd preview "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

快速拟合：

```powershell
.\dual-water-tank.cmd fit "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

## 仓库结构

```text
dual_water_tank_mcp/          Python package and MCP server
test_cases/25C_0.1C/          Example full-cell dataset plus anode/cathode OCV files
references/original_resource/ Original MATLAB scripts, notes, and source references
examples/                     MCP configuration examples
Desktop/dual water tank output/ Generated results outside the repository
```

## 本地调试

快速预览：

```powershell
.\dual-water-tank.cmd preview "test_cases\25C_0.1C\25C_0.1C.xlsx"
```

快速拟合但不保存文件：

```powershell
.\dual-water-tank.cmd fit "test_cases\25C_0.1C\25C_0.1C.xlsx" --no-save --population-size 20 --generations 1 --max-points 100
```

运行符号诊断脚本：

```powershell
python scripts\diagnose_parameter_gap.py
```

开发者安装方式，仅在需要修改代码时使用：

```powershell
python -m venv .venv
.\.venv\Scripts\activate
pip install -e .
```

## 许可证

本仓库 Python 代码使用 Apache License 2.0，见 `LICENSE`。项目署名见 `NOTICE`。

Apache License 2.0 包含明确的专利授权和专利终止条款。`references/original_resource/` 中的参考资料可能有其原始版权、专利或使用限制。本仓库代码使用 Apache License 2.0 不会改变这些外部参考资料的权属或许可状态。
