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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use crate::clue_errors::*;
use crate::config::token::*;
use crate::config::token_expressions::*;
use substring::Substring;

//------------------------------------------------------------------------------
/// The function takes a `Vec::<Token>` and inserts a token at the
/// specified index.
pub fn add_token_at_index(add_this_token: Token, idx: usize, 
    tokens: Vec::<Token>, line_number: usize)
  -> Result<Vec::<Token>,CluEError>
{
  if idx > tokens.len(){
    return Err(CluEError::IndexOutOfBounds(line_number, idx,tokens.len() +1));
  }

  let mut out = Vec::<Token>::with_capacity(tokens.len() +1);
  
  for (ii,token) in tokens.iter().enumerate(){
    if ii == idx{
      out.push(add_this_token.clone());
    }
    out.push((*token).clone());
  }

  Ok(out)
}  
//------------------------------------------------------------------------------
/// This function unwraps TokenExpression right hand side or returns an
/// appropriate error message.
pub fn extract_rhs(expression: &TokenExpression)
  -> Result<Vec::<Token>,CluEError>
{

  let tokens: Vec::<Token>;
  if let Some(toks) = &expression.rhs{
    tokens = toks.clone();
  }else{
    return Err(CluEError::NoRHS(expression.line_number));
  }

  Ok(tokens)
}
//------------------------------------------------------------------------------
/// This function takes `Vec::<Token>`, splits apart on commas and places
/// each of the resulting `Vec::<Token>`s into a `Vec::<Vec::<Token>>`.
/// This function will return an `Err` if there are unmatched/out-of-order 
/// square brackets or multiple square bracket pairs.
pub fn get_vector_elements(tokens: Vec::<Token>, line_number: usize)
 -> Result<Vec::<Vec::<Token>>, CluEError>
{
  let indices = find_brackets(&tokens,line_number)?;


  let vector_elements: Vec::<Vec::<Token>>;

  if let Some((idx0,idx1)) = indices{
    vector_elements =  split_on_token(
      tokens[idx0+1..idx1].to_vec(), Token::Comma);
  }else{
    vector_elements = vec![tokens];
  }

  Ok(vector_elements)
}
//------------------------------------------------------------------------------
/// This function counts the number of delimiter pairs.  
/// It will err if the opening and closing delimiters to not have the same
/// count, but no type checking is done.
pub fn count_delimiter_pairs(tokens: &[Token], 
    opening_delimiter: &Token, closing_delimiter: &Token, 
    line_number: usize)
  -> Result<usize, CluEError>{
  
  let n_open = count_token(opening_delimiter, tokens);  
  let n_close = count_token(closing_delimiter, tokens);  
  

  if n_open != n_close
  {
    return Err(CluEError::UnmatchedDelimiter(line_number) ) 
  }

  Ok(n_open)
}

