File: Path.pm

package info (click to toggle)
libdemeter-perl 0.9.27%2Bds6-9
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 74,028 kB
  • sloc: perl: 73,233; python: 2,196; makefile: 1,999; ansic: 1,368; lisp: 454; sh: 74
file content (1193 lines) | stat: -rw-r--r-- 37,418 bytes parent folder | download
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
package Demeter::Path;

=for Copyright
 .
 Copyright (c) 2006-2019 Bruce Ravel (L<http://bruceravel.github.io/home>).
 All rights reserved.
 .
 This file is free software; you can redistribute it and/or
 modify it under the same terms as Perl itself. See The Perl
 Artistic License.
 .
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

=cut

use autodie qw(open close);

use Moose;
use MooseX::Aliases;
extends 'Demeter';
use Demeter::StrTypes qw( Empty PathParam FileName ElementSymbol );
use Demeter::NumTypes qw( Natural PosInt NonNeg );

with 'Demeter::Data::Arrays';
with 'Demeter::Data::IO';
with 'Demeter::Data::XDI';
with 'Demeter::Path::Process';
with 'Demeter::Path::Sanity';
with 'Demeter::UI::Screen::Pause' if ($Demeter::mode->ui eq 'screen');

use Carp;
use File::Copy;
use File::Spec;
use List::Util qw(max);
use Regexp::Assemble;
use Scalar::Util qw(looks_like_number);
use Xray::BondValence qw(bvparams);

has '+plottable'      => (default => 1);
has '+pathtype'       => (default => 1);
has '+data'           => (isa => Empty.'|Demeter::Data');
has 'label'	      => (is=>'rw', isa=>'Str',    default => q{});

has 'n'		      => (is=>'rw', isa=>'LaxNum', default =>  0);

has 's02'	      => (is=>'rw', isa=>'Str',    default => '1'); # trigger value into _stored
has 's02_stored'      => (is=>'rw', isa=>'Str',    default => '1');
has 's02_value'	      => (is=>'rw', isa=>'LaxNum', default =>  1);
has 's02_stderr'      => (is=>'rw', isa=>'LaxNum', default =>  1);

has 'e0'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'e0_stored'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'e0_value'	      => (is=>'rw', isa=>'LaxNum', default =>  0);
has 'e0_stderr'	      => (is=>'rw', isa=>'LaxNum', default =>  0);

has 'delr'	      => (is=>'rw', isa=>'Str',    default => '0', alias => 'deltar');
has 'delr_stored'     => (is=>'rw', isa=>'Str',    default => '0', alias => 'deltar_stored');
has 'delr_value'      => (is=>'rw', isa=>'LaxNum', default =>  0,  alias => 'deltar_value' );
has 'delr_stderr'     => (is=>'rw', isa=>'LaxNum', default =>  0,  alias => 'deltar_stderr');

has 'sigma2'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'sigma2_stored'   => (is=>'rw', isa=>'Str',    default => '0');
has 'sigma2_value'    => (is=>'rw', isa=>'LaxNum', default =>  0);
has 'sigma2_stderr'   => (is=>'rw', isa=>'LaxNum', default =>  0);

has 'ei'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'ei_stored'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'ei_value'	      => (is=>'rw', isa=>'LaxNum', default =>  0);
has 'ei_stderr'	      => (is=>'rw', isa=>'LaxNum', default =>  0);

has 'third'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'third_stored'    => (is=>'rw', isa=>'Str',    default => '0');
has 'third_value'     => (is=>'rw', isa=>'LaxNum', default =>  0);
has 'third_stderr'    => (is=>'rw', isa=>'LaxNum', default =>  0);

has 'fourth'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'fourth_stored'   => (is=>'rw', isa=>'Str',    default => '0');
has 'fourth_value'    => (is=>'rw', isa=>'LaxNum', default =>  0);
has 'fourth_stderr'   => (is=>'rw', isa=>'LaxNum', default =>  0);

has 'dphase'	      => (is=>'rw', isa=>'Str',    default => '0');
has 'dphase_stored'   => (is=>'rw', isa=>'Str',    default => '0');
has 'dphase_value'    => (is=>'rw', isa=>'LaxNum', default =>  0);
has 'dphase_stderr'   => (is=>'rw', isa=>'LaxNum', default =>  0);

has 'id'	      => (is=>'rw', isa=>'Str',    default => q{});
has 'k_array'	      => (is=>'rw', isa=>'Str',    default => q{});
has 'amp_array'	      => (is=>'rw', isa=>'Str',    default => q{});
has 'phase_array'     => (is=>'rw', isa=>'Str',    default => q{});

has 'save_mag'        => (is=>'rw', isa=>'Bool',   default => 0);

## these four provide a generic way of storing cumulant information
## about a Path or Path-like object.  this is used, for instance, in
## Demeter::Feff::Distributions to store the cumulants computed from
## the SS distribution in an FPath object created from a histogram
has 'c1'              => (is=>'rw', isa=>'LaxNum', default =>  0, documentation => "the computed first cumulant");
has 'c2'              => (is=>'rw', isa=>'LaxNum', default =>  0, documentation => "the computed second cumulant");
has 'c3'              => (is=>'rw', isa=>'LaxNum', default =>  0, documentation => "the computed third cumulant");
has 'c4'              => (is=>'rw', isa=>'LaxNum', default =>  0, documentation => "the computed fourth cumulant");


## object relationships
has 'parentgroup'     => (is=>'rw', isa => 'Str', default => q{});
has 'parent'          => (is=>'rw', isa => 'Any', default => q{},  # Empty.'|Demeter::Feff'
			  trigger => \&set_parent,
			  alias   => 'feff');
has 'spgroup'         => (is=>'rw', isa => 'Str', default => q{});
has 'sp'              => (is=>'rw', isa => 'Any',                  # Empty.'|Demeter::ScatteringPath|Demeter::SSPath'
			  trigger => sub{ my($self, $new) = @_; 
					  if ($new) {
					    $self->zcwif($new->zcwif);
					    $self->spgroup($new->group);
					    $self->parent($new->feff) if not $self->parent;
					    $self->bvscat($new->scatterer);
					    $self->set_scatterer_valence;
					    $self->make_name if not $self->name;
					  };
					});
has 'datagroup'       => (is=>'rw', isa => 'Str', default => q{});



has 'folder'          => (is=>'rw', isa=> 'Str',    default => q{},
			  trigger => sub{ shift->parse_nnnn });
has 'file'            => (is=>'rw', isa=> FileName, default => q{},
			  trigger => sub{ shift->parse_nnnn });
has 'Index'           => (is=>'rw', isa=>  Natural, default => 0);
has 'include'         => (is=>'rw', isa=>  'Bool',  default => 1);

has 'is_col'          => (is=>'rw', isa=>  'Bool',  default => 0);
has 'is_ss'           => (is=>'rw', isa=>  'Bool',  default => 1);
has 'plot_after_fit'  => (is=>'rw', isa=>  'Bool',  default => 0);
has 'default_path'    => (is=>'rw', isa=>  'Bool',  default => 0);
has 'pc'              => (is=>'rw', isa=>  'Bool',  default => 0);

## feff interpretation parameters
has 'degen'           => (is=>'rw', isa=>  NonNeg,  default => 0);
has 'nleg'            => (is=>'rw', isa=>  PosInt,  default => 2);
has 'reff'            => (is=>'rw', isa=> 'LaxNum', default => 0);
has 'zcwif'           => (is=>'rw', isa=> 'LaxNum', default => 0, alias => 'population');
has 'intrpline'       => (is=>'rw', isa=> 'Str',    default => q{});
has 'geometry'        => (is=>'rw', isa=> 'Str',    default => q{});

## data processing flags
has 'update_path'     => (is=>'rw', isa=>  'Bool',  default => 1,
			  trigger => sub{ my($self, $new) = @_; $self->update_fft(1) if $new});
has 'update_fft'      => (is=>'rw', isa=>  'Bool',  default => 1,
			  trigger => sub{ my($self, $new) = @_; $self->update_bft(1) if $new});
has 'update_bft'      => (is=>'rw', isa=>  'Bool',  default => 1);

## for computing bond valence sums
has 'bvabs'        => (is=>'rw', isa =>  ElementSymbol, default => 'He', coerce => 1);
has 'valence_abs'  => (is=>'rw', isa=>  'Int',  default =>  2);
has 'bvscat'       => (is=>'rw', isa =>  ElementSymbol, default => 'He', coerce => 1);
has 'valence_scat' => (is=>'rw', isa=>  'Int',  default => -2);

my $pp_regex = Regexp::Assemble->new()->add(qw(s02 e0 delr e0 sigma2 ei third fourth dphase))->re;

sub BUILD {
  my ($self, @arguments) = @_;
  my $val = $self->get_mode("datadefault");
  if ((ref($self->data) !~ m{Data}) and (ref($val) !~ m{Data})) {
    $self->mo->datadefault(Demeter::Data->new(group=>'default___',
					      name=>'default___',
					      fft_kmin=>3, fft_kmax=>15,
					      bft_rmin=>1, bft_rmax=>6,
					     ));
  };
  $self->data($self->mo->datadefault) if (ref($self->data) !~ m{Data});
  $self->mo->push_Path($self) if (ref($self) eq "Demeter::Path"); # don't do this for SSPath objects
  my $i = $self->mo->pathindex;
  $self->Index($i);
  $self->mo->pathindex(++$i);
};
#sub DEMOLISH {
#  my ($self) = @_;
#  $self->alldone;
#};

override all => sub {
  my ($self) = @_;
  my %all = $self->SUPER::all;
  delete $all{$_} foreach (qw(Index sp parent sentinal));
  return %all;
};

override Clone => sub {
  my ($self, @arguments) = @_;
  my $new = $self->SUPER::Clone();
  $new->parent($self->parent);
  $new->data($self->data);
  $new->sp($self->sp);

  $new->set(@arguments);
  return $new;
};

sub set_parent {
  my ($self, $feff) = @_;
  $self->set_parent_method($feff);
};
sub set_parent_method {
  my ($self, $feff) = @_;
  if ($feff) {
    $self->parentgroup($feff->group);
    $self->bvabs($feff->abs_species);
  };
};

### ---- this will be different working from a ScatteringPath object
###      snarfing from the object will have to be part of an update
sub _update {
  my ($self, $which) = @_;
  $which = lc($which);
 WHICH: {
    ($which eq 'path') and do {
      $self->path(1) if $self->update_path;
      last WHICH;
    };
    ($which eq 'fft') and do {
      $self->path(1) if ($self->update_path);
      last WHICH;
    };
    ($which eq 'bft') and do {
      $self->path(1) if ($self->update_path);
      $self->fft     if ($self->update_fft);  #<--- kweight may have changed, just redo this
      last WHICH;
    };
    ($which eq 'all') and do {
      $self->path(1) if ($self->update_path);
      $self->fft     if ($self->update_fft);
      $self->bft     if ($self->update_bft);
      last WHICH;
    };
  };
  #$self->ifeffit_heap;
  return $self;
};

sub rm {
  my ($self) = @_;
  unlink File::Spec->catfile($self->get(qw(folder file)));
  return $self;
};

#sub read_data {
#  my ($self) = @_;
#  my $string = $self->read_data('feff.dat');
#  return $string;
#};


## need a make_name for a path that does not come from ScatteringPath
sub make_name {
  my ($self) = @_;
  my $sp = $self->sp;
  my $pattern = $self->co->default("pathfinder", "label");
  my $token = $self->co->default("pathfinder", "token");
  my $noends = $sp->intrplist;
  my $re = qr(\Q$token\E);	# \Q...\E quotes the metacharacters, see perlre
  $noends =~ s{\A$re}{};
  $noends =~ s{$re.*\z}{};
  my %table = (i   => $self->sp->pathfinder_index,
	       I   => sprintf("%4.4d", $self->sp->pathfinder_index),
	       p   => $sp->intrplist,
	       P   => $noends,
	       r   => sprintf("%.3f", $sp->fuzzy),
	       n   => $sp->nleg,
	       d   => $sp->n,
	       t   => $sp->Type,
	       m   => $sp->weight,
	       g   => $sp->group,
	       f   => $sp->feff->name,
	       a   => $sp->angleout,
	       A   => $sp->anglein,
	       '%' => '%',
	      );
  #Demeter->Dump(\%table);
  my $regex = '[' . join('', keys(%table)) . ']';

  $pattern =~ s{\%($regex)}{$table{$1}}g;
  $pattern =~ s{\s+}{ }g;
  $pattern =~ s{\A\s+}{ }g;
  $pattern =~ s{\s+\z}{ }g;
  $self->label($pattern);

  $pattern = $self->co->default("pathfinder", "name");
  $pattern =~ s{\%($regex)}{$table{$1}}g;
  $pattern =~ s{\s+}{ }g;
  $self->name($pattern);
  return $self;
};



## how to handle extended path parameters?
## $index, $folder, $stash_dir all need to be known to the object
sub path {
  my ($self, $do_ff2chi) = @_;
  $self->_update_from_ScatteringPath if $self->sp;

  my $this_command = $self->_path_command($do_ff2chi);
  $this_command =~ s{(?<!sigma2_)(debye|eins)\(}{sigma2_$1\(}g if (Demeter->is_larch);
  $this_command =~ s{sigma2_(debye|eins)\(}{$1\(}g if (Demeter->is_ifeffit);

  $self->dispose($this_command);
  $self->update_path(0);
  return $self;
};
sub _update_from_ScatteringPath {
  my ($self) = @_;
  #print $/, join("|", ">>>>", $self->data->name, $self->reff, $self->sp->fuzzy), $/;
  ## generate from a ScatteringPath object
  my $sp     = $self->sp;
  my $feff   = $self->parent;
  my ($workspace, $fname) = ($feff->workspace, $sp->randstring);

  ## this feffNNNN.dat has already been generated
  if ($fname and (-e File::Spec->catfile($workspace, $fname))) {
    #print File::Spec->catfile($workspace, $fname), $/;
    #print join("|", "||||", $self->data->name, $self->reff, $self->sp->fuzzy), $/, $/;
    $self->set(folder => $workspace,
	       file   => $fname);
    return $self;
  };

  $feff -> make_one_path($sp)
    -> make_feffinp("genfmt")
      -> run_feff;
  $self -> make_name if not $self->name;

  my $tempfile = "feff" . $self->co->default('pathfinder', 'one_off_index') . ".dat";
  $fname ||= $sp->randstring;
  move(File::Spec->catfile($workspace, $tempfile),
       File::Spec->catfile($workspace, $fname));
  $self->set(folder => $workspace,
	     file   => $fname);
  $self->sp->set(folder => $workspace,
		 file   => $fname);
  ##print "++", File::Spec->catfile($workspace, $fname), $/;
  my $label = $self -> name || $sp->intrplist;
  $self->set(name=>$label);
  #print join("|", "<<<<", $self->data->name, $self->reff, $self->sp->fuzzy), $/, $/;

  #unlink File::Spec->catfile($feff->workspace, "paths.dat");
  unlink File::Spec->catfile($feff->workspace, "feff.run");
  #unlink File::Spec->catfile($feff->workspace, "nstar.dat");
  if (not $feff->save) {
    #unlink File::Spec->catfile($feff->workspace, "feff.inp");
    #unlink File::Spec->catfile($feff->workspace, "files.dat");
  };
  return $self;
};
sub _path_command {
  my ($self, $do_ff2chi) = @_;
  ## fret about long file names
  my $string = $self->template("fit", "path");
  $string   .= $self->template("fit", "ff2chi", {do_mag=>$self->save_mag}) if $do_ff2chi;
  return $string;
};
sub rewrite_cv {
  my ($self) = @_;
  my $data   = $self->data;
  my $cv     = $data->cv;
  #$cv       =~ s{\.}{_}g;
  foreach my $pp (qw(e0 ei sigma2 s02 delr third fourth dphase)) {
    my $me = $self->$pp;
    $me =~ s{\[?cv\]?}{$cv}g;
    $self->$pp($me);
  };
  foreach my $pp (qw(name label)) {
    my $this = $self->$pp;
    $this =~ s{\[cv\]}{$cv}g;
    $self->$pp($this);
  };
};

sub plot {
  my ($self, $space) = @_;
  $space ||= $self->po->space;
  my $which = q{update_path};
  if (lc($space) =~ m{\Ak}) {
    $self -> _update("fft");
    $which = "update_path";
  } elsif (lc($space) =~ m{\Ar}) {
    $self -> _update("bft");
    $which = "update_fft";
  } elsif (lc($space) eq 'q') {
    $self -> _update("all");
    $which = "update_bft";
  };
  $self->mo->path($self);
  $self->dispose($self->_plot_command($space), "plotting");
  $self->po->after_plot_hook($self);
  $self->mo->path(q{});
  $self->po->increment;
  $self->$which(0);
};

sub save {
  my ($self, $what, $filename) = @_;
  croak("No filename specified for save") unless $filename;
  ($what = 'chi') if (lc($what) eq 'k');
  croak("Valid save types are: chi r q") if ($what !~ m{\A(?:chi|r|q)\z});
 WHAT: {
    (lc($what) eq 'chi') and do {
      $self->_update("path");
      $self->data->_update('bft'); # need window from data object
      $self->dispose($self->_save_chi_command('k', $filename));
      last WHAT;
    };
    (lc($what) eq 'r') and do {
      $self->_update("bft");
      $self->data->_update('all');
      $self->dispose($self->_save_chi_command('r', $filename));
      last WHAT;
    };
    (lc($what) eq 'q') and do {
      $self->_update("all");
      $self->data->_update('bft');
      $self->dispose($self->_save_chi_command('q', $filename));
      last WHAT;
    };
  };
};


sub parse_nnnn {
  my ($self) = @_;
  my $oneoff = "feff" . $self->co->default('pathfinder', 'one_off_index');
  my ($folder, $file) = $self->get(qw(folder file));
  my $fname = $self->follow_link(File::Spec -> catfile($folder, $file));
  return if not -f $fname;

  open (my $NNNN, $fname);
  my ($header, $geometry) = (0, q{});
  while (<$NNNN>) {
    if (m{\A\s*-------}) {
      $header = 1;
      next;
    };
    next if not $header;
    last if m{\A\s+k\s+real};
    $geometry .= $_;
  };
  close $NNNN;
  $self->set(geometry=>$geometry);

  my @list = split(" ", $geometry);
  my $n_set = $self->n;
  $self->set(degen => int($list[1]),
	     n     => $n_set || $list[1],
	     nleg  => $list[0],
	     reff  => $list[2]
	    );
  return 0 if $self->sp;

  $fname = File::Spec -> catfile($folder, 'files.dat');
  if (-e $fname) {
    open (my $FILESDAT, $fname);
    while (<$FILESDAT>) {
      next if ($_ !~ /(?:$file|$oneoff)/); # $oneoff is matched when working from a ScatteringPath object
      @list = split(" ", $_);
      $n_set = $self->n;
      $self->zcwif($list[2]) if (not $self->sp);   # zcwif is imported from the feffNNNN.dat only when
      $self->set(degen => int($list[3]),	   # the sp attribute is not set, otherwise zcwif is inherited
		 n     => $n_set || int($list[3]), # from the ScatteringPath object
		 nleg  => $list[4],
		 reff  => $list[5]
		);
    };
    close $FILESDAT;
  };
  return 0;
};


my @path_text = ();
my %_pp_trans = ('3rd'=>"third", '4th'=>"fourth", dphase=>"dphase",
		 dr=>"delr", e0=>"e0", ei=>"ei", s02=>"s02", ss2=>"sigma2");
sub fetch {
  my ($self) = @_;

  if (Demeter->is_ifeffit) {
    @path_text = ();
    my @save = ($self->toggle_echo(0),
		$self->get_mode("feedback"));

    $self->set_mode(feedback=>sub{push @path_text, $_[0]}); # set feedback coderef
    $self->dispense("fit", "show_path");
    $self->toggle_echo($save[0]);	# reset everything
    $self->set_mode(feedback=>$save[1]);

    my $found = 0;
    foreach my $l (@path_text) {
      ($found = 1), next if ($l =~ m{\A\s*PATH}x);
      next if not $found;
      chomp $l;
      my @line = split(/\s+=\s*/, $l);
    SWITCH: {

	($line[0] eq 'id') and do {
	  $self -> set(id=>$line[1]);
	  last SWITCH;
	};

	($line[0] =~ m{(?:3rd|4th|d(?:phase|r)|e[0i]|s[0s]2)}) and do {
	  $self -> evaluate($_pp_trans{$line[0]}, $line[1]);
	  last SWITCH;
	}

      };
    };

  } elsif (Demeter->is_larch) {
    $self -> id($self->fetch_string(join('.', $self->group, 'label')));

    $self -> s02_value ($self->fetch_scalar(join('.', $self->group, 's02', 'value' )));
    $self -> s02_stderr($self->fetch_scalar(join('.', $self->group, 's02', 'stderr')));

    $self -> e0_value ($self->fetch_scalar(join('.', $self->group, 'e0', 'value' )));
    $self -> e0_stderr($self->fetch_scalar(join('.', $self->group, 'e0', 'stderr')));

    $self -> delr_value ($self->fetch_scalar(join('.', $self->group, 'deltar', 'value' )));
    $self -> delr_stderr($self->fetch_scalar(join('.', $self->group, 'deltar', 'stderr')));

    $self -> sigma2_value ($self->fetch_scalar(join('.', $self->group, 'sigma2', 'value' )));
    $self -> sigma2_stderr($self->fetch_scalar(join('.', $self->group, 'sigma2', 'stderr')));

    $self -> ei_value ($self->fetch_scalar(join('.', $self->group, 'ei', 'value' )));
    $self -> ei_stderr($self->fetch_scalar(join('.', $self->group, 'ei', 'stderr')));

    $self -> third_value ($self->fetch_scalar(join('.', $self->group, 'third', 'value' )));
    $self -> third_stderr($self->fetch_scalar(join('.', $self->group, 'third', 'stderr')));

    $self -> fourth_value ($self->fetch_scalar(join('.', $self->group, 'fourth', 'value' )));
    $self -> fourth_stderr($self->fetch_scalar(join('.', $self->group, 'fourth', 'stderr')));

  };
  return 0;
};

## path parameter tools
sub evaluate {
  my ($self, $key, $value) = @_;
  my $param = $key."_value";
  if (not looks_like_number($value)) {
    $value = ($key eq 's02') ? 1 : 0;
  };
  $self->$param($value);
  return 0;
};
sub value {
  my ($self, $pathparam) = @_;
  return 0 if (not is_PathParam($pathparam));
  my $key = $pathparam."_value";
  return $self->$key
};

sub identity {
  my ($self) = @_;
  return sprintf("%s", $self->name);
  ##return sprintf("%s : %s", $self->parent->name, $self->name);
};


sub bv {
  my ($self, $s02) = @_;
  $s02 ||= 1;
  my %hash = bvparams($self->bvabs, $self->valence_abs, $self->bvscat);
  return 0 if not (exists $hash{r0} and exists $hash{b});
  return ($self->n * $self->s02_value / $s02) * exp( ($hash{r0} - $self->R) / $hash{b} );
};
sub set_scatterer_valence {
  my ($self) = @_;
  my $scat = ucfirst(lc($self->bvscat));
  my $val = ($scat eq 'As') ? -3
          : ($scat eq 'B' ) ?  3
          : ($scat eq 'Br') ? -1
          : ($scat eq 'C' ) ? -4
          : ($scat eq 'Cl') ? -1
          : ($scat eq 'Co') ? -1
          : ($scat eq 'F' ) ? -1
          : ($scat eq 'Cl') ? -1
          : ($scat eq 'H' ) ? -1
          : ($scat eq 'Hg') ?  2
          : ($scat eq 'I' ) ? -1
          : ($scat eq 'Mn') ? -2
          : ($scat eq 'N')  ? -3
          : ($scat eq 'O')  ? -2
          : ($scat eq 'P')  ? -3
          : ($scat eq 'S')  ? -2
          : ($scat eq 'Se') ? -2
          : ($scat eq 'Te') ? -2
	  :                   -2;
  $self->valence_scat($val);
};

## log file tools

sub R {
  my ($self) = @_;
  return $self->reff + $self->delr_value;
};
sub longest_leg {
  my ($self) = @_;
  return max(@{ $self -> sp -> rleg });
};
sub paragraph {
  my ($self) = @_;
  my $string = sprintf("    feff   = %s\n",     File::Spec->catfile($self->get(qw(folder file))));
  $string   .= sprintf("    id     = %s\n",     $self->id);
  $string   .= sprintf("    name   = %s\n",     $self->name);
  $string   .= sprintf("    r      = %12.6f\n", $self->R);
  $string   .= sprintf("    degen  = %12.6f\n", $self->n);
  foreach my $pp (qw(s02 e0 delr sigma2 third fourth ei)) {
    $string .= sprintf("    %-6s = %12.6f\n",   $pp, $self->value($pp)||0);
  };
  return $string;
};
sub row_main_label {
  my ($self, $width) = @_;
  $width ||= 15;
  return $self->template("report", "log_firstrow_label",  {width=>$width});
};
sub row_main {
  my ($self, $width) = @_;
  $width ||= 15;
  return $self->template("report", "log_firstrow",        {width=>$width});
}

sub row_second_label {
  my ($self, $width) = @_;
  $width ||= 15;
  return $self->template("report", "log_secondrow_label", {width=>$width});
};
sub row_second {
  my ($self, $width) = @_;
  $width ||= 15;
  return $self->template("report", "log_secondrow",        {width=>$width});
};

__PACKAGE__->meta->make_immutable;
1;


=head1 NAME

Demeter - Single and multiple scattering paths for EXAFS fitting


=head1 VERSION

This documentation refers to Demeter version 0.9.26.


=head1 SYNOPSIS

  $path_object -> new();
  $path_object -> set(data     => $dobject,
		      folder   => 'example/cu/',
		      file     => "feff0001.dat",
		      name     => "path 1",
		      s02      => 'amp',
		      e0       => 'enot',
		      delr     => 'alpha*reff',
		      sigma2   => 'debye(temp, theta) + sigmm',
		     );

or

  $path_object -> new();
  $path_object -> set(data     => $dobject,
                      sp       => $scattering_path_object
		      name     => "path 1",
		      s02      => 'amp',
		      e0       => 'enot',
		      delr     => 'alpha*reff',
		      sigma2   => 'debye(temp, theta) + sigmm',
		     );

=head1 DESCRIPTION

This subclass of the Demeter class is for holding information
pertaining to theoretical paths from Feff for use in a fit.

=head1 ATTRIBUTES

The following are the attributes of the Path object.  Attempting to
access an attribute not on this list will throw and exception.

The type of argument expected in given in parentheses.  Several of the
attributes take an anonymous array as the value.  In each case, the
zeroth element of the annonymous array is the math expressionfor the
path and the first element is its evaluation.  See the discussion
below in L</METHODS> for a description of how these attributes
interacts with the accessor methods.  See also the description of the
C<evaluate> method for how the second element of the anonymous array
gets set.

The defaults for all path parameter math expressions is 0 except for
C<s02>, which is 1.  The C<*_value> path parameter attributes contain
the evaluation of the path parameter after the fit is made or the path
is otherwise evaluated.

For this Path object to be included in a fit, it is necessary that it
be gathered into a Fit object.  See L<Demeter::Fit> for
details.

=head2 General attributes

=over 4

=item C<group> (string)

This is the Ifeffit or Larch group name used for this path.  That is,
its arrays will be called I<group>.k, I<group>.chi, and so on.  It is
best if this is a reasonably short word and it B<must> follow the
conventions of a valid group name in Ifeffit or Larch.  By default,
this is a random, five-letter string.

=item C<name> (string)

This is a text string used to describe this object in a user
interface.  While the C<group> attribute should be short, this can be
more verbose.  But it should be a single line, unlike the C<title>
attibute.

=item C<parent> (Feff object)

This is the reference to the Feff object that this Path is a part of.
C<feff> is an alias for C<parent>.

=item C<data> (Data object)

This is the reference to the Data object that this path is associated
with.  There exists a default Data object so that you can successfully
Fourier transform and plot Path objects which are not associated with
a Data object, as might be the case for a sum of paths.

=item C<sp> (ScatteringPath object)

This is the reference to the ScatteringPath object that is used to
generate the F<feffNNNN.dat> file.  Once the sp attribute is set,
the file and folder attributes will be overwritten based on the
settings and actions of the Feff and ScatteringPath objects.  To set a
specific F<feffNNNN.dat> file, you must also set the sp attribute to
an empty string.

=item C<folder> (string)

This is a string that takes the fully qualified path (in the file
system sense) to the C<`feffNNNN.dat'> file associated with this Path
object.

If the C<SP> attribute is set, then this attribute will be set
automatically and changing it via the Path object's C<set> method will
be forbidden.

=item C<file> (filename)

This is the name of the F<feffNNNN.dat> file associated with this
Path object.

If the C<sp> attribute is set, then this attribute will be set
automatically.

=item C<Index> (integer)

This is the path index as required in the definition of an Ifeffit
Path.  It is rarely necessary to set this by hand.  Indexing is
typically handled by Demeter.  Demeter organization of the fit makes
use of lists of Path objects, so you are encouraged to think that way
rather than to fret about the path indeces.

=item C<include> (boolean)

When this is true, this Path will be included in the next fit.

=item C<plot_after_fit> (boolean)

This is a flag for use by a user interface to indicate that after a
fit is finished, this Path should be plotted.

=item C<default_path> (boolean)

This path will be set to the default path after the fit for the
purpose of evaluating C<def>, C<after>, and other parameters.  This is
only relevant if any C<def>, C<after> or other parameters depend
explicitly on path-specific quantites such as C<reff> or the
evaluation of the Debye or Eins functions.

=item C<pc> (boolean)

This is a flag indicating that the phase of this path should be used
to perform phase corrected plots.

=item C<save_mag> (boolean)

When true, this tells Ifeffit to save an array containing the
magnitude of chi(k).  This is used in ranking paths -- see
L<Demeter::ScatteringPath::Rank>.

=back

=head2 Path parameters

For each of these (except C<n> and C<id> which do not take math
expressions and the array path parameters which do not evaluate to
scalars), the first item listed is the attribute which takes the math
expression.  The second item listed is the evaluation of the math
expression after the fit is prefromed.  The evaluation cannot be set
by hand.  Instead you must change the values of GDS objects and
re-evaluate the fit using either of the C<fit> or C<sum> methods.

=over 4

=item C<n> (number)

This is the path degeneracy in the definition of an Ifeffit or Larch
path.  This is a number, not a math expression.  Use the C<s02>
attribute to parameterize the amplitude of the path.

=item C<s02> (string)

=item C<s02_value> (number)

This is the amplitude term for the path.

=item C<e0> (string)

=item C<e0_value> (number)

This is the energy shift term for the path.

=item C<delr> (string)

=item C<delr_value> (number)

This is the path length correction term for the path.

=item C<sigma2> (string)

=item C<sigma2_value> (number)

This is the mean square displacement shift term for the path.

=item C<ei> (string)

=item C<ei_value> (number)

This is the imaginary energy correction term for the path.

=item C<third> (string)

=item C<third_value> (number)

This is the third cumulant term for the path.

=item C<fourth> (string)

=item C<fourth_value> (number)

This is the fourth cumulant term for the path.

=item C<dphase> (string)

=item C<dphase_value> (number)

This is the constant phase shift term for the path.

=item C<id> (string)

This is Ifeffit's identification string for the path.

=item C<k_array> (string)

This takes the math expression for the infrequently used C<k_array>
path parameter.  You really need to know what you are doing to use the
array valued path parameters!

=item C<amp_array> (string)

This takes the math expression for the infrequently used C<amp_array>
path parameter.  You really need to know what you are doing to use the
array valued path parameters!

=item C<phase_array> (string)

This takes the math expression for the infrequently used
C<phase_array> path parameter.  You really need to know what you are
doing to use the array valued path parameters!

=back

=head2 Feff interpretation attributes

Where possible, these attributes will be taken from the ScatteringPath
object associated with the Path.

=over 4

=item C<degen> (number)

This is the degeneracy in the F<feffNNNN.dat> file associated with
this Path object.

=item C<nleg> (integer)

This is the number of legs in the F<feffNNNN.dat> file associated
with this Path object.

=item C<reff> (number)

This is the effective path length in the F<feffNNNN.dat> file
associated with this Path object.

=item C<zcwif> (number)

This is the amplitude (i.e. "Zabinsky curved wave importance factor")
for the F<feffNNNN.dat> file associated with this Path object.

Note that this is always 0 for paths that come from ScatteringPath
objects, since the ScatteringPath objct does not, at this time, have a
way of computing the ZCWIF.

=item C<intrpline> (string)

This is a line of text relating to this path from the interpretation
the Feff calculation.

=item C<geometry> (multiline string)

This is a textual description of the scattering geometry associated
with this path.

=item C<is_col> (boolean)

This is true when the path associated with this object is a colinear
or nearly colinear multiple scattering path.

=item C<is_ss> (boolean)

This is true when the path associated with this object is a single
scattering path.

=back

=head1 METHODS

The Path object inherits creation (C<new> and C<Clone>) and accessor
methods (C<set>, C<get>) from the parent class described in the
L<Demeter> documentation.

Additionally the Path object provides these methods:

=head2 I/O methods

=over 4

=item C<save>

This method returns the Ifeffit or Larch commands necessary to write
column data files based on the Path object.  See C<Demeter::Data::IO>
for details.  Only the C<chi>, C<r>, and C<q> options are available
for writing Path column data files.

=back

=head2 Convenience methods

=over 4

=item C<data>

This method returns the reference to the Data object that this Path is
associated with.  This method is meant to be used with the Data
object's C<data> method.  Path and Data objects can be put into a loop
and the correct Data object can be identified for each kind of object.

  foreach my $obj (@data_objects, @paths_objects) {
     my $d = $obj->data;
     ## do something with $d
  };

Note that this works because Data objects have a C<data> method which
self-identifies.

=item C<value>

This method returns the evaluated value of a path parameter after a
fit is made or a path is otherwise evaluated.

   my $val = $path_object->value("sigma2");

=item C<rm>

Delete the F<feffNNNN.dat> file associated with this Path.

  $path -> rm;

=back

=head2 Ifeffit/Larch interaction methods

=over 4

=item C<read_data>

This is completely different from the C<read_data> method called on a
Data object.  Or, it's exactly the same, depending on your
perspective.  It is not normally necessary to call read_data on a
F<feffNNNN.dat> file in the course of data analysis.  That file is
imported into Ifeffit or Larch as a part of the C<write_path> method.

When C<read_data> is called on a Path object, the Ifeffit/Larch
command for reading the F<feffNNNN.dat> file as a column data file is
returned.  This is useful if you ever need to examine the raw columns
of the F<feffNNNN.dat> file.

  $command = $path_object -> read_data;

=item C<write_path>

This method returns the Ifeffit or Larch commands to import and define
a Feff path.  It takes a boolean argument which tells the method
whether to also generate the Ifeffit or Larch command for converting
the defined path into arrays for plotting or other manipulations.
That argument is set true as part of the C<display> method, but false
when the fit is defined.

  $command = $path_object -> write_path($do_ff2chi);

=back

=head2 Information reporting methods

These methods are useful for generating log files and other reports.

=over 4

=item C<paragraph>

This method returns a multiline text string reporting on the
evaluation of the Path's math expressions.  This text looks very much
like the text that Ifeffit returns when you use Ifeffit's C<show
@group> command.

  print $path_object -> paragraph;

=item C<row_main>

This method returns a newline-terminated line of text containing the
values of several path parameters in a format suitable for making a
table of fitting results.  The path parameters included in this line
are C<n>, C<s02>, C<e0>, C<sigma2>, C<delr>, C<reff>, and the sum of
C<delr> and C<reff>.

The optional argument specifies the width of the first column, which
contains the path labels.

  print $path[0] -> row_main($width);

With this optional argument, you can scan the path labels before
creating the table and pre-size the first column, leading to a much
more attractive table.  The default width is 10 characters.  The
C<row_main_label>, C<row_second>, and C<row_second_label> methods also
take this same optional argument.

=item C<row_main_label>

This method returns a newline-terminated line of text suitable for the
header of the table made by repeated calls to the C<row_main> method.
Something like this will make a nice table

   print $path[0] -> row_main_label;
   print $path[0] -> row_main;
   print $path[1] -> row_main;
   print $path[2] -> row_main;

=item C<row_second>

This method returns a newline-terminated line of text containing the
values of several path parameters in a format suitable for making a
table of fitting results.  The path parameters included in this line
are C<ei>, C<dphase>, C<third>, C<fourth>.

=item C<row_second_label>

This method returns a newline-terminated line of text suitable for the
header of the table made by repeated calls to the C<row_second>
method.  Something like this will make a nice table

   print $path[0] -> row_second_label;
   print $path[0] -> row_second;
   print $path[1] -> row_second;
   print $path[2] -> row_second;

=item C<R>

This method returns the sum of the C<reff> attribute and the
evaluation of the C<delr> path parameter.  This:

  print $path_object -> R, $/;

is equivalent to (and fewer keystrokes than):

  ($reff, $delr) = $path_object->get(qw(reff delr_value));
  $R = $reff + $delr;
  print $R, $/;

=item C<longest_leg>

This returns the length in Angstrom of the longest leg of a path.

  print $path_object -> longest_leg, $/;

This is determined by searching the C<rleg> attribute of the
associated ScatteringPath object and returning the longest value.

=back

=head1 DIAGNOSTICS

=over 4

=item C<Demeter::Path: "group" is not a valid group name>

(F) You have used a group name that does not follow Ifeffit's or
Larch's rules for group names.  The group name must start with a
letter.  After that only letters, numbers, &, ?, _, and : are
acceptable characters.  The group name must be no longer than 64
characters.

=item C<Demeter::Path: the sp attribute must be ScatteringPath object>

(F) You have set the C<sp> attribute to something other than a
ScatteringPath object.

=back

=head1 SERIALIZATION AND DESERIALIZATION

See the discussion of serialization and deserialization in
C<Demeter::Fit>.

=head1 CONFIGURATION AND ENVIRONMENT

See L<Demeter::Config> for a description of the configuration system.

=head1 DEPENDENCIES

Demeter's dependencies are in the F<Build.PL> file.

=head1 BUGS AND LIMITATIONS

=over 4

=item *

Automated indexing currently only works when doing a fit.  If you want
to plot paths before doing a fit, you will need to assign indeces by
hand.

=back

Please report problems to the Ifeffit Mailing List
(L<http://cars9.uchicago.edu/mailman/listinfo/ifeffit/>)

Patches are welcome.

=head1 AUTHOR

Bruce Ravel, L<http://bruceravel.github.io/home>

L<http://bruceravel.github.io/demeter/>


=head1 LICENCE AND COPYRIGHT

Copyright (c) 2006-2019 Bruce Ravel (L<http://bruceravel.github.io/home>). All rights reserved.

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlgpl>.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

=cut