cdi-stools 0.3.4__tar.gz → 0.4.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.
Files changed (33) hide show
  1. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/CHANGELOG.md +39 -0
  2. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/PKG-INFO +46 -1
  3. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/README.md +45 -0
  4. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/pyproject.toml +1 -1
  5. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/__init__.py +1 -1
  6. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/bcdi_core.py +90 -90
  7. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/bcdi_gui.py +87 -31
  8. cdi_stools-0.4.0/src/cdi_st/cxi.py +55 -0
  9. cdi_stools-0.4.0/src/cdi_st/defects.py +143 -0
  10. cdi_stools-0.4.0/src/cdi_st/geometry.py +92 -0
  11. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_autophase_infer.py +39 -7
  12. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_data_generator.py +131 -30
  13. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_dataset.py +46 -74
  14. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_demo.py +2 -2
  15. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_experimental_loader.py +60 -44
  16. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_gui_tabs.py +276 -79
  17. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_phase_model.py +102 -90
  18. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_phase_retrieval.py +5 -2
  19. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_train.py +33 -30
  20. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/ortho.py +35 -0
  21. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/recon.py +6 -2
  22. cdi_stools-0.4.0/src/cdi_st/strain.py +40 -0
  23. cdi_stools-0.4.0/src/cdi_st/theme.py +275 -0
  24. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/LICENSE +0 -0
  25. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/CDI_ST_logo.png +0 -0
  26. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/__main__.py +0 -0
  27. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/facets.py +0 -0
  28. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_autophase_model.py +0 -0
  29. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_autophase_train.py +0 -0
  30. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/nn_visualize.py +0 -0
  31. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/requirements.txt +0 -0
  32. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/trainlog.py +0 -0
  33. {cdi_stools-0.3.4 → cdi_stools-0.4.0}/src/cdi_st/viz3d.py +0 -0
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.0] - 2026-12-04
4
+
5
+ ### Changed
6
+
7
+ - **Phase convention: φ = -G·u**, as numpy's FFT requires (Carnis et al., Sci. Rep. 9, 17357, 2019). Strain from experimental data now has the right sign, and simulated patterns are the true patterns of the given displacement.
8
+ - Every simulated strain field uses the vector G = h b1 + k b2 + l b3, not |G|.
9
+ - The strain type `edge_dislocation` is now `screw_dislocation`, which is what it always computed. The old name still works.
10
+ - Radial strain model: u(r) = ε0·(|r|/R)·r.
11
+ - Training data: dislocations use lattice Burgers vectors and slip-plane line directions. Each sample records b, the line direction and g·b.
12
+ - CDI_NN predicts density and phase and is trained with L = α‖ρ̂-ρ‖² + β‖φ̂-φ‖² + γ‖|F[ψ̂]|-|F_meas|‖²: linear diffraction amplitude, wrapped phase difference that ignores a global offset and the twin image, and augmentations that keep input and targets consistent. Defaults (α, β, γ) = (1.0, 0.5, 0.1), batch size 4. Phase-only checkpoints still load.
13
+
14
+ ### Added
15
+
16
+ - Full isotropic dislocation field (Hirth & Lothe) with any Burgers vector and line direction, in the diffraction and in the atom view.
17
+ - ID01 SPEC/EDF: energy read from the SPEC header; direct beam, distance and pixel size as inputs; voxel size from the full 3D sampling geometry.
18
+ - Real-space orthogonalisation of detector-frame reconstructions (Maddali et al., J. Appl. Cryst. 53, 393, 2020).
19
+ - Signed strain along G in the 3D viewer, the 2D slices and the VTI export. |∇φ| is now given in rad/nm.
20
+ - Diffractometer presets for ID01 and P10.
21
+ - CXI export, a light theme for exported figures, and an optional dead-time model.
22
+ - Checkpoints load at the width they were trained with.
23
+ - `tests/test_physics.py`, `scripts/benchmark_hybrid.py`, and a class-fraction report for training sets.
24
+ - **Light mode is available !** Light mode for the whole interface, exported figures follow the chosen theme.
25
+
26
+ ### Fixed
27
+
28
+ - Prismatic loops: the solid angle is exact, with no jump at the loop radius.
29
+ - The random strain field was the same in every sample.
30
+ - Command-line dataset generation failed on every sample.
31
+ - Resampling to the model grid no longer changes the voxel size.
32
+ - The simulation grid matches the FFT sampling.
33
+ - Angular offset with a strained or shaped crystal no longer crashes.
34
+ - CDI_NN did not learn: the log-scaled input was used as the measured amplitude and the predicted phase collapsed to a constant.
35
+
36
+ ### Known issues
37
+
38
+ - P10 conversion does not compute the voxel size yet.
39
+ - Loops use the solid-angle term of the displacement only.
40
+ - Some VTI export in 2D.
41
+
3
42
  ## [0.3.4] - 2026-11-23
4
43
 
5
44
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cdi-stools
3
- Version: 0.3.4
3
+ Version: 0.4.0
4
4
  Summary: Coherent Diffraction Imaging Simulation Tools: BCDI simulation and NN-based phase retrieval
5
5
  Project-URL: Homepage, https://github.com/SAIDIsoufiane/CDI-St
6
6
  Project-URL: Documentation, https://github.com/SAIDIsoufiane/CDI-St#readme
@@ -223,6 +223,11 @@ epochs on 2,000+ samples. The best checkpoint is saved automatically.
223
223
  A 3D U-Net that predicts the phase field from the diffraction magnitude, trained
224
224
  against the ground-truth phase from the data generator.
225
225
 
226
+ Since v0.4.0 it predicts the density as well as the phase and is trained with
227
+ L = α‖ρ̂-ρ‖² + β‖φ̂-φ‖² + γ‖|F[ψ̂]|-|F_meas|‖² (defaults 1.0, 0.5, 0.1). The phase term
228
+ is wrapped and ignores a global phase offset and the twin image; the Fourier term
229
+ compares linear diffraction amplitudes.
230
+
226
231
  Use AutoPhase_NN when you don't trust your simulator's ground truth (or have
227
232
  none). Use CDI_NN when you have a high-fidelity simulator and want a direct
228
233
  mapping. Use both via **Both networks averaged** in the Reconstruction tab.
@@ -306,6 +311,46 @@ Controls:
306
311
  - Mouse: left-drag rotate, right-drag pan, wheel zoom, double-click reset
307
312
  - Export PNG snapshot or VTI (ParaView)
308
313
 
