coordinate-system 5.2.2__cp313-cp313-win_amd64.whl → 6.0.0__cp313-cp313-win_amd64.whl

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.
@@ -1,675 +1,792 @@
1
1
  """
2
- 量子复标架代数 - 基于非对易几何的完整实现
3
- =======================================
4
-
5
- 实现了完整的复标架场理论,包括:
6
- 1. 连续谱复标架 (|x⟩, |p⟩) 满足 ⟨x|x'⟩ = δ(x-x')
7
- 2. 非对易代数 [x̂, p̂] = iħ
8
- 3. 量子联络与曲率
9
- 4. 外尔关系与量子二项式展开
10
-
11
- 核心创新:
12
- - 连续标架场的离散逼近保持几何结构
13
- - 算符代数与态矢代数分离
14
- - 非对易性的几何实现
15
- - 量子傅立叶变换作为标架旋转
16
-
17
- 作者: DeepSeek
18
- 日期: 2025-12-02
2
+ 复数量子化标架场 (Complex Quantum Frame Field)
3
+ ==============================================
4
+
5
+ 统一傅里叶变换与路径积分的几何框架。
6
+
7
+ 核心思想:
8
+ - 傅里叶变换 = 复标架场的相位旋转 (QFrame * e^{iθ})
9
+ - 共形变换 = 复标架场的缩放 (QFrame * λ, λ∈ℝ⁺)
10
+ - 路径积分 = 标架场上的测度积分
11
+
12
+ 数学框架:
13
+ - 复标度因子 Q ∈ ℂ 编码几何与谱空间的关系
14
+ - 标架乘法实现变换复合
15
+ - 行列式给出积分测度
16
+
17
+ Author: Quantum Frame Theory
18
+ Date: 2025-12-03
19
19
  """
20
20
 
21
21
  import numpy as np
22
- from typing import List, Tuple, Union, Optional, Callable
23
- import sympy as sp
22
+ from typing import List, Tuple, Dict, Optional, Union, Any
24
23
  from dataclasses import dataclass
25
- from scipy import integrate, linalg
26
- from scipy.special import hermite
27
- import matplotlib.pyplot as plt
28
24
 
29
- # 物理常数
30
- HBAR = 1.0 # 简化普朗克常数
31
-
32
- # ========== 基础数学结构 ==========
25
+ # 导入坐标系统
26
+ try:
27
+ from .coordinate_system import coord3, vec3, quat
28
+ except ImportError:
29
+ try:
30
+ from coordinate_system import coord3, vec3, quat
31
+ except ImportError:
32
+ # 延迟导入,允许独立使用
33
+ coord3 = None
34
+ vec3 = None
35
+ quat = None
33
36
 
34
- @dataclass
35
- class DiracVector:
36
- """狄拉克符号中的态矢基元"""
37
- value: float # 本征值 (x 或 p)
38
- basis: str # 'position' 或 'momentum'
39
-
40
- def __repr__(self):
41
- symbol = 'x' if self.basis == 'position' else 'p'
42
- return f"|{symbol}={self.value:.2f}⟩"
37
+ # 物理常数
38
+ HBAR = 1.0 # 约化普朗克常数(自然单位)
43
39
 
44
- class Bra:
45
- """左矢 ⟨ψ|"""
46
- def __init__(self, state: 'QState'):
47
- self.state = state
48
-
49
- def __or__(self, other: 'Ket') -> complex:
50
- """内积 ⟨ψ|φ⟩"""
51
- return self.state.inner_product(other.state)
40
+ # GPU 可用性检查
41
+ try:
42
+ import cupy as cp
43
+ import cupyx.scipy.fft as cufft
44
+ GPU_AVAILABLE = True
45
+ except ImportError:
46
+ GPU_AVAILABLE = False
47
+ cp = None
48
+ cufft = None
52
49
 
53
- class Ket:
54
- """右矢 |φ⟩"""
55
- def __init__(self, state: 'QState'):
56
- self.state = state
57
-
58
- def __matmul__(self, other: 'Bra') -> 'Operator':
59
- """外积 |φ⟩⟨ψ|"""
60
- return OuterProduct(self, other)
61
50
 
62
- # ========== 复标架场实现 ==========
51
+ # ============================================================
52
+ # 核心复标架代数
53
+ # ============================================================
63
54
 
64
55
  class QFrame:
65
56
  """
66
- 复标架场 - 连续正交归一基的数学实现
67
-
68
- 数学定义:
69
- 位置标架场: ℱₓ = {|x⟩: x∈ℝ}, ⟨x|x'⟩ = δ(x-x')
70
- 动量标架场: ℱₚ = {|p⟩: p∈ℝ}, ⟨p|p'⟩ = δ(p-p')
71
-
72
- 变换关系:⟨x|p⟩ = (1/√(2πħ)) e^{ipx/ħ}
57
+ 量子标架 - 统一傅里叶变换与路径积分的几何框架
58
+
59
+ 核心属性:
60
+ - base_coord: 基础坐标系 (coord3 对象)
61
+ - Q: 复标度因子 Q ℂ,编码相位与缩放
62
+
63
+ 关键变换:
64
+ - QFrame * e^{iθ} = 傅里叶变换 (θ=π/2 为标准变换)
65
+ - QFrame * λ = 共形变换 (λ∈ℝ⁺)
66
+ - QFrame * QFrame = 标架复合 (对应路径积分中的复合)
73
67
  """
74
-
75
- def __init__(self, basis_type: str, hbar: float = HBAR):
76
- self.basis_type = basis_type
77
- self.hbar = hbar
78
- self._symbol = 'x' if basis_type == 'position' else 'p'
79
-
80
- def ket(self, value: float) -> Ket:
81
- """生成标架基矢 |x⟩ |p⟩"""
82
- return Ket(QState([(value, 1.0)], self.basis_type))
83
-
84
- def bra(self, value: float) -> Bra:
85
- """生成对偶标架 ⟨x| 或 ⟨p|"""
86
- return Bra(QState([(value, 1.0)], self.basis_type))
87
-
88
- def delta_function(self, x1: float, x2: float, epsilon: float = 1e-3) -> float:
68
+
69
+ def __init__(self, base_coord=None, q_factor=1.0+0j):
70
+ """
71
+ 初始化量子标架
72
+
73
+ Args:
74
+ base_coord: 基础坐标系 (coord3 对象),None 时使用单位标架
75
+ q_factor: 复标度因子 Q ∈ ℂ
76
+ """
77
+ if base_coord is None:
78
+ if coord3 is not None:
79
+ self.base = coord3.identity()
80
+ else:
81
+ self.base = None
82
+ else:
83
+ self.base = base_coord
84
+
85
+ self.Q = complex(q_factor) # 确保是复数
86
+ self.dim = 3
87
+
88
+ # -------------------- 复标架属性 --------------------
89
+
90
+ @property
91
+ def o(self):
92
+ """复位置向量"""
93
+ if self.base is None:
94
+ return None
95
+ o_base = self.base.o
96
+ # 复扩展:实部为原位置,虚部编码相位信息
97
+ return vec3(
98
+ o_base.x * self.Q.real + 1j * o_base.x * self.Q.imag,
99
+ o_base.y * self.Q.real + 1j * o_base.y * self.Q.imag,
100
+ o_base.z * self.Q.real + 1j * o_base.z * self.Q.imag
101
+ ) if vec3 else None
102
+
103
+ @property
104
+ def s(self):
105
+ """复缩放向量: s_Q = s_base · Q"""
106
+ if self.base is None:
107
+ return None
108
+ s_base = self.base.s
109
+ return vec3(
110
+ s_base.x * self.Q.real + 1j * s_base.x * self.Q.imag,
111
+ s_base.y * self.Q.real + 1j * s_base.y * self.Q.imag,
112
+ s_base.z * self.Q.real + 1j * s_base.z * self.Q.imag
113
+ ) if vec3 else None
114
+
115
+ @property
116
+ def phase(self):
117
+ """相位 arg(Q)"""
118
+ return np.angle(self.Q)
119
+
120
+ @property
121
+ def magnitude(self):
122
+ """模 |Q|"""
123
+ return np.abs(self.Q)
124
+
125
+ @property
126
+ def det(self):
89
127
  """
90
- 狄拉克δ函数的离散近似
91
- δ(x1-x2) ≈ (1/√(2πϵ)) exp(-(x1-x2)²/(2ϵ))
128
+ 行列式: Det(QFrame)
129
+
130
+ 用于路径积分测度 ∫ Dφ · Det[QFrame] · exp(iS/ħ)
92
131
  """