//------------------------------------------------------------------------------
/// This function finds the outermost pair of parentheses.
/// An `Ok` result containes `None` if there are no pairs or the indices of the 
/// pair as `Some((usize,usize))`.  Unmatched parentheses will lead to an `Err`. 
pub fn find_outermost_parentheses(tokens: &[Token], line_number: usize) 
  -> Result<Option<(usize,usize)>, CluEError>
{

  let n_pairs = count_delimiter_pairs(tokens,
      &Token::ParenthesisOpen, &Token::ParenthesisClose,
      line_number)?;
  
  if n_pairs == 0{
    return Ok(None);
  }

  let (depths, _max_depth) = get_delimiter_depths(tokens,line_number)?;

  let mut found_open_of_depth_1 = false; 
  let mut found_close_of_depth_1 = false; 
  let mut idx_open = 0;
  let mut idx_close = tokens.len() - 1;

  for (ii, depth) in depths.iter().enumerate(){
    if !found_open_of_depth_1{
      if *depth == 1{
        idx_open = ii;
        found_open_of_depth_1 = true;
      }
    } else if !found_close_of_depth_1 && *depth < 1{
      idx_close = ii;
      found_close_of_depth_1 = true;
    }  
  }

  if !found_open_of_depth_1 || !found_close_of_depth_1{
    return Err(CluEError::UnmatchedDelimiter(line_number) ) 
  }

  let are_matched = are_delimiters_paired(
      &tokens[idx_open], &tokens[idx_close],line_number)?;
  
  if !are_matched{
    return Err(CluEError::UnmatchedDelimiter(line_number) ) 
  }

  Ok( Some( (idx_open,idx_close) ) )
}
//------------------------------------------------------------------------------
/// This function finds the first pair of delimiters that do not contain
/// other delimiters.
pub fn find_deepest_parentheses(tokens: &[Token], line_number: usize) 
  -> Result<Option<(usize,usize)>, CluEError>{

  
  let n_pairs = count_delimiter_pairs(tokens,
      &Token::ParenthesisOpen, &Token::ParenthesisClose,
      line_number)?;
  
  if n_pairs == 0{
    return Ok(None);
  }


  let (depths, max_depth) = get_delimiter_depths(tokens,line_number)?;


  let mut found_open_of_max_depth = false; 
  let mut found_close_of_max_depth = false; 
  let mut idx_open = 0;
  let mut idx_close = tokens.len() - 1;

  for (ii, depth) in depths.iter().enumerate(){
    if !found_open_of_max_depth{
      if *depth == max_depth{
        idx_open = ii;
        found_open_of_max_depth = true;
      }
    } else if !found_close_of_max_depth && *depth < max_depth{
      idx_close = ii;
      found_close_of_max_depth = true;
    }  
  }

  if !found_open_of_max_depth || !found_close_of_max_depth{
    return Err(CluEError::UnmatchedDelimiter(line_number) ) 
  }

  let are_matched = are_delimiters_paired(
      &tokens[idx_open], &tokens[idx_close],line_number)?;
  
  if !are_matched{
    return Err(CluEError::UnmatchedDelimiter(line_number) ) 
  }

  Ok( Some( (idx_open,idx_close) ) )

}
//------------------------------------------------------------------------------
/// This function takes a `Vec::<Token>` and replaces each 
/// `Token::UserInputValue(String)` with a `Token::Float(f64)`.
/// The function will err if the conversion fails.
pub fn read_strings_as_floats(tokens: Vec::<Token>, line_number: usize)
-> Result<Vec::<Token>, CluEError>
{

  // Initialized output.
  let mut out = Vec::<Token>::with_capacity(tokens.len());

  for token in tokens.iter(){
    
    match token{
    
      Token::UserInputValue(val0) => {
    
        let mut val = val0.to_string();

        let push_time_ten_hat: bool;
        if val.len() >= 2 && val.substring( val.len()-1,val.len())=="e"{
          val = val.substring(0, val.len()-1).to_string();
          push_time_ten_hat = true;
        }else{
          push_time_ten_hat = false;
        }
        match val.parse(){
          Ok(x) => out.push(Token::Float(x)),
          Err(_) => return Err(CluEError::CannotConvertToFloat(
                line_number,val.to_string() )),
        }
        if push_time_ten_hat{
          out.push(Token::Times);
          out.push(Token::Float(10.0));
          out.push(Token::Hat);
        }
      }, 
    
      _ => out.push((*token).clone() )
    }
  }

  Ok(out)
  
}
//------------------------------------------------------------------------------
/// This function takes a `Vec::<Token>` and replaces each 
/// `Token::UserInputValue(String)` with a `Token::Int(i32)`.
/// The function will err if the conversion fails.
pub fn read_strings_as_integers(tokens: Vec::<Token>, line_number: usize)
-> Result<Vec::<Token>, CluEError>
{

  // Initialized output.
  let mut out = Vec::<Token>::with_capacity(tokens.len());

  for token in tokens.iter(){
    
    match token{
    
      Token::UserInputValue(val0) => {
        let mut val = val0.to_string();

        let push_time_ten_hat: bool;
        if val.len() >= 2 && val.substring( val.len()-1,val.len())=="e"{
          val = val.substring(0, val.len()-1).to_string();
          push_time_ten_hat = true;
        }else{
          push_time_ten_hat = false;
        }
    
        match val.parse(){
          Ok(a) => out.push(Token::Int(a)),
          Err(_) => return Err(CluEError::CannotConvertToFloat(
                line_number,val.to_string() )),
        }
        if push_time_ten_hat{
          out.push(Token::Times);
          out.push(Token::Int(10));
          out.push(Token::Hat);
        }
      }, 
    
      _ => out.push((*token).clone() )
    }
  }

  Ok(out)
  
}
//------------------------------------------------------------------------------
/// This function takes a vector of tokens and return a vector of vector of
/// tokens, split on the specified token.  
/// The specified token in removed from the output.
pub fn split_on_token(tokens: Vec::<Token>, split_on: Token) 
 -> Vec::<Vec::<Token>>
{
    // Count statements.
    let mut num_statements = count_token(&split_on,&tokens);
    if tokens[tokens.len()-1] != split_on{
      num_statements += 1;
    }

    // Get Statements.
    let mut statements = Vec::<Vec::<Token>>::with_capacity(num_statements);

    let mut read_from = 0;
    for _istatement in 0..num_statements{
    
      // Count tokens in statement.
      let mut num_tokens_in_statement = 0;
      
      let mut read_to = tokens.len();
      for (ii,token) in tokens.iter().enumerate().skip(read_from){
        if *token == split_on { 
          read_to = ii;
          break;
        }
        num_tokens_in_statement += 1;
      }


      // Get statement.
      let mut statement = Vec::<Token>::with_capacity(num_tokens_in_statement);

      for token in tokens.iter().take(read_to).skip(read_from){
        statement.push(token.clone());
      }

      read_from = read_to + 1;
      statements.push(statement);
    } 

    statements
}
//------------------------------------------------------------------------------


