coordinate-system 5.2.0__cp313-cp313-win_amd64.whl → 5.2.2__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,18 +1,71 @@
1
- # coordinate_system/fourier_spectral.py
1
+ """
2
+ Quantum Frame Spectral Analysis - 量子标架谱分析
3
+ ==============================================
4
+
5
+ 基于量子复标架理论的坐标场谱分析系统。
6
+ 将傅里叶谱分析升级为量子几何框架。
7
+
8
+ 核心概念转换:
9
+ - 传统傅里叶谱 → 量子标架场谱
10
+ - FFT/IFFT → 标架旋转算符
11
+ - 频域分析 → 动量标架表示
12
+ - 谱密度 → 量子几何能量密度
13
+ - 坐标场变换 → 复标架场旋转
14
+
15
+ 量子几何特性:
16
+ - 非对易代数 [x̂, p̂] = iħ
17
+ - 标架旋转 = 傅里叶变换
18
+ - 量子联络与曲率
19
+ - Berry 相位与拓扑不变量
20
+ - 外尔关系验证
21
+
22
+ GPU 加速:
23
+ - 支持 CuPy 加速的标架变换
24
+ - 批量坐标变换优化
25
+ - 大规模场计算
26
+
27
+ Author: Quantum Frame Theory Edition
28
+ Date: 2025-12-02
29
+ """
2
30
 
3
31
  import numpy as np
4
32
  from typing import List, Tuple, Dict, Optional, Union, Any
5
33
  from dataclasses import dataclass
6
- from .coordinate_system import coord3, vec3, quat
34
+ from scipy import integrate, linalg
35
+
36
+ # 导入坐标系统
37
+ try:
38
+ from .coordinate_system import coord3, vec3, quat
39
+ except ImportError:
40
+ import coordinate_system
41
+ coord3 = coordinate_system.coord3
42
+ vec3 = coordinate_system.vec3
43
+ quat = coordinate_system.quat
44
+
45
+ # 导入量子复标架
46
+ try:
47
+ from .qframes import (
48
+ QFrame, QState, QOperator, WeylRelation, QConnection,
49
+ coherent_state, uncertainty_product, HBAR
50
+ )
51
+ except ImportError:
52
+ import qframes
53
+ QFrame = qframes.QFrame
54
+ QState = qframes.QState
55
+ QOperator = qframes.QOperator
56
+ WeylRelation = qframes.WeylRelation
57
+ QConnection = qframes.QConnection
58
+ coherent_state = qframes.coherent_state
59
+ uncertainty_product = qframes.uncertainty_product
60
+ HBAR = qframes.HBAR
7
61
 
8
- # GPU availability check with proper error handling
62
+ # GPU 可用性检查
9
63
  try:
10
64
  import cupy as cp
11
65
  import cupyx.scipy.fft as cufft
12
66
  GPU_AVAILABLE = True
13
67
  except ImportError:
14
68
  GPU_AVAILABLE = False
15
- # Create dummy types for type checking when GPU is not available
16
69
  class DummyCP:
17
70
  ndarray = np.ndarray
18
71
  def asarray(self, *args, **kwargs):
@@ -22,355 +75,689 @@ except ImportError:
22
75
  cp = DummyCP()
23
76
  cufft = None
24
77
 
78
+
25
79
  @dataclass
26
- class FrameFieldSpectrum:
27
- """Fourier spectrum representation of coordinate frame field"""
28
- ux_spectrum: np.ndarray # Fourier coefficients for x-axis basis vectors
29
- uy_spectrum: np.ndarray # Fourier coefficients for y-axis basis vectors
30
- uz_spectrum: np.ndarray # Fourier coefficients for z-axis basis vectors
31
- origin_spectrum: np.ndarray # Fourier coefficients for origin positions
32
- frequencies: Tuple[np.ndarray, np.ndarray] # Frequency grids (kx, ky)
33
-
80
+ class QuantumFrameSpectrum:
81
+ """
82
+ 量子标架场谱 - 坐标场在动量标架下的表示
83
+
84
+ 物理意义:
85
+ - 每个坐标场分量在动量空间的分布
86
+ - 量子几何的频谱特征
87
+ - 标架旋转后的复振幅
88
+
89
+ 数学形式:
90
+ ψ̃(p) = ∫ ⟨p|x⟩ ψ(x) dx
91
+ 其中 ⟨p|x⟩ = (1/√(2πħ)) e^{-ipx/ħ}
92
+ """
93
+ ux_spectrum: np.ndarray # x轴基矢量的动量谱
94
+ uy_spectrum: np.ndarray # y轴基矢量的动量谱
95
+ uz_spectrum: np.ndarray # z轴基矢量的动量谱
96
+ origin_spectrum: np.ndarray # 原点位置的动量谱
97
+
98
+ # 动量网格(kx, ky)
99
+ momentum_grid: Tuple[np.ndarray, np.ndarray]
100
+
101
+ # 量子几何参数
102
+ hbar: float = HBAR
103
+
104
+ # 量子几何量(可选)
105
+ curvature: Optional[np.ndarray] = None # 量子曲率场
106
+ berry_phase: Optional[complex] = None # Berry 相位
107
+ chern_number: Optional[int] = None # Chern 数(拓扑不变量)
108
+
34
109
  def __post_init__(self):
35
- """Validate spectrum data dimension consistency"""
36
- shapes = [self.ux_spectrum.shape, self.uy_spectrum.shape,
37
- self.uz_spectrum.shape, self.origin_spectrum.shape]
110
+ """验证谱数据维度一致性"""
111
+ shapes = [
112
+ self.ux_spectrum.shape,
113
+ self.uy_spectrum.shape,
114
+ self.uz_spectrum.shape,
115
+ self.origin_spectrum.shape
116
+ ]
38
117
  if not all(shape == shapes[0] for shape in shapes):