93
- return np.exp(-(x1 - x2)**2 / (2 * epsilon)) / np.sqrt(2 * np.pi * epsilon)
94
-
95
- def fourier_kernel(self, x: float, p: float) -> complex:
96
- """傅立叶核 x|p⟩ = (1/√(2πħ)) e^{ipx/ħ}"""
97
- return np.exp(1j * p * x / self.hbar) / np.sqrt(2 * np.pi * self.hbar)
98
-
99
- def completeness_relation(self, grid: np.ndarray) -> np.ndarray:
132
+ if self.base is None:
133
+ return self.Q ** 3 # 3维标架
134
+ s = self.base.s
135
+ det_s = s.x * s.y * s.z
136
+ return det_s * (self.Q ** 3)
137
+
138
+ # -------------------- 标架运算 --------------------
139
+
140
+ def __mul__(self, other):
100
141
  """
101
- 完备性关系的离散实现:∫|x⟩⟨x|dx I
102
-
103
- 返回投影算符在离散基下的矩阵表示
142
+ 标架乘法 - 核心变换操作
143
+
144
+ 支持:
145
+ - QFrame * complex: 相位旋转/缩放 (傅里叶变换)
146
+ - QFrame * QFrame: 标架复合 (路径积分复合)
147
+ - QFrame * vec3: 向量变换
104
148
  """
105
- n = len(grid)
106
- identity = np.eye(n, dtype=complex)
107
-
108
- # 对于连续基,离散化需要权重
109
- dx = grid[1] - grid[0] if len(grid) > 1 else 1.0
110
- return identity * dx # 近似
111
-
149
+ if isinstance(other, (int, float, complex)):
150
+ # 标量乘法实现傅里叶变换
151
+ new_Q = self.Q * other
152
+ return QFrame(self.base, new_Q)
153
+
154
+ elif isinstance(other, QFrame):
155
+ # 标架复合
156
+ if self.base is not None and other.base is not None:
157
+ new_base = self.base * other.base
158
+ else:
159
+ new_base = self.base or other.base
160
+ new_Q = self.Q * other.Q
161
+ return QFrame(new_base, new_Q)
162
+
163
+ elif vec3 is not None and isinstance(other, vec3):
164
+ # 向量变换
165
+ return vec3(
166
+ other.x * self.Q.real,
167
+ other.y * self.Q.real,
168
+ other.z * self.Q.real
169
+ )
170
+
171
+ return NotImplemented
172
+
173
+ def __rmul__(self, other):
174
+ """右乘法"""
175
+ return self.__mul__(other)
176
+
177
+ def __truediv__(self, other):
178
+ """标架除法 - 逆变换"""
179
+ if isinstance(other, (int, float, complex)):
180
+ return QFrame(self.base, self.Q / other)
181
+ elif isinstance(other, QFrame):
182
+ if self.base is not None and other.base is not None:
183
+ new_base = self.base / other.base
184
+ else:
185
+ new_base = self.base
186
+ return QFrame(new_base, self.Q / other.Q)
187
+ return NotImplemented
188
+
189
+ def __pow__(self, n):
190
+ """幂运算: 对应多次变换"""
191
+ if isinstance(n, (int, float, complex)):
192
+ return QFrame(self.base, self.Q ** n)
193
+ return NotImplemented
194
+
195
+ def __eq__(self, other):
196
+ """相等比较"""
197
+ if not isinstance(other, QFrame):
198
+ return False
199
+ return np.isclose(self.Q, other.Q)
200
+
112
201
  def __repr__(self):
