第一轮分析工作暂存

This commit is contained in:
Frank14f
2026-06-09 18:46:59 +08:00
parent 4612928398
commit d1b9922c6b
111 changed files with 24287 additions and 1581 deletions
-295
View File
@@ -1,295 +0,0 @@
# DynamisLab 重构总结
## 概述
已成功创建标准化、模块化的 DynamisLab 机器学习研究框架,基于最新的 gym_env.py 和 d1a3o12.py 重构而来。
## 主要改进
### 1. 标准化项目结构 (Src Layout)
```
DynamisLabNew/
├── src/ # ✨ 主包(src layout
│ ├── __init__.py # 包初始化
│ ├── config.py # ✨ 统一配置管理
│ └── environments/ # ✨ 标准化环境
│ ├── __init__.py
│ └── cfd_env.py # ✨ 重构的CFD环境
├── scripts/ # 训练和评估脚本
│ └── train_ppo.py # ✨ 重构的训练脚本
├── configs/ # 配置文件
├── models/ # 模型检查点(.gitignore
├── output/ # 训练输出(.gitignore
├── tensorboard/ # TensorBoard日志(.gitignore
├── docs/ # 文档
├── README.md # ✨ 完整文档
├── requirements.txt # ✨ 依赖列表
├── pyproject.toml # ✨ 现代打包配置
├── LICENSE # MIT许可证
└── .gitignore # Git规则
```
### 2. 代码重构亮点
#### A. 统一配置管理 (`src/dynamis/config.py`)
**原代码问题:**
```python
# 硬编码路径,重复代码
current_dir = os.path.dirname(os.path.abspath("__file__"))
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
sys.path.append(parent_dir)
config_cuda = utils.load_cuda_config(os.path.join(parent_dir, "configs", "config_cuda.json"))
```
**新方案:**
```python
from dynamis.config import load_celeris_configs
# 自动查找配置,支持环境变量和submodule
config_cuda, config_field = load_celeris_configs()
```
**优点:**
- ✅ 自动处理CelerisLab导入(支持pip安装或submodule
- ✅ 智能配置路径查找
- ✅ 统一的输出目录管理(models/, output/, tensorboard/
- ✅ 辅助函数(`get_model_path()`, `get_tensorboard_logdir()`等)
#### B. 标准化环境 (`src/dynamis/environments/cfd_env.py`)
**原代码:`gym_env.py` (259行)**
**新代码:`CFDFlowControlEnv` (更模块化,318行但更清晰)**
**改进:**
-**完整docstrings**:类和所有方法都有详细文档
-**类型提示**:所有参数和返回值带类型
-**参数化设计**:所有魔法数字变为可配置参数
```python
def __init__(
self,
device_id: int = 0,
n_control_cylinders: int = 3,
n_sensors: int = 3,
max_steps: int = 500,
sample_interval: int = 800,
# ... 所有参数都可配置
):
```
- ✅ **清晰的方法分离**
- `_init_flow_field()` - 初始化CFD模拟
- `_calculate_normalization()` - 计算归一化因子
- `_normalize_state()` - 状态归一化
- `_compute_reward()` - 奖励计算
- ✅ **Gymnasium新API**:使用最新的 `terminated` / `truncated` 分离
- ✅ **丰富的info字典**:返回详细的诊断信息(cd, cl, 各reward分量)
#### C. 专业训练脚本 (`scripts/train_ppo.py`)
**原代码:`d1a3o12.py` (72行,简单循环)**
**新代码:`train_ppo.py` (319行,完整功能)**
**新增功能:**
- ✅ **命令行参数**:15+可配置参数
```bash
python scripts/train_ppo.py --help # 查看所有选项
```
- ✅ **实验追踪**
- TensorBoard集成
- 定期保存最佳模型
- 详细的评估指标
- ✅ **模型管理**
- 自动保存最佳模型
- 定期检查点
- 支持恢复训练 (`--resume`)
- ✅ **评估函数**
```python
evaluate_policy(model, env, n_episodes=5)
# 返回完整的评估指标和轨迹数据
```
- ✅ **自定义回调**
- `TensorboardCallback` 记录额外指标
- 可扩展的回调系统
### 3. 文档和可维护性
#### README.md
- 📖 完整的安装指南
- 🚀 Quick Start示例
- 🔧 配置说明
- 📊 环境详细规格
- 💡 高级用法(恢复训练、多GPU等)
- 📝 引用格式
#### 类型提示和Docstrings
所有代码都包含:
```python
def reset(
self,
seed: Optional[int] = None,
options: Optional[Dict[str, Any]] = None
) -> Tuple[np.ndarray, Dict[str, Any]]:
"""
Reset the environment to initial state.
Args:
seed: Random seed for reproducibility
options: Additional options
Returns:
Tuple of (observation, info)
"""
```
#### 配置文件
- `pyproject.toml` - 现代Python打包标准
- `requirements.txt` - 清晰的依赖列表
- `.gitignore` - 完善的忽略规则
## 使用方法
### 快速开始
```bash
# 1. 假设CelerisLab已安装(作为submodule或pip
cd DynamisLabNew
# 2. 安装依赖
pip install -r requirements.txt
# 3. 安装DynamisLab(开发模式)
pip install -e .
# 4. 训练
python scripts/train_ppo.py \
--run-name test_run \
--device-id 0 \
--total-timesteps 50 \
--activation sin
# 5. 监控
tensorboard --logdir tensorboard/
```
### 编程使用
```python
from dynamis.environments import CFDFlowControlEnv
from dynamis.config import load_celeris_configs
# 加载配置
config_cuda, config_field = load_celeris_configs()
# 创建环境
env = CFDFlowControlEnv(
device_id=0,
config_cuda=config_cuda,
config_field=config_field,
max_steps=500,
)
# 训练或评估
obs, info = env.reset()
for step in range(100):
action = env.action_space.sample()
obs, reward, terminated, truncated, info = env.step(action)
print(f"Step {step}: Reward={reward:.3f}, CD={info['cd']:.4f}")
if terminated or truncated:
break
env.close()
```
## 代码质量改进对比
| 方面 | 原代码 | 新代码 | 改进 |
|------|--------|--------|------|
| **结构** | 单文件,混杂 | src layout,模块化 | ✅ 专业结构 |
| **配置** | 硬编码路径 | 统一config模块 | ✅ 灵活可配 |
| **类型提示** | 无 | 完整类型提示 | ✅ IDE支持 |
| **Docstrings** | 最小 | 完整文档 | ✅ 可维护性 |
| **参数化** | 魔法数字 | 可配置参数 | ✅ 可调试 |
| **错误处理** | 基本 | 友好错误信息 | ✅ 用户友好 |
| **日志** | print语句 | TensorBoard | ✅ 专业追踪 |
| **测试** | 无 | 结构支持测试 | ✅ 可测试 |
| **文档** | README基本 | 完整文档 | ✅ 易上手 |
| **Git** | 基本ignore | 完善.gitignore | ✅ 清洁仓库 |
## 与CelerisLab集成
### 方式1Git Submodule(推荐)
```bash
cd DynamisLabNew
git submodule add https://github.com/frank14f/CelerisLab.git
cd CelerisLab
pip install -e .
cd ..
```
`config.py` 会自动检测submodule并添加到Python path。
### 方式2:独立安装
```bash
# 在CelerisLab目录
pip install -e ../CelerisLabNew
# 设置环境变量(可选)
export CELERISLAB_CONFIG_DIR=/path/to/DynamisLab/configs
```
## 下一步
### 上传到Git
```bash
cd DynamisLabNew
git init
git add .
git commit -m "Initial commit: DynamisLab v0.1.0 - Refactored ML framework"
# 配置双远程
git remote add origin <github_url>
git remote set-url --add --push origin <github_url>
git remote set-url --add --push origin <gitea_url>
git push -u origin main
```
### 添加CelerisLab Submodule
```bash
git submodule add https://github.com/frank14f/CelerisLab.git
git commit -m "Add CelerisLab as submodule"
git push
```
## 主要文件说明
| 文件 | 行数 | 功能 | 状态 |
|------|------|------|------|
| `src/dynamis/__init__.py` | 11 | 包初始化 | ✅ 完成 |
| `src/dynamis/config.py` | 118 | 配置管理 | ✅ 完成 |
| `src/dynamis/environments/__init__.py` | 7 | 环境注册 | ✅ 完成 |
| `src/dynamis/environments/cfd_env.py` | 318 | CFD环境 | ✅ 完成 |
| `scripts/train_ppo.py` | 319 | 训练脚本 | ✅ 完成 |
| `README.md` | 291 | 项目文档 | ✅ 完成 |
| `requirements.txt` | 29 | 依赖列表 | ✅ 完成 |
| `pyproject.toml` | 97 | 打包配置 | ✅ 完成 |
| `.gitignore` | 89 | Git规则 | ✅ 完成 |
| `LICENSE` | 21 | MIT许可 | ✅ 完成 |
## 总结
**代码质量**:从研究脚本提升到生产级代码
**可维护性**:清晰的结构,完整的文档
**可扩展性**:模块化设计,易于添加新环境和算法
**专业性**:遵循Python最佳实践和Gymnasium标准
**用户友好**:详细的README和命令行接口
**Git友好**:完善的.gitignore,准备双远程推送
🎉 **DynamisLab 已准备好用于生产和发布!**
-480
View File
@@ -1,480 +0,0 @@
# Git Submodule 开发工作流指南
## 项目结构
你的开发环境:
```
/home/frank14f/
├── CelerisLab/ # 独立仓库 - CFD库
│ ├── .git/
│ ├── src/
│ │ └── CelerisLab/
│ └── ...
└── DynamisLab/ # 独立仓库 - ML框架
├── .git/
├── CelerisLab/ # 作为submodule指向上面的CelerisLab仓库
│ ├── .git # 这是软链接,指向真实的git仓库
│ └── ...
├── src/
├── scripts/
└── ...
```
## 开发工作流
### 场景1:开发 CelerisLabCFD功能)
**在 `/home/frank14f/CelerisLab` 下工作**
```bash
cd /home/frank14f/CelerisLab
# 1. 创建功能分支(可选)
git checkout -b feature/new-cfd-feature
# 2. 修改代码
vim src/CelerisLab/driver.py
# 3. 测试改动
python -c "from CelerisLab import FlowField; print('OK')"
# 4. 提交改动
git add src/CelerisLab/driver.py
git commit -m "feat: add new CFD feature"
# 5. 推送到远程(双推送到GitHub和Gitea
git push origin main
# 因为配置了双push URL,这会自动推送到两个远程
```
### 场景2:在 DynamisLab 中使用更新的 CelerisLab
**方式A:更新submodule到最新版本**
```bash
cd /home/frank14f/DynamisLab
# 1. 进入submodule目录
cd CelerisLab
# 2. 拉取最新的CelerisLab代码
git fetch origin
git checkout main # 或特定的tag/branch
git pull origin main
# 3. 回到DynamisLab主目录
cd ..
# 4. 提交submodule引用的更新
git add CelerisLab
git commit -m "chore: update CelerisLab submodule to latest"
# 5. 推送DynamisLab的更新
git push
```
**方式B:自动更新submodule**
```bash
cd /home/frank14f/DynamisLab
# 一行命令更新所有submodule到远程最新版本
git submodule update --remote --merge
# 提交更新
git add CelerisLab
git commit -m "chore: update CelerisLab submodule"
git push
```
### 场景3:同时开发 CelerisLab 和 DynamisLab
**这是你问的核心场景!**
#### 方法1:在独立目录开发(推荐)
```bash
# Terminal 1: 开发CelerisLab
cd /home/frank14f/CelerisLab
# 修改 CFD 功能
vim src/CelerisLab/utils.py
git commit -am "fix: improve config loading"
git push # 推送到远程
# Terminal 2: 开发DynamisLab
cd /home/frank14f/DynamisLab
# 更新submodule获取最新CelerisLab
git submodule update --remote CelerisLab
# 修改ML代码使用新功能
vim src/environments/cfd_env.py
git add CelerisLab src/ # 同时提交submodule更新和代码修改
git commit -m "feat: use new CelerisLab config feature"
git push
```
#### 方法2:在DynamisLab的submodule中开发CelerisLab
> ⚠️ **不推荐**:容易混淆,但技术上可行
```bash
cd /home/frank14f/DynamisLab/CelerisLab # 进入submodule
# 这个目录实际上是一个完整的git仓库
git checkout -b feature/my-fix
# 修改代码
vim src/CelerisLab/driver.py
git commit -am "fix: bug in driver"
# 推送到CelerisLab远程仓库
git push origin feature/my-fix
# 回到DynamisLab主目录
cd ..
git add CelerisLab
git commit -m "chore: update CelerisLab with bug fix"
git push
```
### 场景4:克隆项目时的工作流
**新电脑/新环境上开始工作**
```bash
# 1. 克隆DynamisLab(包含submodule
git clone --recurse-submodules https://github.com/frank14f/DynamisLab.git
cd DynamisLab
# 2. 安装CelerisLab
cd CelerisLab
pip install -e .
cd ..
# 3. 安装DynamisLab
pip install -r requirements.txt
pip install -e .
# 4. 开始工作
python scripts/train_ppo.py --help
```
**如果忘记 `--recurse-submodules`**
```bash
git clone https://github.com/frank14f/DynamisLab.git
cd DynamisLab
# 初始化submodule
git submodule init
git submodule update
# 或简化为:
git submodule update --init --recursive
```
## 常用 Submodule 命令
### 查看状态
```bash
cd /home/frank14f/DynamisLab
# 查看submodule状态
git submodule status
# 输出示例:
# a1b2c3d4 CelerisLab (v0.2.0)
# 前面的hash是当前指向的commit
# 查看submodule的URL
git config --file .gitmodules --get-regexp url
```
### 更新 Submodule
```bash
# 方法1:更新到远程最新版本
git submodule update --remote CelerisLab
# 方法2:手动进入submodule更新
cd CelerisLab
git pull origin main
cd ..
git add CelerisLab
# 方法3:更新所有submodule并合并
git submodule update --remote --merge
```
### 固定 Submodule 到特定版本
```bash
cd /home/frank14f/DynamisLab/CelerisLab
# 切换到特定commit或tag
git checkout v0.2.0 # 或 commit hash
cd ..
git add CelerisLab
git commit -m "pin CelerisLab to v0.2.0"
git push
```
### 修改 Submodule URL
```bash
# 如果CelerisLab的仓库地址变了
git config --file=.gitmodules submodule.CelerisLab.url https://new-url.git
git submodule sync
git submodule update --remote
```
## Python 包安装策略
### 开发模式(推荐)
```bash
# 在DynamisLab下
pip install -e ./CelerisLab # submodule作为editable安装
pip install -e . # DynamisLab自己也是editable
# 好处:修改代码立即生效,无需重新安装
```
### 环境变量方式
```bash
# 在 ~/.bashrc 中添加
export PYTHONPATH="/home/frank14f/DynamisLab/CelerisLab/src:$PYTHONPATH"
# 重新加载
source ~/.bashrc
```
## 推荐的工作流程
### 日常开发循环
**CFD功能开发:**
```bash
# === Terminal 1: CelerisLab ===
cd ~/CelerisLab
# 1. 修改CFD代码
vim src/CelerisLab/utils.py
# 2. 本地测试
python test_utils_only.py
# 3. 提交
git commit -am "feat: smart config loading"
git push
# === Terminal 2: DynamisLab ===
cd ~/DynamisLab
# 4. 拉取最新CelerisLab
git submodule update --remote CelerisLab
# 5. 测试集成
python scripts/train_ppo.py --total-timesteps 5
# 6. 如果工作正常,提交submodule更新
git add CelerisLab
git commit -m "chore: update CelerisLab"
git push
```
**ML功能开发:**
```bash
cd ~/DynamisLab
# 1. 修改ML代码
vim src/environments/cfd_env.py
# 2. 测试
python scripts/train_ppo.py --total-timesteps 10
# 3. 提交
git commit -am "feat: improve reward function"
git push
# CelerisLab submodule保持不变
```
## VSCode 多仓库开发
### Workspace 配置
创建 `~/DynamisLab.code-workspace`
```json
{
"folders": [
{
"path": ".",
"name": "DynamisLab (Root)"
},
{
"path": "CelerisLab",
"name": "CelerisLab (Submodule)"
}
],
"settings": {
"python.analysis.extraPaths": [
"./CelerisLab/src"
],
"git.detectSubmodules": true,
"git.showSubmoduleStatus": true
}
}
```
在VSCode中:
1. `File``Open Workspace from File`
2. 选择 `DynamisLab.code-workspace`
3. 左侧会显示两个文件夹,可以分别管理Git
## 常见问题排查
### Q1: Submodule 显示 "modified content"
```bash
cd CelerisLab
git status # 查看有什么改动
# 如果不需要这些改动
git checkout .
git clean -fd
# 如果需要保存
git commit -am "local changes"
```
### Q2: Submodule 指向错误的 commit
```bash
cd DynamisLab
# 查看submodule应该指向哪个commit
git diff CelerisLab # 看HEAD和实际的差异
# 重置到正确的commit
cd CelerisLab
git fetch
git checkout <正确的hash>
cd ..
git add CelerisLab
```
### Q3: 推送时忘记推送 submodule 的改动
```bash
# 先推送submodule
cd CelerisLab
git push
# 再推送主仓库
cd ..
git push
```
设置自动检查:
```bash
git config --global push.recurseSubmodules check
# 这样push主仓库时会检查submodule是否已推送
```
### Q4: 多人协作时 submodule 冲突
```bash
# 拉取主仓库
git pull
# 更新submodule到正确版本
git submodule update --init --recursive
```
## 版本发布策略
### 发布 CelerisLab 新版本
```bash
cd ~/CelerisLab
# 1. 更新版本号
vim src/CelerisLab/__init__.py # __version__ = '0.3.0'
vim setup.py # version='0.3.0'
# 2. 提交
git commit -am "chore: bump version to 0.3.0"
# 3. 打tag
git tag -a v0.3.0 -m "Release v0.3.0"
git push origin main --tags
```
### DynamisLab 使用特定 CelerisLab 版本
```bash
cd ~/DynamisLab/CelerisLab
# 切换到tag
git checkout v0.3.0
cd ..
git add CelerisLab
git commit -m "chore: pin CelerisLab to v0.3.0"
git push
```
## 最佳实践总结
**DO - 推荐做法**
1. ✅ 在独立的 `~/CelerisLab` 目录开发CFD功能
2. ✅ 开发完成后push,然后在 `~/DynamisLab` 中update submodule
3. ✅ 使用 `pip install -e` 安装两个包(开发模式)
4. ✅ 经常运行 `git submodule update --remote` 保持同步
5. ✅ CelerisLab稳定时打tagDynamisLab引用tag而不是main
6. ✅ VSCode使用workspace配置同时管理两个仓库
**DON'T - 避免的做法**
1. ❌ 不要在 `~/DynamisLab/CelerisLab` submodule内直接开发(除非临时修复)
2. ❌ 不要忘记提交submodule引用的更新
3. ❌ 不要在DynamisLab中硬编码CelerisLab版本(用submodule管理)
4. ❌ 推送DynamisLab前确保CelerisLab的改动已推送
5. ❌ 不要手动复制粘贴代码在两个项目间,用git管理
## 快速参考
```bash
# === 开发CelerisLab ===
cd ~/CelerisLab
# 改代码 → commit → push
# === 同步到DynamisLab ===
cd ~/DynamisLab
git submodule update --remote
git add CelerisLab
git commit -m "update CelerisLab"
git push
# === 开发DynamisLab ===
cd ~/DynamisLab
# 改代码 → commit → push
# (submodule不变)
# === 检查submodule状态 ===
git submodule status
# === 重置submodule ===
git submodule update --init --recursive
```
---
这样你就可以高效地在两个独立项目中开发,同时通过submodule保持它们的连接!🚀