clue_oxide 0.2.1

CluE Oxide (Cluster Evolution Oxide) is a spin dynamics simulation program for electron spin decoherence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

use crate::build_adjacency_list;
use crate::find_clusters;
use crate::config::{Config,ClusterMethod,OrientationAveraging};
use crate::CluEError;
use crate::cluster::methyl_clusters::partition_cluster_set_by_exchange_groups;
use crate::cluster::{find_clusters::ClusterSet, 
  read_clusters::read_cluster_file};
use crate::HamiltonianTensors;
use crate::integration_grid::IntegrationGrid;
use crate::physical_constants::{ONE,PI};
use crate::signal::Signal;
use crate::signal::write_vec_signals;
use crate::signal::cluster_correlation_expansion::*;
use crate::signal::calculate_analytic_restricted_2cluster_signals::{
  calculate_analytic_restricted_2cluster_signals};
use crate::Structure;
use crate::quantum::spin_hamiltonian::*;
use crate::math;
use crate::space_3d::UnitSpherePoint;

use num_complex::Complex;
use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng};
use rand_distr::{Distribution,Uniform};

//------------------------------------------------------------------------------
/// This function averages of `number_system_instances` instances of building
/// a system and calculating the signal.
pub fn calculate_signals(rng: &mut ChaCha20Rng, config: &Config,
    path_opt: &Option<String>) -> Result<Vec::<Signal>,CluEError>
{
  let Some(max_cluster_size) = config.max_cluster_size else {
    return Err(CluEError::NoMaxClusterSize);
  };
  let Some(number_system_instances) = config.number_system_instances else {
    return Err(CluEError::NoNumberSystemInstances);
  }; 

  let range = Uniform::from(0..std::u64::MAX);
  let new_seeds = (0..number_system_instances).map(|_ii|
      range.sample(rng) )
    .collect::<Vec::<u64>>();

  let n_tot = config.number_timepoints.iter().sum::<usize>();

  let mut signals = (0..max_cluster_size).map(|_ii| Signal::zeros(n_tot))
    .collect::<Vec::<Signal>>();

  for (ii,&seed) in new_seeds.iter().enumerate(){

    println!("\nSystem instance: {}/{}.", ii+1, number_system_instances);

    let mut inst_rng = ChaCha20Rng::seed_from_u64(seed);
    let inst_signals = calculate_structure_signal(&mut inst_rng, 
        config, path_opt)?;

    for (order_idx, sig) in inst_signals.iter().enumerate(){
      signals[order_idx] = &signals[order_idx] + sig;
    }
  }

  for sig in signals.iter_mut(){
    sig.scale(ONE/(number_system_instances as f64));
  }
  Ok(signals)
}
//------------------------------------------------------------------------------
// This function builds the spin structure and calculates the signal over
// one or multiple orientations.
fn calculate_structure_signal(rng: &mut ChaCha20Rng, config: &Config,
    path_opt: &Option<String>) -> Result<Vec::<Signal>,CluEError>
{

  // Build input structure.
  let structure = Structure::build_structure(rng,config)?;
  

  // Determine if/where to save results.
  let save_dir_opt = match path_opt{
    Some(path) => {
      
      
      let save_dir = match &config.system_name{
        Some(system_name) => {
          format!("{}/{}",path,system_name)
        },
        None => {
          let structure_hash = math::str_hash(&structure);
          format!("{}/system-{}",path,structure_hash)
        }
      };

      match std::fs::create_dir_all(save_dir.clone()){
        Ok(_) => (),
        Err(_) => return Err(CluEError::CannotCreateDir(save_dir)),
      }
  
      if let Some(info_dir) = &config.write_info{

        let info_path = format!("{}/{}",save_dir,info_dir);

        if std::fs::create_dir_all(info_path.clone()).is_err(){
          return Err(CluEError::CannotCreateDir(info_path));
        }

        if let Some(filename) = &config.write_bath{
          structure.bath_to_csv(&format!("{}/{}.csv", info_path, filename),
              config)?;
        }

        if let Some(filename) = &config.write_structure_pdb{
          structure.write_pdb(&format!("{}/{}.pdb", info_path, filename))?;
        }

        if let Some(exchange_group_manager) = &structure.exchange_groups{
          if let Some(filename) = &config.write_exchange_groups{
            let csv_file = format!("{}/{}.csv",info_path,filename);
            exchange_group_manager.to_csv(&csv_file,&structure)?;
          }
        }
      }
      Some(save_dir)
    },
    None => None,
  };



  // Determine maximum cluster size.
  let Some(max_cluster_size) = config.max_cluster_size else{
    return Err(CluEError::NoMaxClusterSize);
  };

  // Get number of data points per trace.
  let n_tot = config.number_timepoints.iter().sum::<usize>();
  
  // Initialize output.
  let mut order_n_signals = (0..max_cluster_size).map(|_| Signal::zeros(n_tot))
    .collect::<Vec::<Signal>>();

  
  // Generate coupling tensors.
  let tensors = HamiltonianTensors::generate(&structure, config)?;
  if let Some(save_dir) = &save_dir_opt{
    if let Some(info_dir) = &config.write_info{
      let info_path = format!("{}/{}",save_dir,info_dir);
      
      if let Some(tensor_save_name) = &config.write_tensors{
        if std::fs::create_dir_all(info_path.clone()).is_err(){
          return Err(CluEError::CannotCreateDir(info_path));
        }
        let tensor_path = format!("{}/{}.txt",info_path,tensor_save_name);

        tensors.save(&tensor_path,&structure)?;
      }
    }
  }


  // Determin orientation averaging method.
  let integration_grid = match &config.orientation_grid{
    Some(OrientationAveraging::Grid(grid)) => grid.clone(),
    Some(OrientationAveraging::Lebedev(n_ori)) 
      => IntegrationGrid::lebedev(*n_ori)?.remove_3d_hemisphere(),
    Some(OrientationAveraging::Random(n_ori)) 
      => IntegrationGrid::random_unit_sphere(*n_ori,rng),
    None => IntegrationGrid::z_3d(),
  };

  // Loop over orientation.
  for iori in 0..integration_grid.len(){
    
    let rot_dir = UnitSpherePoint::from(integration_grid.xyz(iori)?);
    
    let mut ori_sigs = calculate_signal_at_orientation(
        rot_dir,tensors.clone(), &structure,config, &save_dir_opt )?;

    let weight = Complex::<f64>{ re: integration_grid.weight(iori), im: 0.0};

    for size_idx in 0..max_cluster_size{
      ori_sigs[size_idx].scale(weight);
      order_n_signals[size_idx] 
        = &order_n_signals[size_idx] + &ori_sigs[size_idx];
    }

  }

  if let Some(save_dir) =  &save_dir_opt{
    let save_path = format!("{}/signal.csv", save_dir);
    let headers = (1..=max_cluster_size)
      .map(|ii| format!("signal_{}",ii))
      .collect::<Vec::<String>>();
    write_vec_signals(&order_n_signals, headers, &save_path)?;
  }
  Ok(order_n_signals)
}
//------------------------------------------------------------------------------
// This function calculates the signal for the input structure at the input
// orientation.
fn calculate_signal_at_orientation(rot_dir: UnitSpherePoint,
    mut tensors: HamiltonianTensors, structure: &Structure,
    config: &Config, path_opt: &Option<String>)
  -> Result<Vec::<Signal>,CluEError>
{
  
  let theta_degrees = rot_dir.theta()*180.0/PI;
  let phi_degrees = rot_dir.phi()*180.0/PI;
  println!(
      "\nMagnetic field orientation: θ = {} degrees; φ = {} degrees.", 
      theta_degrees, phi_degrees);
  // Determine if/where to save results.
  let save_dir_opt = match path_opt{
    Some(path) => {

      if let Some(ori_path) = &config.write_orientation_signals{ 
      
        let save_dir = format!("{}/{}/theta_{}deg_phi_{}deg",path, ori_path,
            theta_degrees, phi_degrees);
      
        match std::fs::create_dir_all(save_dir.clone()){
          Ok(_) => (),
          Err(_) => return Err(CluEError::CannotCreateDir(save_dir)),
        }

        Some(save_dir)
      }else{
        None
      }
    },
    None => None,
  };
  

  // Rotate the coupling tensor to the specified orientation.
  tensors.rotate_pasive(&rot_dir);


  // Determine maximum cluster size.
  let Some(max_cluster_size) = config.max_cluster_size else{
    return Err(CluEError::NoMaxClusterSize);
  };

  // Determine adjacencies.
  let adjacency_list = build_adjacency_list(&tensors, structure, config)?;

  // Find clusters.
  let mut cluster_set = if let Some(clusters_file) = &config.clusters_file{
    read_cluster_file(clusters_file, structure)?
  }else{
    find_clusters(&adjacency_list, max_cluster_size)?
  };
  // Remove partial methyls.
  let Some(do_remove_partial_methyls) = &config.remove_partial_methyls else{
    return Err(CluEError::NoRemovePartialMethyls);
  };
  if *do_remove_partial_methyls{
    cluster_set.remove_partial_methyls(structure)?;
  }

  for (size_idx,clusters_of_size) in cluster_set.clusters.iter().enumerate(){
    println!("Found {} clusters of size {}.",clusters_of_size.len(),size_idx+1);
  }

  if let Some(path) = &save_dir_opt{
    if let Some(cluster_file) = &config.write_clusters{
      let cluster_save_path = format!("{}/{}.txt",path,cluster_file);
      cluster_set.save(&cluster_save_path,structure)?;
    }
  }


  // Calculate cluster signals.
  let order_n_signals = match &config.cluster_method{
    Some(ClusterMethod::AnalyticRestricted2CCE) => 
      calculate_analytic_restricted_2cluster_signals(&mut cluster_set, &tensors,
          config,&save_dir_opt,structure)?,
    Some(_cce) => {
      let spin_multiplicity_set =
        math::unique(tensors.spin_multiplicities.clone());
      let spin_ops = ClusterSpinOperators::new(&spin_multiplicity_set,
          max_cluster_size)?;
      do_cluster_correlation_expansion(&mut cluster_set, &spin_ops, &tensors, 
          config,&save_dir_opt,structure)?
    },
    None => return Err(CluEError::NoClusterMethod)
  };


  if let Some(save_dir) =  &save_dir_opt{
    let save_path = format!("{}/signal.csv", save_dir);
    let headers = (1..=max_cluster_size)
      .map(|ii| format!("signal_{}",ii))
      .collect::<Vec::<String>>();
    write_vec_signals(&order_n_signals, headers, &save_path)?;

    if let Some(save_name) = &config.write_sans_spin_signals{
      let save_path = format!("{}/{}",save_dir,save_name);

      caculate_sans_spin_signals(&order_n_signals[max_cluster_size - 1],
        &cluster_set, structure, config, &save_path)?;
    }


    if let Some(save_name) = &config.write_methyl_partitions{
      let save_path = format!("{}/{}",save_dir,save_name);
      
      calculate_methyl_partition_cce(cluster_set, structure, config, 
          &save_path)?;
    }
  }

  Ok(order_n_signals)
} 
//------------------------------------------------------------------------------
// For each active spin in structure, this function calculates the signal,
// where the spin is dropped. 
fn caculate_sans_spin_signals(ref_signal: &Signal,
    cluster_set: &ClusterSet, structure: &Structure, config: &Config, 
    save_path: &str)
  -> Result<(),CluEError>
{
  
  let mut spin_signals 
    = caculate_bath_spin_contributions(cluster_set, structure, config)?;

  for sig in spin_signals.iter_mut(){
    *sig = ref_signal / sig;
  }

  let headers = structure.bath_particles.iter().enumerate()
    .filter_map(|(idx,particle)| 
        if particle.active{
          Some( format!("sans_{}",idx) )
        }else{
          None
        }
    ).collect::< Vec::<String> >();

  write_vec_signals(&spin_signals,headers,save_path)
}
//------------------------------------------------------------------------------
// For each active spin in structure, this function calculates the product of
// auxiliary signals for clusters that contain the spin.
// Note that since clusters contain multiple spins, the contributions from
// multiple spins are not independent of each other, 
// meaning that the product of contributions will not in general equal the 
// calculated signal.
fn caculate_bath_spin_contributions(
    cluster_set: &ClusterSet, structure: &Structure, config: &Config)
  -> Result<Vec::<Signal>,CluEError>
{

  // Get number of data points per trace.
  let n_tot = config.number_timepoints.iter().sum::<usize>();

  let mut spin_contributions = (0..structure.number_active())
    .map(|_| Signal::ones(n_tot)).collect::<Vec::<Signal>>();

  let mut index = 0;
  let vertex_to_index = structure.bath_particles.iter()
    .filter_map(|particle| 
        if particle.active{
          let idx = index;
          index += 1;
          Some(idx)
        }else{
          None
        }  
    ).collect::< Vec::<usize> >();

  for clusters_of_size in cluster_set.clusters.iter(){

    for cluster in clusters_of_size{

      for &vertex in cluster.vertices(){

        let idx = vertex_to_index[vertex-1];

        match &cluster.signal{
          Ok(Some(signal)) => 
            spin_contributions[idx] = &spin_contributions[idx] * signal,
          Ok(None) => (),
          Err(err) => return Err(err.clone()),
        }
      } 
    }

  }

  Ok(spin_contributions)
}
//------------------------------------------------------------------------------
// This function partition the auxiliary signals by which methyl groups
// contribute to them and saves the partitions to csv files.
fn calculate_methyl_partition_cce(
    cluster_set: ClusterSet, structure: &Structure, config: &Config, 
    save_path: &str)
  -> Result<(),CluEError>
{
  if let Some(exchange_group_manager) = &structure.exchange_groups{
    let cluster_partitions = partition_cluster_set_by_exchange_groups(
        cluster_set, exchange_group_manager, structure)?;

    let n_tot = config.number_timepoints.iter().sum::<usize>();

    for (key_name, value_cluster_set) in cluster_partitions.iter(){

      let mut part_signal = Signal::ones(n_tot);

      for size_idx in 0..(*value_cluster_set).len() {
        for cluster in value_cluster_set.clusters[size_idx].iter(){
          if let Ok(Some(aux_signal)) = &cluster.signal{
            part_signal = &part_signal * aux_signal;
          }
        }
      }

      let part_save_path = format!("{}/{}.csv",
          save_path,key_name);
      part_signal.write_to_csv(&part_save_path)?;
    }
  }

  //let signal = do_cluster_correlation_expansion_product(&cluster_set,config)?;
  Ok(())
}