314
+ ### Conventions and experimental geometry
315
+
316
+ **Phase and strain.** CDI-St uses numpy's FFT, whose kernel is exp(-iq·r), so the
317
+ reconstructed object is ρ(r)·exp(-iG·u(r)): the phase is φ = -G·u (Carnis et al.,
318
+ Sci. Rep. 9, 17357, 2019). The strain shown along G is ε = ∂u_G/∂s = -(1/|G|)·∂φ/∂s,
319
+ with s the coordinate along G. It is unchanged by the twin solution. Phase
320
+ differences are taken from neighbour products of the complex object, so no
321
+ unwrapping is needed; the surface layer is excluded.
322
+
323
+ **Simulated strain fields** (all φ = -G·u, G = h b1 + k b2 + l b3):
324
+ - radial gradient: u(r) = ε0·(|r|/R)·r, R half the mean particle size
325
+ - screw dislocation along z: b the shortest lattice translation along z
326
+ - line dislocations: isotropic infinite-medium field (Hirth & Lothe, 1982) for any
327
+ Burgers vector and line direction, given in lattice units [u v w] or by the
328
+ axis options
329
+ - prismatic loops: solid-angle term (b/4π)·Ω·n, with the exact solid angle
330
+
331
+ **ID01 SPEC/EDF data.** Give the direct-beam pixel and the detector distance from
332
+ your detector calibration; the energy is read from the SPEC header (`nrj`, keV)
333
+ unless you set it. Defaults from an old experiment are used with a warning. The
334
+ converted .npz stores the sampling matrix B (∂q per index, at the Bragg peak), the
335
+ real-space steps A = 2π·(B·diag(N))^(-T) and q at the Bragg peak. After a
336
+ reconstruction, the object is resampled from the sheared basis A onto an
337
+ orthogonal grid (Maddali et al., J. Appl. Cryst. 53, 393, 2020), so voxel size,
338
+ shape and strain are in real space. Resampling to the model grid keeps the voxel
339
+ size: the same q range on more or fewer points changes the field of view, and the
340
+ oversampling with it.
341
+
342
+ **Exports.** VTI (ParaView) holds |ρ|, φ, |∇φ| in rad/nm and, when G is known, the
343
+ signed strain. CXI holds the complex object, its support, the voxel size and the
344
+ basis, in the layout PyNX and cdiutils read. Exported figures follow the interface
345
+ theme, dark or light, chosen on the start screen.
346
+
347
+ ### Pretrained weights
348
+
349
+ Trained AutoPhase_NN and CDI_NN checkpoints can be found in here : https://doi.org/10.5281/zenodo.24826193
350
+ (it is recommended to use AutoPhase_NN for better results)
351
+ Load one with *Resume from checkpoint* in either network tab, or as the model in
352
+ the Reconstruction tab; the network width is read from the checkpoint.
353
+
309
354
  ---
310
355
 
311
356
  ## Citing
@@ -172,6 +172,11 @@ epochs on 2,000+ samples. The best checkpoint is saved automatically.
172
172
  A 3D U-Net that predicts the phase field from the diffraction magnitude, trained
173
173
  against the ground-truth phase from the data generator.
174
174
 
175
+ Since v0.4.0 it predicts the density as well as the phase and is trained with
176
+ L = α‖ρ̂-ρ‖² + β‖φ̂-φ‖² + γ‖|F[ψ̂]|-|F_meas|‖² (defaults 1.0, 0.5, 0.1). The phase term
177
+ is wrapped and ignores a global phase offset and the twin image; the Fourier term
178
+ compares linear diffraction amplitudes.
179
+
175
180
  Use AutoPhase_NN when you don't trust your simulator's ground truth (or have
176
181
  none). Use CDI_NN when you have a high-fidelity simulator and want a direct
177
182
  mapping. Use both via **Both networks averaged** in the Reconstruction tab.
@@ -255,6 +260,46 @@ Controls:
255
260
  - Mouse: left-drag rotate, right-drag pan, wheel zoom, double-click reset
256
261
  - Export PNG snapshot or VTI (ParaView)
257
262
 
263
+ ### Conventions and experimental geometry
264
+
265
+ **Phase and strain.** CDI-St uses numpy's FFT, whose kernel is exp(-iq·r), so the
266
+ reconstructed object is ρ(r)·exp(-iG·u(r)): the phase is φ = -G·u (Carnis et al.,
267
+ Sci. Rep. 9, 17357, 2019). The strain shown along G is ε = ∂u_G/∂s = -(1/|G|)·∂φ/∂s,
268
+ with s the coordinate along G. It is unchanged by the twin solution. Phase
269
+ differences are taken from neighbour products of the complex object, so no
270
+ unwrapping is needed; the surface layer is excluded.
271
+
272
+ **Simulated strain fields** (all φ = -G·u, G = h b1 + k b2 + l b3):
273
+ - radial gradient: u(r) = ε0·(|r|/R)·r, R half the mean particle size
274
+ - screw dislocation along z: b the shortest lattice translation along z
275
+ - line dislocations: isotropic infinite-medium field (Hirth & Lothe, 1982) for any
276
+ Burgers vector and line direction, given in lattice units [u v w] or by the
277
+ axis options
278
+ - prismatic loops: solid-angle term (b/4π)·Ω·n, with the exact solid angle
279
+
280
+ **ID01 SPEC/EDF data.** Give the direct-beam pixel and the detector distance from
281
+ your detector calibration; the energy is read from the SPEC header (`nrj`, keV)
282
+ unless you set it. Defaults from an old experiment are used with a warning. The
283
+ converted .npz stores the sampling matrix B (∂q per index, at the Bragg peak), the
284
+ real-space steps A = 2π·(B·diag(N))^(-T) and q at the Bragg peak. After a
285
+ reconstruction, the object is resampled from the sheared basis A onto an
286
+ orthogonal grid (Maddali et al., J. Appl. Cryst. 53, 393, 2020), so voxel size,
287
+ shape and strain are in real space. Resampling to the model grid keeps the voxel
288
+ size: the same q range on more or fewer points changes the field of view, and the
289
+ oversampling with it.
290
+
291
+ **Exports.** VTI (ParaView) holds |ρ|, φ, |∇φ| in rad/nm and, when G is known, the
292
+ signed strain. CXI holds the complex object, its support, the voxel size and the
293
+ basis, in the layout PyNX and cdiutils read. Exported figures follow the interface
294
+ theme, dark or light, chosen on the start screen.
295
+
296
+ ### Pretrained weights
297
+
298
+ Trained AutoPhase_NN and CDI_NN checkpoints can be found in here : https://doi.org/10.5281/zenodo.24826193
299
+ (it is recommended to use AutoPhase_NN for better results)
300
+ Load one with *Resume from checkpoint* in either network tab, or as the model in
301
+ the Reconstruction tab; the network width is read from the checkpoint.
302
+
258
303
  ---
259
304
 
260
305
  ## Citing
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cdi-stools"
7
- version = "0.3.4"
7
+ version = "0.4.0"
8
8
  description = "Coherent Diffraction Imaging Simulation Tools: BCDI simulation and NN-based phase retrieval"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,4 +1,4 @@
1
- __version__ = "0.3.4"
1
+ __version__ = "0.4.0"
2
2
  __author__ = "Soufiane SAIDI"
3
3
  __email__ = "saidisoufiane@hotmail.com"
4
4
  __license__ = "MIT"
@@ -13,8 +13,8 @@ try:
13
13
  import xrayutilities as xu; _HAS_XU=True
14
14
  except: xu=None; _HAS_XU=False
15
15
  warnings.filterwarnings('ignore')
16
- if __package__: from . import facets, ortho
17
- else: import facets, ortho
16
+ if __package__: from . import facets, ortho, defects, theme as _th
17
+ else: import facets, ortho, defects, theme as _th
18
18
 