113
- return f"QFrame({self.basis_type}, ħ={self.hbar})"
202
+ if self.base is not None:
203
+ return f"QFrame(Q={self.Q:.4f}, o={self.base.o})"
204
+ return f"QFrame(Q={self.Q:.4f})"
205
+
206
+ # -------------------- 傅里叶变换 --------------------
207
+
208
+ def fourier_transform(self, theta: float = np.pi/2) -> 'QFrame':
209
+ """
210
+ 傅里叶变换: F_θ[QFrame] = QFrame · e^{iθ}
211
+
212
+ Args:
213
+ theta: 旋转角度,π/2 为标准傅里叶变换
214
+
215
+ Returns:
216
+ 变换后的 QFrame
217
+
218
+ 性质:
219
+ - F^4 = I (四次变换回到自身)
220
+ - F^2 = P (宇称变换)
221
+ """
222
+ ft_factor = np.exp(1j * theta)
223
+ return self * ft_factor
224
+
225
+ def inverse_fourier_transform(self, theta: float = np.pi/2) -> 'QFrame':
226
+ """逆傅里叶变换: F^{-1} = F_{-θ}"""
227
+ return self.fourier_transform(-theta)
228
+
229
+ def conformal_transform(self, lambda_factor: float) -> 'QFrame':
230
+ """
231
+ 共形变换: C → C · λ, λ ∈ ℝ⁺
232
+
233
+ 实现缩放变换,保持角度不变
234
+ """
235
+ return self * lambda_factor
236
+
237
+ # -------------------- 谱变换 (整合自 fourier_spectral) --------------------
238
+
239
+ @staticmethod
240
+ def spectral_transform_2d(field: np.ndarray, hbar: float = HBAR) -> np.ndarray:
241
+ """
242
+ 二维谱变换:位置空间 → 动量空间
243
+
244
+ 数学形式:
245
+ ψ̃(k) = ∫ e^{ikx/ħ} ψ(x) dx / √(2πħ)
246
+
247
+ Args:
248
+ field: 输入场,形状 [ny, nx, ...] 或 [ny, nx]
249
+ hbar: 约化普朗克常数
250
+
251
+ Returns:
252
+ 动量空间谱
253
+ """
254
+ # 确定 FFT 的轴
255
+ if field.ndim >= 2:
256
+ axes = (0, 1)
257
+ else:
258
+ axes = None
259
+
260
+ spectrum = np.fft.fft2(field, axes=axes)
261
+
262
+ # 量子力学归一化
263
+ normalization = 1.0 / np.sqrt(2 * np.pi * hbar)
264
+ return spectrum * normalization
265
+
266
+ @staticmethod
267
+ def inverse_spectral_transform_2d(spectrum: np.ndarray, hbar: float = HBAR) -> np.ndarray:
268
+ """
269
+ 二维逆谱变换:动量空间 → 位置空间
270
+
271
+ Args:
272
+ spectrum: 动量空间谱
273
+ hbar: 约化普朗克常数
274
+
275
+ Returns:
276
+ 位置空间场
277
+ """
278
+ if spectrum.ndim >= 2:
279
+ axes = (0, 1)
280
+ else:
281
+ axes = None
282
+
283
+ denormalization = np.sqrt(2 * np.pi * hbar)
284
+ return np.fft.ifft2(spectrum * denormalization, axes=axes).real
285
+
286
+ @staticmethod
287
+ def spectral_transform_2d_gpu(field: np.ndarray, hbar: float = HBAR) -> np.ndarray:
288
+ """GPU 加速的二维谱变换"""
289
+ if not GPU_AVAILABLE:
290
+ raise RuntimeError("CuPy 不可用,无法使用 GPU 加速")
291
+
292
+ field_gpu = cp.asarray(field)
293
+ spectrum_gpu = cufft.fft2(field_gpu, axes=(0, 1))
294
+ normalization = 1.0 / np.sqrt(2 * np.pi * hbar)
295
+ spectrum_gpu *= normalization
296
+ return cp.asnumpy(spectrum_gpu)
297
+
298
+ @classmethod
299
+ def from_coord_field(cls, coord_field: List[List], hbar: float = HBAR) -> 'QFrameSpectrum':
300
+ """
301
+ 从坐标场创建谱表示
302
+
303
+ 将坐标场的各分量进行谱变换
304
+
305
+ Args:
306
+ coord_field: 二维坐标场列表 [[coord3, ...], ...]
307
+ hbar: 约化普朗克常数
114
308
 
115
- # ========== 量子态实现 ==========
309
+ Returns:
310
+ QFrameSpectrum 对象
311
+ """
312
+ ny = len(coord_field)
313
+ nx = len(coord_field[0]) if ny > 0 else 0
314
+
315
+ # 提取场分量
316
+ tensor_field = np.zeros((ny, nx, 12), dtype=np.float64)
317
+ for i in range(ny):
318
+ for j in range(nx):
319
+ coord = coord_field[i][j]
320
+ tensor_field[i, j, 0:3] = [coord.o.x, coord.o.y, coord.o.z]
321
+ tensor_field[i, j, 3:6] = [coord.ux.x, coord.ux.y, coord.ux.z]
322
+ tensor_field[i, j, 6:9] = [coord.uy.x, coord.uy.y, coord.uy.z]
323
+ tensor_field[i, j, 9:12] = [coord.uz.x, coord.uz.y, coord.uz.z]
324
+
325
+ # 谱变换各分量
326
+ origin_spectrum = cls.spectral_transform_2d(tensor_field[..., 0:3], hbar)
327
+ ux_spectrum = cls.spectral_transform_2d(tensor_field[..., 3:6], hbar)
328
+ uy_spectrum = cls.spectral_transform_2d(tensor_field[..., 6:9], hbar)
329
+ uz_spectrum = cls.spectral_transform_2d(tensor_field[..., 9:12], hbar)
330
+
331
+ # 动量网格
332
+ kx = 2 * np.pi * np.fft.fftfreq(nx) / hbar
333
+ ky = 2 * np.pi * np.fft.fftfreq(ny) / hbar
334
+
335
+ return QFrameSpectrum(
336
+ ux_spectrum=ux_spectrum,
337
+ uy_spectrum=uy_spectrum,
338
+ uz_spectrum=uz_spectrum,
339
+ origin_spectrum=origin_spectrum,
340
+ momentum_grid=(kx, ky),
341
+ hbar=hbar
342
+ )
343
+
344
+ # -------------------- 路径积分 --------------------
345
+
346
+ def path_integral_measure(self, field_values: List) -> complex:
347
+ """
348
+ 路径积分测度: Det[QFrame] · exp(iS/ħ)
349
+
350
+ Args:
351
+ field_values: 场构型列表
352
+
353
+ Returns:
354
+ 积分权重
355
+ """
356
+ det_frame = self.det
357
+ action = self._compute_action(field_values)
358
+ return det_frame * np.exp(1j * action)
359
+
360
+ def _compute_action(self, field_values: List) -> float:
361
+ """计算作用量 S[φ, QFrame]"""
362
+ if not field_values:
363
+ return 0.0
364
+
365
+ # 简化的标量场作用量
366
+ kinetic = 0.0
367
+ mass_term = 0.0
116
368
 
117
- class QState:
369
+ for i, phi in enumerate(field_values):
370
+ if i < len(field_values) - 1:
371
+ phi_next = field_values[i + 1]
372
+ grad = (phi_next - phi) * self.Q
373
+ kinetic += np.abs(grad) ** 2
374
+ mass_term += np.abs(phi) ** 2
375
+
376
+ return 0.5 * (kinetic + mass_term)
377
+
378
+ # -------------------- 狄拉克符号导出 --------------------
379
+
380
+ def to_dirac_notation(self, basis: str = 'position') -> str:
381
+ """
382
+ 转换为狄拉克符号表示(导出用)
383
+
384
+ Args:
385
+ basis: 'position' | 'momentum'
386
+
387
+ Returns:
388
+ 狄拉克符号字符串
389
+ """
390
+ symbol = 'x' if basis == 'position' else 'p'
391
+ return f"⟨{symbol}|Q⟩ = {self.Q:.4f}|{symbol}⟩"
392
+
393
+
394
+ # ============================================================
395
+ # 量子态表示
396
+ # ============================================================
397
+
398
+ class QuantumState:
118
399
  """
119
- 量子态 |ψ⟩ = ∫ ψ(ξ) |ξ⟩ dξ
120
-
121
- 其中 ξ x p,ψ(ξ) 是概率幅
400
+ 量子态在 QFrame 下的表示
401
+
402
+ |ψ⟩ = amplitude · |basis⟩ QFrame
122
403
  """
123
-
124
- def __init__(self,
125
- components: List[Tuple[float, complex]], # [(ξ_i, amplitude_i)]
126
- basis: str = 'position',
127
- hbar: float = HBAR):
128
- self.components = components # 离散表示
404
+
405
+ def __init__(self, amplitude: complex = 1.0+0j,
406
+ frame: QFrame = None,
407
+ basis: str = 'position'):
408
+ self.amplitude = complex(amplitude)
409
+ self.frame = frame or QFrame()
129
410
  self.basis = basis