//------------------------------------------------------------------------------
// This function compares two tokens and checks that they form are an
// opening delimier and closing delimiter of the same kind,
// such as ( and ), [ and ], or { and }, 
// but not { and ] or ) and ).
fn are_delimiters_paired(open: &Token, close: &Token, line_number: usize) 
 -> Result<bool,CluEError>{

  // Ckeck if token is (, [, or {.
  if !is_opening_delimiter(open){
    return Err(CluEError::InvalidToken(line_number, open.to_string()));
  }

  // Ckeck if token is ), ], or }.
  if !is_closing_delimiter(close){
    return Err(CluEError::InvalidToken(line_number, close.to_string()));
  } 

  if (*open == Token::ParenthesisOpen && *close == Token::ParenthesisClose)  
    || (*open == Token::SquareBracketOpen 
        && *close == Token::SquareBracketClose)
    || (*open == Token::CurlyBracketOpen && *close == Token::CurlyBracketClose){
      return Ok(true);
    }
  Ok(false)
}
 
//------------------------------------------------------------------------------
/// The functions take a token slice and return the index of the first "[" 
/// and the following  "]".  The finction will err if there are nested brackets.
/// This function will return an `Err` if there are unmatched/out-of-order 
/// square brackets or multiple square bracket pairs.
pub fn find_brackets(tokens: &[Token], line_number: usize) 
 -> Result<Option<(usize,usize)>, CluEError>
{
  // Find brackets.

  let n_pairs = count_delimiter_pairs(tokens, 
      &Token::SquareBracketOpen, &Token::SquareBracketClose,
      line_number)?;
  
  if n_pairs > 1{
    return Err(CluEError::CannotConvertToVector(line_number));
  }

  if n_pairs == 0{
    return Ok(None); 
  }


  let index0 = find_token(&Token::SquareBracketOpen, tokens);
  let index0 = index0[0];

  let index1 = find_token(&Token::SquareBracketClose, tokens);
  let index1 = index1[0];


  if index0 + 1 >= index1{
    return Err(CluEError::CannotConvertToFloat(
          line_number,"[]".to_string()) );
  }
 
  Ok(Some( (index0,index1) ))
}
//------------------------------------------------------------------------------
// This function assigns a delimiter depth to each token.
// For example, let t be an unspecified token, then the depths of
// t t ( t t ( t ) t ( ) t ) t are
// 0 0 1 1 1 2 2 1 1 2 2 1 0 0.
// The function will err if the dept is ever negative.
fn get_delimiter_depths(tokens: &[Token], line_number: usize)
  -> Result<(Vec::<i32>, i32), CluEError>{

  let mut depths = Vec::<i32>::with_capacity(tokens.len()); 
  let mut depth: i32 = 0; 
  let mut max_depth: i32 = 0;

  for token in tokens.iter(){
    if is_opening_delimiter(token){
      depth += 1;
    } else if is_closing_delimiter(token){
      depth -= 1;
    }
     
    if depth < 0{
      return Err(CluEError::UnmatchedDelimiter(line_number) ) 
    }

    max_depth = std::cmp::max(max_depth, depth);

    depths.push(depth);
  }

  if depth != 0{
    return Err(CluEError::UnmatchedDelimiter(line_number) ) 
  }

  Ok((depths, max_depth))
} 
//------------------------------------------------------------------------------




