- name
- run-solver
- description
- 运行数学模型求解器。在本地 Python/MATLAB 环境执行求解代码,收集结果,超时保护。当用户说'运行求解'、'run solver'、'跑代码'时使用。
- argument-hint
- ["solver-script-or-description"]
- allowed-tools
- Bash(*), Read, Grep, Glob, Edit, Write, Agent
# 运行求解器
在本地环境执行数模求解代码: $ARGUMENTS
## Workflow
### Step 1: 检测环境
Read the project's `CLAUDE.md` to determine the compute environment:
- **Python**: Look for Python version, virtualenv/conda info, required packages
- **MATLAB**: Look for MATLAB installation path and license info
If no environment info is found in `CLAUDE.md`, auto-detect:
```bash
# Check Python
python3 --version 2>/dev/null || python --version 2>/dev/null
pip list 2>/dev/null | grep -E "numpy|scipy|matplotlib|pandas|sklearn|pulp|cvxpy"
# Check MATLAB
which matlab 2>/dev/null && matlab -batch "disp('MATLAB OK')" 2>/dev/null
```
### Step 2: 预检查
Check compute environment readiness:
```bash
# Check available memory
python3 -c "import psutil; print(f'RAM: {psutil.virtual_memory().total/1e9:.1f} GB, Available: {psutil.virtual_memory().available/1e9:.1f} GB')"
# Check required packages
python3 -c "
import importlib, sys
required = ['numpy', 'scipy', 'matplotlib', 'pandas']
missing = [p for p in required if importlib.util.find_spec(p) is None]
if missing: print(f'Missing: {missing}'); sys.exit(1)
print('All required packages available')
"
```
If packages are missing, install them:
```bash
pip install numpy scipy matplotlib pandas scikit-learn
```
### Step 3: 准备求解脚本
1. **Read the solve plan**: Check `SOLVE_PLAN.md` or `refine-logs/SOLVE_PLAN.md` for the execution order
2. **Locate scripts**: Find solver scripts in the project directory
```
Glob: **/*.py, **/*.m
```
3. **Validate scripts**: Quick syntax check before running
```bash
python3 -m py_compile <script>
```
### Step 3.5: 日志配置
Ensure the solver scripts have proper logging:
1. **Check if logging is already in the script** — look for `import logging` or `print` statements with progress info. If present, skip to Step 4.
2. **If not present, add basic logging** to the solver script:
```python
import logging, time
logging.basicConfig(filename='solve_log.txt', level=logging.INFO,
format='%(asctime)s - %(message)s')
# Inside solving loop:
logging.info(f"Iteration {i}: objective={obj_value:.6f}, residual={residual:.6e}")
# After completion:
logging.info(f"Solving complete. Total time: {time.time()-start:.1f}s")
```
3. **Metrics to log** (add whichever apply to the solver):
- `iteration` — current iteration number
- `objective` — objective function value
- `residual` — convergence residual
- `elapsed_time` — time since start
- `R²`, `RMSE`, or other relevant metrics
- Any custom metrics the solver already computes
> Log files are saved to the project directory for later inspection by `/monitor-solver` and `/analyze-results`.
### Step 4: 执行求解
#### Python
```bash
# Run solver with timeout protection
timeout 3600 python3 <script> <args> 2>&1 | tee solve_log.txt
# For long-running solvers, use background execution
python3 <script> <args> > solve_log.txt 2>&1 &
echo $! > solver_pid.txt
```
#### MATLAB
```bash
# Run MATLAB script
timeout 3600 matlab -batch "run('<script>')" 2>&1 | tee solve_log.txt
```
For long-running jobs, use `run_in_background: true` to keep the conversation responsive.
### Step 5: 验证启动
Check process is running and producing output:
```bash
# Check if process is still running
ps aux | grep -E "python|matlab" | grep -v grep
# Check if log file is growing
ls -la solve_log.txt
tail -5 solve_log.txt
```
### Step 6: 结果收集
After solver completes:
1. Check exit code for errors
2. Collect output files (results, figures, data)
3. Save a brief execution summary
```bash
echo "=== 求解完成 ==="
echo "退出码: $?"
echo "耗时: $(cat solve_log.txt | grep 'Total time' | tail -1)"
echo "输出文件:"
ls -la results/ output/ figures/ 2>/dev/null
```
## Key Rules
- **Large file handling**: If the Write tool fails due to file size, immediately retry using Bash (`cat << 'EOF' > file`) to write in chunks. Do NOT ask the user for permission — just do it silently.
- ALWAYS check environment readiness first — never blindly run scripts
- Each solver gets its own background process with timeout protection
- Use `tee` to save logs for later inspection
- Run long commands with `run_in_background: true` to keep conversation responsive
- Report back: which script, what arguments, estimated time, PID
- If multiple sub-problems, run independent solvers in parallel
- Default timeout: 60 minutes. Warn if solver is expected to take longer.
- If solver fails, capture error output and suggest fixes
## CLAUDE.md Example
Users should add their environment info to their project's `CLAUDE.md`:
```markdown
## 计算环境
- Python: 3.10+ with numpy, scipy, matplotlib, pandas, scikit-learn
- MATLAB: R2024a (optional)
- 额外包: cvxpy (for optimization), networkx (for graph problems)
- 超时限制: 60 minutes per solver
- 数据目录: data/
- 结果目录: results/
```
> **环境配置**: Ensure all required packages are installed before running. The skill will auto-detect and install missing Python packages, but MATLAB toolboxes must be pre-installed.
عرض على GitHub