130
- self.hbar = hbar
131
- self._normalize()
132
-
133
- def _normalize(self):
134
- """归一化:∫ |ψ(ξ)|² = 1"""
135
- total = sum(abs(amp)**2 for _, amp in self.components)
136
- if total > 0:
137
- norm = 1.0 / np.sqrt(total)
138
- self.components = [(xi, amp * norm) for xi, amp in self.components]
139
-
140
- def wavefunction(self, grid: np.ndarray) -> np.ndarray:
141
- """在网格上计算波函数 ψ(ξ)"""
142
- psi = np.zeros(len(grid), dtype=complex)
143
- for xi, amp in self.components:
144
- # 用高斯函数近似δ函数
145
- psi += amp * np.exp(-(grid - xi)**2 / (2 * 0.1))
146
- return psi / np.sqrt(np.sum(np.abs(psi)**2))
147
-
148
- def inner_product(self, other: 'QState') -> complex:
149
- """内积 ⟨ψ|φ⟩ = ∫ ψ*(ξ)φ(ξ) dξ"""
150
- if self.basis != other.basis:
151
- raise ValueError("States must be in same basis for inner product")
152
-
153
- # 离散近似
154
- total = 0j
155
- for xi, amp_self in self.components:
156
- for xj, amp_other in other.components:
157
- # 近似δ函数内积
158
- if abs(xi - xj) < 1e-6:
159
- total += np.conj(amp_self) * amp_other
160
- return total
161
-
162
- def transform_to(self, target_basis: str, grid: np.ndarray) -> 'QState':
163
- """傅立叶变换到另一标架"""
164
- if self.basis == target_basis:
165
- return self
166
-
167
- frame = QFrame(self.basis, self.hbar)
168
- target_frame = QFrame(target_basis, self.hbar)
169
-
170
- # 离散傅立叶变换
171
- amplitudes = []
172
- for x in grid:
173
- total_amp = 0j
174
- for xi, amp in self.components:
175
- if self.basis == 'position' and target_basis == 'momentum':
176
- kernel = target_frame.fourier_kernel(xi, x) # ⟨p|x⟩
177
- else:
178
- kernel = np.conj(target_frame.fourier_kernel(x, xi)) # ⟨x|p⟩*
179
- total_amp += np.conj(kernel) * amp
180
- amplitudes.append((x, total_amp))
181
-
182
- return QState(amplitudes, target_basis, self.hbar)
183
-
184
- def __repr__(self):
185
- main_comps = []
186
- for xi, amp in self.components[:3]: # 只显示前3个主要分量
187
- if abs(amp) > 0.05:
188
- symbol = 'x' if self.basis == 'position' else 'p'
189
- main_comps.append(f"{amp:.2f}|{symbol}={xi:.1f}⟩")
190
-
191
- if len(self.components) > 3:
192
- return " + ".join(main_comps) + " + ..."
193
- return " + ".join(main_comps) if main_comps else "|0⟩"
194
-
195
- # ========== 量子算符代数 ==========
196
-
197
- class QOperator:
198
- """
199
- 量子算符代数:实现非对易结构
200
-
201
- 核心:[x̂, p̂] = iħ
202
- """
203
-
204
- def __init__(self, name: str, matrix_rep: np.ndarray = None):
205
- self.name = name
206
- self.matrix = matrix_rep
207
-
208
- @classmethod
209
- def position_operator(cls, grid: np.ndarray, hbar: float = HBAR) -> 'QOperator':
210
- """位置算符 x̂ 在离散基下的矩阵表示"""
211
- n = len(grid)
212
- X = np.diag(grid)
213
- return cls("x̂", X)
214
-
215
- @classmethod
216
- def momentum_operator(cls, grid: np.ndarray, hbar: float = HBAR) -> 'QOperator':
217
- """动量算符 p̂ = -iħ ∂/∂x 在离散基下的矩阵表示"""
218
- n = len(grid)
219
- dx = grid[1] - grid[0]
220
-
221
- # 使用中心差分近似导数
222
- P = np.zeros((n, n), dtype=complex)
223
- for i in range(1, n-1):
224
- P[i, i+1] = -1j * hbar / (2 * dx)
225
- P[i, i-1] = 1j * hbar / (2 * dx)
226
-
227
- # 边界条件
228
- P[0, 1] = -1j * hbar / dx
229
- P[n-1, n-2] = 1j * hbar / dx
230
-
231
- return cls("p̂", P)
232
-
233
- def __add__(self, other: 'QOperator') -> 'QOperator':
234
- """算符加法"""
235
- if self.matrix.shape != other.matrix.shape:
236
- raise ValueError("Operators must have same dimension")
237
- return QOperator(f"({self.name}+{other.name})", self.matrix + other.matrix)
238
-
239
- def __sub__(self, other: 'QOperator') -> 'QOperator':
240
- """算符减法"""
241
- if self.matrix.shape != other.matrix.shape:
242
- raise ValueError("Operators must have same dimension")
243
- return QOperator(f"({self.name}-{other.name})", self.matrix - other.matrix)
244
-
245
- def __mul__(self, other: Union['QOperator', complex, float]) -> 'QOperator':
246
- """算符乘法或数乘"""
247
- if isinstance(other, (int, float, complex)):
248
- return QOperator(f"{other}*{self.name}", other * self.matrix)
249
- elif isinstance(other, QOperator):
250
- return QOperator(f"{self.name}{other.name}", self.matrix @ other.matrix)
251
- raise TypeError(f"Unsupported type: {type(other)}")
252
-
253
- def __rmul__(self, other: Union[complex, float]) -> 'QOperator':
254
- """右数乘"""
411
+
412
+ def __mul__(self, other):
413
+ """量子态变换: |ψ⟩ → QFrame · |ψ⟩"""
414
+ if isinstance(other, QFrame):
415
+ new_amplitude = self.amplitude * other.Q
416
+ new_frame = self.frame * other
417
+ return QuantumState(new_amplitude, new_frame, self.basis)
418
+ return NotImplemented
419
+
420
+ def __rmul__(self, other):
255
421
  return self.__mul__(other)
256
-
257
- def commutator(self, other: 'QOperator') -> 'QOperator':
258
- """对易子 [A,B] = AB - BA"""
259
- comm = self.matrix @ other.matrix - other.matrix @ self.matrix
260
- return QOperator(f"[{self.name},{other.name}]", comm)
261
-
262
- def trace(self) -> complex:
263
- """迹 tr(A)"""
264
- return np.trace(self.matrix)
265
-
266
- def act_on_state(self, state: QState, grid: np.ndarray) -> QState:
267
- """算符作用于态:A|ψ⟩"""
268
- # 将态投影到离散基
269
- psi = state.wavefunction(grid)
270
- psi_new = self.matrix @ psi
271
-
272
- # 转换回QState表示
273
- amplitudes = [(grid[i], psi_new[i]) for i in range(len(grid))]
274
- return QState(amplitudes, state.basis, state.hbar)
275
-
422
+
423
+ def fourier_transform(self) -> 'QuantumState':
424
+ """傅里叶变换量子态"""
425
+ ft_frame = QFrame(q_factor=1j) # 乘以 i
426
+ new_basis = 'momentum' if self.basis == 'position' else 'position'
427
+ result = self * ft_frame
428
+ result.basis = new_basis
429
+ return result
430
+
431
+ def expectation_value(self) -> float:
432
+ """期望值: ⟨ψ|Q|ψ⟩"""
433
+ return (np.conj(self.amplitude) * self.amplitude * self.frame.det).real
434
+
435
+ def norm(self) -> float:
436
+ """范数: ||ψ||"""
437
+ return np.abs(self.amplitude)
438
+
439
+ def normalize(self) -> 'QuantumState':
440
+ """归一化"""
441
+ n = self.norm()
442
+ if n > 0:
443
+ return QuantumState(self.amplitude / n, self.frame, self.basis)
444
+ return self
445
+
276
446
  def __repr__(self):
277
- return f"QOperator({self.name}, shape={self.matrix.shape})"
447
+ basis_symbol = 'x' if self.basis == 'position' else 'p'
448
+ return f"{self.amplitude:.4f}|{basis_symbol}⟩ ⊗ {self.frame}"
449
+
278
450
 
279
- # ========== 外尔关系与量子二项式 ==========
451
+ # ============================================================
452
+ # 路径积分
453
+ # ============================================================
280
454
 
281
- class WeylRelation:
455
+ class PathIntegral:
282
456
  """
283
- 外尔关系:T(a)U(b) = e^{-iab/ħ} U(b)T(a)
284
-
285
- 其中:
286
- T(a) = exp(-iap̂/ħ) - 动量平移
287
- U(b) = exp(-ibx̂/ħ) - 位置平移
457
+ 路径积分计算器
458
+
459
+ Z = ∫ Dφ · Det[QFrame] · exp(iS/ħ)
288
460
  """