39
- raise ValueError("All spectrum components must have the same dimensions")
118
+ raise ValueError("所有谱分量必须具有相同的维度")
119
+
120
+ def total_energy(self) -> float:
121
+ """
122
+ 计算谱的总能量(量子几何能量)
123
+
124
+ E = ∫ |ψ̃(p)|² dp
125
+ """
126
+ energy = (
127
+ np.sum(np.abs(self.ux_spectrum)**2) +
128
+ np.sum(np.abs(self.uy_spectrum)**2) +
129
+ np.sum(np.abs(self.uz_spectrum)**2) +
130
+ np.sum(np.abs(self.origin_spectrum)**2)
131
+ )
132
+ return float(energy)
133
+
134
+ def uncertainty_product(self) -> float:
135
+ """
136
+ 计算不确定性乘积 ΔxΔp
137
+
138
+ 通过位置谱和动量谱的宽度计算
139
+ """
140
+ # 简化计算:使用谱的二阶矩
141
+ kx, ky = self.momentum_grid
142
+ k_mag = np.sqrt(kx[:, None]**2 + ky[None, :]**2)
40
143
 
41
- class FourierTransformer:
42
- """Base Fourier transformer class"""
43
-
44
- def __init__(self, grid_size: Tuple[int, int] = (64, 64)):
144
+ # 动量宽度
145
+ total_spectrum = (
146
+ np.abs(self.ux_spectrum)**2 +
147
+ np.abs(self.uy_spectrum)**2 +
148
+ np.abs(self.uz_spectrum)**2
149
+ ).mean(axis=-1) # 对矢量分量平均
150
+
151
+ total_norm = np.sum(total_spectrum)
152
+ if total_norm < 1e-15:
153
+ # 谱太小,返回不确定性下限
154
+ return self.hbar / 2
155
+
156
+ delta_p_squared = np.sum(k_mag**2 * total_spectrum) / total_norm
157
+ delta_p = np.sqrt(delta_p_squared) if delta_p_squared > 0 else 1.0
158
+
159
+ # 根据不确定性原理估计位置宽度
160
+ delta_x = self.hbar / (2 * delta_p) if delta_p > 1e-10 else 1.0
161
+
162
+ return delta_x * delta_p
163
+
164
+
165
+ class QuantumFrameTransformer:
166
+ """
167
+ 量子标架变换器 - 基于量子复标架理论的坐标场变换
168
+
169
+ 核心原理:
170
+ 1. 将坐标场视为复标架场 {|x⟩} 的叠加
171
+ 2. 使用 QFrame.fourier_kernel 进行标架旋转
172
+ 3. 位置标架 ↔ 动量标架的幺正变换
173
+
174
+ 数学框架:
175
+ - 标架旋转核:⟨p|x⟩ = (1/√(2πħ)) e^{ipx/ħ}
176
+ - 非对易性:[x̂, p̂] = iħ
177
+ - 幺正性:∫ |⟨p|x⟩|² dx = 1
178
+ """
179
+
180
+ def __init__(self, grid_size: Tuple[int, int] = (64, 64), hbar: float = HBAR):
181
+ """
182
+ 初始化量子标架变换器
183
+
184
+ Args:
185
+ grid_size: 网格尺寸 (ny, nx)
186
+ hbar: 约化普朗克常数
187
+ """
45
188
  self.grid_size = grid_size
46
189
  self.ny, self.nx = grid_size
47
-
190
+ self.hbar = hbar
191
+
192
+ # 创建位置和动量标架
193
+ self.position_frame = QFrame('position', hbar)
194
+ self.momentum_frame = QFrame('momentum', hbar)
195
+
48
196
  def coord_field_to_tensor(self, coord_field: List[List[coord3]]) -> np.ndarray:
49
- """Convert coordinate field to tensor representation"""
50
- # Validate grid dimensions
197
+ """
198
+ 将坐标场转换为张量表示
199
+
200
+ 张量结构: [ny, nx, 12]
201
+ - [0:3]: 原点位置 (ox, oy, oz)
202
+ - [3:6]: x轴基矢量 (ux.x, ux.y, ux.z)
203
+ - [6:9]: y轴基矢量 (uy.x, uy.y, uy.z)
204
+ - [9:12]: z轴基矢量 (uz.x, uz.y, uz.z)
205
+ """
51
206
  actual_ny = len(coord_field)
52
207
  actual_nx = len(coord_field[0]) if actual_ny > 0 else 0
53
-
208
+
54
209
  if actual_ny != self.ny or actual_nx != self.nx:
55
- raise ValueError(f"Coordinate field dimensions ({actual_ny}x{actual_nx}) "
56
- f"do not match expected grid size ({self.ny}x{self.nx})")
57
-
210
+ raise ValueError(
211
+ f"坐标场维度 ({actual_ny}x{actual_nx}) "
212
+ f"与期望网格尺寸 ({self.ny}x{self.nx}) 不匹配"
213
+ )
214
+
58
215
  tensor_field = np.zeros((self.ny, self.nx, 12), dtype=np.float64)
59
-
216
+
60
217
  for i in range(self.ny):
61
218
  for j in range(self.nx):
62
219
  coord = coord_field[i][j]
63
- # Position (3), basis vectors (9)
220
+ # 原点位置 (3) + 基矢量 (9)
64
221
  tensor_field[i, j, 0:3] = [coord.o.x, coord.o.y, coord.o.z]
65
222
  tensor_field[i, j, 3:6] = [coord.ux.x, coord.ux.y, coord.ux.z]
66
223
  tensor_field[i, j, 6:9] = [coord.uy.x, coord.uy.y, coord.uy.z]
67
224
  tensor_field[i, j, 9:12] = [coord.uz.x, coord.uz.y, coord.uz.z]
68
-
225
+
69
226
  return tensor_field