19
19
  def _6c_R3m(z):
20
20
  return [[0,0,z%1],[2/3,1/3,(z+1/3)%1],[1/3,2/3,(z+2/3)%1],[0,0,(1-z)%1],[2/3,1/3,(1-z+1/3)%1],[1/3,2/3,(1-z+2/3)%1]]
@@ -136,14 +136,23 @@ def find_preset(q):
136
136
  return None
137
137
 
138
138
  class DislocationConfig:
139
- def __init__(self,dtype='edge',pos_frac=(.5,.5),line_dir='Z',b_angstrom=None,nu=.3,b_edge=None,b_screw=None):
139
+ # b_vec, line_vec: Cartesian (A) in the crystal frame; when both are given they
140
+ # replace dtype/line_dir/b_angstrom/b_edge/b_screw
141
+ def __init__(self,dtype='edge',pos_frac=(.5,.5),line_dir='Z',b_angstrom=None,nu=.3,b_edge=None,b_screw=None,b_vec=None,line_vec=None):
140
142
  self.dtype=dtype;self.pos_frac=pos_frac;self.line_dir=line_dir;self.b_angstrom=b_angstrom;self.nu=nu;self.b_edge=b_edge;self.b_screw=b_screw
143
+ self.b_vec=None if b_vec is None else np.asarray(b_vec,float);self.line_vec=None if line_vec is None else np.asarray(line_vec,float)
144
+
145
+ def _loop_normal(dl):
146
+ v=getattr(dl,'normal_vec',None)
147
+ if v is not None: return defects._unit(v)
148
+ return {'X':np.array([1.,0,0]),'Y':np.array([0,1.,0]),'Z':np.array([0,0,1.])}[dl.normal]
141
149
 
142
150
  class DislocationLoopConfig:
143
151
  def __init__(self,center_frac=(.5,.5,.5),radius_angstrom=20.,b_angstrom=None,
144
- normal='Z',nu=.3):
152
+ normal='Z',nu=.3,normal_vec=None):
145
153
  self.center_frac=center_frac;self.radius_angstrom=radius_angstrom
146
154
  self.b_angstrom=b_angstrom;self.normal=normal;self.nu=nu
155
+ self.normal_vec=None if normal_vec is None else np.asarray(normal_vec,float)
147
156
 
148
157
  class BCDIConfig:
149
158
  HC_KEV_ANG=12.3984
@@ -242,47 +251,20 @@ class CrystalBuilder:
242
251
  if dc is None or self.supercell_positions_ang is None: return
243
252
  pos_ideal=self.supercell_positions_ang.copy();pos=pos_ideal.copy()
244
253
  center=(pos.max(0)+pos.min(0))/2.;ext=pos.max(0)-pos.min(0)+1e-10
245
- b=dc.b_angstrom if dc.b_angstrom else self.config.LATTICE_A;nu=dc.nu
246
- px=center[0]+(dc.pos_frac[0]-0.5)*ext[0];py=center[1]+(dc.pos_frac[1]-0.5)*ext[1]
247
- if dc.line_dir=='Z': DX=pos[:,0]-px;DY=pos[:,1]-py;di=(0,1)
248
- elif dc.line_dir=='Y': DX=pos[:,0]-px;DY=pos[:,2]-py;di=(0,2)
249
- else: DX=pos[:,1]-px;DY=pos[:,2]-py;di=(1,2)
250
- R2=DX**2+DY**2+1e-20;theta=np.arctan2(DY,DX)
251
- if dc.dtype=='edge': pos[:,di[0]]+=(b/(2*np.pi))*(theta+DX*DY/(2*(1-nu)*R2))
252
- elif dc.dtype=='screw': la={'Z':2,'Y':1,'X':0}[dc.line_dir];pos[:,la]+=(b/(2*np.pi))*theta
253
- elif dc.dtype=='mixed':
254
- be=dc.b_edge if dc.b_edge else b*.866;bs=dc.b_screw if dc.b_screw else b*.5
255
- pos[:,di[0]]+=(be/(2*np.pi))*(theta+DX*DY/(2*(1-nu)*R2));la={'Z':2,'Y':1,'X':0}[dc.line_dir];pos[:,la]+=(bs/(2*np.pi))*theta
254
+ bv,xi=defects.dislocation_vectors(dc,self.config);o=defects.dislocation_origin(dc,center,ext,bv,xi)
255
+ u=defects.dislocation_displacement(pos[:,0],pos[:,1],pos[:,2],bv,xi,o,dc.nu)
256
+ for i in range(3): pos[:,i]+=u[i]
256
257
  self.supercell_positions_ang=pos;self._displacement_magnitudes=np.linalg.norm(pos-pos_ideal,axis=1)
257
258
  def apply_dislocation_loop(self):
258
- """Prismatic dislocation loop: u(r) = (b/4pi)*Omega(r) where Omega is solid angle."""
259
+ # prismatic loop, solid-angle term of the Burgers formula: u = (b/4pi)*Omega*n
259
260
  dl=self.config.DISLOCATION_LOOP
260
261
  if dl is None or self.supercell_positions_ang is None: return
261
262
  pos_ideal=self.supercell_positions_ang.copy();pos=pos_ideal.copy()
262
263
  center=(pos.max(0)+pos.min(0))/2.;ext=pos.max(0)-pos.min(0)+1e-10
263
- b=dl.b_angstrom if dl.b_angstrom else self.config.LATTICE_A;R=dl.radius_angstrom
264
- cx=center[0]+(dl.center_frac[0]-0.5)*ext[0]
265
- cy=center[1]+(dl.center_frac[1]-0.5)*ext[1]
266
- cz=center[2]+(dl.center_frac[2]-0.5)*ext[2]
267
- ndir={'X':np.array([1,0,0]),'Y':np.array([0,1,0]),'Z':np.array([0,0,1])}[dl.normal]
268
- # Vector from loop center to each atom
269
- dx=pos[:,0]-cx;dy=pos[:,1]-cy;dz=pos[:,2]-cz
270
- d_along=dx*ndir[0]+dy*ndir[1]+dz*ndir[2]
271
- perp_x=dx-d_along*ndir[0];perp_y=dy-d_along*ndir[1];perp_z=dz-d_along*ndir[2]
272
- rho=np.sqrt(perp_x**2+perp_y**2+perp_z**2)
273
- # Solid angle: Omega = 2*pi*sign(d)*(1 - |d|/sqrt(d^2+R^2)) for rho<R (inside)
274
- # Omega ~ pi*R^2*d/(d^2+rho^2)^(3/2) for rho>R (outside)
275
- dist2=d_along**2+1e-20
276
- inside=rho<R
277
- Omega=np.zeros(len(pos))
278
- # Inside the loop projection
279
- Omega[inside]=2*np.pi*np.sign(d_along[inside]+1e-30)*(1-np.abs(d_along[inside])/np.sqrt(dist2[inside]+R**2))
280
- # Outside: approximate
281
- r3=(dist2[~inside]+rho[~inside]**2)**1.5+1e-30
282
- Omega[~inside]=np.pi*R**2*d_along[~inside]/r3
283
- # Displacement: u = b/(4*pi) * Omega along normal
284
- u_mag=b/(4*np.pi)*Omega
285
- pos[:,0]+=u_mag*ndir[0];pos[:,1]+=u_mag*ndir[1];pos[:,2]+=u_mag*ndir[2]
264
+ b=dl.b_angstrom if dl.b_angstrom else self.config.LATTICE_A
265
+ c=center+(np.asarray(dl.center_frac,float)-0.5)*ext;n=_loop_normal(dl)
266
+ u_mag=b/(4*np.pi)*defects.loop_solid_angle(pos[:,0],pos[:,1],pos[:,2],c,n,dl.radius_angstrom)
267
+ for i in range(3): pos[:,i]+=u_mag*n[i]
286
268
  self.supercell_positions_ang=pos;self._displacement_magnitudes=np.linalg.norm(pos-pos_ideal,axis=1)