//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#[cfg(test)]
mod tests{
  use super::*;
  
  #[test]
  fn test_read_strings_as_floats(){
    let tokens = vec![Token::SquareBracketOpen, 
        Token::UserInputValue("1".to_string()),Token::Comma, 
        Token::UserInputValue("-1".to_string()),
      Token::SquareBracketClose];

    let result = read_strings_as_floats(tokens,0).unwrap();
    assert_eq!(result, vec![Token::SquareBracketOpen, 
        Token::Float(1.0),Token::Comma, Token::Float(-1.0),
        Token::SquareBracketClose]
        );
  }
  //----------------------------------------------------------------------------
  #[test]
  fn test_read_strings_as_integers(){
    let tokens = vec![Token::SquareBracketOpen, 
        Token::UserInputValue("1".to_string()),Token::Comma, 
        Token::UserInputValue("-1".to_string()),
      Token::SquareBracketClose];

    let result = read_strings_as_integers(tokens,0).unwrap();
    assert_eq!(result, vec![Token::SquareBracketOpen, 
        Token::Int(1),Token::Comma, Token::Int(-1),
        Token::SquareBracketClose]
        );
  }
  
  //----------------------------------------------------------------------------
  #[test]
  fn test_split_on_token(){
  
    let tokens = vec![
      Token::SquareBracketOpen,
        Token::UserInputValue("SOL".to_string()), Token::Comma, 
        Token::UserInputValue("WAT".to_string()), Token::Comma, 
        Token::UserInputValue("GLY".to_string()) ,
      Token::SquareBracketClose];

    let result = split_on_token(tokens,Token::Comma);


    assert_eq!(result, vec![
      vec![Token::SquareBracketOpen, Token::UserInputValue("SOL".to_string())],
      vec![Token::UserInputValue("WAT".to_string())],
      vec![Token::UserInputValue("GLY".to_string()),Token::SquareBracketClose]  
    ]);

    let tokens = vec![
        Token::Float(2.0), Token::Comma, Token::Float(-2.0) 
    ];

    let result = split_on_token(tokens,Token::Comma);

    assert_eq!(result, vec![
        vec![Token::Float(2.0)],
        vec![Token::Float(-2.0)]  ]);

  }
  
  //----------------------------------------------------------------------------
  #[test]
  fn test_find_deepest_parentheses(){
    
    let tokens = vec![Token::ParenthesisClose, Token::ParenthesisOpen];
    let result = find_deepest_parentheses(&tokens,0);
    assert_eq!(result,Err(CluEError::UnmatchedDelimiter(0)));

    let tokens = vec![Token::ParenthesisOpen, Token::SquareBracketClose];
    let result = find_deepest_parentheses(&tokens,0);
    assert_eq!(result,Err(CluEError::UnmatchedDelimiter(0)));

    let tokens = vec![Token::Comma, Token::Equals];
    let option = find_deepest_parentheses(&tokens,0).unwrap();
    assert_eq!(option,None);

    let tokens = vec![Token::ParenthesisOpen, Token::ParenthesisClose];
    let (idx_open, idx_close) = find_deepest_parentheses(&tokens,0)
      .unwrap().unwrap();
    assert_eq!(idx_open,0);
    assert_eq!(idx_close,1);

    let tokens = vec![
      Token::ParenthesisOpen,
        Token::ParenthesisOpen,
          Token::Minus,Token::Float(2.0), 
        Token::ParenthesisClose, Token::Hat, Token::Float(2.0),
        Token::Plus, Token::Float(3.0), 
      Token::ParenthesisClose,
      Token::Times, Token::Float(12.0),
      Token::Slash, Token::Float(7.0), Token::Minus, 
      Token::ParenthesisOpen,
        Token::Float(-2.0), Token::Plus, Token::Float(-2.0),
      Token::ParenthesisClose,
    ];
    
    let option = find_deepest_parentheses(&tokens,0).unwrap();
    assert_eq!(option,Some((1,4)));
  }
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>