289
-
290
- def __init__(self, hbar: float = HBAR):
461
+
462
+ def __init__(self, frame: QFrame = None, hbar: float = HBAR):
463
+ self.frame = frame or QFrame()
291
464
  self.hbar = hbar
292
-
293
- def translation_operators(self, grid: np.ndarray, a: float, b: float):
294
- """生成平移算符 T(a) 和 U(b)"""
295
- X = QOperator.position_operator(grid, self.hbar).matrix
296
- P = QOperator.momentum_operator(grid, self.hbar).matrix
297
-
298
- # T(a) = exp(-i*a*P/ħ)
299
- T_a = linalg.expm(-1j * a * P / self.hbar)
300
-
301
- # U(b) = exp(-i*b*X/ħ)
302
- U_b = linalg.expm(-1j * b * X / self.hbar)
303
-
304
- return T_a, U_b
305
-
306
- def verify(self, grid: np.ndarray, a: float = 1.0, b: float = 1.0, tol: float = 1e-6):
307
- """验证外尔关系"""
308
- T_a, U_b = self.translation_operators(grid, a, b)
309
-
310
- # 计算 T(a)U(b)
311
- TU = T_a @ U_b
312
-
313
- # 计算 e^{-iab/ħ} U(b)T(a)
314
- phase = np.exp(-1j * a * b / self.hbar)
315
- UT = phase * (U_b @ T_a)
316
-
317
- # 比较
318
- diff = np.max(np.abs(TU - UT))
319
- is_valid = diff < tol
320
-
321
- return {
322
- 'valid': is_valid,
323
- 'max_difference': diff,
324
- 'expected_phase': phase,
325
- 'actual_phase': np.trace(TU @ linalg.inv(UT)) / len(grid) if len(grid) > 0 else 0
326
- }
327
-
328
- def quantum_binomial_coefficient(self, n: int, k: int, q: complex) -> complex:
465
+ self.field_configs = []
466
+
467
+ def add_configuration(self, field_value):
468
+ """添加场构型"""
469
+ self.field_configs.append(field_value)
470
+
471
+ def add_configurations(self, field_values: List):
472
+ """批量添加场构型"""
473
+ self.field_configs.extend(field_values)
474
+
475
+ def clear(self):
476
+ """清除所有构型"""
477
+ self.field_configs.clear()
478
+
479
+ def compute(self) -> complex:
329
480
  """
330
- 量子二项式系数 (n choose k)_q
331
-
332
- 用于展开 (A+B)^n,其中 BA = q AB
481
+ 计算路径积分
482
+
483
+ Returns:
484
+ 配分函数 Z
333
485
  """
334
- def q_number(m: int, q: complex) -> complex:
335
- """q-数 [m]_q = (1-q^m)/(1-q)"""
336
- if abs(q - 1) < 1e-10:
337
- return m
338
- return (1 - q**m) / (1 - q)
339
-
340
- def q_factorial(m: int, q: complex) -> complex:
341
- """q-阶乘 [m]_q! = [1]_q [2]_q ... [m]_q"""
342
- result = 1 + 0j
343
- for i in range(1, m+1):
344
- result *= q_number(i, q)
345
- return result
346
-
347
- if k < 0 or k > n:
348
- return 0
349
-
350
- num = q_factorial(n, q)
351
- den = q_factorial(k, q) * q_factorial(n - k, q)
352
-
353
- return num / den
354
-
355
- # ========== 量子联络与曲率 ==========
356
-
357
- class QConnection:
358
- """
359
- 量子联络:描述标架场的平行输运
360
-
361
- 定义:A_μ = ∂_μ|ℂ⟩⟨ℂ| - 标架场的梯度
362
- """
363
-
364
- def __init__(self, frame_field: QFrame):
365
- self.frame = frame_field
366
-
367
- def connection_form(self, grid: np.ndarray, mu: str) -> QOperator:
486
+ if not self.field_configs:
487
+ return 0.0 + 0j
488
+
489
+ total = 0.0 + 0j
490
+ for phi in self.field_configs:
491
+ weight = self.frame.path_integral_measure([phi])
492
+ total += weight
493
+
494
+ return total / len(self.field_configs)
495
+
496
+ def classical_limit(self) -> Tuple[Any, float]:
368
497
  """
369
- 联络1-形式 A_μ
370
-
371
- μ ∈ {'x', 'p'} 表示沿哪个方向变化
498
+ 经典极限: δS/δφ = 0 的解
499
+
500
+ Returns:
501
+ (最优构型, 最小作用量)
372
502
  """
373
- n = len(grid)
374
- dx = grid[1] - grid[0]
375
-
376
- if mu == 'x':
377
- # 沿位置方向的联络
378
- A = np.zeros((n, n), dtype=complex)
379
- for i in range(n):
380
- for j in range(n):
381
- if i == j:
382
- # 对角元为零(规范选择)
383
- A[i, j] = 0
384
- elif abs(i - j) == 1:
385
- # 最近邻耦合
386
- A[i, j] = -1j * (grid[j] - grid[i]) / (2 * dx * self.frame.hbar)
387
- else: # mu == 'p'
388
- # 沿动量方向的联络
389
- A = np.zeros((n, n), dtype=complex)
390
- # 在动量空间中,联络与位置算符有关
391
- for i in range(n):
392
- for j in range(n):
393
- if abs(i - j) == 1:
394
- A[i, j] = 1j * dx * grid[i] / (2 * self.frame.hbar)
395
-
396
- return QOperator(f"A_{mu}", A)
397
-
398
- def curvature(self, grid: np.ndarray) -> QOperator:
503
+ best_config = None
504
+ min_action = float('inf')
505
+
506
+ for phi in self.field_configs:
507
+ action = self.frame._compute_action([phi])
508
+ if action < min_action:
509
+ min_action = action
510
+ best_config = phi
511
+
512
+ return best_config, min_action
513
+
514
+ def __repr__(self):
515
+ return f"PathIntegral(n_configs={len(self.field_configs)}, frame={self.frame})"
516
+
517
+
518
+ # ============================================================
519
+ # 谱数据结构
520
+ # ============================================================
521
+
522
+ @dataclass
523
+ class QFrameSpectrum:
524
+ """
525
+ QFrame 谱表示 - 坐标场在动量空间的表示
526
+
527
+ 存储坐标场各分量的傅里叶谱
528
+ """
529
+ ux_spectrum: np.ndarray # x轴基矢量谱
530
+ uy_spectrum: np.ndarray # y轴基矢量谱
531
+ uz_spectrum: np.ndarray # z轴基矢量谱
532
+ origin_spectrum: np.ndarray # 原点位置谱
533
+ momentum_grid: Tuple[np.ndarray, np.ndarray] # (kx, ky)
534
+ hbar: float = HBAR
535
+
536
+ def __post_init__(self):
537
+ """验证维度一致性"""
538
+ shapes = [
539
+ self.ux_spectrum.shape,
540
+ self.uy_spectrum.shape,
541
+ self.uz_spectrum.shape,
542
+ self.origin_spectrum.shape
543
+ ]
544
+ if not all(s == shapes[0] for s in shapes):
545
+ raise ValueError("所有谱分量必须具有相同维度")
546
+
547
+ @property
548
+ def shape(self) -> Tuple[int, int]:
549
+ """谱的空间形状"""
550
+ return self.ux_spectrum.shape[:2]
551
+
552
+ def total_energy(self) -> float:
553
+ """总能量 E = ∫ |ψ̃(k)|² dk"""
554
+ return float(
555
+ np.sum(np.abs(self.ux_spectrum)**2) +
556
+ np.sum(np.abs(self.uy_spectrum)**2) +
557
+ np.sum(np.abs(self.uz_spectrum)**2) +
558
+ np.sum(np.abs(self.origin_spectrum)**2)
559
+ )
560
+
561
+ def spectral_density(self) -> np.ndarray:
562
+ """谱密度 ρ(k) = Σ_μ |ψ̃_μ(k)|²"""
563
+ density = (
564
+ np.abs(self.ux_spectrum)**2 +
565
+ np.abs(self.uy_spectrum)**2 +
566
+ np.abs(self.uz_spectrum)**2 +
567
+ np.abs(self.origin_spectrum)**2
568
+ )
569
+ return np.mean(density, axis=-1) if density.ndim > 2 else density
570
+
571
+ def radial_average(self) -> Tuple[np.ndarray, np.ndarray]:
399
572
  """
400
- 量子曲率 R = [A_x, A_p] - 非对易性的几何度量
573
+ 径向平均谱 (ShapeDNA)
574
+
575
+ Returns:
576
+ (k_bins, radial_spectrum)
401
577
  """