287
269
  def get_pmg_structure(self):
288
270
  if self.pmg_structure is None: self.build()
@@ -405,10 +387,17 @@ class ReflectionCalculator:
405
387
  t=(int(h),int(k),int(l));m=df[df['_cls'].apply(lambda f:t in f)]
406
388
  if len(m)==0: raise ValueError(f'Reflection ({h} {k} {l}) not found')
407
389
  sel=m.iloc[0]
390
+ # 'hkl' is the reflection asked for (it sets the direction of G), 'hkl_rep' the stored
391
+ # family member; |F| is for the requested hkl, as Bijvoet pairs differ (f'')
392
+ req=tuple(int(x) for x in (hkl if hkl is not None else sel.get('hkl_canonical',sel['hkl'])))
393
+ c=self.config;stol=np.sin(np.radians(sel['_tt']/2.))/c.wavelength_angstrom
394
+ F2=float(np.abs(self._F(req[0],req[1],req[2],c.BEAM_ENERGY_KEV*1e3,stol))**2)
395
+ G=defects.g_vector(c,req)
408
396
  # full-precision values; the rounded columns are for display only
409
- return{'hkl':sel['hkl'],'hkl_str':sel.get('hkl_display',sel['hkl_str']),'hkl_raw':sel['hkl_str'],
397
+ return{'hkl':req,'hkl_rep':tuple(int(x) for x in sel['hkl']),'hkl_str':f'({req[0]} {req[1]} {req[2]})',
398
+ 'hkl_family':sel.get('hkl_display',sel['hkl_str']),'hkl_raw':sel['hkl_str'],
410
399
  'd_hkl':float(sel['_d']),'theta_B_rad':np.radians(sel['_tt']/2.),'two_theta_rad':np.radians(sel['_tt']),
411
- 'q_magnitude':float(sel['_q']),'F_squared':float(sel['_F2']),'LP_factor':float(sel['_LP']),
400
+ 'q_magnitude':float(np.linalg.norm(G)),'G_vector':G,'F_squared':F2,'LP_factor':float(sel['_LP']),
412
401
  'intensity_norm':float(sel['I_norm'])}
413
402
 
414
403
  class BCDISimulator:
@@ -423,44 +412,47 @@ class BCDISimulator:
423
412
  sx=k0*(c.SOURCE_SIZE_H_UM*1e4)/RA/dx if dx>0 and RA>0 else 0.;sy=k0*(c.SOURCE_SIZE_V_UM*1e4)/RA/dy if dy>0 and RA>0 else 0.;sz=k0*c.MONOCHR_BANDWIDTH/dz if dz>0 else 0.
424
413
  if max(sx,sy,sz)<.1: return vol
425
414
  return gaussian_filter(vol.astype(np.float64),sigma=[sx,sy,sz]).astype(np.float32)
415
+ def _G(self):
416
+ G=self.reflection.get('G_vector')
417
+ return np.asarray(G if G is not None else defects.g_vector(self.config,self.reflection['hkl']),float)
418
+ @staticmethod
419
+ def _axis(N,L):
420
+ # DFT-consistent sampling: step L/N, zero at index N//2 (the ifftshift origin)
421
+ return ((np.arange(N)-N//2)*(L/N)).astype(np.float32)
426
422
  def _displacement(self,N,tA,OS):
427
- cfg=self.config;G=self.reflection['q_magnitude'];ext=tA*OS
428
- x=np.linspace(-ext[0]/2,ext[0]/2,N,dtype=np.float32);y=np.linspace(-ext[1]/2,ext[1]/2,N,dtype=np.float32);z=np.linspace(-ext[2]/2,ext[2]/2,N,dtype=np.float32)
429
- X,Y,Z=np.meshgrid(x,y,z,indexing='ij');phase=np.zeros((N,N,N),np.float32);eps=cfg.STRAIN_MAGNITUDE
430
- if cfg.STRAIN_TYPE=='radial_gradient': phase+=G*eps*np.sqrt(X**2+Y**2+Z**2)
431
- elif cfg.STRAIN_TYPE=='edge_dislocation': phase+=G*(cfg.LATTICE_A/(2*np.pi))*np.arctan2(Y,X+1e-10)
432
- elif cfg.STRAIN_TYPE=='random':
433
- from scipy.ndimage import gaussian_filter as gf;np.random.seed(42);raw=gf(np.random.randn(N,N,N).astype(np.float32),sigma=N/8);raw/=np.abs(raw).max()+1e-12;phase+=G*eps*np.mean(tA)/2.*raw
423
+ # phase of the object, PHASE_SIGN*G.u(r), with G = h b1 + k b2 + l b3 in the crystal frame
424
+ cfg=self.config;G=self._G();sg=defects.PHASE_SIGN;ext=tA*OS
425
+ X,Y,Z=np.meshgrid(*[self._axis(N,ext[i]) for i in range(3)],indexing='ij')
426
+ phase=np.zeros((N,N,N),np.float32);eps=cfg.STRAIN_MAGNITUDE;st=cfg.STRAIN_TYPE
427
+ Gx,Gy,Gz=(float(v) for v in G)
428
+ if st=='radial_gradient':
429
+ # u(r) = eps*(|r|/R)*r with R half the mean particle size
430
+ R=0.5*float(np.mean(tA))
431
+ phase+=sg*eps/R*np.sqrt(X**2+Y**2+Z**2)*(Gx*X+Gy*Y+Gz*Z)
432
+ elif st in('screw_dislocation','edge_dislocation'):
433
+ # screw along z through the centre, b = shortest lattice translation along z
434
+ bz=defects.shortest_along(cfg,[0,0,1]) or cfg.LATTICE_A
435
+ phase+=sg*Gz*(bz/(2*np.pi))*np.arctan2(Y,X)
436
+ elif st=='random':
437
+ # smooth random vector displacement, |u| up to eps*R
438
+ from scipy.ndimage import gaussian_filter as gf
439
+ rng=np.random.default_rng(getattr(cfg,'STRAIN_SEED',42));R=0.5*float(np.mean(tA))
440
+ for g in(Gx,Gy,Gz):
441
+ w=gf(rng.standard_normal((N,N,N)).astype(np.float32),sigma=N/8);w/=np.abs(w).max()+1e-12
442
+ phase+=np.float32(sg*g*eps*R)*w
434
443
  dc=cfg.DISLOCATION
435
444
  if dc is not None:
436
- b=dc.b_angstrom if dc.b_angstrom else cfg.LATTICE_A;nu=dc.nu
437
- px=(dc.pos_frac[0]-0.5)*tA[0];py=(dc.pos_frac[1]-0.5)*tA[1]
438
- if dc.line_dir=='Z': DX,DY=X-px,Y-py
439
- elif dc.line_dir=='Y': DX,DY=X-px,Z-py
440
- else: DX,DY=Y-px,Z-py
441
- R2=DX**2+DY**2+1e-20;theta=np.arctan2(DY,DX)
442
- if dc.dtype=='edge': phase+=G*(b/(2*np.pi))*(theta+DX*DY/(2*(1-nu)*R2))
443
- elif dc.dtype=='screw': phase+=G*(b/(2*np.pi))*theta
444
- elif dc.dtype=='mixed':
445
- be=dc.b_edge if dc.b_edge else b*.866;bs=dc.b_screw if dc.b_screw else b*.5
446
- phase+=G*((be/(2*np.pi))*(theta+DX*DY/(2*(1-nu)*R2))+(bs/(2*np.pi))*theta)
445
+ bv,xi=defects.dislocation_vectors(dc,cfg);o=defects.dislocation_origin(dc,np.zeros(3),tA,bv,xi)
446
+ u=defects.dislocation_displacement(X,Y,Z,bv,xi,o,dc.nu)
447
+ phase+=sg*(Gx*u[0]+Gy*u[1]+Gz*u[2])
447
448
  dl=cfg.DISLOCATION_LOOP
448
449
  if dl is not None:
449
- b=dl.b_angstrom if dl.b_angstrom else cfg.LATTICE_A;R_loop=dl.radius_angstrom
450
- lcx=(dl.center_frac[0]-0.5)*tA[0];lcy=(dl.center_frac[1]-0.5)*tA[1];lcz=(dl.center_frac[2]-0.5)*tA[2]
451
- ndir={'X':np.array([1,0,0]),'Y':np.array([0,1,0]),'Z':np.array([0,0,1])}[dl.normal]
452
- d_along=(X-lcx)*ndir[0]+(Y-lcy)*ndir[1]+(Z-lcz)*ndir[2]
453
- perp2=(X-lcx)**2+(Y-lcy)**2+(Z-lcz)**2-d_along**2
454
- rho=np.sqrt(np.maximum(perp2,0))
455
- inside=rho<R_loop;dist2=d_along**2+1e-20
456
- Omega=np.zeros_like(X)
457
- Omega[inside]=2*np.pi*np.sign(d_along[inside]+1e-30)*(1-np.abs(d_along[inside])/np.sqrt(dist2[inside]+R_loop**2))
458
- r3=(dist2[~inside]+rho[~inside]**2)**1.5+1e-30
459
- Omega[~inside]=np.pi*R_loop**2*d_along[~inside]/r3
460
- phase+=G*(b/(4*np.pi))*Omega
450
+ b=dl.b_angstrom if dl.b_angstrom else cfg.LATTICE_A;n=_loop_normal(dl)
451
+ c=(np.asarray(dl.center_frac,float)-0.5)*tA
452
+ phase+=sg*float(G@n)*(b/(4*np.pi))*defects.loop_solid_angle(X,Y,Z,c,n,dl.radius_angstrom)
461
453
  return phase.astype(np.float32)
462
454
  def _sup(self,N,OS):
463
- h=.5/OS;x=np.linspace(-.5,.5,N,np.float32);X,Y,Z=np.meshgrid(x,x,x,indexing='ij');s=self.config.PARTICLE_SHAPE
455
+ h=.5/OS;x=self._axis(N,1.);X,Y,Z=np.meshgrid(x,x,x,indexing='ij');s=self.config.PARTICLE_SHAPE
464
456
  if s=='cylinder': return(np.sqrt(X**2+Y**2)<=h)&(np.abs(Z)<=h)
465
457
  if s=='sphere': return np.sqrt(X**2+Y**2+Z**2)<=h
466
458
  if s=='hexagonal':
@@ -483,7 +475,7 @@ class BCDISimulator:
483
475
  delta_th=np.radians(c.ANGULAR_OFFSET_DEG/2.)
484
476
  delta_q=(4*np.pi/c.wavelength_angstrom)*np.cos(self.reflection['theta_B_rad'])*delta_th
485
477
  # Phase ramp along first spatial axis
486
- rx=np.linspace(-ext[0]/2,ext[0]/2,N,dtype=np.float32)
478
+ rx=self._axis(N,tA[0]*OS)
487
479
  phase_ramp=np.exp(1j*delta_q*rx)[:,None,None]
488
480
  psi=psi*phase_ramp
489
481
  pq=np.fft.fftshift(np.fft.fftn(np.fft.ifftshift(psi)))
@@ -509,13 +501,19 @@ class BCDISimulator:
509
501
 
510
502
  def add_experimental_noise(vol,n_photons=None,photon_mode='total',poisson=True,air_scatter=0,
511
503
  readout_noise=0,dark_cps=0,exposure_s=1.,dead_pixels_frac=0,
512
- hot_pixels_frac=0,counting=True,seed=42):
504
+ hot_pixels_frac=0,counting=True,seed=42,dead_time_s=0.):
505
+ # dead_time_s > 0: paralysable counter with exposure exposure_s, applied to the
506
+ # expected counts before the Poisson draw (needs a photon budget to set the rate)
513
507
  rng=np.random.default_rng(seed);out=np.asarray(vol,np.float64)
514
508
  if air_scatter>0:
515
509
  N=out.shape[0];c=N//2;r0=max(1,N//4);x=np.arange(N)-c;QX,QY,QZ=np.meshgrid(x,x,x,indexing='ij')
516
510
  rn=(QX**2+QY**2+QZ**2)/(r0**2+1e-10);out=out+max(1.,out.max())*air_scatter*1e-6/(1.+rn**2)
511
+ dt=dead_time_s and dead_time_s>0 and n_photons and n_photons>0
517
512
  if n_photons and n_photons>0:
518
- out=ortho.apply_photons(out,n_photons,photon_mode,poisson=poisson,seed=seed).astype(np.float64)
513
+ out=ortho.apply_photons(out,n_photons,photon_mode,poisson=poisson and not dt,seed=seed).astype(np.float64)
514
+ if dt:
515
+ out=ortho.apply_dead_time(out,dead_time_s,exposure_s)
516
+ if poisson: out=rng.poisson(np.clip(out,0,1e15)).astype(np.float64)
519
517
  elif poisson:
520
518
  sc=1e6/max(1,out.max());out=rng.poisson(np.clip(out*sc,0,1e12)).astype(np.float64)/sc
521
519
  return ortho.detector_noise(out,dark_cps=dark_cps,exposure_s=exposure_s,
@@ -546,7 +544,8 @@ def export_measurement(sim,refl,cfg,filepath,noise_opts=None):
546
544
  vol=sim.diff_volume.copy()
547
545
  if noise_opts: vol=add_experimental_noise(vol,**noise_opts)
548
546
  data={'diffraction_volume':vol,'qx':sim.q_grids['qx'],'qy':sim.q_grids['qy'],'qz':sim.q_grids['qz'],
549
- 'hkl':np.array(refl['hkl']),'d_hkl':refl['d_hkl'],'two_theta':np.degrees(refl['two_theta_rad']),
547
+ 'hkl':np.array(refl['hkl']),'G_vector':np.asarray(refl.get('G_vector',defects.g_vector(cfg,refl['hkl'])),float),
548
+ 'phase_sign':defects.PHASE_SIGN,'d_hkl':refl['d_hkl'],'two_theta':np.degrees(refl['two_theta_rad']),
550
549
  'energy_keV':cfg.BEAM_ENERGY_KEV,'wavelength_A':cfg.wavelength_angstrom,
551
550
  'material':cfg.MATERIAL_NAME,'space_group':cfg.SPACE_GROUP,
552
551
  'lattice_a':cfg.LATTICE_A,'lattice_b':cfg.LATTICE_B,'lattice_c':cfg.LATTICE_C,
@@ -556,7 +555,8 @@ def export_measurement(sim,refl,cfg,filepath,noise_opts=None):
556
555
  'beam_size_um':cfg.BEAM_SIZE_UM,'oversampling':cfg.TARGET_OVERSAMPLING,
557
556
  'n_photons':getattr(cfg,'N_PHOTONS',0),'photon_mode':getattr(cfg,'PHOTON_MODE','total'),
558
557
  'q_frame':getattr(cfg,'Q_FRAME','lab'),'detector_counting':getattr(cfg,'DET_COUNTING',True),
559
- 'particle_size_nm':cfg.particle_size_nm}
558
+ 'particle_size_nm':cfg.particle_size_nm,
559
+ 'voxel_size_nm':np.asarray(cfg.particle_size_angstrom*cfg.TARGET_OVERSAMPLING/cfg.DETECTOR_N_PIXELS/10.,np.float32)}
560
560
  if filepath.endswith('.h5') or filepath.endswith('.hdf5'):
561
561
  import h5py
562
562
  with h5py.File(filepath,'w') as f:
@@ -576,7 +576,7 @@ def _sr(label,sid,mn,mx,val,step,jsfn,unit='%'):
576
576
 
577
577
  def _loading_html(title="Rendering 3D..."):
578
578
 
579
- return f'''<div id="loadOvr" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#0d0e12;z-index:99999;display:flex;align-items:center;justify-content:center;flex-direction:column"><div style="color:#4f98a3;font-size:16px;font-weight:700;margin-bottom:20px">{title}</div><div style="width:220px;height:6px;background:#161b22;border-radius:3px;overflow:hidden"><div id="loadBar" style="width:0%;height:100%;background:#4f98a3;border-radius:3px;transition:width 0.3s"></div></div><div id="loadPct" style="color:#8b949e;font-size:11px;margin-top:8px">0%</div></div><script>(function(){{var b=document.getElementById("loadBar"),t=document.getElementById("loadPct"),o=document.getElementById("loadOvr"),p=0;var iv=setInterval(function(){{p=Math.min(p+2+Math.random()*4,90);b.style.width=p+"%";t.innerText=Math.round(p)+"%"}},200);function done(){{clearInterval(iv);b.style.width="100%";t.innerText="100%";setTimeout(function(){{o.style.opacity="0";o.style.transition="opacity 0.3s";setTimeout(function(){{o.style.display="none"}},350)}},200)}};var gd=document.querySelector(".plotly-graph-div");if(gd&&gd.on)gd.on("plotly_afterplot",done);setTimeout(done,8000)}})();</script>'''
579
+ return _th.c(f'''<div id="loadOvr" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#0d0e12;z-index:99999;display:flex;align-items:center;justify-content:center;flex-direction:column"><div style="color:#4f98a3;font-size:16px;font-weight:700;margin-bottom:20px">{title}</div><div style="width:220px;height:6px;background:#161b22;border-radius:3px;overflow:hidden"><div id="loadBar" style="width:0%;height:100%;background:#4f98a3;border-radius:3px;transition:width 0.3s"></div></div><div id="loadPct" style="color:#8b949e;font-size:11px;margin-top:8px">0%</div></div><script>(function(){{var b=document.getElementById("loadBar"),t=document.getElementById("loadPct"),o=document.getElementById("loadOvr"),p=0;var iv=setInterval(function(){{p=Math.min(p+2+Math.random()*4,90);b.style.width=p+"%";t.innerText=Math.round(p)+"%"}},200);function done(){{clearInterval(iv);b.style.width="100%";t.innerText="100%";setTimeout(function(){{o.style.opacity="0";o.style.transition="opacity 0.3s";setTimeout(function(){{o.style.display="none"}},350)}},200)}};var gd=document.querySelector(".plotly-graph-div");if(gd&&gd.on)gd.on("plotly_afterplot",done);setTimeout(done,8000)}})();</script>''')
580
580
 
581
581
  def lattice_html_with_controls(builder,max_atoms=50000,atom_size=3,show_bonds=False,show_strain=False,show_dislocation=False):
582
582
  import plotly.graph_objects as go
@@ -596,17 +596,17 @@ def lattice_html_with_controls(builder,max_atoms=50000,atom_size=3,show_bonds=Fa
596
596
  p_d=pos[displaced_mask];d_d=disp[displaced_mask]
597
597
  traces.append(go.Scatter3d(x=p_d[:,0],y=p_d[:,1],z=p_d[:,2],mode='markers',name='Displaced',
598
598
  marker=dict(size=atom_size+1,color=d_d,colorscale='Turbo',cmin=0,cmax=disp.max(),
599
- showscale=True,colorbar=dict(title='|u| (A)',thickness=12,len=0.6,x=0.02),opacity=.95,line=dict(width=0)),
599
+ showscale=True,colorbar=dict(title='|u| (A)',thickness=12,len=0.6,x=0.02),opacity=.95,line=_th.pick(dict(width=0),dict(width=1,color='rgba(40,32,24,.45)'))),
600
600
  hovertemplate='|u|=%{marker.color:.3f} A<extra></extra>'));nat+=1
601
601
  elif show_strain and disp is not None and disp.max()>1e-6:
602
602
  traces.append(go.Scatter3d(x=pos[:,0],y=pos[:,1],z=pos[:,2],mode='markers',name='Displacement',
603
603
  marker=dict(size=atom_size,color=disp,colorscale='Inferno',cmin=0,cmax=disp.max(),
604
- showscale=True,colorbar=dict(title='|u| (A)',thickness=12,len=0.6,x=0.02),opacity=.9,line=dict(width=0)),
604
+ showscale=True,colorbar=dict(title='|u| (A)',thickness=12,len=0.6,x=0.02),opacity=.9,line=_th.pick(dict(width=0),dict(width=1,color='rgba(40,32,24,.45)'))),
605
605
  hovertemplate='|u|=%{marker.color:.3f} A<extra></extra>'));nat=1
606
606
  else:
607
607
  for s in dict.fromkeys(sp):
608
608
  m=sa==s;p_=pos[m]
609
- traces.append(go.Scatter3d(x=p_[:,0],y=p_[:,1],z=p_[:,2],mode='markers',name=s,marker=dict(size=atom_size,color=CPK.get(s,'#AAA'),opacity=.85,line=dict(width=0)),hovertemplate=f'<b>{s}</b><br>%{{x:.2f}},%{{y:.2f}},%{{z:.2f}}<extra></extra>'));nat+=1
609
+ traces.append(go.Scatter3d(x=p_[:,0],y=p_[:,1],z=p_[:,2],mode='markers',name=s,marker=dict(size=atom_size,color=CPK.get(s,'#AAA'),opacity=.85,line=_th.pick(dict(width=0),dict(width=1,color='rgba(40,32,24,.45)'))),hovertemplate=f'<b>{s}</b><br>%{{x:.2f}},%{{y:.2f}},%{{z:.2f}}<extra></extra>'));nat+=1
610
610
  bond_trace_idx=-1
611
611
  if show_bonds:
612
612
  cfg=builder.config;M=cfg.lattice_vectors_cartesian;nb=len(cfg.BASIS_COORDS)
@@ -619,14 +619,14 @@ def lattice_html_with_controls(builder,max_atoms=50000,atom_size=3,show_bonds=Fa
619
619
  if 0<len(pairs)<500000:
620
620
  bx,by,bz=[],[],[]
621
621
  for i,j in pairs: bx+=[pos[i,0],pos[j,0],None];by+=[pos[i,1],pos[j,1],None];bz+=[pos[i,2],pos[j,2],None]
622
- traces.append(go.Scatter3d(x=bx,y=by,z=bz,mode='lines',name='Bonds',line=dict(color='rgba(255,255,255,0.25)',width=1),hoverinfo='skip'));bond_trace_idx=len(traces)-1
622
+ traces.append(go.Scatter3d(x=bx,y=by,z=bz,mode='lines',name='Bonds',line=dict(color=_th.c('rgba(255,255,255,0.25)'),width=1),hoverinfo='skip'));bond_trace_idx=len(traces)-1
623
623
  cfg=builder.config;M=cfg.lattice_vectors_cartesian;nx,ny,nz=cfg.SUPERCELL_MULT
624
624
  v=np.array([[i,j,k] for i in(0,nx) for j in(0,ny) for k in(0,nz)],float);corners=v@M
625
625
  edges=[(0,1),(0,2),(0,4),(1,3),(1,5),(2,3),(2,6),(4,5),(4,6),(3,7),(5,7),(6,7)]
626
626
  ex,ey,ez=[],[],[]
627
627
  for i,j in edges: ex+=[corners[i,0],corners[j,0],None];ey+=[corners[i,1],corners[j,1],None];ez+=[corners[i,2],corners[j,2],None]
628
- traces.append(go.Scatter3d(x=ex,y=ey,z=ez,mode='lines',line=dict(color='#FFF',width=2),opacity=.5,hoverinfo='skip',showlegend=False))
629
- sz=cfg.particle_size_nm;ax=dict(backgroundcolor='#0a0d12',gridcolor='rgba(255,255,255,.08)',showbackground=True,color='#c0c4cc',zeroline=False)
628
+ traces.append(go.Scatter3d(x=ex,y=ey,z=ez,mode='lines',line=dict(color=_th.pick('#FFF','#5c5446'),width=2),opacity=.5,hoverinfo='skip',showlegend=False))
629
+ sz=cfg.particle_size_nm;ax=dict(backgroundcolor=_th.c('#0a0d12'),gridcolor=_th.c('rgba(255,255,255,.08)'),showbackground=True,color=_th.c('#c0c4cc'),zeroline=False)
630
630
  dc=cfg.DISLOCATION;dl=cfg.DISLOCATION_LOOP
631
631
  ds=""
632
632
  if dc: ds=f" | disl:{dc.dtype}@({dc.pos_frac[0]:.2f},{dc.pos_frac[1]:.2f})"
@@ -634,7 +634,7 @@ def lattice_html_with_controls(builder,max_atoms=50000,atom_size=3,show_bonds=Fa
634
634
  fig=go.Figure(data=traces)
635
635
  # Camera: for hex/layered systems, tilt to show lateral arrangement
636
636
  cam=dict(eye=dict(x=1.6,y=0.4,z=0.8)) if cfg.LATTICE_GAMMA==120 else dict(eye=dict(x=1.25,y=1.25,z=1.25))
637
- fig.update_layout(title=dict(text=f'{cfg.MATERIAL_NAME} {nx}x{ny}x{nz} {sz[0]:.1f}x{sz[1]:.1f}x{sz[2]:.1f}nm {len(pos):,}atoms{ds}',font=dict(size=12,color='#c0c4cc'),x=.5,xanchor='center'),scene=dict(xaxis=dict(**ax,title='x(A)'),yaxis=dict(**ax,title='y(A)'),zaxis=dict(**ax,title='z(A)'),aspectmode='data',camera=cam,bgcolor='#0a0d12'),paper_bgcolor='#0d0e12',font=dict(family='Consolas,monospace',size=11,color='#c0c4cc'),legend=dict(bgcolor='rgba(15,15,20,.8)',bordercolor='rgba(255,255,255,.15)',borderwidth=1,font=dict(size=10)),margin=dict(l=0,r=0,t=40,b=0),template='plotly_dark')
637
+ fig.update_layout(title=dict(text=f'{cfg.MATERIAL_NAME} {nx}x{ny}x{nz} {sz[0]:.1f}x{sz[1]:.1f}x{sz[2]:.1f}nm {len(pos):,}atoms{ds}',font=dict(size=12,color=_th.c('#c0c4cc')),x=.5,xanchor='center'),scene=dict(xaxis=dict(**ax,title='x(A)'),yaxis=dict(**ax,title='y(A)'),zaxis=dict(**ax,title='z(A)'),aspectmode='data',camera=cam,bgcolor=_th.c('#0a0d12')),paper_bgcolor=_th.c('#0d0e12'),font=dict(family='Consolas,monospace',size=11,color=_th.c('#c0c4cc')),legend=dict(bgcolor=_th.c('rgba(15,15,20,.8)'),bordercolor=_th.c('rgba(255,255,255,.15)'),borderwidth=1,font=dict(size=10)),margin=dict(l=0,r=0,t=40,b=0),template=_th.plotly_template())
638
638
  html=fig.to_html(include_plotlyjs=True,full_html=True,config={'displaylogo':False})
639
639
  # Loading overlay with fallback timeout (dismisses after 8s max)
640
640
  idxs=str(list(range(nat)));bond_js="";bond_js_fn=""
@@ -646,7 +646,7 @@ def lattice_html_with_controls(builder,max_atoms=50000,atom_size=3,show_bonds=Fa
646
646
  dm=f"{disp.max():.2f}";strain_ctrl=_sr("Strain min","smin","0",dm,"0","0.01","updSmin","A")+_sr("Strain max","smax","0",dm,dm,"0.01","updSmax","A")
647
647
  PANEL=_SL+f'<div style="font-size:12px;font-weight:700;margin-bottom:10px;color:#4f98a3">Lattice View</div>'+_sr("Atom size","asz","1","12",str(atom_size),"1","updSz","")+strain_ctrl+bond_js+f'</div><script>(function(){{var gd=document.querySelector(".plotly-graph-div");window.updSz=function(v){{document.getElementById("aszV").innerText=v;Plotly.restyle(gd,{{"marker.size":parseInt(v)}},{idxs})}};{bond_js_fn}if(document.getElementById("smin")){{window.updSmin=function(v){{document.getElementById("sminV").innerText=v+"A";Plotly.restyle(gd,{{"marker.cmin":Number(v)}},[0])}};window.updSmax=function(v){{document.getElementById("smaxV").innerText=v+"A";Plotly.restyle(gd,{{"marker.cmax":Number(v)}},[0])}}}}}})();</script>'
648
648
  html=html.replace('<body>','<body>'+_loading_html('Rendering 3D Lattice...'),1)
649
- return html.replace('</body>',PANEL+'</body>',1)
649
+ return html.replace('</body>',_th.c(PANEL)+'</body>',1)
650
650
 
651
651
  def bragg_html_with_controls(sim,downsample=2,threshold_frac=1e-4,noise_opts=None,vol=None,frame_label=''):
652
652
  import plotly.graph_objects as go
@@ -659,8 +659,8 @@ def bragg_html_with_controls(sim,downsample=2,threshold_frac=1e-4,noise_opts=Non
659
659
  vl=np.log10(d3+1.).astype(np.float32);vm=float(vl.max())
660
660
  QX,QY,QZ=np.meshgrid(qx,qy,qz,indexing='ij')
661
661
  fig=go.Figure()
662
- fig.add_trace(go.Volume(x=QX.ravel(),y=QY.ravel(),z=QZ.ravel(),value=vl.ravel(),isomin=vm*.75,isomax=vm,opacity=1,surface_count=21,colorscale=[[0,'#030d1e'],[.12,'#0a2a6e'],[.30,'#1060c8'],[.50,'#30b0e8'],[.65,'#e8d830'],[.80,'#e87010'],[.92,'#d01808'],[1.,'#ffffff']],showscale=True,colorbar=dict(thickness=14,len=.9,title=dict(text='log10(I+1)',side='right'),tickfont=dict(size=10,color='#c0c4cc')),caps=dict(x_show=False,y_show=False,z_show=False)))
663
- cfg=sim.config;sz=cfg.particle_size_nm;ax=dict(backgroundcolor='#080a0e',gridcolor='rgba(255,255,255,.09)',showbackground=True,color='#c0c4cc',zeroline=False)
662
+ fig.add_trace(go.Volume(x=QX.ravel(),y=QY.ravel(),z=QZ.ravel(),value=vl.ravel(),isomin=vm*.75,isomax=vm,opacity=1,surface_count=21,colorscale=[[0,'#030d1e'],[.12,'#0a2a6e'],[.30,'#1060c8'],[.50,'#30b0e8'],[.65,'#e8d830'],[.80,'#e87010'],[.92,'#d01808'],[1.,'#ffffff']],showscale=True,colorbar=dict(thickness=14,len=.9,title=dict(text='log10(I+1)',side='right'),tickfont=dict(size=10,color=_th.c('#c0c4cc'))),caps=dict(x_show=False,y_show=False,z_show=False)))
663
+ cfg=sim.config;sz=cfg.particle_size_nm;ax=dict(backgroundcolor=_th.c('#080a0e'),gridcolor=_th.c('rgba(255,255,255,.09)'),showbackground=True,color=_th.c('#c0c4cc'),zeroline=False)
664
664
  noise_str=""
665
665
  if noise_opts:
666
666
  parts=[]
@@ -670,7 +670,7 @@ def bragg_html_with_controls(sim,downsample=2,threshold_frac=1e-4,noise_opts=Non
670
670
  if noise_opts.get('dead_pixels_frac',0)>0: parts.append("dead")
671
671
  if parts: noise_str=" | "+", ".join(parts)
672
672
  if frame_label: noise_str+=" | "+frame_label
673
- fig.update_layout(template='plotly_dark',paper_bgcolor='#0d0e12',scene=dict(xaxis=dict(**ax,title='qx(1/A)'),yaxis=dict(**ax,title='qy(1/A)'),zaxis=dict(**ax,title='qz(1/A)'),camera=dict(eye=dict(x=1.4,y=1.4,z=.7)),aspectmode='data'),font=dict(family='Consolas,monospace',size=11,color='#c0c4cc'),title=dict(text=f'{cfg.MATERIAL_NAME} {sim.reflection["hkl_str"]} | {sz[0]:.0f}x{sz[1]:.0f}x{sz[2]:.0f}nm{noise_str}',font=dict(size=12),x=.5,xanchor='center'),margin=dict(l=0,r=0,t=40,b=0))
673
+ fig.update_layout(template=_th.plotly_template(),paper_bgcolor=_th.c('#0d0e12'),scene=dict(xaxis=dict(**ax,title='qx(1/A)'),yaxis=dict(**ax,title='qy(1/A)'),zaxis=dict(**ax,title='qz(1/A)'),camera=dict(eye=dict(x=1.4,y=1.4,z=.7)),aspectmode='data'),font=dict(family='Consolas,monospace',size=11,color=_th.c('#c0c4cc')),title=dict(text=f'{cfg.MATERIAL_NAME} {sim.reflection["hkl_str"]} | {sz[0]:.0f}x{sz[1]:.0f}x{sz[2]:.0f}nm{noise_str}',font=dict(size=12),x=.5,xanchor='center'),margin=dict(l=0,r=0,t=40,b=0))
674
674
  # Fringe measurement JS
675
675
  measure_js="""<div id="meas" style="position:fixed;top:16px;right:16px;z-index:9999;background:rgba(13,14,18,.93);border:1px solid rgba(255,255,255,.13);border-radius:10px;padding:8px 12px;font-family:Consolas,monospace;font-size:11px;color:#c0c4cc;display:none">
676
676
  <div style="color:#4f98a3;font-weight:700;margin-bottom:4px">Measure fringes</div>
@@ -694,4 +694,4 @@ if(mp.length>=2){{var dx=mp[1].x-mp[0].x,dy=mp[1].y-mp[0].y,dz=mp[1].z-mp[0].z,d
694
694
  var d_ang=2*Math.PI/dist;document.getElementById("mdist").innerText="dq="+dist.toFixed(4)+" 1/A => d="+d_ang.toFixed(2)+" A ("+( d_ang/10).toFixed(3)+" nm)";
695
695
  document.getElementById("mpts").innerText="Pt1-Pt2: dq="+dist.toFixed(4);mp=[]}}}});
696
696
  }})();</script>"""
697
- return html.replace('</body>',PANEL+'</body>',1)
697
+ return html.replace('</body>',_th.c(PANEL)+'</body>',1)