70
-
71
- def fft2_coord_field(self, coord_field: List[List[coord3]]) -> FrameFieldSpectrum:
72
- """Perform 2D Fourier transform on coordinate field"""
227
+
228
+ def quantum_frame_transform(self, coord_field: List[List[coord3]]) -> QuantumFrameSpectrum:
229
+ """
230
+ 量子标架变换:位置标架 → 动量标架
231
+
232
+ 使用量子复标架的 fourier_kernel 进行标架旋转
233
+
234
+ 数学形式:
235
+ ψ̃_μ(kx, ky) = ∫∫ ⟨k|x⟩ ψ_μ(x, y) dx dy
236
+
237
+ 其中 μ ∈ {ux, uy, uz, origin}
238
+ """
73
239
  tensor_field = self.coord_field_to_tensor(coord_field)
74
-
75
- # Separate components
76
- origin_field = tensor_field[..., 0:3] # Position field
77
- ux_field = tensor_field[..., 3:6] # x-axis basis field
78
- uy_field = tensor_field[..., 6:9] # y-axis basis field
79
- uz_field = tensor_field[..., 9:12] # z-axis basis field
80
-
81
- # Fourier transform
82
- origin_spectrum = np.fft.fft2(origin_field, axes=(0, 1))
83
- ux_spectrum = np.fft.fft2(ux_field, axes=(0, 1))
84
- uy_spectrum = np.fft.fft2(uy_field, axes=(0, 1))
85
- uz_spectrum = np.fft.fft2(uz_field, axes=(0, 1))
86
-
87
- # Frequency grids
88
- kx = np.fft.fftfreq(self.nx)
89
- ky = np.fft.fftfreq(self.ny)
90
-
91
- return FrameFieldSpectrum(
240
+
241
+ # 分离各分量
242
+ origin_field = tensor_field[..., 0:3]
243
+ ux_field = tensor_field[..., 3:6]
244
+ uy_field = tensor_field[..., 6:9]
245
+ uz_field = tensor_field[..., 9:12]
246
+
247
+ # 使用量子标架进行变换(标架旋转)
248
+ origin_spectrum = self._qframe_transform_2d(origin_field)
249
+ ux_spectrum = self._qframe_transform_2d(ux_field)
250
+ uy_spectrum = self._qframe_transform_2d(uy_field)
251
+ uz_spectrum = self._qframe_transform_2d(uz_field)
252
+
253
+ # 动量网格
254
+ kx = 2 * np.pi * np.fft.fftfreq(self.nx) / self.hbar
255
+ ky = 2 * np.pi * np.fft.fftfreq(self.ny) / self.hbar
256
+
257
+ return QuantumFrameSpectrum(
92
258
  ux_spectrum=ux_spectrum,
93
259
  uy_spectrum=uy_spectrum,
94
260
  uz_spectrum=uz_spectrum,
95
261
  origin_spectrum=origin_spectrum,
96
- frequencies=(kx, ky)
262
+ momentum_grid=(kx, ky),
263
+ hbar=self.hbar
97
264
  )
98
-
99
- def ifft2_spectrum(self, spectrum: FrameFieldSpectrum) -> List[List[coord3]]:
100
- """Inverse Fourier transform to reconstruct coordinate field"""
101
- # Inverse transform each component
102
- origin_field = np.fft.ifft2(spectrum.origin_spectrum, axes=(0, 1)).real
103
- ux_field = np.fft.ifft2(spectrum.ux_spectrum, axes=(0, 1)).real
104
- uy_field = np.fft.ifft2(spectrum.uy_spectrum, axes=(0, 1)).real
105
- uz_field = np.fft.ifft2(spectrum.uz_spectrum, axes=(0, 1)).real
106
-
107
- # Reconstruct coordinate field
265
+
266
+ def _qframe_transform_2d(self, field: np.ndarray) -> np.ndarray:
267
+ """
268
+ 二维量子标架变换
269
+
270
+ 使用 FFT 实现高效的标架旋转
271
+ (FFT 是量子标架变换的离散逼近)
272
+
273
+ Args:
274
+ field: 形状为 [ny, nx, n_components] 的场
275
+
276
+ Returns:
277
+ 动量标架下的谱,形状同上
278
+ """
279
+ # 对空间维度进行 FFT(标架旋转)
280
+ # FFT 是 ⟨p|x⟩ = (1/√(2πħ)) e^{ipx/ħ} 的离散实现
281
+ spectrum = np.fft.fft2(field, axes=(0, 1))
282
+
283
+ # 归一化因子(量子标架归一化)
284
+ normalization = 1.0 / np.sqrt(2 * np.pi * self.hbar)
285
+ spectrum *= normalization
286
+
287
+ return spectrum
288
+
289
+ def inverse_quantum_transform(self, spectrum: QuantumFrameSpectrum) -> List[List[coord3]]:
290
+ """
291
+ 逆量子标架变换:动量标架 → 位置标架
292
+
293
+ 重建坐标场
294
+
295
+ 数学形式:
296
+ ψ_μ(x, y) = ∫∫ ⟨x|k⟩ ψ̃_μ(kx, ky) dkx dky
297
+ """
298
+ # 逆变换各分量
299
+ origin_field = self._qframe_inverse_transform_2d(spectrum.origin_spectrum)
300
+ ux_field = self._qframe_inverse_transform_2d(spectrum.ux_spectrum)
301
+ uy_field = self._qframe_inverse_transform_2d(spectrum.uy_spectrum)
302
+ uz_field = self._qframe_inverse_transform_2d(spectrum.uz_spectrum)
303
+
304
+ # 重建坐标场
108
305
  coord_field = []
109
306
  for i in range(self.ny):
110
307
  row = []
111
308
  for j in range(self.nx):
112
- o = vec3(origin_field[i, j, 0], origin_field[i, j, 1], origin_field[i, j, 2])
309
+ o = vec3(
310
+ origin_field[i, j, 0],
311
+ origin_field[i, j, 1],
312
+ origin_field[i, j, 2]
313
+ )
113
314
  ux = vec3(ux_field[i, j, 0], ux_field[i, j, 1], ux_field[i, j, 2])
114
315
  uy = vec3(uy_field[i, j, 0], uy_field[i, j, 1], uy_field[i, j, 2])
115
316
  uz = vec3(uz_field[i, j, 0], uz_field[i, j, 1], uz_field[i, j, 2])
116
-
117
- # Create coordinate system (using unit quaternion, unit scale)
317
+
318
+ # 创建坐标系统(使用单位四元数和尺度)
118
319
  coord = coord3(o, quat(1, 0, 0, 0), vec3(1, 1, 1))
119
320
  coord.ux, coord.uy, coord.uz = ux, uy, uz
120
321
  row.append(coord)
121
322
  coord_field.append(row)
122
-
323
+
123
324
  return coord_field
124
325
 
125
- class GPUFourierTransformer(FourierTransformer):
126
- """GPU-accelerated Fourier transformer"""
127
-
128
- def __init__(self, grid_size: Tuple[int, int] = (64, 64)):
129
- super().__init__(grid_size)
130
- if not GPU_AVAILABLE:
131
- raise RuntimeError("CuPy not available. GPU acceleration requires CuPy installation.")
132
-
133
- def fft2_coord_field(self, coord_field: List[List[coord3]]) -> FrameFieldSpectrum:
134
- """GPU-accelerated Fourier transform of coordinate field"""
135
- tensor_field = self.coord_field_to_tensor(coord_field)
136
-
137
- # Transfer to GPU
138
- tensor_field_gpu = cp.asarray(tensor_field)
139
-
140
- # Separate components
141
- origin_field = tensor_field_gpu[..., 0:3]
142
- ux_field = tensor_field_gpu[..., 3:6]
143
- uy_field = tensor_field_gpu[..., 6:9]
144
- uz_field = tensor_field_gpu[..., 9:12]
145
-
146
- # GPU Fourier transform
147
- origin_spectrum = cufft.fft2(origin_field, axes=(0, 1))
148
- ux_spectrum = cufft.fft2(ux_field, axes=(0, 1))
149
- uy_spectrum = cufft.fft2(uy_field, axes=(0, 1))
150
- uz_spectrum = cufft.fft2(uz_field, axes=(0, 1))
151
-
152
- # Transfer back to CPU
153
- origin_spectrum = cp.asnumpy(origin_spectrum)
154
- ux_spectrum = cp.asnumpy(ux_spectrum)
155
- uy_spectrum = cp.asnumpy(uy_spectrum)
156
- uz_spectrum = cp.asnumpy(uz_spectrum)
157
-
158
- kx = np.fft.fftfreq(self.nx)
159
- ky = np.fft.fftfreq(self.ny)
160
-
161
- return FrameFieldSpectrum(
162
- ux_spectrum=ux_spectrum,
163
- uy_spectrum=uy_spectrum,
164
- uz_spectrum=uz_spectrum,
165
- origin_spectrum=origin_spectrum,
166
- frequencies=(kx, ky)
326
+ def _qframe_inverse_transform_2d(self, spectrum: np.ndarray) -> np.ndarray:
327
+ """
328
+ 二维逆量子标架变换
329
+
330
+ Args:
331
+ spectrum: 动量标架下的谱
332
+
333
+ Returns:
334
+ 位置标架下的场
335
+ """
336
+ # 反归一化
337
+ denormalization = np.sqrt(2 * np.pi * self.hbar)
338
+ spectrum_scaled = spectrum * denormalization
339
+
340
+ # IFFT(逆标架旋转)
341
+ field = np.fft.ifft2(spectrum_scaled, axes=(0, 1)).real
342
+
343
+ return field
344
+
345
+ def compute_quantum_curvature(self, spectrum: QuantumFrameSpectrum) -> np.ndarray:
346
+ """
347
+ 计算量子曲率场
348
+
349
+ 基于量子联络的曲率:R = [A_x, A_y]
350
+
351
+ Returns:
352
+ 曲率场,形状为 [ny, nx]
353
+ """
354
+ kx, ky = spectrum.momentum_grid
355
+
356
+ # 使用谱的梯度近似计算曲率
357
+ # ∂_x ψ̃ ~ i kx ψ̃
358
+ # ∂_y ψ̃ ~ i ky ψ̃
359
+
360
+ total_spectrum = (
361
+ spectrum.ux_spectrum +
362
+ spectrum.uy_spectrum +
363
+ spectrum.uz_spectrum +
364
+ spectrum.origin_spectrum
167
365
  )
168
-
169
- def ifft2_spectrum(self, spectrum: FrameFieldSpectrum) -> List[List[coord3]]:
170
- """GPU-accelerated inverse Fourier transform"""
171
- # Transfer to GPU
172
- origin_spectrum_gpu = cp.asarray(spectrum.origin_spectrum)
173
- ux_spectrum_gpu = cp.asarray(spectrum.ux_spectrum)
174
- uy_spectrum_gpu = cp.asarray(spectrum.uy_spectrum)
175
- uz_spectrum_gpu = cp.asarray(spectrum.uz_spectrum)
176
-
177
- # GPU inverse transform
178
- origin_field = cufft.ifft2(origin_spectrum_gpu, axes=(0, 1)).real
179
- ux_field = cufft.ifft2(ux_spectrum_gpu, axes=(0, 1)).real
180
- uy_field = cufft.ifft2(uy_spectrum_gpu, axes=(0, 1)).real
181
- uz_field = cufft.ifft2(uz_spectrum_gpu, axes=(0, 1)).real
182
-
183
- # Transfer back to CPU
184
- origin_field = cp.asnumpy(origin_field)
185
- ux_field = cp.asnumpy(ux_field)
186
- uy_field = cp.asnumpy(uy_field)
187
- uz_field = cp.asnumpy(uz_field)
188
-
189
- # Reconstruct coordinate field
190
- coord_field = []
366
+
367
+ # 动量梯度(量子联络的近似)
368
+ grad_x = 1j * kx[:, None, None] * total_spectrum
369
+ grad_y = 1j * ky[None, :, None] * total_spectrum
370
+
371
+ # 曲率 ~ [∂_x, ∂_y]
372
+ curvature = np.abs(grad_x * grad_y - grad_y * grad_x).mean(axis=-1)
373
+
374
+ return curvature
375
+
376
+ def verify_unitarity(self, coord_field: List[List[coord3]]) -> Dict[str, float]:
377
+ """
378
+ 验证量子标架变换的幺正性
379
+
380
+ 检验:∫ |⟨p|x⟩|² dx = 1
381
+
382
+ 通过往返变换测试:field spectrum → field'
383
+ """
384
+ # 前向变换
385
+ spectrum = self.quantum_frame_transform(coord_field)
386
+
387
+ # 逆变换
388
+ reconstructed = self.inverse_quantum_transform(spectrum)
389
+
390
+ # 计算重建误差
391
+ max_error = 0.0
191
392
  for i in range(self.ny):
192
- row = []
193
393
  for j in range(self.nx):
194
- o = vec3(origin_field[i, j, 0], origin_field[i, j, 1], origin_field[i, j, 2])
195
- ux = vec3(ux_field[i, j, 0], ux_field[i, j, 1], ux_field[i, j, 2])
196
- uy = vec3(uy_field[i, j, 0], uy_field[i, j, 1], uy_field[i, j, 2])
197
- uz = vec3(uz_field[i, j, 0], uz_field[i, j, 1], uz_field[i, j, 2])
198
-
199
- coord = coord3(o, quat(1, 0, 0, 0), vec3(1, 1, 1))
200
- coord.ux, coord.uy, coord.uz = ux, uy, uz
201
- row.append(coord)
202
- coord_field.append(row)
203
-
204
- return coord_field
394
+ orig = coord_field[i][j]
395
+ recon = reconstructed[i][j]
396
+
397
+ error = (
398
+ abs(orig.o.x - recon.o.x) +
399
+ abs(orig.o.y - recon.o.y) +
400
+ abs(orig.o.z - recon.o.z)
401
+ ) / 3
402
+
403
+ max_error = max(max_error, error)
404
+
405
+ return {
406
+ 'max_reconstruction_error': max_error,
407
+ 'is_unitary': max_error < 1e-10,
408
+ 'relative_error': max_error / (self.nx * self.ny)
409
+ }
410
+
411
+
412
+ class GPUQuantumFrameTransformer(QuantumFrameTransformer):
413
+ """
414
+ GPU 加速的量子标架变换器
415
+
416
+ 使用 CuPy 加速大规模场的标架旋转
417
+ """
418
+
419
+ def __init__(self, grid_size: Tuple[int, int] = (64, 64), hbar: float = HBAR):
420
+ super().__init__(grid_size, hbar)
421
+ if not GPU_AVAILABLE:
422
+ raise RuntimeError("CuPy 不可用。GPU 加速需要安装 CuPy。")
423
+
424
+ def _qframe_transform_2d(self, field: np.ndarray) -> np.ndarray:
425
+ """GPU 加速的二维量子标架变换"""
426
+ # 转移到 GPU
427
+ field_gpu = cp.asarray(field)
428
+
429
+ # GPU FFT(标架旋转)
430
+ spectrum_gpu = cufft.fft2(field_gpu, axes=(0, 1))
431
+
432
+ # 归一化
433
+ normalization = 1.0 / np.sqrt(2 * np.pi * self.hbar)
434
+ spectrum_gpu *= normalization
435
+
436
+ # 转回 CPU
437
+ return cp.asnumpy(spectrum_gpu)
438
+
439
+ def _qframe_inverse_transform_2d(self, spectrum: np.ndarray) -> np.ndarray:
440
+ """GPU 加速的二维逆量子标架变换"""
441
+ # 转移到 GPU
442
+ spectrum_gpu = cp.asarray(spectrum)
443
+
444
+ # 反归一化
445
+ denormalization = np.sqrt(2 * np.pi * self.hbar)
446
+ spectrum_gpu *= denormalization
447
+
448
+ # GPU IFFT
449
+ field_gpu = cufft.ifft2(spectrum_gpu, axes=(0, 1)).real
450
+
451
+ # 转回 CPU
452
+ return cp.asnumpy(field_gpu)
453
+
454
+
455
+ class QuantumSpectralAnalyzer:
456
+ """
457
+ 量子谱分析器 - 量子几何与拓扑分析
458
+
459
+ 功能:
460
+ - 量子能量谱密度
461
+ - 径向谱平均(ShapeDNA)
462
+ - Berry 相位计算
463
+ - Chern 数(拓扑不变量)
464
+ - 外尔关系验证
465
+ """
466
+
467
+ def __init__(self, transformer: QuantumFrameTransformer = None):
468
+ self.transformer = transformer or QuantumFrameTransformer()
469
+
470
+ def compute_spectral_density(self, spectrum: QuantumFrameSpectrum) -> np.ndarray:
471
+ """
472
+ 计算量子谱密度
473
+
474
+ ρ(k) = Σ_μ |ψ̃_μ(k)|²
205
475
 
206
- class BatchCoordTransformer:
207
- """Batch coordinate transformer (GPU accelerated)"""
208
-
209
- def __init__(self, batch_size: int = 32):
210
- self.batch_size = batch_size
211
- self.gpu_available = GPU_AVAILABLE
212
-
213
- def batch_coord_transform(self, coords: List[coord3],
214
- transformations: List[coord3]) -> List[coord3]:
215
- """Batch coordinate transformation"""
216
- if len(coords) != len(transformations):
217
- raise ValueError("Number of coordinates and transformations must match")
218
-
219
- if self.gpu_available and len(coords) > 100:
220
- return self._gpu_batch_transform(coords, transformations)
221
- else:
222
- return self._cpu_batch_transform(coords, transformations)
223
-
224
- def _cpu_batch_transform(self, coords: List[coord3],
225
- transformations: List[coord3]) -> List[coord3]:
226
- """CPU batch transformation"""
227
- results = []
228
- for coord, transform in zip(coords, transformations):
229
- results.append(coord * transform)
230
- return results
231
-
232
- def _gpu_batch_transform(self, coords: List[coord3],
233
- transformations: List[coord3]) -> List[coord3]:
234
- """GPU batch transformation"""
235
- if not self.gpu_available:
236
- return self._cpu_batch_transform(coords, transformations)
237
-
238
- # Convert coordinate data to tensors
239
- coord_tensors = self._coords_to_tensor_batch(coords)
240
- transform_tensors = self._coords_to_tensor_batch(transformations)
241
-
242
- # Transfer to GPU and perform batch matrix operations
243
- coord_tensors_gpu = cp.asarray(coord_tensors)
244
- transform_tensors_gpu = cp.asarray(transform_tensors)
245
-
246
- # Execute batch coordinate multiplication
247
- result_tensors_gpu = self._gpu_coord_multiply(coord_tensors_gpu, transform_tensors_gpu)
248
-
249
- # Transfer back to CPU and reconstruct coordinates
250
- result_tensors = cp.asnumpy(result_tensors_gpu)
251
- return self._tensor_batch_to_coords(result_tensors)
252
-
253
- def _coords_to_tensor_batch(self, coords: List[coord3]) -> np.ndarray:
254
- """Convert batch coordinates to tensors"""
255
- batch_size = len(coords)
256
- tensors = np.zeros((batch_size, 4, 4), dtype=np.float64)
257
-
258
- for i, coord in enumerate(coords):
259
- # Build 4x4 homogeneous transformation matrix
260
- tensors[i, 0, 0:3] = [coord.ux.x, coord.uy.x, coord.uz.x]
261
- tensors[i, 1, 0:3] = [coord.ux.y, coord.uy.y, coord.uz.y]
262
- tensors[i, 2, 0:3] = [coord.ux.z, coord.uy.z, coord.uz.z]
263
- tensors[i, 3, 0:3] = [coord.o.x, coord.o.y, coord.o.z]
264
- tensors[i, 3, 3] = 1.0
265
-
266
- return tensors
267
-
268
- def _tensor_batch_to_coords(self, tensors: np.ndarray) -> List[coord3]:
269
- """Convert tensor batch to coordinates"""
270
- coords = []
271
- for i in range(tensors.shape[0]):
272
- matrix = tensors[i]
273
- o = vec3(matrix[3, 0], matrix[3, 1], matrix[3, 2])
274
- ux = vec3(matrix[0, 0], matrix[1, 0], matrix[2, 0])
275
- uy = vec3(matrix[0, 1], matrix[1, 1], matrix[2, 1])
276
- uz = vec3(matrix[0, 2], matrix[1, 2], matrix[2, 2])
277
-
278
- coord = coord3(o, quat(1, 0, 0, 0), vec3(1, 1, 1))
279
- coord.ux, coord.uy, coord.uz = ux, uy, uz
280
- coords.append(coord)
281
-
282
- return coords
283
-
284
- def _gpu_coord_multiply(self, A: Any, B: Any) -> Any:
285
- """Batch coordinate multiplication on GPU"""
286
- if not self.gpu_available:
287
- # Fallback to CPU implementation
288
- A_np = A if isinstance(A, np.ndarray) else cp.asnumpy(A)
289
- B_np = B if isinstance(B, np.ndarray) else cp.asnumpy(B)
290
- return np.matmul(A_np, B_np)
291
-
292
- # GPU matrix multiplication
293
- return cp.matmul(A, B)
294
-
295
- class SpectralAnalyzer:
296
- """Spectral geometry analyzer"""
297
-
298
- def __init__(self, transformer: FourierTransformer = None):
299
- self.transformer = transformer or FourierTransformer()
300
-
301
- def compute_spectral_density(self, spectrum: FrameFieldSpectrum) -> np.ndarray:
302
- """Compute spectral energy density"""
303
- energy_density = (np.abs(spectrum.ux_spectrum)**2 +
304
- np.abs(spectrum.uy_spectrum)**2 +
305
- np.abs(spectrum.uz_spectrum)**2)
306
- return np.mean(energy_density, axis=-1) # Average over vector components
307
-
308
- def radial_spectrum_average(self, spectrum: FrameFieldSpectrum) -> Tuple[np.ndarray, np.ndarray]:
309
- """Radial spectrum average (ShapeDNA)"""
310
- kx, ky = spectrum.frequencies
476
+ 物理意义:动量空间的能量分布
477
+ """
478
+ energy_density = (
479
+ np.abs(spectrum.ux_spectrum)**2 +
480
+ np.abs(spectrum.uy_spectrum)**2 +
481
+ np.abs(spectrum.uz_spectrum)**2 +
482
+ np.abs(spectrum.origin_spectrum)**2
483
+ )
484
+ return np.mean(energy_density, axis=-1) # 对矢量分量平均
485
+
486
+ def radial_spectrum_average(self, spectrum: QuantumFrameSpectrum) -> Tuple[np.ndarray, np.ndarray]:
487
+ """
488
+ 径向谱平均(Quantum ShapeDNA)
489
+
490
+ 将二维动量谱投影到径向分布
491
+
492
+ Returns:
493
+ (k_bins, radial_avg): 动量大小与对应的平均谱密度
494
+ """
495
+ kx, ky = spectrum.momentum_grid
311
496
  k_mag = np.sqrt(kx[:, None]**2 + ky[None, :]**2)
312
-
497
+
313
498
  spectral_density = self.compute_spectral_density(spectrum)
314
-
315
- # Radial binning
499
+
500
+ # 径向分箱
316
501
  k_max = np.max(k_mag)
317
502
  k_bins = np.linspace(0, k_max, 50)
318
503
  radial_avg = np.zeros_like(k_bins)
319
-
320
- for i, k_val in enumerate(k_bins[:-1]):
321
- mask = (k_mag >= k_bins[i]) & (k_mag < k_bins[i+1])
504
+
505
+ for i in range(len(k_bins) - 1):
506
+ mask = (k_mag >= k_bins[i]) & (k_mag < k_bins[i + 1])
322
507
  if np.any(mask):
323
508
  radial_avg[i] = np.mean(spectral_density[mask])
324
-
509
+
325
510
  return k_bins, radial_avg
326
511
 
327
- # Convenience functions
328
- def fft2_coord_field(coord_field: List[List[coord3]],
329
- grid_size: Tuple[int, int] = (64, 64),
330
- use_gpu: bool = False) -> FrameFieldSpectrum:
331
- """2D Fourier transform of coordinate field"""
512
+ def compute_berry_phase(self, spectrum: QuantumFrameSpectrum,
513
+ path_indices: List[Tuple[int, int]]) -> complex:
514
+ """
515
+ 计算 Berry 相位
516
+
517
+ γ = i ∮ ⟨ψ|∇_k|ψ⟩ · dk
518
+
519
+ Args:
520
+ spectrum: 量子标架谱
521
+ path_indices: 动量空间中的闭合路径(索引列表)
522
+
523
+ Returns:
524
+ Berry 相位(复数)
525
+ """
526
+ total_spectrum = (
527
+ spectrum.ux_spectrum +
528
+ spectrum.uy_spectrum +
529
+ spectrum.uz_spectrum +
530
+ spectrum.origin_spectrum
531
+ )
532
+
533
+ berry_phase = 0j
534
+ n_points = len(path_indices)
535
+
536
+ for i in range(n_points):
537
+ idx_current = path_indices[i]
538
+ idx_next = path_indices[(i + 1) % n_points]
539
+
540
+ # 当前点和下一点的波函数
541
+ psi_current = total_spectrum[idx_current]
542
+ psi_next = total_spectrum[idx_next]
543
+
544
+ # Berry 联络的近似:A ~ ⟨ψ|∇|ψ⟩
545
+ # 使用相位差近似
546
+ overlap = np.vdot(psi_current, psi_next)
547
+ berry_phase += np.angle(overlap)
548
+
549
+ return berry_phase
550
+
551
+ def compute_chern_number(self, spectrum: QuantumFrameSpectrum) -> int:
552
+ """
553
+ 计算 Chern 数(拓扑不变量)
554
+
555
+ C = (1/2πi) ∫∫ F(k) dkx dky
556
+
557
+ 其中 F 是 Berry 曲率
558
+
559
+ Returns:
560
+ Chern 数(整数)
561
+ """
562
+ # 简化计算:使用曲率场的积分
563
+ curvature_field = self.transformer.compute_quantum_curvature(spectrum)
564
+
565
+ # 对整个 Brillouin 区积分
566
+ total_curvature = np.sum(curvature_field)
567
+
568
+ # Chern 数应该是整数
569
+ chern = int(np.round(total_curvature / (2 * np.pi)))
570
+
571
+ return chern
572
+
573
+ def verify_weyl_relation(self, grid_size: int = 10) -> Dict[str, Any]:
574
+ """
575
+ 验证外尔关系 T(a)U(b) = e^{-iab/ħ} U(b)T(a)
576
+
577
+ Args:
578
+ grid_size: 用于验证的网格大小
579
+
580
+ Returns:
581
+ 验证结果字典
582
+ """
583
+ grid = np.linspace(-5, 5, grid_size)
584
+ weyl = WeylRelation(hbar=self.transformer.hbar)
585
+
586
+ result = weyl.verify(grid, a=1.0, b=1.0)
587
+
588
+ return {
589
+ 'weyl_relation_valid': result['valid'],
590
+ 'max_difference': result['max_difference'],
591
+ 'expected_phase': result['expected_phase'],
592
+ 'grid_size': grid_size
593
+ }
594
+
595
+
596
+ # ========== 便利函数 ==========
597
+
598
+ def quantum_frame_transform(coord_field: List[List[coord3]],
599
+ grid_size: Tuple[int, int] = (64, 64),
600
+ use_gpu: bool = False,
601
+ hbar: float = HBAR) -> QuantumFrameSpectrum:
602
+ """
603
+ 量子标架变换:坐标场 → 动量谱
604
+
605
+ Args:
606
+ coord_field: 坐标场
607
+ grid_size: 网格尺寸
608
+ use_gpu: 是否使用 GPU 加速
609
+ hbar: 约化普朗克常数
610
+
611
+ Returns:
612
+ 量子标架谱
613
+ """
332
614
  if use_gpu and GPU_AVAILABLE:
333
- transformer = GPUFourierTransformer(grid_size)
615
+ transformer = GPUQuantumFrameTransformer(grid_size, hbar)
334
616
  else:
335
- transformer = FourierTransformer(grid_size)
336
- return transformer.fft2_coord_field(coord_field)
617
+ transformer = QuantumFrameTransformer(grid_size, hbar)
618
+
619
+ return transformer.quantum_frame_transform(coord_field)
620
+
621
+
622
+ def inverse_quantum_transform(spectrum: QuantumFrameSpectrum,
623
+ use_gpu: bool = False) -> List[List[coord3]]:
624
+ """
625
+ 逆量子标架变换:动量谱 → 坐标场
626
+
627
+ Args:
628
+ spectrum: 量子标架谱
629
+ use_gpu: 是否使用 GPU 加速
630
+
631
+ Returns:
632
+ 重建的坐标场
633
+ """
634
+ grid_size = spectrum.ux_spectrum.shape[:2]
337
635
 
338
- def ifft2_spectrum(spectrum: FrameFieldSpectrum,
339
- use_gpu: bool = False) -> List[List[coord3]]:
340
- """Inverse Fourier transform to reconstruct coordinate field"""
341
636
  if use_gpu and GPU_AVAILABLE:
342
- transformer = GPUFourierTransformer()
637
+ transformer = GPUQuantumFrameTransformer(grid_size, spectrum.hbar)
343
638
  else:
344
- transformer = FourierTransformer()
345
- return transformer.ifft2_spectrum(spectrum)
639
+ transformer = QuantumFrameTransformer(grid_size, spectrum.hbar)
640
+
641
+ return transformer.inverse_quantum_transform(spectrum)
642
+
346
643
 
347
- def compute_spectral_density(spectrum: FrameFieldSpectrum) -> np.ndarray:
348
- """Compute spectral energy density"""
349
- analyzer = SpectralAnalyzer()
644
+ def compute_quantum_spectral_density(spectrum: QuantumFrameSpectrum) -> np.ndarray:
645
+ """
646
+ 计算量子谱密度
647
+
648
+ Args:
649
+ spectrum: 量子标架谱
650
+
651
+ Returns:
652
+ 谱密度数组
653
+ """
654
+ analyzer = QuantumSpectralAnalyzer()
350
655
  return analyzer.compute_spectral_density(spectrum)
351
656
 
352
- def radial_spectrum_average(spectrum: FrameFieldSpectrum) -> Tuple[np.ndarray, np.ndarray]:
353
- """Radial spectrum average"""
354
- analyzer = SpectralAnalyzer()
657
+
658
+ def compute_radial_spectrum(spectrum: QuantumFrameSpectrum) -> Tuple[np.ndarray, np.ndarray]:
659
+ """
660
+ 计算径向谱(Quantum ShapeDNA)
661
+
662
+ Args:
663
+ spectrum: 量子标架谱
664
+
665
+ Returns:
666
+ (k_bins, radial_avg): 动量大小与谱密度
667
+ """
668
+ analyzer = QuantumSpectralAnalyzer()
355
669
  return analyzer.radial_spectrum_average(spectrum)
356
670
 
357
- # Placeholder functions - to be implemented in complete version
358
- def spectral_intrinsic_gradient(spectrum: FrameFieldSpectrum) -> FrameFieldSpectrum:
359
- """Intrinsic gradient calculation in spectral space"""
360
- # Implement intrinsic gradient operator in spectral space
361
- return spectrum
362
-
363
- def spectral_curvature_calculator(spectrum: FrameFieldSpectrum) -> Dict:
364
- """Spectral curvature calculation"""
365
- # Implement curvature calculation based on spectrum
366
- return {}
367
-
368
- def berry_phase_calculator(spectrum: FrameFieldSpectrum) -> float:
369
- """Berry phase calculation"""
370
- # Implement topological invariant calculation
371
- return 0.0
372
-
373
- def topological_invariant_analyzer(spectrum: FrameFieldSpectrum) -> Dict:
374
- """Topological invariant analysis"""
375
- # Implement complete topological analysis
376
- return {}
671
+
672
+ def verify_quantum_unitarity(coord_field: List[List[coord3]],
673
+ grid_size: Tuple[int, int] = (64, 64)) -> Dict[str, float]:
674
+ """
675
+ 验证量子标架变换的幺正性
676
+
677
+ Args:
678
+ coord_field: 坐标场
679
+ grid_size: 网格尺寸
680
+
681
+ Returns:
682
+ 验证结果字典
683
+ """
684
+ transformer = QuantumFrameTransformer(grid_size)
685
+ return transformer.verify_unitarity(coord_field)
686
+
687
+
688
+ # ========== 高级量子几何分析 ==========
689
+
690
+ def compute_quantum_curvature_field(spectrum: QuantumFrameSpectrum) -> np.ndarray:
691
+ """
692
+ 计算量子曲率场 R = [A_x, A_y]
693
+
694
+ Args:
695
+ spectrum: 量子标架谱
696
+
697
+ Returns:
698
+ 曲率场
699
+ """
700
+ grid_size = spectrum.ux_spectrum.shape[:2]
701
+ transformer = QuantumFrameTransformer(grid_size, spectrum.hbar)
702
+ return transformer.compute_quantum_curvature(spectrum)
703
+
704
+
705
+ def compute_berry_phase(spectrum: QuantumFrameSpectrum,
706
+ path_indices: List[Tuple[int, int]]) -> complex:
707
+ """
708
+ 计算 Berry 相位
709
+
710
+ Args:
711
+ spectrum: 量子标架谱
712
+ path_indices: 动量空间闭合路径
713
+
714
+ Returns:
715
+ Berry 相位
716
+ """
717
+ analyzer = QuantumSpectralAnalyzer()
718
+ return analyzer.compute_berry_phase(spectrum, path_indices)
719
+
720
+
721
+ def compute_topological_invariants(spectrum: QuantumFrameSpectrum) -> Dict[str, Any]:
722
+ """
723
+ 计算拓扑不变量
724
+
725
+ Args:
726
+ spectrum: 量子标架谱
727
+
728
+ Returns:
729
+ 拓扑不变量字典(Chern 数等)
730
+ """
731
+ analyzer = QuantumSpectralAnalyzer()
732
+
733
+ chern_number = analyzer.compute_chern_number(spectrum)
734
+
735
+ return {
736
+ 'chern_number': chern_number,
737
+ 'total_energy': spectrum.total_energy(),
738
+ 'uncertainty_product': spectrum.uncertainty_product(),
739
+ 'hbar': spectrum.hbar
740
+ }
741
+
742
+
743
+ # ========== 导出 ==========
744
+
745
+ __all__ = [
746
+ # 核心类
747
+ 'QuantumFrameSpectrum',
748
+ 'QuantumFrameTransformer',
749
+ 'GPUQuantumFrameTransformer',
750
+ 'QuantumSpectralAnalyzer',
751
+
752
+ # 基础函数
753
+ 'quantum_frame_transform',
754
+ 'inverse_quantum_transform',
755
+ 'compute_quantum_spectral_density',
756
+ 'compute_radial_spectrum',
757
+ 'verify_quantum_unitarity',
758
+
759
+ # 高级量子几何
760
+ 'compute_quantum_curvature_field',
761
+ 'compute_berry_phase',
762
+ 'compute_topological_invariants',
763
+ ]