402
- A_x = self.connection_form(grid, 'x')
403
- A_p = self.connection_form(grid, 'p')
404
-
405
- # 曲率 = 联络的对易子
406
- R = A_x.commutator(A_p)
407
- R.name = "R"
408
-
409
- return R
410
-
411
- def berry_phase(self, grid: np.ndarray, path: np.ndarray) -> complex:
578
+ kx, ky = self.momentum_grid
579
+ k_mag = np.sqrt(kx[:, None]**2 + ky[None, :]**2)
580
+
581
+ density = self.spectral_density()
582
+
583
+ k_max = np.max(k_mag)
584
+ k_bins = np.linspace(0, k_max, 50)
585
+ radial_avg = np.zeros(len(k_bins))
586
+
587
+ for i in range(len(k_bins) - 1):
588
+ mask = (k_mag >= k_bins[i]) & (k_mag < k_bins[i + 1])
589
+ if np.any(mask):
590
+ radial_avg[i] = np.mean(density[mask])
591
+
592
+ return k_bins, radial_avg
593
+
594
+ def to_coord_field(self) -> List[List]:
412
595
  """
413
- Berry相位:γ = ∮ A_μ dx^μ
414
-
415
- path: 路径上的点序列 [(x1, p1), (x2, p2), ...]
596
+ 逆变换:谱 坐标场
597
+
598
+ Returns:
599
+ 二维坐标场列表
416
600
  """
417
- gamma = 0j
418
- n_points = len(path)
419
-
420
- for i in range(n_points):
421
- x, p = path[i]
422
- x_next, p_next = path[(i+1) % n_points]
423
-
424
- # 离散近似
425
- dx = x_next - x
426
- dp = p_next - p
427
-
428
- # 计算联络在这段路径上的贡献
429
- A_x = self.connection_form(np.array([x, x_next]), 'x')
430
- A_p = self.connection_form(np.array([p, p_next]), 'p')
431
-
432
- # 近似积分
433
- gamma += np.trace(A_x.matrix)[0] * dx + np.trace(A_p.matrix)[0] * dp
434
-
435
- return gamma
436
-
437
- # ========== 高斯波包与不确定关系 ==========
438
-
439
- def coherent_state(center_x: float = 0.0, center_p: float = 0.0,
440
- sigma: float = 1.0, grid: np.ndarray = None,
441
- hbar: float = HBAR) -> QState:
601
+ ny, nx = self.shape
602
+
603
+ origin_field = QFrame.inverse_spectral_transform_2d(self.origin_spectrum, self.hbar)
604
+ ux_field = QFrame.inverse_spectral_transform_2d(self.ux_spectrum, self.hbar)
605
+ uy_field = QFrame.inverse_spectral_transform_2d(self.uy_spectrum, self.hbar)
606
+ uz_field = QFrame.inverse_spectral_transform_2d(self.uz_spectrum, self.hbar)
607
+
608
+ coord_field = []
609
+ for i in range(ny):
610
+ row = []
611
+ for j in range(nx):
612
+ o = vec3(origin_field[i, j, 0], origin_field[i, j, 1], origin_field[i, j, 2])
613
+ ux = vec3(ux_field[i, j, 0], ux_field[i, j, 1], ux_field[i, j, 2])
614
+ uy = vec3(uy_field[i, j, 0], uy_field[i, j, 1], uy_field[i, j, 2])
615
+ uz = vec3(uz_field[i, j, 0], uz_field[i, j, 1], uz_field[i, j, 2])
616
+
617
+ c = coord3(o, quat(1, 0, 0, 0), vec3(1, 1, 1))
618
+ c.ux, c.uy, c.uz = ux, uy, uz
619
+ row.append(c)
620
+ coord_field.append(row)
621
+
622
+ return coord_field
623
+
624
+
625
+ # ============================================================
626
+ # 狄拉克符号(可选导出)
627
+ # ============================================================
628
+
629
+ class DiracBra:
630
+ """左矢 ⟨ψ| - 狄拉克符号导出"""
631
+
632
+ def __init__(self, state: QuantumState):
633
+ self.state = state
634
+
635
+ def __or__(self, other: 'DiracKet') -> complex:
636
+ """内积 ⟨ψ|φ⟩"""
637
+ return np.conj(self.state.amplitude) * other.state.amplitude
638
+
639
+
640
+ class DiracKet:
641
+ """右矢 |φ⟩ - 狄拉克符号导出"""
642
+
643
+ def __init__(self, state: QuantumState):
644
+ self.state = state
645
+
646
+
647
+ def bra(state: QuantumState) -> DiracBra:
648
+ """创建左矢"""
649
+ return DiracBra(state)
650
+
651
+
652
+ def ket(state: QuantumState) -> DiracKet:
653
+ """创建右矢"""
654
+ return DiracKet(state)
655
+
656
+
657
+ # ============================================================
658
+ # 便利函数
659
+ # ============================================================
660
+
661
+ def spectral_transform(coord_field: List[List],
662
+ hbar: float = HBAR,
663
+ use_gpu: bool = False) -> QFrameSpectrum:
442
664
  """
443
- 相干态(最小不确定态) - 高斯波包
444
-
445
- ψ(x) = (1/(πσ²))^{1/4} exp(-(x-x₀)²/(2σ²)) exp(i p₀ x/ħ)
665
+ 坐标场谱变换
666
+
667
+ Args:
668
+ coord_field: 二维坐标场
669
+ hbar: 约化普朗克常数
670
+ use_gpu: 是否使用 GPU 加速
671
+
672
+ Returns:
673
+ QFrameSpectrum 对象
446
674
  """
447
- if grid is None:
448
- grid = np.linspace(-5, 5, 100)
449
-
450
- # 高斯波函数
451
- normalization = (1.0 / (np.pi * sigma**2))**0.25
452
- psi = normalization * np.exp(-(grid - center_x)**2 / (2 * sigma**2))
453
- psi *= np.exp(1j * center_p * grid / hbar)
454
-
455
- # 归一化
456
- norm = np.sqrt(np.sum(np.abs(psi)**2) * (grid[1] - grid[0]))
457
- psi /= norm
458
-
459
- # 转换为QState
460
- amplitudes = [(grid[i], psi[i]) for i in range(len(grid))]
461
- return QState(amplitudes, 'position', hbar)
462
-
463
- def uncertainty_product(state: QState, grid: np.ndarray) -> dict:
675
+ return QFrame.from_coord_field(coord_field, hbar)
676
+
677
+
678
+ def inverse_spectral_transform(spectrum: QFrameSpectrum) -> List[List]:
464
679
  """
465
- 计算不确定关系:Δx Δp ≥ ħ/2
680
+ 逆谱变换
681
+
682
+ Args:
683
+ spectrum: QFrameSpectrum 对象
684
+
685
+ Returns:
686
+ 重建的坐标场
466
687
  """
