summaryrefslogtreecommitdiff
path: root/src/fisx_multilayer.cpp
blob: 124b967428c64daee1fe0ce879f797ce3a3969a3 (plain)
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
#/*##########################################################################
#
# The fisx library for X-Ray Fluorescence
#
# Copyright (c) 2014-2018 European Synchrotron Radiation Facility
#
# This file is part of the fisx X-ray developed by V.A. Sole
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
#include "fisx_xrf.h"
#include "fisx_math.h"
#include <cmath>
#include <stdexcept>
//#include <iostream>
#include <sstream>
#include <iomanip>

namespace fisx
{

std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > > \
                XRF::getMultilayerFluorescence(const std::vector<std::string> & elementList,
                                               const Elements & elementsLibrary, \
                                               const std::vector<int> & layerList, \
                                               const std::vector<std::string> &  familyList, \
                                               const int & secondary, \
                                               const int & useGeometricEfficiency,
                                               const int & useMassFractions, \
                                               const double & secondaryCalculationLimit)
{
    // get all the needed configuration
    const Beam & beam = this->configuration.getBeam();
    std::vector<std::vector<double> >actualRays = beam.getBeamAsDoubleVectors();
    std::vector<double>::size_type iRay;
    const std::vector<Layer> & filters = this->configuration.getBeamFilters();;
    const std::vector<Layer> & sample = this->configuration.getSample();
    const std::vector<Layer> & attenuators = this->configuration.getAttenuators();
    const Layer* layerPtr;
    std::vector<Layer>::size_type iLayer;
    std::vector<Layer>::size_type jLayer;
    std::vector<Layer>::size_type bLayer;
    Detector detector = this->configuration.getDetector();
    std::string msg;
    const double PI = acos(-1.0);
    const double & alphaIn = this->configuration.getAlphaIn();
    const double & alphaOut = this->configuration.getAlphaOut();
    std::vector<double> geometricEfficiency;
    double sinAlphaIn = sin(alphaIn*(PI/180.));
    double sinAlphaOut = sin(alphaOut*(PI/180.));
    double tmpDouble;
    const std::vector<double> & energies = actualRays[0];
    std::vector<double> weights;
    std::vector<double> doubleVector;
    std::map<std::string, std::map<std::string, double> > result;
    std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > > actualResult;
    std::vector<double> energyThresholdList;

    energyThresholdList.clear();
    // beam is ordered
    // maxEnergy = energies[energies.size() - 1];

    // get the beam after the beam filters
    std::vector<double> muTotal;
    muTotal.resize(energies.size());
    doubleVector.resize(energies.size());
    std::fill(muTotal.begin(), muTotal.end(), 0.0);
    for (iLayer = 0; iLayer < filters.size(); iLayer++)
    {
        doubleVector = filters[iLayer].getTransmission(energies, elementsLibrary);
        for (iRay = 0; iRay < energies.size(); iRay++)
        {
            actualRays[1][iRay] *= doubleVector[iRay];
        }
    }

    // we can already calculate the geometric efficiency
    geometricEfficiency.resize(sample.size());
    if (useGeometricEfficiency != 0)
    {
        for (iLayer = 0; iLayer < sample.size(); iLayer++)
        {
            geometricEfficiency[iLayer] = this->getGeometricEfficiency(iLayer);
        }
    }
    else
    {
        for (iLayer = 0; iLayer < sample.size(); iLayer++)
        {
            geometricEfficiency[iLayer] = 1.0;
        }
    }

    std::vector<std::vector<double> >sampleLayerEnergies;
    std::vector<std::vector<std::string> > sampleLayerEnergyNames;
    std::vector<std::vector<double> >sampleLayerRates;
    std::vector<std::vector<double> >sampleLayerMuTotal;
    std::map<std::string, double> sampleLayerComposition;
    std::vector<double>::size_type iLambda;
    std::vector<std::string> sampleLayerFamilies;
    std::vector<std::vector<std::pair<std::string, double> > >sampleLayerPeakFamilies;
    std::vector<std::pair<std::string, double> >::size_type iPeakFamily;
    std::vector<double> sampleLayerDensity;
    std::vector<double> sampleLayerThickness;
    std::vector<double> sampleLayerWeight;
    std::map< std::string, std::map<std::string, double> > escapeRates;

    // * implement a cache
    std::map< std::string, std::map< double, std::map<std::string, std::map<std::string, double> > > > \
                                        excitationFactorsCache;

    int updateEscape;
    updateEscape = 1;

    sampleLayerEnergies.resize(sample.size());
    sampleLayerEnergyNames.resize(sample.size());
    sampleLayerRates.resize(sample.size());
    sampleLayerFamilies.resize(sample.size());
    sampleLayerPeakFamilies.resize(sample.size());
    sampleLayerMuTotal.resize(sample.size());
    sampleLayerDensity.resize(sample.size());
    sampleLayerThickness.resize(sample.size());
    sampleLayerWeight.resize(sample.size());
    escapeRates.clear();

    iRay = energies.size();
    muTotal.resize(sample.size());
    weights.resize(actualRays[1].size());
    double minimumExcitationEnergy = -1.0;
    while (iRay > 0)
    {
        if (minimumExcitationEnergy < 0.0)
        {
            for (std::vector<std::string>::size_type iElement = 0; iElement < energyThresholdList.size(); iElement++)
            {
                if ((energyThresholdList[iElement] < minimumExcitationEnergy) ||
                    (minimumExcitationEnergy < 0.0))
                {
                    minimumExcitationEnergy = energyThresholdList[iElement];
                }
            }
        }
        --iRay;
        if (energies[iRay] < minimumExcitationEnergy)
        {
            // std::cout << "Stopped at Ray " << iRay << std::endl;
            continue;
        }
        weights[iRay] = actualRays[1][iRay];
        tmpDouble = 0.0;
        for(iLayer = 0; iLayer < sample.size(); iLayer++)
        {
            // get muTotal at the incident energy
            layerPtr = &sample[iLayer];
            if (iLayer == 0)
                sampleLayerWeight[iLayer] = 1.0;
            else
                sampleLayerWeight[iLayer] = exp(-tmpDouble);
            muTotal[iLayer] = (*layerPtr).getMassAttenuationCoefficients( \
                                                            energies[iRay], \
                                                            elementsLibrary)["total"];
            // layer thickness and density
            sampleLayerDensity[iLayer] = (*layerPtr).getDensity();
            sampleLayerThickness[iLayer] = (*layerPtr).getThickness();
            tmpDouble += sampleLayerDensity[iLayer] * sampleLayerThickness[iLayer] *\
                         muTotal[iLayer]/sinAlphaIn;
        }

        if (secondary > 0)
        {
            // get the excitation factor for each layer at incident energy
            for(iLayer = 0; iLayer < sample.size(); iLayer++)
            {
                sampleLayerEnergies[iLayer].clear();
                sampleLayerEnergyNames[iLayer].clear();
                sampleLayerRates[iLayer].clear();
                sampleLayerFamilies[iLayer].clear();
                sampleLayerMuTotal[iLayer].clear();
                layerPtr = &sample[iLayer];
                sampleLayerPeakFamilies[iLayer] = (*layerPtr).getPeakFamilies(energies[iRay], elementsLibrary);
                // They are ordered by increasing increasing binding energy
                std::string::size_type iString;
                std::string ele;
                std::string lastEle="dummytext";
                std::string family;
                std::map<std::string, std::map<std::string, double> > tmpResult;
                std::map<std::string, std::map<std::string, double> >::const_iterator c_it;
                std::map<std::string, double> sampleLayerComposition;
                std::map<std::string, double>::const_iterator mapIt;
                std::map<std::string, double>::const_iterator mapIt2;
                sampleLayerComposition = (*layerPtr).getComposition(elementsLibrary);
                for (iPeakFamily = 0 ; iPeakFamily < sampleLayerPeakFamilies[iLayer].size(); iPeakFamily++)
                {
                    iString = sampleLayerPeakFamilies[iLayer][iPeakFamily].first.find(' ');
                    family = sampleLayerPeakFamilies[iLayer][iPeakFamily].first.substr(iString + 1, \
                                    sampleLayerPeakFamilies[iLayer][iPeakFamily].first.size() - iString - 1);
                    ele = sampleLayerPeakFamilies[iLayer][iPeakFamily].first.substr(0, iString);
                    if (ele != lastEle)
                    {
                        // The secondary rates NOT corrected for the beam intensity reaching the layer
                        // The secondary rates NOT corrected for mass of element fraction in layer
                        tmpResult = elementsLibrary.getExcitationFactors(ele, \
                                                                     energies[iRay], \
                                                                     1.0);
                        lastEle = ele;
                    }
                    // and add the energies and rates to the sampleLayerLines
                    for (c_it = tmpResult.begin(); c_it != tmpResult.end(); ++c_it)
                    {
                        // be carefull not to add twice an element
                        if (c_it->first.compare(0, family.length(), family) == 0)
                        {
                            mapIt2 = c_it->second.find("rate");
                            if ((mapIt2->second * sampleLayerComposition[ele]) <= 0.0)
                            {
                                // std::cout << " Lower equal zero " << mapIt2->second << std::endl;
                                continue;
                            }
                            if (secondaryCalculationLimit > 0.0)
                            {
                                if ((mapIt2->second * sampleLayerComposition[ele]) < secondaryCalculationLimit)
                                {
                                    continue;
                                };
                            }
                            mapIt2 = c_it->second.find("energy");
                            if (mapIt2->second < minimumExcitationEnergy)
                            {
                                continue;
                            }
                            sampleLayerEnergies[iLayer].push_back(mapIt2->second);
                            mapIt2 = c_it->second.find("rate");
                            // Store rates already corrected for the beam intensity reaching the layer
                            // Store rates already corrected for the element mass fraction
                            sampleLayerRates[iLayer].push_back(mapIt2->second * sampleLayerComposition[ele] * \
                                                               weights[iRay] * sampleLayerWeight[iLayer]);
                            sampleLayerFamilies[iLayer].push_back(iString);
                            sampleLayerEnergyNames[iLayer].push_back(ele + \
                                                                     " " +\
                                                                     c_it->first);
                        }
                    }
                }
                // We have to add the contribution of coherent scattering
                // We do so by assuming an isotropic emission of the same energy as the
                // incident beam
                sampleLayerEnergyNames[iLayer].push_back("coherent scattering");
                sampleLayerEnergies[iLayer].push_back(energies[iRay]);
                // calculate sample mu total at all those energies
                std::map<std::string, std::vector<double> > tmpStringDoubleVecMap;
                tmpStringDoubleVecMap = (*layerPtr).getMassAttenuationCoefficients( \
                                                                sampleLayerEnergies[iLayer], \
                                                                elementsLibrary);
                sampleLayerMuTotal[iLayer] = tmpStringDoubleVecMap["total"];

                sampleLayerRates[iLayer].push_back((weights[iRay] * sampleLayerWeight[iLayer])*\
                tmpStringDoubleVecMap["coherent"].back());
            }
        }
        // we start calculation
        // mu_1_lambda = Mass attenuation coefficient of iLayer at incident energy
        double mu_1_lambda;
        // mu_1_i = Mass attenuation coefficient of iLayer at fluorescent energy
        double mu_1_i;
        // density and thickness of fluorescent layer
        double density_1;
        double thickness_1;
        // density and thickness of second layer
        double density_2;
        double thickness_2;
        // mu_a_lambda = Mass attenuation coefficient of layers above iLayer at incident energy
        // mu_a_i = Mass attenuation coefficient of layers above iLayer at fluorescent energy
        // mu_b_lambda = Mass attenuation coefficient of layers between iLayer and jLayer at incident energy
        // mu_b_j = Mass attenuation coefficient of layers between iLayer and jLayer at jLayer fluorescent energy j
        // mu_b_j_d_t sum of product mu * density * thickness of layers between iLayer and jLayer at jLayer fluorescent energy j
        double mu_b_j_d_t;
        // mu_2_lambda = Mass attenuation coefficient of jLayer at incident energy
        double mu_2_lambda;
        // mu_2_j = Mass attenuation coefficient of jLayer at jLayer fluorescent energy j
        double mu_2_j;
        // mu_1_j = Mass attenuation coefficient of iLayer at jLayer fluorescent energy j
        double mu_1_j;
        // elementName is the element to be analyzed
        // lineFamily is the family of  elementName X-ray lines to be considered
        double energyThreshold;

        // this line can be moved out of the loop
        std::map<std::string, std::map<std::string, double> > primaryExcitationFactors;
        std::map<std::string, std::map<std::string, double> > tmpExcitationFactors;
        std::map<std::string, std::map<std::string, double> >::const_iterator c_it;
        std::map<std::string, double>::const_iterator mapIt;
        std::map<std::string, double> muTotalFluo;
        double detectionEfficiency;
        double energy;
        std::string key;
        std::string tmpString;
        std::ostringstream tmpStringStream;
        for (std::vector<std::string>::size_type iElement = 0; iElement < elementList.size(); iElement++)
        {
            const std::string & elementName = elementList[iElement];
            const std::string & lineFamily = familyList[iElement];
            int calculationLayer;
            std::string actualLineFamily;
            if (layerList.size() > 1)
                calculationLayer = layerList[iElement];
            else
                calculationLayer = layerList[0];
            actualLineFamily = lineFamily;
            if (lineFamily == "Ka")
            {
                actualLineFamily = "KL";
            }
            if (lineFamily == "Kb")
            {
                // carefull, the actual condition is to start by K and not to be followed by L
                actualLineFamily = "KM";
            }
            if (actualLineFamily == "")
            {
                throw std::runtime_error("All line families case not implemented yet!!!");
            }
            if (iElement < energyThresholdList.size())
            {
                energyThreshold = energyThresholdList[iElement];
            }
            else
            {
                energyThreshold = this->getEnergyThreshold(elementName, \
                                                       actualLineFamily.substr(0, 1), \
                                                       elementsLibrary);
                energyThresholdList.push_back(energyThreshold);
            }

            if (energyThreshold > energies[iRay])
            {
                continue;
            }
            primaryExcitationFactors = elementsLibrary.getExcitationFactors(elementName, \
                                                                        energies[iRay], \
                                                                        weights[iRay]);
            for (iLayer = 0; iLayer < sample.size(); iLayer++)
            {
                double elementMassFractionFactor;
                double elementMassFraction;
                if ((calculationLayer >= 0) && ((iLayer - calculationLayer) != 0))
                {
                    // no need to calculate this layer
                    continue;
                }
                elementMassFractionFactor = 1.0;
                if(true)
                {
                    std::map<std::string, double> sampleLayerComposition;
                    layerPtr = &sample[iLayer];
                    sampleLayerComposition = (*layerPtr).getComposition(elementsLibrary);
                    if (sampleLayerComposition.find(elementName) == sampleLayerComposition.end())
                    {
                        elementMassFraction = 0.0;
                    }
                    else
                    {
                        elementMassFraction = sampleLayerComposition[elementName];
                    }
                }
                if (useMassFractions)
                {
                    elementMassFractionFactor = elementMassFraction;
                }
                // here I should loop for all elements and families
                key = elementName + " " + lineFamily;
                // we need to calculate the layer mass attenuation coefficients at the fluorescent energies
                result.clear();
                if (elementMassFractionFactor == 0.0)
                    continue;
                for (c_it = primaryExcitationFactors.begin(); c_it != primaryExcitationFactors.end(); ++c_it)
                {
                    if ((c_it->first.compare(0, actualLineFamily.length(), actualLineFamily) == 0) || \
                        ((lineFamily == "Kb") && (c_it->first[0] == 'K') && (c_it->first[1] != 'L')))
                    {
                        mapIt = c_it->second.find("factor");
                        if (mapIt == c_it->second.end())
                        {
                            std::cout << "Key <factor> not found in excitation factor" << std::endl;
                        }
                        if (mapIt->second <= 0.0)
                        {
                            // not excited
                            continue;
                        }
                        mapIt = c_it->second.find("energy");
                        energy = mapIt->second;
                        result[c_it->first]["energy"] = energy;
                        mapIt = c_it->second.find("rate");
                        result[c_it->first]["rate"] = mapIt->second;
                        mapIt = c_it->second.find("factor");
                        result[c_it->first]["factor"] = mapIt->second;
                        if (actualResult[key][iLayer].find(c_it->first) == actualResult[key][iLayer].end())
                        {
                            // calculate layer mu total at fluorescent energy
                            // std::cout << "CALCULATING mu_1_i for " << c_it->first << " ";
                            // std::cout << "energy " << energy;
                            result[c_it->first]["mu_1_i"] = \
                                    sample[iLayer].getMassAttenuationCoefficients(energy, \
                                                                                elementsLibrary) ["total"];
                            // calculate detection efficiency of fluorescent energy
                            detectionEfficiency = 1.0;
                            // transmission through upper layers
                            jLayer = iLayer;
                            while (jLayer > 0)
                            {
                                jLayer--;
                                layerPtr = &sample[jLayer];
                                detectionEfficiency *= (*layerPtr).getTransmission(energy, \
                                                                                   elementsLibrary, \
                                                                                   alphaOut);
                            }
                            // transmission through attenuators
                            for (jLayer = 0; jLayer < attenuators.size(); jLayer++)
                            {
                                layerPtr = &attenuators[jLayer];
                                detectionEfficiency *= (*layerPtr).getTransmission(energy, \
                                                                                   elementsLibrary, \
                                                                                   90.0);
                            }

                            // detection efficiency decomposed in geometric and intrinsic
                            detectionEfficiency *= geometricEfficiency[iLayer];

                            if (detector.hasMaterialComposition() || (detector.getMaterialName().size() > 0 ))
                            {
                                if ((detector.getDensity() > 0.0) && (detector.getThickness() > 0.0))
                                {
                                    // calculate intrinsic efficiency
                                    // assuming normal incidence on detector surface
                                    detectionEfficiency *= (1.0 - detector.getTransmission(energy, \
                                                                                elementsLibrary, \
                                                                                90.0));
                                }
                                // calculate escape ratio assuming normal incidence on detector surface
                                escapeRates = detector.getEscape(energy, \
                                                                 elementsLibrary, \
                                                                 elementName + c_it->first, \
                                                                 updateEscape);
                                updateEscape = 0;
                            }


                            result[c_it->first]["energy_threshold"] = energyThreshold;
                            result[c_it->first]["efficiency"] = detectionEfficiency;
                            actualResult[key][iLayer][c_it->first]["efficiency"] = detectionEfficiency;
                            actualResult[key][iLayer][c_it->first]["energy"] = energy;
                            actualResult[key][iLayer][c_it->first]["energy_threshold"] = energyThreshold;
                            actualResult[key][iLayer][c_it->first]["mu_1_i"] = result[c_it->first]["mu_1_i"];
                            actualResult[key][iLayer][c_it->first]["rate"] = 0.0;
                            actualResult[key][iLayer][c_it->first]["primary"] = 0.0;
                            actualResult[key][iLayer][c_it->first]["secondary"] = 0.0;
                        }
                        else
                        {
                            // std::cout << "USING mu_1_i for " << c_it->first << " ";
                            // std::cout << "energy " << energy;
                            result[c_it->first]["efficiency"] = \
                                        actualResult[key][iLayer][c_it->first]["efficiency"];
                            result[c_it->first]["energy"] = actualResult[key][iLayer][c_it->first]["energy"];
                            result[c_it->first]["energy_threshold"] = \
                                                    actualResult[key][iLayer][c_it->first]["energy_threshold"];
                            result[c_it->first]["mu_1_i"] = actualResult[key][iLayer][c_it->first]["mu_1_i"];
                        }
                    }
                }
                if (result.size() == 0)
                {
                    // no need to calculate anything
                    continue;
                }
                // primary
                mu_1_lambda = sample[iLayer].getMassAttenuationCoefficients( \
                                                                energies[iRay], \
                                                                elementsLibrary)["total"];
                density_1 = sample[iLayer].getDensity();
                thickness_1 = sample[iLayer].getThickness();
                for (c_it = result.begin(); c_it != result.end(); ++c_it)
                {
                    mapIt = c_it->second.find("mu_1_i");
                    if (mapIt == c_it->second.end())
                    {
                        throw std::runtime_error("Mass attenuation coefficient not calculated!!!");
                    }
                    mu_1_i = mapIt->second;
                    tmpDouble = (mu_1_lambda / sinAlphaIn) + (mu_1_i / sinAlphaOut);
                    // keep factor for deciding if secondary excitation is to be considered or not
                    tmpDouble = (1.0 - exp( - tmpDouble * density_1 * thickness_1)) / tmpDouble;
                    //result[c_it->first]["criterium"] = tmpDouble;
                    tmpDouble *= (elementMassFractionFactor / sinAlphaIn);
                    result[c_it->first]["primary"] = tmpDouble * \
                                                     primaryExcitationFactors[c_it->first]["rate"] * \
                                                     sampleLayerWeight[iLayer];
                    result[c_it->first]["rate"] = result[c_it->first]["primary"] * \
                                                  result[c_it->first]["efficiency"];
                    result[c_it->first]["secondary"] = 0.0;
                    //std::cout << c_it->first << "efficiency = " << result[c_it->first]["efficiency"] << std::endl;
                    //std::cout << c_it->first << "primary = " << result[c_it->first]["primary"] << std::endl;
                    //std::cout << c_it->first << "energy = " << result[c_it->first]["energy"] << std::endl;
                    //std::cout << c_it->first << "mu_1_i = " << result[c_it->first]["mu_1_i"] << std::endl;
                    /*
                    if ((c_it->first == "KL2") && (iLayer == 0))
                    {
                        std::cout << c_it->first << "efficiency = " << result[c_it->first]["efficiency"] << std::endl;
                        std::cout << c_it->first << "primary = " << result[c_it->first]["primary"] << std::endl;
                        std::cout << c_it->first << "sampleLayerWeight = " << sampleLayerWeight[iLayer] << std::endl;
                        std::cout << c_it->first << "Excitation E = " << energies[iRay] << std::endl;
                        std::cout << c_it->first << "Fluorescence E = " << result[c_it->first]["energy"] << std::endl;
                        std::cout << c_it->first << "mu_1_i = " << mu_1_i << std::endl;
                        std::cout << c_it->first << "mu_1_lambda = " << mu_1_lambda<< std::endl;
                        std::cout << c_it->first << "d * t = " << density_1 * thickness_1 << std::endl;
                        std::cout << c_it->first << "mu_1_lambda/sinALphain = " << mu_1_lambda / sinAlphaIn<< std::endl;
                        std::cout << c_it->first << "mu_1_i/sinALphaOut = " << mu_1_i / sinAlphaOut<< std::endl;
                    }
                    */
                }

                if (secondary > 0)
                {
                    // calculate secondary
                    for (jLayer = 0; jLayer < sample.size(); jLayer++)
                    {
                        if (iLayer == jLayer)
                        {
                            double criteriumMax=secondaryCalculationLimit;
                            // intralayer secondary
                            for(iLambda = 0; iLambda < sampleLayerEnergies[jLayer].size(); iLambda++)
                            {
                                // analogous to incident beam
                                if (energyThreshold > sampleLayerEnergies[jLayer][iLambda])
                                    continue;
                                bool calculate;
                                calculate = true;
                                if (excitationFactorsCache.find(elementName) != excitationFactorsCache.end())
                                {
                                    if (excitationFactorsCache[elementName].find(sampleLayerEnergies[jLayer][iLambda]) \
                                            != excitationFactorsCache[elementName].end())
                                    {
                                        calculate = false;
                                    }
                                }
                                if (calculate)
                                {
                                    excitationFactorsCache[elementName] \
                                                [sampleLayerEnergies[jLayer][iLambda]] = \
                                                        elementsLibrary.getExcitationFactors(elementName, \
                                                        sampleLayerEnergies[jLayer][iLambda], \
                                                        1.0);
                                }
                                tmpExcitationFactors = excitationFactorsCache[elementName] \
                                                        [sampleLayerEnergies[jLayer][iLambda]];
                                double criterium;
                                for (c_it = result.begin(); c_it != result.end(); ++c_it)
                                {
                                    if (tmpExcitationFactors.find(c_it->first) == tmpExcitationFactors.end())
                                    {
                                        continue;
                                    }
                                    mapIt = result[c_it->first].find("mu_1_i");
                                    if (mapIt == result[c_it->first].end())
                                        throw std::runtime_error(" mu_1_i key. Mass attenuation not present???");
                                    criterium = tmpExcitationFactors[c_it->first]["rate"] * \
                                                    sampleLayerRates[jLayer][iLambda];
                                    criterium /= (primaryExcitationFactors[c_it->first]["rate"] * \
                                                     sampleLayerWeight[iLayer]);
                                    if (criterium <= criteriumMax)
                                    {
                                        // std::cout << " criterium = " << criterium;
                                        // std::cout << " criterium Max = " << criteriumMax << std::endl;
                                        continue;
                                    }
                                    mu_1_i = mapIt->second;
                                    tmpDouble = Math::deBoerL0(mu_1_lambda / sinAlphaIn,
                                                               mu_1_i / sinAlphaOut,
                                                               sampleLayerMuTotal[jLayer][iLambda],
                                                               density_1,
                                                               thickness_1);
                                    // Workaround incident angle of 90 degrees and scatter contribution
                                    if ((mu_1_lambda / sinAlphaIn) == sampleLayerMuTotal[jLayer][iLambda])
                                        tmpDouble += Math::deBoerL0(mu_1_i / sinAlphaOut,
                                                               mu_1_lambda / (0.99999*sinAlphaIn),
                                                               sampleLayerMuTotal[jLayer][iLambda],
                                                               density_1,
                                                               thickness_1);
                                    else
                                        tmpDouble += Math::deBoerL0(mu_1_i / sinAlphaOut,
                                                               mu_1_lambda / sinAlphaIn,
                                                               sampleLayerMuTotal[jLayer][iLambda],
                                                               density_1,
                                                               thickness_1);
                                    tmpDouble *= elementMassFractionFactor * (0.5/sinAlphaIn);
                                    tmpDouble *= tmpExcitationFactors[c_it->first]["rate"] * \
                                                    sampleLayerRates[jLayer][iLambda];
                                    tmpStringStream.str(std::string());
                                    tmpStringStream.clear();
                                    tmpStringStream << std::setfill('0') << std::setw(2) << jLayer;
                                    tmpString = sampleLayerEnergyNames[jLayer][iLambda] + " " + tmpStringStream.str();
                                    actualResult[elementName + " " + lineFamily][iLayer][c_it->first][tmpString] = \
                                                                                                    tmpDouble;
                                    result[c_it->first]["secondary"] += tmpDouble;
                                    result[c_it->first]["rate"] += tmpDouble * \
                                                                   result[c_it->first]["efficiency"];
                                    if (criteriumMax > 0.0)
                                    {
                                        if ((tmpDouble/result[c_it->first]["primary"]) < 0.00001)
                                        {
                                            if (criterium > criteriumMax)
                                            {
                                                criteriumMax = criterium;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if ((sampleLayerWeight[jLayer] / sampleLayerWeight[iLayer]) < 1.0E-4)
                            {
                                // The incident reaching the layer originating the secondary excitation
                                // is relatively much weaker. In the common energy range of XRF interest,
                                // one will certainly recover less than of 50 % of the incident photons
                                // reaching the jLayer originating the secondary excitation "beam".
                                // An additional factor 100 is accounted for because of the possible ratio
                                // of attenuation coefficient of the element at incident and secondary excitation
                                // photon energies
                                continue;
                            }

                            double criterium;
                            // continue;
                            mu_2_lambda = muTotal[jLayer];
                            density_2 = sampleLayerDensity[jLayer];
                            thickness_2 = sampleLayerThickness[jLayer];
                            if (iLayer < jLayer)
                            {
                                double criteriumMax = secondaryCalculationLimit;
                                // interlayer case a)
                                for(iLambda = 0;
                                    iLambda < sampleLayerEnergies[jLayer].size(); \
                                    iLambda++)
                                {
                                    // analogous to incident beam
                                    energy = sampleLayerEnergies[jLayer][iLambda];
                                    if (energyThreshold > energy)
                                        continue;
                                    bool calculate;
                                    calculate = true;
                                    if (excitationFactorsCache.find(elementName) != excitationFactorsCache.end())
                                    {
                                        if (excitationFactorsCache[elementName].find(sampleLayerEnergies[jLayer][iLambda]) \
                                                != excitationFactorsCache[elementName].end())
                                        {
                                            calculate = false;
                                        }
                                    }
                                    if (calculate)
                                    {
                                        excitationFactorsCache[elementName] \
                                                    [sampleLayerEnergies[jLayer][iLambda]] = \
                                                            elementsLibrary.getExcitationFactors(elementName, \
                                                            sampleLayerEnergies[jLayer][iLambda], \
                                                            1.0);
                                    }
                                    tmpExcitationFactors = excitationFactorsCache[elementName] \
                                                            [sampleLayerEnergies[jLayer][iLambda]];
                                    for (c_it = result.begin(); c_it != result.end(); ++c_it)
                                    {
                                        if (tmpExcitationFactors.find(c_it->first) == tmpExcitationFactors.end())
                                        {
                                            // This happens when we look for K lines, but obviously L lines are
                                            // present
                                            //std::cout << "Not considered " << c_it->first ;
                                            //std::cout << " energy = " << sampleLayerEnergies[iLayer][iLambda] << std::endl;
                                            continue;
                                        }
                                        if (tmpExcitationFactors[c_it->first]["rate"] < 1.0e-30)
                                        {
                                            continue;
                                        }
                                        criterium = tmpExcitationFactors[c_it->first]["rate"] * \
                                                    sampleLayerRates[jLayer][iLambda];
                                        criterium /= (primaryExcitationFactors[c_it->first]["rate"] * \
                                                     sampleLayerWeight[iLayer]);
                                        if (criterium <= criteriumMax)
                                            continue;

                                        mapIt = result[c_it->first].find("mu_1_i");
                                        if (mapIt == result[c_it->first].end())
                                            throw std::runtime_error(" mu_1_i key. Mass attenuation not present???");
                                        mu_1_i = mapIt->second;
                                        mu_1_j = \
                                            sample[iLayer].getMassAttenuationCoefficients(energy, \
                                                                                elementsLibrary)["total"];
                                        mu_2_j = sampleLayerMuTotal[jLayer][iLambda];
                                        bLayer = iLayer + 1;
                                        mu_b_j_d_t = 0.0;
                                        while (bLayer < jLayer)
                                        {
                                            mu_b_j_d_t += sampleLayerDensity[bLayer] * \
                                                          sampleLayerThickness[bLayer] * \
                                                          sample[bLayer].getMassAttenuationCoefficients(energy, \
                                                                                    elementsLibrary)["total"];
                                            bLayer++;
                                        }
                                        tmpDouble = std::exp(-mu_1_i * density_1 * thickness_1/sinAlphaOut);
                                        if (tmpDouble < 0.001)
                                            continue;
                                        tmpDouble *= sampleLayerRates[jLayer][iLambda];
                                        if (-(mu_2_lambda/sinAlphaIn) == mu_2_j)
                                            tmpDouble *= Math::deBoerX(mu_2_lambda/(0.99999*sinAlphaIn), \
                                                                  mu_1_i/sinAlphaOut, \
                                                                  density_1 * thickness_1, \
                                                                  density_2 * thickness_2, \
                                                                  mu_1_j, \
                                                                  mu_2_j, \
                                                                  mu_b_j_d_t);
                                        else
                                            tmpDouble *= Math::deBoerX(mu_2_lambda/sinAlphaIn, \
                                                                  mu_1_i/sinAlphaOut, \
                                                                  density_1 * thickness_1, \
                                                                  density_2 * thickness_2, \
                                                                  mu_1_j, \
                                                                  mu_2_j, \
                                                                  mu_b_j_d_t);
                                        tmpDouble *= elementMassFractionFactor * (0.5/sinAlphaIn);
                                        tmpDouble *= tmpExcitationFactors[c_it->first]["rate"];
                                        tmpStringStream.str(std::string());
                                        tmpStringStream.clear();
                                        tmpStringStream << std::setfill('0') << std::setw(2) << jLayer;
                                        tmpString = sampleLayerEnergyNames[jLayer][iLambda] + " " + tmpStringStream.str();
                                        actualResult[elementName + " " + lineFamily][iLayer][c_it->first][tmpString] = \
                                                                                                        tmpDouble;
                                        result[c_it->first]["secondary"] += tmpDouble;
                                        result[c_it->first]["rate"] += tmpDouble * \
                                                                       result[c_it->first]["efficiency"];
                                        if (criteriumMax > 0.0)
                                        {
                                            if ((tmpDouble/result[c_it->first]["primary"]) < 0.00001)
                                            {
                                                if (criterium > criteriumMax)
                                                {
                                                    criteriumMax = criterium;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (iLayer > jLayer)
                            {
                                double criteriumMax = secondaryCalculationLimit;
                                // interlayer case b)
                                double layerFactor;
                                layerFactor = std::exp(-mu_2_lambda * density_2 * thickness_2/sinAlphaIn);
                                /*
                                This test has been removed in favour of the one dealing with the relative
                                weights of each layer. Indeed, the relative amount of secondary excitation
                                can be huge important. Other point is if we are going to detect something.
                                if (layerFactor < 0.001)
                                {
                                    // No need to calculate anything, the top layer attenuates too much the
                                    // incoming beam
                                    continue;
                                }
                                */
                                for(iLambda = 0;
                                    iLambda < sampleLayerEnergies[jLayer].size(); \
                                    iLambda++)
                                {
                                    // analogous to incident beam
                                    energy = sampleLayerEnergies[jLayer][iLambda];
                                    if (energyThreshold > energy)
                                        continue;
                                    bool calculate;
                                    calculate = true;
                                    if (excitationFactorsCache.find(elementName) != excitationFactorsCache.end())
                                    {
                                        if (excitationFactorsCache[elementName].find(sampleLayerEnergies[jLayer][iLambda]) \
                                                != excitationFactorsCache[elementName].end())
                                        {
                                            calculate = false;
                                        }
                                    }
                                    if (calculate)
                                    {
                                        excitationFactorsCache[elementName] \
                                                    [sampleLayerEnergies[jLayer][iLambda]] = \
                                                            elementsLibrary.getExcitationFactors(elementName, \
                                                            sampleLayerEnergies[jLayer][iLambda], \
                                                            1.0);
                                    }
                                    tmpExcitationFactors = excitationFactorsCache[elementName] \
                                                            [sampleLayerEnergies[jLayer][iLambda]];
                                    for (c_it = result.begin(); c_it != result.end(); ++c_it)
                                    {
                                        if (tmpExcitationFactors.find(c_it->first) == tmpExcitationFactors.end())
                                        {
                                            // This happens when, for instance, we look for K lines, but obviously
                                            // L lines are present
                                            //std::cout << "Not considered " << c_it->first ;
                                            //std::cout << " energy = " << sampleLayerEnergies[iLayer][iLambda] << std::endl;
                                            continue;
                                        }
                                        if (tmpExcitationFactors[c_it->first]["rate"] < 1.0e-30)
                                        {
                                            continue;
                                        }
                                        criterium = tmpExcitationFactors[c_it->first]["rate"] * \
                                                    sampleLayerRates[jLayer][iLambda];
                                        criterium /= (primaryExcitationFactors[c_it->first]["rate"] * \
                                                     sampleLayerWeight[iLayer]);
                                        if (criterium <= criteriumMax)
                                            continue;
                                        mapIt = result[c_it->first].find("mu_1_i");
                                        if (mapIt == result[c_it->first].end())
                                            throw std::runtime_error(" mu_1_i key. Mass attenuation not present???");
                                        mu_1_i = mapIt->second;
                                        mu_1_j = \
                                            sample[iLayer].getMassAttenuationCoefficients(energy, \
                                                                                elementsLibrary)["total"];
                                        mu_2_j = sampleLayerMuTotal[jLayer][iLambda];
                                        bLayer = jLayer + 1;
                                        mu_b_j_d_t = 0.0;
                                        while (bLayer < iLayer)
                                        {
                                            mu_b_j_d_t += sampleLayerDensity[bLayer] * \
                                                          sampleLayerThickness[bLayer] * \
                                                          sample[bLayer].getMassAttenuationCoefficients(energy, \
                                                                                    elementsLibrary)["total"];
                                            bLayer++;
                                        }
                                        tmpDouble = layerFactor * sampleLayerRates[jLayer][iLambda];
                                        if ((mu_2_lambda/sinAlphaIn) == mu_2_j)
                                            tmpDouble *= Math::deBoerX(-mu_2_lambda/(0.99999*sinAlphaIn), \
                                                                  -mu_1_i/sinAlphaOut, \
                                                                  density_1 * thickness_1, \
                                                                  density_2 * thickness_2, \
                                                                  mu_1_j, \
                                                                  mu_2_j, \
                                                                  mu_b_j_d_t);
                                        else
                                            tmpDouble *= Math::deBoerX(-mu_2_lambda/sinAlphaIn, \
                                                                  -mu_1_i/sinAlphaOut, \
                                                                  density_1 * thickness_1, \
                                                                  density_2 * thickness_2, \
                                                                  mu_1_j, \
                                                                  mu_2_j, \
                                                                  mu_b_j_d_t);
                                        tmpDouble *= elementMassFractionFactor * (0.5/sinAlphaIn);
                                        tmpDouble *= tmpExcitationFactors[c_it->first]["rate"];
                                        tmpStringStream.str(std::string());
                                        tmpStringStream.clear();
                                        tmpStringStream << std::setfill('0') << std::setw(2) << jLayer;
                                        tmpString = sampleLayerEnergyNames[jLayer][iLambda] + " " + tmpStringStream.str();
                                        actualResult[elementName + " " + lineFamily][iLayer][c_it->first][tmpString] = \
                                                                                                        tmpDouble;
                                        result[c_it->first]["secondary"] += tmpDouble;
                                        result[c_it->first]["rate"] += tmpDouble * \
                                                                       result[c_it->first]["efficiency"];
                                        if (criteriumMax > 0.0)
                                        {
                                            if ((tmpDouble/result[c_it->first]["primary"]) < 0.00001)
                                            {
                                                if (criterium > criteriumMax)
                                                {
                                                    criteriumMax = criterium;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // here we are done for the element and the layer
                key = elementName + " " + lineFamily;
                for (c_it = result.begin(); c_it != result.end(); ++c_it)
                {
                    double totalEscape = 0.0;
                    if (detector.hasMaterialComposition() || (detector.getMaterialName().size() > 0 ))
                    {
                        // calculate (if needed) escape ratio
                        escapeRates = detector.getEscape(result[c_it->first]["energy"], \
                                                         elementsLibrary, \
                                                         elementName + c_it->first, \
                                                         updateEscape);
                        if (escapeRates.size())
                        {
                            updateEscape = 0;
                            std::map<std::string, std::map<std::string, double> >::const_iterator c_it2;
     //                       std::map<std::string, double>::const_iterator mapIt;
                            for( c_it2 = escapeRates.begin(); c_it2!= escapeRates.end(); ++c_it2)
                            {
                                tmpString = c_it->first + " "+ c_it2->first;
                                if (actualResult[key][iLayer].find(tmpString) == actualResult[key][iLayer].end())
                                {
                                    mapIt = c_it2->second.find("energy");
                                    if (mapIt == c_it2->second.end())
                                    {
                                        throw std::runtime_error("Missing energy key in escape peak information!");
                                    }
                                    actualResult[key][iLayer][tmpString]["energy"] = mapIt->second;
                                    actualResult[key][iLayer][tmpString]["rate"] = 0.0;
                                    actualResult[key][iLayer][tmpString]["ratio"] = 0.0;
                                    actualResult[key][iLayer][tmpString]["primary"] = 0.0;
                                    actualResult[key][iLayer][tmpString]["secondary"] = 0.0;
                                }
                                mapIt = c_it2->second.find("rate");
                                if (mapIt == c_it2->second.end())
                                {
                                    throw std::runtime_error("Missing rate key in escape peak information!");
                                }
                                totalEscape += mapIt->second;
                                actualResult[key][iLayer][tmpString]["rate"] += mapIt->second * result[c_it->first]["rate"];
                                actualResult[key][iLayer][tmpString]["ratio"] = mapIt->second;
                                // The only meaning of filling "primary" and "secondary" for a escape peak is in order to
                                // be able to evaluate the ratio without having to refer to the actual parent line.
                                actualResult[key][iLayer][tmpString]["primary"] += mapIt->second * result[c_it->first]["primary"];
                                actualResult[key][iLayer][tmpString]["secondary"] += mapIt->second * result[c_it->first]["secondary"];
                            }
                        }
                    }
                    actualResult[key][iLayer][c_it->first]["rate"] += (1.0 - totalEscape) * result[c_it->first]["rate"];
                    // primary and secondary are the same independently of having escape or not.
                    actualResult[key][iLayer][c_it->first]["primary"] += result[c_it->first]["primary"];
                    actualResult[key][iLayer][c_it->first]["secondary"] += result[c_it->first]["secondary"];
                    actualResult[key][iLayer][c_it->first]["massFraction"] = elementMassFraction;
                }
            }
        }
    }
    if (secondary > 1)
    {
        // std::cout << "WARNING: Tertiary excitation under development " << std::endl;
        // approximate tertiary excitation
        // we ignore the case of excitation after double rayleigh/coherent scattering
        std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > >::iterator actualResultIt;
        std::map<std::string, std::map<std::string, double> >::iterator c_it;
        std::map<std::string, std::map<std::string, double> >::iterator it;
        std::map<std::string, std::map<std::string, double> >::iterator it2;
        std::map<std::string, double> contributingKeys;
        std::map<std::string, double>::iterator contributingKeysIt;
        std::string key;
        std::ostringstream tmpStringStream;
        double factorFirst;
        double tertiary;
        std::string ele;
        for (actualResultIt = actualResult.begin(); actualResultIt != actualResult.end(); ++actualResultIt)
        {
            ele = actualResultIt->first.substr(0, actualResultIt->first.find(' '));
            for (iLayer = 0; iLayer < actualResultIt->second.size(); iLayer++)
            {
                for (it = actualResultIt->second[iLayer].begin(); \
                     it != actualResultIt->second[iLayer].end(); ++it)
                {
                    //std::cout << it->first << std::endl;
                    if (it->first.find("esc") != std::string::npos)
                    {
                        // this is a escape line -> Ignore it
                        continue;
                    }
                    if (it->second["massFraction"] < 5.0E-3)
                    {
                        // one should be able to neglect tertiary excitation from elements
                        // with less than 1 % concentration
                        break;
                    }
                    factorFirst = 1.0;
                    if (it->second["primary"] > 0.0)
                    {
                        factorFirst = (it->second["primary"] + it->second["secondary"]) / \
                                     it->second["primary"];
                    }
                    if (factorFirst < 1.01)
                    {
                        // tertiary contribution should already be less than 1 % -> Ignore it
                        continue;
                    }
                    else
                    {
                        tmpStringStream.str(std::string());
                        tmpStringStream.clear();
                        tmpStringStream << std::setfill('0') << std::setw(2) << iLayer;
                        key = ele + " " + it->first + " " + tmpStringStream.str();
                        contributingKeys[key] = factorFirst;
                        // the factor will be the same for all lines starting by KL2, being escape or not
                    }
                }
            }
        }

        for (actualResultIt = actualResult.begin(); actualResultIt != actualResult.end(); ++actualResultIt)
        {
            for (iLayer = 0; iLayer < actualResultIt->second.size(); iLayer++)
            {
                for (it = actualResultIt->second[iLayer].begin(); \
                     it != actualResultIt->second[iLayer].end(); ++it)
                {
                    factorFirst = 1.0;
                    tertiary = 0.0;
                    if (it->second["primary"] > 0.0)
                    {
                        factorFirst = (it->second["primary"] + it->second["secondary"]) / \
                                     it->second["primary"];
                    }
                    if (factorFirst < 1.01)
                    {
                        // It had less than 1 % secondary, we assume tertiary will be even less
                        it->second["tertiary"] = 0.0;
                        continue;
                    }
                    if (it->first.find("esc") != std::string::npos)
                    {
                        // this is a escape line -> the contribution to be used is the one of
                        // the originating line that should already be calculated
                        key = it->first.substr(0, it->first.find(" "));
                        tertiary = (it->second["primary"] + it->second["secondary"]) * \
                                   (actualResultIt->second[iLayer][key]["tertiary"] /  \
                                   (actualResultIt->second[iLayer][key]["primary"] +   \
                                    actualResultIt->second[iLayer][key]["secondary"]));
                    }
                    else
                    {
                        for (contributingKeysIt = contributingKeys.begin(); \
                             contributingKeysIt != contributingKeys.end(); ++contributingKeysIt)
                        {
                            if (it->second.find(contributingKeysIt->first) != it->second.end())
                            {
                                tertiary += it->second[contributingKeysIt->first] * \
                                            (contributingKeysIt->second - 1.0);
                            }
                        }
                    }
                    it->second["tertiary"] = tertiary;
                    // update the total rate to account for primary, secondary and tertiary
                    // rate was equal to (primary + secondary) times a certain efficiency factor
                    // rate = A * (primary + secondary) therefore  now we must update the rate to
                    // account for tertiary rate = A * (primary + secondary + tertiary)
                    it->second["rate"] *= (tertiary + it->second["primary"] + it->second["secondary"]) \
                                          / (it->second["primary"] + it->second["secondary"]);
                }
            }
        }
    }
    this->lastMultilayerFluorescence = actualResult;
    return actualResult;
}

} // namespace fisx