nmos2d 0.2.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,19 @@
1
+ cmake_minimum_required(VERSION 3.15)
2
+ project(nmos2d LANGUAGES CXX)
3
+ find_package(Threads REQUIRED)
4
+ add_executable(mesh_demo main.cpp device/device.cpp grid/grid.cpp batch/pilot.cpp
5
+ solver/dc_solver.cpp solver/poisson.cpp solver/transport.cpp solver/sweep.cpp
6
+ results/fields.cpp results/metrics.cpp)
7
+ target_compile_features(mesh_demo PRIVATE cxx_std_17)
8
+ target_link_libraries(mesh_demo PRIVATE Threads::Threads)
9
+ if(MINGW)
10
+ target_link_options(mesh_demo PRIVATE -static)
11
+ elseif(MSVC)
12
+ target_compile_options(mesh_demo PRIVATE /utf-8)
13
+ set_property(TARGET mesh_demo PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
14
+ endif()
15
+ install(TARGETS mesh_demo RUNTIME DESTINATION nmos2d/bin)
16
+
17
+ if(SKBUILD)
18
+ install(FILES examples/planar_nmos.py DESTINATION "${SKBUILD_DATA_DIR}/share/nmos2d/examples")
19
+ endif()
nmos2d-0.2.0/NMOS.h ADDED
@@ -0,0 +1,71 @@
1
+ #pragma once
2
+
3
+ #include <string>
4
+ #include <vector>
5
+
6
+ // 二维硅 NMOS 器件参数
7
+ class MOSFET {
8
+ public:
9
+ // 1. 器件剖面尺寸。x 从硅区左边界向右,深度从硅表面向下。
10
+ // 矩形源区的 x 范围为 [0, Ls],矩形漏区为 [SiL - Ld, SiL]。
11
+ double Lg; // 栅长,um(沿源->漏)
12
+ double W; // 沟道宽度,um(垂直于剖面)
13
+ double tox; // 栅氧厚度,nm
14
+
15
+ double SiL; // 仿真硅区总长,um
16
+ double SiD; // 仿真硅区总深,um
17
+
18
+ double Ls; // 源区横向长度,um
19
+ double Ld; // 漏区横向长度,um
20
+ double xjs; // 源结结深,um(矩形源区的深度)
21
+ double xjd; // 漏结结深,um(矩形漏区的深度)
22
+
23
+ // 栅极以硅区为中心,坐标单位为 um。
24
+ double gateStartUm()
25
+ const noexcept {
26
+ return (SiL - Lg) / 2.0; }
27
+ double gateEndUm()
28
+ const noexcept {
29
+ return gateStartUm() + Lg; }
30
+
31
+ // 2. 掺杂浓度,cm^-3
32
+ double NA; // P 型衬底受主浓度
33
+ double NDs; // N+ 源区施主浓度
34
+ double NDd; // N+ 漏区施主浓度
35
+
36
+ // 3. 栅极
37
+ std::string gate_mat; // 栅极材料,如 "n+ polysilicon"
38
+ double phiM; // 功函数,eV
39
+ bool useVFB; // 题目直接给 VFB 时置 true
40
+ double VFB; // 平带电压,V
41
+
42
+ // 4. 材料与温度
43
+ double epsSi; // 硅相对介电常数
44
+ double epsOx; // 二氧化硅相对介电常数
45
+ double ni; // 本征载流子浓度,cm^-3
46
+ double mu_n; // 电子迁移率,cm^2/(V·s)
47
+ double mu_p; // 空穴迁移率,cm^2/(V·s)
48
+ double T; // 温度,K
49
+
50
+ // 网格划分数。硅区和栅氧层在纵向分别划分,共用交界面。
51
+ int Nx; // 横向网格数
52
+ int NySi; // 硅区纵向网格数
53
+ int NyOx; // 栅氧层纵向网格数
54
+ double surfaceMeshDepthUm = 0.0; // 硅表面加密深度,0 表示关闭
55
+
56
+ // 衬底接源极,所有工作点和扫压共用 VBS = 0 V。
57
+ static constexpr double Vbs = 0.0;
58
+
59
+ // 5. 六张分布图的两个工作点
60
+ double Vgs_off, Vds_off; // 关断
61
+ double Vgs_on, Vds_on; // 导通
62
+
63
+ // 6. 输出特性:几条固定 VGS,扫 VDS
64
+ std::vector<double> Vgs_list; // 固定的几个 VGS,V
65
+ double VdsFrom, VdsTo, VdsStep; // VDS 扫描范围与步长,V
66
+
67
+ // 7. 转移特性:固定 VDS,扫 VGS
68
+ double VgsFrom, VgsTo, VgsStep; // VGS 扫描范围与步长,V
69
+ double highVds, differenceStep, thresholdCurrent, electrostaticGate;
70
+ double Vds_transfer; // 转移特性的固定 VDS,V
71
+ };
nmos2d-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.2
2
+ Name: nmos2d
3
+ Version: 0.2.0
4
+ Summary: Two-dimensional drift-diffusion simulation of planar silicon NMOS devices
5
+ Keywords: NMOS,semiconductor,drift-diffusion,finite-volume
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+
9
+ # nmos2d · 二维平面 NMOS 器件仿真
10
+
11
+ [Documentation](https://qianyuyingluo.github.io/nmos2d/) · [中文文档](https://qianyuyingluo.github.io/nmos2d/zh.html)
12
+
13
+ nmos2d 在硅和栅氧层的二维网格上联立求解泊松方程与载流子漂移扩散方程,计算端口电流、栅电荷及器件内部的物理场。Python 接口调用随 wheel 安装的 C++ 求解器,运行时只依赖 Python 标准库。
14
+
15
+ ## 安装与发行示例
16
+
17
+ Windows x64,Python 3.10 及以上:
18
+
19
+ ```powershell
20
+ python -m pip install .\nmos2d-0.2.0-py3-none-win_amd64.whl
21
+ ```
22
+
23
+ 发行示例 `examples/planar_nmos.py` 显式填写论文的器件、网格、偏压和阈值提取电流。将示例复制到工作目录,在 IDLE 中打开后按 F5 运行。安装 wheel 后可在 PowerShell 中复制示例:
24
+
25
+ ```powershell
26
+ python -c "from importlib.metadata import distribution; from shutil import copyfile; f = next(p for p in distribution('nmos2d').files if p.name == 'planar_nmos.py'); copyfile(f.locate(), 'planar_nmos.py')"
27
+ ```
28
+
29
+ 各计算入口都要求传入 `device` 和 `mesh`。例如,使用自己填写的器件和网格求单个工作点:
30
+
31
+ ```python
32
+ point = nmos2d.solve(device, mesh=mesh, vgs_v=vg, vds_v=vd)
33
+ print(point.drain_current_a)
34
+ ```
35
+
36
+ ## 器件与网格
37
+
38
+ 创建 `Device` 时按下表填写。平带电压和栅功函数均须显式传入,其中一项填数值,另一项填 `None`。衬底接源极。
39
+
40
+ | Device 参数 | 含义 |
41
+ | --- | --- |
42
+ | `gate_length_um`, `width_um` | 栅长、垂直于二维剖面的沟道宽度,µm |
43
+ | `oxide_thickness_nm`, `silicon_depth_um` | 栅氧厚度(nm)、硅区深度(µm) |
44
+ | `source_length_um`, `drain_length_um` | 源区、漏区横向长度,µm。总长由源长、栅长和漏长相加得到,栅极居中 |
45
+ | `source_junction_depth_um`, `drain_junction_depth_um` | 源结、漏结深度,µm |
46
+ | `substrate_doping_cm3`, `source_doping_cm3`, `drain_doping_cm3` | 衬底受主、源区施主、漏区施主浓度,cm⁻³ |
47
+ | `intrinsic_density_cm3`, `temperature_k` | 本征载流子浓度(cm⁻³)、温度(K) |
48
+ | `silicon_permittivity`, `oxide_permittivity` | 硅和栅氧的相对介电常数 |
49
+ | `electron_mobility_cm2_vs`, `hole_mobility_cm2_vs` | 电子和空穴迁移率,cm²/(V·s) |
50
+ | `flat_band_v`, `gate_work_function_ev` | 平带电压(V)或栅功函数(eV),二选一 |
51
+
52
+ 创建 `Mesh` 时填写 `nx`、`ny_si`、`ny_ox` 和 `surface_refinement_um`,分别是横向列数、硅层数、栅氧层数和表面加密深度(µm)。深度填 0 可关闭表面加密。
53
+
54
+ ## 计算接口
55
+
56
+ | 接口 | 除器件和网格外的仿真输入 |
57
+ | --- | --- |
58
+ | `solve` | 单个工作点的 `vgs_v` 和 `vds_v` |
59
+ | `transfer` | 固定 `vds_v` 及栅压起点、终点、步长 |
60
+ | `output` | `gate_voltages_v` 以及漏压起点、终点、步长 |
61
+ | `scan` | `bias=ScanBias(...)`,包含栅漏扫描起止值与步长、开关态栅漏电压、低/高漏压、差分半步长和阈值参考电流(A) |
62
+ | `characterize` | `bias=Bias(...)`,在上述参数基础上填写输出曲线的栅压列表和静电计算的栅压 `electrostatic_gate_v` |
63
+
64
+ `scan` 用栅压和漏压的笛卡尔积生成直流点,并在导通栅压、高漏压处取四个差分点。开关态和两条转移曲线的取样电压须落在扫描网格上。扫描结果包含端口电流、栅电荷、收敛状态和残差。设置 `save_fields=True` 可导出开关态及高漏压分布。`characterize` 输出伏安曲线、场分布和电学指标。
65
+
66
+ 支持并行的接口默认使用一个线程,传入 `workers=N` 可指定线程数。`scan` 和 `characterize` 的 `output_dir` 用于保存 CSV,省略时创建临时目录。
67
+
68
+ ## 命令行与源码安装
69
+
70
+ `nmos2d --help` 显示命令格式。命令行计算需使用 `--stdin-config`,从标准输入按行读取参数名和值。名称与 Python 接口的字段一致,栅功函数和平带电压只写选用的一项。
71
+
72
+ 从源码构建需要 C++17 编译器。在项目根目录运行 `python -m pip install .`。
nmos2d-0.2.0/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # nmos2d · 二维平面 NMOS 器件仿真
2
+
3
+ [Documentation](https://qianyuyingluo.github.io/nmos2d/) · [中文文档](https://qianyuyingluo.github.io/nmos2d/zh.html)
4
+
5
+ nmos2d 在硅和栅氧层的二维网格上联立求解泊松方程与载流子漂移扩散方程,计算端口电流、栅电荷及器件内部的物理场。Python 接口调用随 wheel 安装的 C++ 求解器,运行时只依赖 Python 标准库。
6
+
7
+ ## 安装与发行示例
8
+
9
+ Windows x64,Python 3.10 及以上:
10
+
11
+ ```powershell
12
+ python -m pip install .\nmos2d-0.2.0-py3-none-win_amd64.whl
13
+ ```
14
+
15
+ 发行示例 `examples/planar_nmos.py` 显式填写论文的器件、网格、偏压和阈值提取电流。将示例复制到工作目录,在 IDLE 中打开后按 F5 运行。安装 wheel 后可在 PowerShell 中复制示例:
16
+
17
+ ```powershell
18
+ python -c "from importlib.metadata import distribution; from shutil import copyfile; f = next(p for p in distribution('nmos2d').files if p.name == 'planar_nmos.py'); copyfile(f.locate(), 'planar_nmos.py')"
19
+ ```
20
+
21
+ 各计算入口都要求传入 `device` 和 `mesh`。例如,使用自己填写的器件和网格求单个工作点:
22
+
23
+ ```python
24
+ point = nmos2d.solve(device, mesh=mesh, vgs_v=vg, vds_v=vd)
25
+ print(point.drain_current_a)
26
+ ```
27
+
28
+ ## 器件与网格
29
+
30
+ 创建 `Device` 时按下表填写。平带电压和栅功函数均须显式传入,其中一项填数值,另一项填 `None`。衬底接源极。
31
+
32
+ | Device 参数 | 含义 |
33
+ | --- | --- |
34
+ | `gate_length_um`, `width_um` | 栅长、垂直于二维剖面的沟道宽度,µm |
35
+ | `oxide_thickness_nm`, `silicon_depth_um` | 栅氧厚度(nm)、硅区深度(µm) |
36
+ | `source_length_um`, `drain_length_um` | 源区、漏区横向长度,µm。总长由源长、栅长和漏长相加得到,栅极居中 |
37
+ | `source_junction_depth_um`, `drain_junction_depth_um` | 源结、漏结深度,µm |
38
+ | `substrate_doping_cm3`, `source_doping_cm3`, `drain_doping_cm3` | 衬底受主、源区施主、漏区施主浓度,cm⁻³ |
39
+ | `intrinsic_density_cm3`, `temperature_k` | 本征载流子浓度(cm⁻³)、温度(K) |
40
+ | `silicon_permittivity`, `oxide_permittivity` | 硅和栅氧的相对介电常数 |
41
+ | `electron_mobility_cm2_vs`, `hole_mobility_cm2_vs` | 电子和空穴迁移率,cm²/(V·s) |
42
+ | `flat_band_v`, `gate_work_function_ev` | 平带电压(V)或栅功函数(eV),二选一 |
43
+
44
+ 创建 `Mesh` 时填写 `nx`、`ny_si`、`ny_ox` 和 `surface_refinement_um`,分别是横向列数、硅层数、栅氧层数和表面加密深度(µm)。深度填 0 可关闭表面加密。
45
+
46
+ ## 计算接口
47
+
48
+ | 接口 | 除器件和网格外的仿真输入 |
49
+ | --- | --- |
50
+ | `solve` | 单个工作点的 `vgs_v` 和 `vds_v` |
51
+ | `transfer` | 固定 `vds_v` 及栅压起点、终点、步长 |
52
+ | `output` | `gate_voltages_v` 以及漏压起点、终点、步长 |
53
+ | `scan` | `bias=ScanBias(...)`,包含栅漏扫描起止值与步长、开关态栅漏电压、低/高漏压、差分半步长和阈值参考电流(A) |
54
+ | `characterize` | `bias=Bias(...)`,在上述参数基础上填写输出曲线的栅压列表和静电计算的栅压 `electrostatic_gate_v` |
55
+
56
+ `scan` 用栅压和漏压的笛卡尔积生成直流点,并在导通栅压、高漏压处取四个差分点。开关态和两条转移曲线的取样电压须落在扫描网格上。扫描结果包含端口电流、栅电荷、收敛状态和残差。设置 `save_fields=True` 可导出开关态及高漏压分布。`characterize` 输出伏安曲线、场分布和电学指标。
57
+
58
+ 支持并行的接口默认使用一个线程,传入 `workers=N` 可指定线程数。`scan` 和 `characterize` 的 `output_dir` 用于保存 CSV,省略时创建临时目录。
59
+
60
+ ## 命令行与源码安装
61
+
62
+ `nmos2d --help` 显示命令格式。命令行计算需使用 `--stdin-config`,从标准输入按行读取参数名和值。名称与 Python 接口的字段一致,栅功函数和平带电压只写选用的一项。
63
+
64
+ 从源码构建需要 C++17 编译器。在项目根目录运行 `python -m pip install .`。
@@ -0,0 +1,359 @@
1
+ #include "pilot.h"
2
+ #include "../solver/worker_budget.h"
3
+ #include "../results/fields.h"
4
+ #include "../results/metrics.h"
5
+
6
+ #include <algorithm>
7
+ #include <array>
8
+ #include <atomic>
9
+ #include <chrono>
10
+ #include <cmath>
11
+ #include <filesystem>
12
+ #include <fstream>
13
+ #include <functional>
14
+ #include <future>
15
+ #include <iomanip>
16
+ #include <iostream>
17
+ #include <limits>
18
+ #include <sstream>
19
+ #include <stdexcept>
20
+ #include <string>
21
+ #include <utility>
22
+
23
+ #ifndef _WIN32
24
+ #include <fcntl.h>
25
+ #include <unistd.h>
26
+ #endif
27
+
28
+ namespace {
29
+
30
+ using Clock = std::chrono::steady_clock;
31
+
32
+ double secondsSince(Clock::time_point start) {
33
+ return std::chrono::duration<double>(Clock::now() - start).count();
34
+ }
35
+
36
+ struct Point {
37
+ double vgs = 0;
38
+ double vds = 0;
39
+ DcResult result;
40
+ DcDiagnostics diagnostics;
41
+ double seconds = 0;
42
+ std::string error;
43
+ };
44
+
45
+ using Row = std::vector<Point>;
46
+ namespace fs = std::filesystem;
47
+
48
+ void syncPath(const fs::path& path) {
49
+ #ifndef _WIN32
50
+ const int handle = open(path.c_str(), O_RDONLY);
51
+ if (handle == -1) throw std::runtime_error("Could not open " + path.string() + " for sync.");
52
+ const int status = fsync(handle);
53
+ close(handle);
54
+ if (status != 0) throw std::runtime_error("Could not sync " + path.string());
55
+ #else
56
+ (void)path;
57
+ #endif
58
+ }
59
+
60
+ void commitFile(const fs::path& temporary, const fs::path& target) {
61
+ syncPath(temporary);
62
+ fs::rename(temporary, target);
63
+ syncPath(target.parent_path());
64
+ }
65
+
66
+ template<class T>
67
+ void writeValue(std::ostream& out, const T& value) {
68
+ out.write(reinterpret_cast<const char*>(&value), sizeof(value));
69
+ }
70
+
71
+ template<class T>
72
+ void readValue(std::istream& in, T& value) {
73
+ in.read(reinterpret_cast<char*>(&value), sizeof(value));
74
+ }
75
+
76
+ fs::path rowFile(const fs::path& checkpoints, std::size_t index) {
77
+ return checkpoints / ("row_" + std::to_string(index) + ".bin");
78
+ }
79
+
80
+ void saveRow(const fs::path& path, const Row& row, std::size_t analogColumn) {
81
+ const fs::path temporary = path.string() + ".tmp";
82
+ std::ofstream out(temporary, std::ios::binary);
83
+ for (std::size_t i = 0; i < row.size(); ++i) {
84
+ const auto& p = row[i];
85
+ const auto& r = p.result;
86
+ for (double value : {p.vgs, p.vds, r.drainCurrentA, r.sourceCurrentA, r.bodyCurrentA,
87
+ r.gateChargeC, p.diagnostics.residual, p.seconds}) {
88
+ writeValue(out, value);
89
+ }
90
+ writeValue(out, p.diagnostics.newtonIterations);
91
+ writeValue(out, p.error.size());
92
+ out.write(p.error.data(), static_cast<std::streamsize>(p.error.size()));
93
+ const std::size_t stateSize = (i == 0 || i == analogColumn) ? r.solution.size() : 0;
94
+ writeValue(out, stateSize);
95
+ if (stateSize) {
96
+ out.write(reinterpret_cast<const char*>(r.solution.data()), stateSize * sizeof(double));
97
+ }
98
+ }
99
+ out.close();
100
+ if (!out) throw std::runtime_error("Could not save scan row " + path.string());
101
+ commitFile(temporary, path);
102
+ }
103
+
104
+ Row loadRow(const fs::path& path, std::size_t expectedStateSize, std::size_t columns) {
105
+ std::ifstream in(path, std::ios::binary);
106
+ Row row(columns);
107
+ for (auto& p : row) {
108
+ auto& r = p.result;
109
+ for (double* value : {&p.vgs, &p.vds, &r.drainCurrentA, &r.sourceCurrentA, &r.bodyCurrentA,
110
+ &r.gateChargeC, &p.diagnostics.residual, &p.seconds}) {
111
+ readValue(in, *value);
112
+ }
113
+ r.vgs = p.vgs;
114
+ r.vds = p.vds;
115
+ readValue(in, p.diagnostics.newtonIterations);
116
+ std::size_t errorSize = 0, stateSize = 0;
117
+ readValue(in, errorSize);
118
+ if (!in || errorSize > 8192) throw std::runtime_error("Invalid checkpoint " + path.string());
119
+ p.error.resize(errorSize);
120
+ in.read(p.error.data(), static_cast<std::streamsize>(errorSize));
121
+ readValue(in, stateSize);
122
+ if (!in || (stateSize != 0 && stateSize != expectedStateSize)) {
123
+ throw std::runtime_error("Invalid checkpoint state in " + path.string());
124
+ }
125
+ r.solution.resize(stateSize);
126
+ if (stateSize) in.read(reinterpret_cast<char*>(r.solution.data()), stateSize * sizeof(double));
127
+ if (!in) throw std::runtime_error("Incomplete checkpoint " + path.string());
128
+ }
129
+ return row;
130
+ }
131
+
132
+ void savePilotField(const char* file, const DeviceMesh& mesh, const Point& point) {
133
+ if (!point.error.empty()) return;
134
+ const std::string temporary = std::string(file) + ".tmp";
135
+ saveFields(temporary, mesh, point.result);
136
+ commitFile(temporary, file);
137
+ }
138
+
139
+ void validateResume(const fs::path& checkpoints, const MOSFET& d, bool fields) {
140
+ const fs::path path = checkpoints / "device.txt";
141
+ std::ostringstream key;
142
+ key << "rows-v2 " << std::setprecision(17) << d.Lg << ' ' << d.W << ' ' << d.tox << ' '
143
+ << d.SiL << ' ' << d.SiD << ' ' << d.Ls << ' ' << d.Ld << ' ' << d.xjs << ' ' << d.xjd << ' '
144
+ << d.NA << ' ' << d.NDs << ' ' << d.NDd << ' ' << d.epsSi << ' ' << d.epsOx << ' '
145
+ << d.ni << ' ' << d.mu_n << ' ' << d.mu_p << ' ' << d.T << ' '
146
+ << (d.useVFB ? d.VFB : d.phiM) << ' ' << d.useVFB << ' ' << d.Nx << ' '
147
+ << d.NySi << ' ' << d.NyOx << ' ' << d.surfaceMeshDepthUm << ' ' << fields;
148
+ for (double value : {d.VgsFrom, d.VgsTo, d.VgsStep, d.VdsFrom, d.VdsTo, d.VdsStep,
149
+ d.Vgs_on, d.Vds_on, d.Vgs_off, d.Vds_off, d.Vds_transfer,
150
+ d.highVds, d.differenceStep, d.thresholdCurrent}) key << ' ' << value;
151
+ if (fs::exists(path)) {
152
+ std::ifstream in(path);
153
+ std::string existing;
154
+ std::getline(in, existing);
155
+ if (existing != key.str()) {
156
+ throw std::runtime_error("Checkpoint settings do not match this device. Use a different working directory.");
157
+ }
158
+ } else {
159
+ const fs::path temporary = path.string() + ".tmp";
160
+ std::ofstream out(temporary);
161
+ out << key.str() << '\n';
162
+ out.close();
163
+ if (!out) throw std::runtime_error("Could not save checkpoint parameters.");
164
+ commitFile(temporary, path);
165
+ }
166
+ }
167
+
168
+ Point measurePoint(const DeviceMesh& mesh, const MOSFET& device, double vgs, double vds,
169
+ const DcResult& previous) {
170
+ Point point;
171
+ point.vgs = vgs;
172
+ point.vds = vds;
173
+ point.diagnostics.timeoutSeconds = 60.0;
174
+ point.diagnostics.maxNewtonIterations = 160;
175
+ const auto start = Clock::now();
176
+ try {
177
+ point.result = solveDc(mesh, device, vgs, vds, &previous, &point.diagnostics);
178
+ } catch (const std::exception& error) {
179
+ point.error = error.what();
180
+ }
181
+ point.seconds = secondsSince(start);
182
+ return point;
183
+ }
184
+
185
+ Row drainRow(const DeviceMesh& mesh, const MOSFET& device, Point first,
186
+ const DcResult& equilibrium, const std::vector<double>& drains) {
187
+ Row row(drains.size());
188
+ row.front() = std::move(first);
189
+ const DcResult* previous = row.front().error.empty() ? &row.front().result : &equilibrium;
190
+ for (std::size_t col = 1; col < drains.size(); ++col) {
191
+ row[col] = measurePoint(mesh, device, row.front().vgs, drains[col], *previous);
192
+ if (row[col].error.empty()) previous = &row[col].result;
193
+ }
194
+ return row;
195
+ }
196
+
197
+ std::size_t sampleIndex(const std::vector<double>& axis, double value, const char* name) {
198
+ auto closest = std::min_element(axis.begin(), axis.end(), [value](double a, double b) {
199
+ return std::abs(a - value) < std::abs(b - value);
200
+ });
201
+ if (std::abs(*closest - value) > 1e-12 * std::max(1.0, std::abs(value)))
202
+ throw std::invalid_argument(std::string(name) + " must be sampled by the scan grid.");
203
+ return static_cast<std::size_t>(closest - axis.begin());
204
+ }
205
+
206
+ void writePoint(std::ostream& csv, const char* kind, const Point& point) {
207
+ csv << kind << ',' << point.vgs << ',' << point.vds << ",0,";
208
+ if (point.error.empty()) {
209
+ csv << point.result.drainCurrentA << ',' << point.result.sourceCurrentA << ','
210
+ << point.result.bodyCurrentA << ',' << point.result.gateChargeC << ",1,";
211
+ } else {
212
+ csv << ",,,,0,";
213
+ }
214
+ csv << point.diagnostics.newtonIterations << ',' << point.diagnostics.residual << ','
215
+ << point.seconds << ',';
216
+ if (!point.error.empty()) {
217
+ csv << '"';
218
+ for (char character : point.error) {
219
+ if (character == '"') csv << '"';
220
+ csv << character;
221
+ }
222
+ csv << '"';
223
+ }
224
+ csv << '\n';
225
+ }
226
+
227
+ } // namespace
228
+
229
+ int runPilot(const DeviceMesh& mesh, const MOSFET& device, int workers, bool fields) {
230
+ if (workers < 1) throw std::invalid_argument("workers must be positive");
231
+ WorkerBudget budget(workers);
232
+ const auto start = Clock::now();
233
+ const auto gates = voltageSteps(device.VgsFrom, device.VgsTo, device.VgsStep);
234
+ const auto drains = voltageSteps(device.VdsFrom, device.VdsTo, device.VdsStep);
235
+ const auto offRow = sampleIndex(gates, device.Vgs_off, "off_vgs_v");
236
+ const auto onRow = sampleIndex(gates, device.Vgs_on, "on_vgs_v");
237
+ const auto offCol = sampleIndex(drains, device.Vds_off, "off_vds_v");
238
+ const auto onCol = sampleIndex(drains, device.Vds_on, "on_vds_v");
239
+ const auto lowCol = sampleIndex(drains, device.Vds_transfer, "transfer_vds_v");
240
+ const auto highCol = sampleIndex(drains, device.highVds, "high_vds_v");
241
+ const fs::path checkpoints = "output/checkpoints";
242
+ fs::create_directories(checkpoints);
243
+ validateResume(checkpoints, device, fields);
244
+ DcDiagnostics equilibriumDiagnostics;
245
+ equilibriumDiagnostics.timeoutSeconds = 60.0;
246
+ const DcResult equilibrium = solveDc(mesh, device, 0, 0, nullptr, &equilibriumDiagnostics);
247
+ std::vector<Point> seeds(gates.size());
248
+ std::vector<Row> rows(gates.size());
249
+ std::vector<std::size_t> remaining;
250
+ auto gateSeed = equilibrium;
251
+ for (std::size_t row = 0; row < gates.size(); ++row) {
252
+ const double gate = gates[row];
253
+ const auto path = rowFile(checkpoints, row);
254
+ if (fs::exists(path)) {
255
+ rows[row] = loadRow(path, mesh.cells.size() * 3, drains.size());
256
+ if (rows[row][0].error.empty()) {
257
+ gateSeed = rows[row][0].result;
258
+ }
259
+ continue;
260
+ }
261
+ auto zero = measurePoint(mesh, device, gate, drains.front(), gateSeed);
262
+ if (zero.error.empty()) {
263
+ gateSeed = zero.result;
264
+ }
265
+ seeds[row] = std::move(zero);
266
+ remaining.push_back(row);
267
+ }
268
+ std::cout << "reused_rows=" << rows.size() - remaining.size() << "/" << gates.size() << std::endl;
269
+
270
+ // 用固定数量的工作线程领取栅压行。每行内部仍按漏压顺序计算。
271
+ std::atomic<std::size_t> nextRow{0};
272
+ std::vector<std::future<void>> tasks;
273
+ auto processRows = [&] {
274
+ for (;;) {
275
+ const std::size_t next = nextRow.fetch_add(1, std::memory_order_relaxed);
276
+ if (next >= remaining.size()) {
277
+ return;
278
+ }
279
+ const std::size_t row = remaining[next];
280
+ rows[row] = drainRow(mesh, device, std::move(seeds[row]), equilibrium, drains);
281
+ if (fields && row == offRow) {
282
+ savePilotField("output/fields_off.csv", mesh, rows[row][offCol]);
283
+ }
284
+ if (fields && row == onRow) {
285
+ savePilotField("output/fields_on.csv", mesh, rows[row][onCol]);
286
+ savePilotField("output/fields_high_vds.csv", mesh, rows[row][highCol]);
287
+ }
288
+ saveRow(rowFile(checkpoints, row), rows[row], row == onRow ? highCol : drains.size());
289
+ }
290
+ };
291
+ const auto rowWorkers = std::min<std::size_t>(workers, remaining.size());
292
+ for (std::size_t i = 1; i < rowWorkers; ++i) {
293
+ tasks.push_back(budget.submit(processRows));
294
+ }
295
+ processRows();
296
+ for (auto& task : tasks) {
297
+ task.get();
298
+ }
299
+
300
+ std::ofstream csv("output/pilot_points.csv.tmp");
301
+ csv << "kind,Vgs_V,Vds_V,Vbs_V,Id_A,Is_A,Ib_A,Qg_C,converged,newton_iterations,"
302
+ "normalized_residual,elapsed_s,error\n" << std::setprecision(16);
303
+ std::vector<TransferPoint> low, high;
304
+ const auto& off = rows[offRow][offCol];
305
+ const auto& on = rows[onRow][onCol];
306
+ const auto& analog = rows[onRow][highCol];
307
+ std::size_t successes = 0;
308
+ double maxImbalance = 0;
309
+ auto record = [&](const char* kind, const Point& point) {
310
+ writePoint(csv, kind, point);
311
+ if (point.error.empty()) {
312
+ ++successes;
313
+ const auto& r = point.result;
314
+ maxImbalance = std::max(maxImbalance, std::abs(r.drainCurrentA + r.sourceCurrentA + r.bodyCurrentA));
315
+ }
316
+ };
317
+ for (std::size_t i = 0; i < rows.size(); ++i) {
318
+ auto& row = rows[i];
319
+ for (const auto& point : row) {
320
+ record("iv", point);
321
+ }
322
+ if (row[lowCol].error.empty()) low.push_back({row[lowCol].vgs, row[lowCol].result.drainCurrentA});
323
+ if (row[highCol].error.empty()) high.push_back({row[highCol].vgs, row[highCol].result.drainCurrentA});
324
+ }
325
+
326
+ const double deltaV = device.differenceStep;
327
+ const double gate = device.Vgs_on, drain = device.highVds;
328
+ const std::array<std::pair<double, double>, 4> biases{{
329
+ {gate - deltaV, drain}, {gate + deltaV, drain}, {gate, drain - deltaV}, {gate, drain + deltaV}
330
+ }};
331
+ std::vector<std::future<Point>> differences;
332
+ const DcResult& seed = analog.error.empty() ? analog.result : equilibrium;
333
+ for (const auto& bias : biases) {
334
+ differences.push_back(budget.submit([&, bias] {
335
+ return measurePoint(mesh, device, bias.first, bias.second, seed);
336
+ }));
337
+ }
338
+ std::array<Point, 4> delta;
339
+ for (std::size_t i = 0; i < delta.size(); ++i) {
340
+ delta[i] = differences[i].get();
341
+ record("metric_difference", delta[i]);
342
+ }
343
+ csv.close();
344
+ if (!csv) throw std::runtime_error("Could not write pilot_points.csv.");
345
+ commitFile("output/pilot_points.csv.tmp", "output/pilot_points.csv");
346
+
347
+ const auto total = gates.size() * drains.size() + biases.size();
348
+ if (successes == total) {
349
+ const double gm = (delta[1].result.drainCurrentA - delta[0].result.drainCurrentA) / (2 * deltaV);
350
+ const double gds = (delta[3].result.drainCurrentA - delta[2].result.drainCurrentA) / (2 * deltaV);
351
+ const double cgg = (delta[1].result.gateChargeC - delta[0].result.gateChargeC) / (2 * deltaV);
352
+ saveMetrics(device, off.result, on.result, low, high, {drain, deltaV},
353
+ {gm, gds > 0 ? 1 / gds : std::numeric_limits<double>::quiet_NaN(), cgg});
354
+ }
355
+ std::cout << std::setprecision(9) << "pilot_seconds=" << secondsSince(start)
356
+ << "\nconverged_points=" << successes << "/" << total << "\nmax_terminal_imbalance_A="
357
+ << maxImbalance << std::endl;
358
+ return successes == total ? 0 : 2;
359
+ }
@@ -0,0 +1,5 @@
1
+ #pragma once
2
+
3
+ #include "../device/device.h"
4
+
5
+ int runPilot(const DeviceMesh& mesh, const MOSFET& device, int workers = 1, bool fields = false);