467
- # 位置空间的期望值和方差
468
- psi_x = state.wavefunction(grid)
469
- dx = grid[1] - grid[0]
470
-
471
- # ⟨x⟩
472
- x_exp = np.sum(grid * np.abs(psi_x)**2) * dx
473
-
474
- # ⟨x²⟩
475
- x2_exp = np.sum(grid**2 * np.abs(psi_x)**2) * dx
476
-
477
- # Δx² = ⟨x²⟩ - ⟨x⟩²
478
- delta_x2 = x2_exp - x_exp**2
479
- delta_x = np.sqrt(delta_x2)
480
-
481
- # 变换到动量空间
482
- psi_p = np.fft.fftshift(np.fft.fft(psi_x))
483
- p_grid = np.fft.fftshift(np.fft.fftfreq(len(grid), d=dx)) * (2 * np.pi * state.hbar)
484
- dp = p_grid[1] - p_grid[0]
485
-
486
- # ⟨p⟩
487
- p_exp = np.sum(p_grid * np.abs(psi_p)**2) * dp
488
-
489
- # ⟨p²⟩
490
- p2_exp = np.sum(p_grid**2 * np.abs(psi_p)**2) * dp
491
-
492
- # Δp² = ⟨p²⟩ - ⟨p⟩²
493
- delta_p2 = p2_exp - p_exp**2
494
- delta_p = np.sqrt(delta_p2)
495
-
496
- # 不确定积
497
- product = delta_x * delta_p
498
- uncertainty_limit = state.hbar / 2
499
-
500
- return {
501
- 'delta_x': delta_x,
502
- 'delta_p': delta_p,
503
- 'product': product,
504
- 'uncertainty_limit': uncertainty_limit,
505
- 'saturated': abs(product - uncertainty_limit) < 1e-6,
506
- 'expectation_x': x_exp,
507
- 'expectation_p': p_exp
508
- }
509
-
510
- # ========== 演示与测试 ==========
511
-
512
- def demonstrate_frame_field():
513
- """演示复标架场的基本功能"""
514
- print("="*60)
515
- print("量子复标架代数演示")
516
- print("="*60)
517
-
518
- # 1. 创建复标架场
519
- position_frame = QFrame('position')
520
- momentum_frame = QFrame('momentum')
521
-
522
- print("1. 复标架场创建:")
523
- print(f" 位置标架场: {position_frame}")
524
- print(f" 动量标架场: {momentum_frame}")
525
- print()
526
-
527
- # 2. 验证傅立叶核
528
- print("2. 傅立叶核验证:")
529
- x, p = 1.0, 2.0
530
- kernel = position_frame.fourier_kernel(x, p)
531
- print(f" ⟨x={x}|p={p}⟩ = {kernel:.4f}")
532
- print(f" 模长: {abs(kernel):.4f}")
533
- print()
534
-
535
- # 3. 创建相干态
536
- print("3. 相干态(最小不确定态):")
537
- grid = np.linspace(-3, 3, 50)
538
- coherent = coherent_state(center_x=0.0, center_p=1.0, sigma=0.5, grid=grid)
539
- print(f" 态: {coherent}")
540
- print()
541
-
542
- # 4. 计算不确定关系
543
- print("4. 海森堡不确定关系:")
544
- uncertainties = uncertainty_product(coherent, grid)
545
- print(f" Δx = {uncertainties['delta_x']:.4f}")
546
- print(f" Δp = {uncertainties['delta_p']:.4f}")
547
- print(f" ΔxΔp = {uncertainties['product']:.4f}")
548
- print(f" 下限 ħ/2 = {uncertainties['uncertainty_limit']:.4f}")
549
- print(f" 是否饱和: {uncertainties['saturated']}")
550
- print()
551
-
552
- # 5. 算符代数
553
- print("5. 非对易代数验证:")
554
- X = QOperator.position_operator(grid[:10]) # 使用小网格演示
555
- P = QOperator.momentum_operator(grid[:10])
556
-
557
- comm = X.commutator(P)
558
- trace_comm = comm.trace()
559
-
560
- print(f" [x̂, p̂] 的迹: {trace_comm:.6f}")
561
- print(f" 期望值 iħ = {1j * HBAR:.6f}")
562
- print(f" 误差: {abs(trace_comm - 1j*HBAR):.6f}")
563
- print()
564
-
565
- # 6. 外尔关系验证
566
- print("6. 外尔关系验证:")
567
- weyl = WeylRelation()
568
- result = weyl.verify(grid[:10], a=0.5, b=0.5)
569
- print(f" 关系是否成立: {result['valid']}")
570
- print(f" 最大差异: {result['max_difference']:.6f}")
571
- print(f" 预期相位: {result['expected_phase']:.4f}")
572
- print()
573
-
574
- # 7. 量子联络与曲率
575
- print("7. 量子几何(联络与曲率):")
576
- connection = QConnection(position_frame)
577
- R = connection.curvature(grid[:5])
578
- print(f" 曲率算符: {R}")
579
- print(f" 曲率迹: {R.trace():.6f}")
580
- print()
581
-
582
- # 8. 量子二项式系数演示
583
- print("8. 量子二项式系数演示:")
584
- q = np.exp(1j * np.pi / 3) # q = e^{iπ/3}
585
- for n in [2, 3, 4]:
586
- print(f" n={n}: ", end="")
587
- coeffs = []
588
- for k in range(n+1):
589
- coeff = weyl.quantum_binomial_coefficient(n, k, q)
590
- coeffs.append(f"({k})_q={coeff.real:.3f}")
591
- print("[" + ", ".join(coeffs) + "]")
592
-
593
- print("\n" + "="*60)
594
-
595
- def plot_gaussian_transformation():
596
- """绘制高斯波包的傅立叶变换"""
597
- # 创建高斯波包
598
- grid_x = np.linspace(-5, 5, 200)
599
- coherent = coherent_state(center_x=0.0, center_p=2.0, sigma=0.8, grid=grid_x)
600
-
601
- # 傅立叶变换到动量空间
602
- psi_x = coherent.wavefunction(grid_x)
603
- psi_p = np.fft.fftshift(np.fft.fft(psi_x))
604
- p_grid = np.fft.fftshift(np.fft.fftfreq(len(grid_x), d=grid_x[1]-grid_x[0])) * (2*np.pi*HBAR)
605
-
606
- # 绘制
607
- fig, axes = plt.subplots(2, 2, figsize=(12, 8))
608
-
609
- # 位置空间波函数
610
- axes[0, 0].plot(grid_x, np.abs(psi_x)**2, 'b-', linewidth=2, label='|ψ(x)|²')
611
- axes[0, 0].plot(grid_x, np.real(psi_x), 'r--', alpha=0.7, label='Re ψ(x)')
612
- axes[0, 0].plot(grid_x, np.imag(psi_x), 'g--', alpha=0.7, label='Im ψ(x)')
613
- axes[0, 0].set_xlabel('位置 x')
614
- axes[0, 0].set_ylabel('波函数')
615
- axes[0, 0].set_title('位置空间表示')
616
- axes[0, 0].legend()
617
- axes[0, 0].grid(True, alpha=0.3)
618
-
619
- # 动量空间波函数
620
- axes[0, 1].plot(p_grid, np.abs(psi_p)**2, 'b-', linewidth=2, label='|ψ(p)|²')
621
- axes[0, 1].plot(p_grid, np.real(psi_p), 'r--', alpha=0.7, label='Re ψ(p)')
622
- axes[0, 1].plot(p_grid, np.imag(psi_p), 'g--', alpha=0.7, label='Im ψ(p)')
623
- axes[0, 1].set_xlabel('动量 p')
624
- axes[0, 1].set_ylabel('波函数')
625
- axes[0, 1].set_title('动量空间表示')
626
- axes[0, 1].legend()
627
- axes[0, 1].grid(True, alpha=0.3)
628
-
629
- # 相空间表示(Wigner函数近似)
630
- axes[1, 0].scatter(grid_x, p_grid[:len(grid_x)],
631
- c=np.outer(np.abs(psi_x), np.abs(psi_p[:len(grid_x)])).flatten(),
632
- cmap='viridis', alpha=0.6)
633
- axes[1, 0].set_xlabel('位置 x')
634
- axes[1, 0].set_ylabel('动量 p')
635
- axes[1, 0].set_title('相空间表示')
636
- axes[1, 0].grid(True, alpha=0.3)
637
-
638
- # 不确定关系示意图
639
- uncertainties = uncertainty_product(coherent, grid_x)
640
- angles = np.linspace(0, 2*np.pi, 100)
641
- x_circle = uncertainties['delta_x'] * np.cos(angles)
642
- p_circle = uncertainties['delta_p'] * np.sin(angles)
643
-
644
- axes[1, 1].plot(x_circle, p_circle, 'b-', label='不确定区域')
645
- axes[1, 1].axhline(y=0, color='k', linestyle='-', alpha=0.3)
646
- axes[1, 1].axvline(x=0, color='k', linestyle='-', alpha=0.3)
647
- axes[1, 1].fill_between(x_circle, p_circle, alpha=0.3)
648
- axes[1, 1].set_xlabel('Δx')
649
- axes[1, 1].set_ylabel('Δp')
650
- axes[1, 1].set_title(f'不确定关系: ΔxΔp = {uncertainties["product"]:.3f} ≥ ħ/2 = {HBAR/2:.3f}')
651
- axes[1, 1].legend()
652
- axes[1, 1].grid(True, alpha=0.3)
653
- axes[1, 1].axis('equal')
654
-
655
- plt.tight_layout()
656
- plt.savefig('quantum_frame_demo.png', dpi=150)
657
- plt.show()
658
-
659
- # ========== 主程序 ==========
688
+ return spectrum.to_coord_field()
689
+
690
+
691
+ # ============================================================
692
+ # 演示
693
+ # ============================================================
694
+
695
+ def demonstrate():
696
+ """演示复标架代数"""
697
+ print("=" * 60)
698
+ print("复数量子化标架场 (QFrame) 演示")
699
+ print("=" * 60)
700
+
701
+ # 1. 创建基础 QFrame
702
+ if coord3 is not None:
703
+ base_frame = coord3.from_position(vec3(1, 0, 0))
704
+ qf = QFrame(base_frame, q_factor=1.0+0.5j)
705
+ else:
706
+ qf = QFrame(q_factor=1.0+0.5j)
707
+
708
+ print(f"\n1. 基础 QFrame: {qf}")
709
+ print(f" 相位: {qf.phase:.4f} rad")
710
+ print(f" 模: {qf.magnitude:.4f}")
711
+ print(f" 行列式: {qf.det:.4f}")
712
+
713
+ # 2. 傅里叶变换
714
+ print(f"\n2. 傅里叶变换:")
715
+ ft = qf.fourier_transform()
716
+ print(f" F[QFrame] = {ft}")
717
+ print(f" F^4[QFrame] ≈ QFrame: {qf.fourier_transform(2*np.pi)}")
718
+
719
+ # 3. 共形变换
720
+ print(f"\n3. 共形变换:")
721
+ conf = qf.conformal_transform(2.0)
722
+ print(f" λ=2: {conf}")
723
+
724
+ # 4. 标架复合
725
+ print(f"\n4. 标架复合:")
726
+ qf2 = QFrame(q_factor=0.5+0.5j)
727
+ composed = qf * qf2
728
+ print(f" QFrame1 * QFrame2 = {composed}")
729
+
730
+ # 5. 量子态
731
+ print(f"\n5. 量子态:")
732
+ psi = QuantumState(amplitude=1.0+0j, frame=qf)
733
+ print(f" 初始: {psi}")
734
+ psi_ft = psi.fourier_transform()
735
+ print(f" 变换: {psi_ft}")
736
+ print(f" 期望值: {psi.expectation_value():.4f}")
737
+
738
+ # 6. 路径积分
739
+ print(f"\n6. 路径积分:")
740
+ pi = PathIntegral(frame=qf)
741
+ for x in np.linspace(-1, 1, 5):
742
+ pi.add_configuration(x + 0j)
743
+
744
+ Z = pi.compute()
745
+ print(f" 配分函数 Z = {Z:.4f}")
746
+
747
+ config, action = pi.classical_limit()
748
+ print(f" 经典解: φ_cl = {config:.4f}, S = {action:.4f}")
749
+
750
+ # 7. 狄拉克符号导出
751
+ print(f"\n7. 狄拉克符号导出:")
752
+ print(f" {qf.to_dirac_notation('position')}")
753
+ print(f" {qf.to_dirac_notation('momentum')}")
754
+
755
+ print("\n" + "=" * 60)
756
+ print("核心特性总结:")
757
+ print(" QFrame * e^{iθ} = 傅里叶变换")
758
+ print(" • QFrame * λ = 共形变换")
759
+ print(" • QFrame * QFrame = 标架复合")
760
+ print(" QFrame.det = 路径积分测度")
761
+ print("=" * 60)
762
+
763
+
764
+ # ============================================================
765
+ # 导出
766
+ # ============================================================
767
+
768
+ __all__ = [
769
+ # 核心类
770
+ 'QFrame',
771
+ 'QuantumState',
772
+ 'PathIntegral',
773
+ 'QFrameSpectrum',
774
+
775
+ # 狄拉克符号导出
776
+ 'DiracBra',
777
+ 'DiracKet',
778
+ 'bra',
779
+ 'ket',
780
+
781
+ # 便利函数
782
+ 'spectral_transform',
783
+ 'inverse_spectral_transform',
784
+
785
+ # 常数
786
+ 'HBAR',
787
+ 'GPU_AVAILABLE',
788
+ ]
789
+
660
790
 
661
791
  if __name__ == "__main__":
662
- # 运行演示
663
- demonstrate_frame_field()
664
-
665
- # 可选:绘制图形演示
666
- if input("\n绘制图形演示?(y/n): ").lower() == 'y':
667
- plot_gaussian_transformation()
668
-
669
- print("\n量子复标架代数实现完成!")
670
- print("核心特性:")
671
- print("1. 复标架场: 连续正交归一基的数学实现")
672
- print("2. 非对易代数: [x̂, p̂] = iħ 的严格实现")
673
- print("3. 外尔关系: T(a)U(b) = e^{-iab/ħ} U(b)T(a)")
674
- print("4. 量子联络与曲率: 非对易性的几何描述")
675
- print("5. 不确定关系: ΔxΔp ≥ ħ/2 的几何解释")
792
+ demonstrate()