MaterialEffectsUpdator.cxx 36.8 KB
Newer Older
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
/*
  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/

///////////////////////////////////////////////////////////////////
// MaterialEffectsUpdator.cxx, (c) ATLAS Detector software
///////////////////////////////////////////////////////////////////

// Trk include
#include "TrkExTools/MaterialEffectsUpdator.h"
#include "TrkExInterfaces/IEnergyLossUpdator.h"
#include "TrkExInterfaces/IMultipleScatteringUpdator.h"
#include "TrkDetDescrInterfaces/IMaterialMapper.h"
#include "TrkParameters/TrackParameters.h"
#include "TrkEventPrimitives/ParamDefs.h"
#include "TrkEventPrimitives/DefinedParameter.h"
#include "TrkSurfaces/Surface.h"
#include "TrkGeometry/Layer.h"
#include "TrkGeometry/CompoundLayer.h"
#include "TrkGeometry/MaterialProperties.h"
#include "TrkGeometry/AssociatedMaterial.h"
#include "TrkGeometry/TrackingVolume.h"
#include "TrkMaterialOnTrack/MaterialEffectsOnTrack.h"
#include "TrkMaterialOnTrack/EnergyLoss.h"
#include "TrkMaterialOnTrack/ScatteringAngles.h"
// Validation mode - TTree includes
#include "TTree.h"
#include "GaudiKernel/ITHistSvc.h" 
// Amg
#include "EventPrimitives/EventPrimitives.h"
#include "GeoPrimitives/GeoPrimitives.h"

// statics doubles 
Trk::ParticleMasses Trk::MaterialEffectsUpdator::s_particleMasses;

// constructor
Trk::MaterialEffectsUpdator::MaterialEffectsUpdator(const std::string& t, const std::string& n, const IInterface* p) :
  AthAlgTool(t,n,p),
//  TrkParametersManipulator(),
  m_eLossUpdator("Trk::EnergyLossUpdator/AtlasEnergyLossUpdator"),
  m_msUpdator("Trk::MultipleScatteringUpdator/AtlasMultipleScatteringUpdator"),
  m_materialMapper("Trk::MaterialMapper/AtlasMaterialMapper"),
  m_doCompoundLayerCheck(false),
  m_doEloss(true),
  m_doMs(true),
  m_momentumCut(50.*Gaudi::Units::MeV),
  m_momentumMax(10.*Gaudi::Units::TeV),
  m_forceMomentum(false),
  m_forcedMomentum(2000.*Gaudi::Units::MeV),
  m_xKalmanStraggling(false),
  m_useMostProbableEloss(false),
  m_msgOutputValidationDirection(true),
  m_msgOutputCorrections(false),
  m_validationMode(false),
  m_validationIgnoreUnmeasured(true),
  m_landauMode(false),
  m_validationDirection(1),
  m_validationLayer(0),
  m_validationSteps(0),
  m_validationPhi(0.),
  m_validationEta(0.),
  m_accumulatedElossSigma(0.)
{
      declareInterface<IMaterialEffectsUpdator>(this);
      // configuration (to be changed to new genconf style)
      declareProperty("CheckForCompoundLayers"              , m_doCompoundLayerCheck);
      declareProperty("EnergyLoss"                          , m_doEloss);
      declareProperty("EnergyLossUpdator"                   , m_eLossUpdator);
      declareProperty("MultipleScattering"                  , m_doMs);
      declareProperty("MultipleScatteringUpdator"           , m_msUpdator);
      // the momentum cut for particle interactions
      declareProperty("MinimalMomentum"                     , m_momentumCut );
      declareProperty("MaximalMomentum"                     , m_momentumMax );
      declareProperty("ForceMomentum"                       , m_forceMomentum );
      declareProperty("ForcedMomentumValue"                 , m_forcedMomentum );
      declareProperty("MostProbableEnergyLoss"              , m_useMostProbableEloss );
      declareProperty("ScreenOutputValidationDirection"     , m_msgOutputValidationDirection );
      declareProperty("ScreenOutputCorrections"             , m_msgOutputCorrections );
      // run validation mode true/false
      declareProperty("ValidationMode"                      , m_validationMode );
      declareProperty("ValidationIgnoreUnmeasured"          , m_validationIgnoreUnmeasured );
      declareProperty("ValidationDirection"                 , m_validationDirection );
      declareProperty("ValidationMaterialMapper"            , m_materialMapper);
      declareProperty("LandauMode"                          , m_landauMode );

}

// destructor
Trk::MaterialEffectsUpdator::~MaterialEffectsUpdator()
{}

// Athena standard methods
// initialize
StatusCode Trk::MaterialEffectsUpdator::initialize()
{
    ATH_MSG_INFO( "Minimal momentum cut for material update : " << m_momentumCut << " MeV" );

    // retrieve the EnergyLoss Updator and Material Effects updator    
    if (m_doEloss) {
      if ( m_eLossUpdator.retrieve().isFailure() ) {
        ATH_MSG_FATAL( "Failed to retrieve tool " << m_eLossUpdator << ". No multiple scattering effects will be taken into account." );
        m_doEloss = false;
        return StatusCode::FAILURE;
      } else 
        ATH_MSG_INFO( "Retrieved tool " << m_eLossUpdator );
    } 
    
    if (m_doMs) {
      if ( m_msUpdator.retrieve().isFailure() ) {
        ATH_MSG_FATAL("Failed to retrieve tool " << m_msUpdator << ". No energy loss effects will be taken into account." );
        m_doMs = false;
        return StatusCode::FAILURE;
      } else
        ATH_MSG_INFO( "Retrieved tool " << m_msUpdator );
    } 

    // retrieve the material mapper for the validation mode
    if (m_validationMode) {
      if ( m_materialMapper.retrieve().isFailure() ) {
        ATH_MSG_FATAL("Failed to retrieve tool " << m_materialMapper << ". No material recording." );
        return StatusCode::FAILURE;
      } else
        ATH_MSG_INFO( "Retrieved tool " << m_materialMapper );
    }

    return StatusCode::SUCCESS;
}

// finalize
StatusCode Trk::MaterialEffectsUpdator::finalize()
{
    ATH_MSG_INFO( "finalize() successful" );
    return StatusCode::SUCCESS;
}

const Trk::TrackParameters*  Trk::MaterialEffectsUpdator::update(const TrackParameters* parm,
                                                                 const Layer& lay,
                                                                 PropDirection dir,
                                                                 ParticleHypothesis particle,
                                                                 MaterialUpdateMode matupmode) const
{      

  // no material properties - pass them back
  if (particle==Trk::geantino || particle==Trk::nonInteractingMuon || (!m_doMs && !m_doEloss) || !lay.isOnLayer(parm->position()) ) return(parm);

  // get the quantities
  const Trk::MaterialProperties* mprop = lay.fullUpdateMaterialProperties(*parm);
  if ( !mprop ) return(parm);

  // get the real pathlength
151
  double pathCorrection = fabs(lay.surfaceRepresentation().pathCorrection(parm->position(),parm->momentum()));
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

  // set the output if restricted to the validation direction 
  bool outputFlag = m_msgOutputValidationDirection ?  dir == int(m_validationDirection) : true;
  
  //--------------------------------------------------------------------------------------------------  
  if (msgLvl(MSG::VERBOSE) && outputFlag){
    double layerR = lay.surfaceRepresentation().bounds().r();
    double layerZ = lay.surfaceRepresentation().center().z();
    double eta    = parm->momentum().eta();
    double sX0    = mprop->thicknessInX0();
    double tX0    = pathCorrection*mprop->thicknessInX0();
    ATH_MSG_VERBOSE( "  [M] full material update,  layer with [r,z] = [ " << layerR << ", " << layerZ << " ] - Index " <<  lay.layerIndex() );
    ATH_MSG_VERBOSE( "      thickness/X0 , path/X0  (eta: g.factor) = " << sX0 << " , " << tX0 << " (" << eta << ": " << pathCorrection << ")");
  }
  //--------------------------------------------------------------------------------------------------

  m_validationLayer = (m_validationMode) ? &lay : 0;

  return (update(parm,*mprop, pathCorrection, dir, particle,matupmode));
}

const Trk::TrackParameters*  Trk::MaterialEffectsUpdator::update( const TrackParameters* parm,
                                                                  const MaterialEffectsOnTrack& meff,
                                                                  ParticleHypothesis particle,
                                                                  MaterialUpdateMode matupmode) const
{

  // no material properties - pass them back
  // TODO, if the parm doesn't have a surface (i.e. its in
  // curvilinear) then should we fall through?
  if (particle==Trk::geantino || particle==Trk::nonInteractingMuon || (!m_doMs && !m_doEloss) ||
      !(&parm->associatedSurface()) || parm->associatedSurface()!=meff.associatedSurface()) return(parm);


  // get the kinematics
  double              p = parm->momentum().mag();
  double updateMomentum = (m_forceMomentum) ? m_forcedMomentum : p;
  double m    = s_particleMasses.mass[particle];
  double E    = sqrt(p*p+m*m);
  double beta = p/E;

  double pathcorrection = 1.;  //Trick the MultipleScatteringUpdator interface

  double energyLoss = 0;
  double energyLossSigma = 0;

  if (meff.energyLoss() != NULL) {
    energyLoss      = meff.energyLoss()->deltaE();
    energyLossSigma = meff.energyLoss()->sigmaDeltaE();
  }

  // update for mean energy loss
  double newP          = p;
  double sigmaQoverP   = 0;
  double sigmaQoverPSq = 0;

  //Landaus mpvs don't just add, if in Landau mode we need to do a different update
  if (m_landauMode && m_accumulatedElossSigma != 0 && energyLossSigma != 0) {
    if(energyLoss>0) energyLoss += energyLossSigma*log(1+m_accumulatedElossSigma/(energyLossSigma))
                + m_accumulatedElossSigma*log(1+energyLossSigma/m_accumulatedElossSigma);
    else energyLoss -= energyLossSigma*log(1+m_accumulatedElossSigma/energyLossSigma)
            + m_accumulatedElossSigma*log(1+energyLossSigma/m_accumulatedElossSigma);
    m_accumulatedElossSigma += energyLossSigma;
  } else if (m_landauMode) {
    m_accumulatedElossSigma += energyLossSigma;    
  }

  double qOverPnew = parm->parameters()[Trk::qOverP];

  if (p > m_momentumCut && p < m_momentumMax && m_doEloss) {
    double newP2 = (E+energyLoss)*(E+energyLoss)-m*m;
    if (newP2 < m_momentumCut*m_momentumCut) return 0; // protect FPE
    if (E+energyLoss < -m) return 0; // protect against flip in correction
    newP = sqrt(newP2);
    sigmaQoverP = energyLossSigma/(beta*p*p);
    sigmaQoverPSq = sigmaQoverP*sigmaQoverP;
    qOverPnew = parm->charge()/newP;
  }
  Trk::DefinedParameter qOverPmod(qOverPnew, Trk::qOverP); 

  // check if Parameters are measured parameters
  // the updatedParameters - first a copy
  const Trk::TrackParameters* mpars = parm;
  AmgVector(5) updatedParameters(mpars->parameters());
  AmgSymMatrix(5)* updatedCovariance = 0;
  // initialize ErrorMatrix pointer
  if (mpars || (m_validationMode && !m_validationIgnoreUnmeasured) ){
    // the new CovarianceMatrix - a copy first
    updatedCovariance = mpars->covariance() ? new AmgSymMatrix(5)(*mpars->covariance()) : 0;

    double angularVariation = 0;
    double sigmaDeltaPhiSq = 0;
    double sigmaDeltaThetaSq = 0;

    if(m_doMs){
      //If the meff has scattering angles use those, otherwise use MEffUpdator
      if(meff.scatteringAngles() == NULL){
       //Trick to keep using existing MultipleScatteringUpdator interface
       //Here we know the path length to be meff.thicknessX0, so we set pathcorrection = 1
       //and create a dummy materialProperties with the properties we are interested in
	MaterialProperties mprop(meff.thicknessInX0(),1.,0.,0.,0.,0.);
       double angularVariation = m_msUpdator->sigmaSquare(mprop, updateMomentum, pathcorrection, Trk::muon);  
       //sigmaDeltaPhiSq = angularVariation/(parm->sinTheta()*parm->sinTheta());
       sigmaDeltaPhiSq = angularVariation/(sin(parm->parameters()[Trk::theta])*sin(parm->parameters()[Trk::theta]));
       sigmaDeltaThetaSq = angularVariation;
     }else{
      // material update from mefots -> D.L.
      sigmaDeltaPhiSq = meff.scatteringAngles()->sigmaDeltaPhi();
      sigmaDeltaPhiSq *= sigmaDeltaPhiSq;
      sigmaDeltaThetaSq = meff.scatteringAngles()->sigmaDeltaTheta();
      sigmaDeltaThetaSq *= sigmaDeltaThetaSq;

     updatedParameters[Trk::phi]=parm->position().phi()  +meff.scatteringAngles()->deltaPhi();
     updatedParameters[Trk::theta]=parm->position().theta()+meff.scatteringAngles()->deltaTheta(); 


      }
    }
    // update the covariance entries - angular variation in phi has dependency on theta direction
    if (updatedCovariance){
    
          // sign of the noise adding -----------------------
          int sign = int(matupmode);
          // checks will only be done in the removeNoise mode
          
          (*updatedCovariance)(Trk::phi,Trk::phi)       += sign*sigmaDeltaPhiSq; 
          (*updatedCovariance)(Trk::theta,Trk::theta)   += sign*sigmaDeltaThetaSq; 
          if (!m_xKalmanStraggling && !m_landauMode)
             (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*sigmaQoverPSq;
          else if(m_xKalmanStraggling)
            { /* to be filled in*/  }
          else if(m_landauMode){
             //subtract what we added up till now and add what we should add up till now
             //Landau's 68% limit is approx 1.6*sigmaParameter
             (*updatedCovariance)(Trk::qOverP,Trk::qOverP) -= sign*std::pow(1.6*(m_accumulatedElossSigma-p*p*sigmaQoverP)/(p*p),2);
             (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*std::pow(1.6*m_accumulatedElossSigma/(newP*newP),2);
  
          }
        // the checks for the remove Noise mode -----------------------------------------------------
         if (matupmode == Trk::removeNoise && !checkCovariance(*updatedCovariance)){
            // the covariance is invalid      
            delete updatedCovariance; return 0;
         }   
                 
        // create the ErrorMatrix
       // updatedError = new Trk::ErrorMatrix(updatedCovariance);
      // -------------------------------------- screen output --------------------------------------
      if (m_msgOutputCorrections){
         double sigmaAngle = sqrt(angularVariation);
         ATH_MSG_VERBOSE( "    sigma(phi) / sigma(theta) = " << sigmaAngle/sin(parm->parameters()[Trk::theta]) << " / " << sigmaAngle );
         ATH_MSG_VERBOSE( "    deltaP / sigmaQoverP      = " << energyLoss << " / " << sigmaQoverP );
       }
      // -------------------------------------------------------------------------------------------
    }
    //----------------------------------------- validation section ----------------------------------
    // validation if configured
    if (m_validationMode && m_validationLayer)
      {
        // all you have from MaterialProperties        
        double pathInX0 = meff.thicknessInX0();

        Trk::AssociatedMaterial assMatHit(parm->position(),
                                          pathInX0,pathInX0,
                                          0,0,0,0,
                                          pathcorrection,
                                          m_validationLayer->enclosingTrackingVolume(),
                                          m_validationLayer);


         // record the Material hit ----------------------------------------------------------------
         m_materialMapper->recordMaterialHit(assMatHit, parm->position());

         // the steps
         m_validationSteps++;
         m_validationPhi += parm->position().phi();
         m_validationEta += parm->position().eta();
         // reset the validation layer
         m_validationLayer = 0;           

      }
    //----------------------------------------- validation section ----------------------------------
    
  }

  //parm = Trk::TrkParametersManipulator::manipulateParameter(parm, qOverPmod, updatedError);
  //return parm;
     updatedParameters[Trk::qOverP]=qOverPnew; 

  return parm->associatedSurface().createTrackParameters(updatedParameters[Trk::loc1],updatedParameters[Trk::loc2],
                                                    updatedParameters[Trk::phi],updatedParameters[Trk::theta],
                                                    updatedParameters[Trk::qOverP],updatedCovariance);
}

const Trk::TrackParameters*  Trk::MaterialEffectsUpdator::preUpdate(const TrackParameters* parm,
                                                                    const Layer& lay,
                                                                    PropDirection dir,
                                                                    ParticleHypothesis particle,
                                                                    MaterialUpdateMode matupmode) const
{  
  

  // no material properties - pass the parameters back
  if (particle==Trk::geantino || particle==Trk::nonInteractingMuon || (!m_doMs && !m_doEloss) ) return(parm);

  // get the split factor
  double preFactor = lay.preUpdateMaterialFactor(*parm, dir); 
  // return if the preFactor is less than one
  if (preFactor < 0.01) return(parm); 

  // get the material properties 
  const Trk::MaterialProperties* mprop =  0;

  // set the output if restricted to the validation direction 
  bool outputFlag = m_msgOutputValidationDirection ?  dir == int(m_validationDirection) : true;

  mprop = mprop ? mprop : lay.fullUpdateMaterialProperties(*parm);
368
  double pathCorrection = fabs(lay.surfaceRepresentation().pathCorrection(parm->position(),parm->momentum()));
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
  pathCorrection *= preFactor;

  // exit if no mprop could be assigned
  if (!mprop) return(parm);
  //--------------------------------------------------------------------------------------------------  
  if (outputFlag){
    double layerR = lay.surfaceRepresentation().bounds().r();
    double layerZ = lay.surfaceRepresentation().center().z();
    double eta    = parm->momentum().eta();
    double sX0    = mprop->thicknessInX0();
    double tX0    = pathCorrection*mprop->thicknessInX0();
    ATH_MSG_VERBOSE( "  [M] pre material update at layer with [r,z] = [ " << layerR << ", " << layerZ << " ] - Index " <<  lay.layerIndex() );
    ATH_MSG_VERBOSE( "      thickness/X0 , path/X0  (eta: g.factor) = " << sX0 << " , " << tX0 << " (" << eta << ": " << pathCorrection << ")");
  }
  //--------------------------------------------------------------------------------------------------

  m_validationLayer = (m_validationMode) ? &lay : 0;

  return (update(parm,*mprop, pathCorrection, dir, particle,matupmode)); 
}


const Trk::TrackParameters*  Trk::MaterialEffectsUpdator::postUpdate(const TrackParameters& parm,
                                                                     const Layer& lay,
                                                                     PropDirection dir,
                                                                     ParticleHypothesis particle,
                                                                     MaterialUpdateMode matupmode) const
{    
  
  // no material properties - pass the parameters back
399
  if (particle==Trk::geantino || particle==Trk::nonInteractingMuon || (!m_doMs && !m_doEloss) || !lay.isOnLayer(parm.position()) ) return(&parm);
400
401
402
403
404
405
  
  // get the quantities
  const Trk::MaterialProperties* mprop  = 0;
  double postFactor = lay.postUpdateMaterialFactor( parm, dir);

  // no material properties - pass them back
406
  if (postFactor < 0.01 ) return(&parm);
407
408
409
410
411

  // set the output if restricted to the validation direction 
  bool outputFlag = m_msgOutputValidationDirection ?  dir == int(m_validationDirection) : true;

  mprop = mprop ? mprop : lay.fullUpdateMaterialProperties(parm);
412
  double pathCorrection = fabs(lay.surfaceRepresentation().pathCorrection(parm.position(),parm.momentum())); 
413
414
415
  pathCorrection *= postFactor;
  
  // exit if no material properties
416
  if (!mprop) return(&parm);
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

  //--------------------------------------------------------------------------------------------------  
  if (outputFlag){
    double layerR = lay.surfaceRepresentation().bounds().r();
    double layerZ = lay.surfaceRepresentation().center().z();
    double eta    = parm.momentum().eta();
    double sX0    = mprop->thicknessInX0();
    double tX0    = pathCorrection*mprop->thicknessInX0();
    ATH_MSG_VERBOSE( "  [M] post material update,  layer with [r,z] = [ " << layerR << ", " << layerZ << " ] - Index " <<  lay.layerIndex() );
    ATH_MSG_VERBOSE( "      thickness/X0 , path/X0  (eta: g.factor) = " << sX0 << " , " << tX0 << " (" << eta << ": " << pathCorrection << ")");
  }
  //--------------------------------------------------------------------------------------------------
  m_validationLayer = (m_validationMode) ? &lay : 0;

  return (update(parm,*mprop, pathCorrection, dir, particle, matupmode)); 
}


// actual update method - manipulation
const Trk::TrackParameters*  Trk::MaterialEffectsUpdator::update(const TrackParameters* parm,
                                                                 const MaterialProperties& matprop,
                                                                 double pathcorrection,
                                                                 PropDirection dir,
                                                                 ParticleHypothesis particle,
                                                                 MaterialUpdateMode matupmode) const
{    

  // no material properties - pass them back
  if (particle==Trk::geantino || particle==Trk::nonInteractingMuon || (!m_doMs && !m_doEloss)) return((parm));
  
  // get the kinematics
  double              p = parm->momentum().mag();
  double updateMomentum = (m_forceMomentum) ? m_forcedMomentum : p;
  double m    = s_particleMasses.mass[particle];
  double E    = sqrt(p*p+m*m);
  double beta = p/E;

  // set the output if restricted to the validation direction
  bool outputFlag = m_msgOutputValidationDirection ?  dir == int(m_validationDirection) : true;

  // no material update below/above a certain cut value
  if (p > m_momentumCut && p < m_momentumMax) {
      // get the delta of the Energy
      EnergyLoss* energyLoss = (m_doEloss) ? 
                    m_eLossUpdator->energyLoss(matprop, updateMomentum, pathcorrection, dir, particle, m_useMostProbableEloss) :
                    0;
      // update for mean energy loss
      double deltaE      = energyLoss ? energyLoss->deltaE() : 0;
      double sigmaDeltaE = energyLoss ? energyLoss->sigmaDeltaE() : 0;
      delete energyLoss;
      if(m_landauMode && m_accumulatedElossSigma != 0 && sigmaDeltaE != 0){
	    if(dir == Trk::oppositeMomentum) deltaE += sigmaDeltaE*log(1+m_accumulatedElossSigma/sigmaDeltaE)
					        + m_accumulatedElossSigma*log(1+sigmaDeltaE/m_accumulatedElossSigma);
	    else deltaE -= sigmaDeltaE*log(1+m_accumulatedElossSigma/sigmaDeltaE)
	            + m_accumulatedElossSigma*log(1+sigmaDeltaE/m_accumulatedElossSigma);

	       m_accumulatedElossSigma += sigmaDeltaE;
      }else if(m_landauMode){
	       m_accumulatedElossSigma += sigmaDeltaE;
      }
      double newP2       = (E+deltaE)*(E+deltaE)-m*m;
      if (E+deltaE < -m) return 0; // protect against flip in correction
      if(newP2 < m_momentumCut*m_momentumCut) return 0; // protect against FPE
      double deltaP      = sqrt(newP2)-p;
      double sigmaQoverP = sigmaDeltaE/std::pow(beta*p,2);

      Trk::DefinedParameter qOverPmod(parm->charge()/(p+deltaP), Trk::qOverP); 
   
      // check if Parameters are measured parameters
      //const Trk::MeasuredTrackParameters* mpars = dynamic_cast<const Trk::MeasuredTrackParameters*>(parm);
      const Trk::TrackParameters* mpars = parm;
      AmgVector(5) updatedParameters(mpars->parameters());
      // initialize ErrorMatrix pointer
      //Trk::ErrorMatrix* updatedError      = 0;
        AmgSymMatrix(5)* updatedCovariance =0;
      if (mpars || (m_validationMode && !m_validationIgnoreUnmeasured) ) {
        // the new CovarianceMatrix - a copy first
         updatedCovariance = mpars->covariance() ? new AmgSymMatrix(5)(*mpars->covariance()) : 0;
        // only update if msUpdator exists
        double angularVariation = (m_doMs) ? m_msUpdator->sigmaSquare(matprop, updateMomentum, pathcorrection, particle) : 0.;  
        // update the covariance entries - angular variation in phi has dependency on theta direction
        if (updatedCovariance){
          
          // sign of the noise adding ----------------------------------------------------------------    
          int sign = int(matupmode);
          // checks will only be done in the removeNoise mode 
          
          (*updatedCovariance)(Trk::phi,Trk::phi)       += sign*angularVariation/(sin(parm->parameters()[Trk::theta])*sin(parm->parameters()[Trk::theta])); 
          (*updatedCovariance)(Trk::theta,Trk::theta)   += sign*angularVariation; 
                
          if (!m_xKalmanStraggling && !m_landauMode)
             (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*sigmaQoverP*sigmaQoverP;
          else if(m_xKalmanStraggling){
             double q    = parm->charge();
             (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*0.2*deltaP*deltaP*q*q*q*q;
          } else if(m_landauMode){
            //subtract what we added up till now and add what we should add up till now
            //Landau's 68% limit is approx 1.6*sigmaParameter
            (*updatedCovariance)(Trk::qOverP,Trk::qOverP) -= sign*std::pow(1.6*(m_accumulatedElossSigma-p*p*sigmaQoverP)/(p*p),2);
            (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*std::pow(1.6*m_accumulatedElossSigma/((p+deltaP)*(p+deltaP)),2);
          }
         // the checks for the remove Noise mode -----------------------------------------------------
         if (matupmode == Trk::removeNoise && !checkCovariance(*updatedCovariance)){
            // the covariance is invalid
            delete updatedCovariance; return 0;
         }

         // create the ErrorMatrix
         //updatedError = new Trk::ErrorMatrix(updatedCovariance);
         
         // -------------------------------------- screen output --------------------------------------
          if (outputFlag && m_msgOutputCorrections){
                double sigmaAngle = sqrt(angularVariation);
                ATH_MSG_VERBOSE( "    sigma(phi) / sigma(theta) = " << sigmaAngle/sin(parm->parameters()[Trk::theta])  << " / " << sigmaAngle );
                ATH_MSG_VERBOSE( "    deltaP / sigmaQoverP      = " << deltaP << " / " << sigmaQoverP );
         }
         // -------------------------------------------------------------------------------------------

         }
      //----------------------------------------- validation section ----------------------------------
      // validation if configured
      if (m_validationMode
          && dir==Trk::PropDirection(m_validationDirection)
          && m_validationLayer
	  && updatedCovariance)
       {
        // all you have from MaterialProperties
        double pathInX0 = pathcorrection*matprop.thicknessInX0();
        double A = 0.;
        double Z = 0.;
        double rho = 0.;
        double l0  = 0.;
        // or better take the extended version for more information
        const Trk::MaterialProperties* extProperties
              = dynamic_cast<const Trk::MaterialProperties*>(&matprop);

         if (extProperties){
             A   = extProperties->averageA();
             Z   = extProperties->averageZ();
             rho = extProperties->averageRho();
             l0  = extProperties->l0();
         }

        Trk::AssociatedMaterial assMatHit(parm->position(),
                                          pathInX0,matprop.x0(),
                                          l0,A,Z,rho,
                                          pathcorrection,
                                          m_validationLayer->enclosingTrackingVolume(),
                                          m_validationLayer);


         // record the Material hit ----------------------------------------------------------------
         m_materialMapper->recordMaterialHit(assMatHit,
                                             parm->position());
         // the steps
         m_validationSteps++;
         m_validationPhi   += parm->position().phi();
         m_validationEta   += parm->position().eta();
         // reset the validation layer
         m_validationLayer = 0;
       }
      //----------------------------------------- validation section ----------------------------------

      }
     // parm = Trk::TrkParametersManipulator::manipulateParameter(parm, qOverPmod, updatedError);
     updatedParameters[Trk::qOverP]=parm->charge()/(p+deltaP); 
     parm = parm->associatedSurface().createTrackParameters(updatedParameters[Trk::loc1],updatedParameters[Trk::loc2],
                                                    updatedParameters[Trk::phi],updatedParameters[Trk::theta],
                                                    updatedParameters[Trk::qOverP],updatedCovariance);


  }
  return parm;
}


// actual update method
const Trk::TrackParameters*  Trk::MaterialEffectsUpdator::update(const TrackParameters& parm,
                                                                 const MaterialProperties& matprop,
                                                                 double pathcorrection,
                                                                 PropDirection dir,
                                                                 ParticleHypothesis particle,
                                                                 MaterialUpdateMode matupmode) const
{    

  // no material properties - pass them back
  if (particle==Trk::geantino || (!m_doMs && !m_doEloss) ) return(&(parm));

  // get the kinematics
  double              p = parm.momentum().mag();
  double updateMomentum = (m_forceMomentum) ? m_forcedMomentum : p;
  double m    = s_particleMasses.mass[particle];
  double E    = sqrt(p*p+m*m);
  double beta = p/E;

  // set the output if restricted to the validation direction 
  bool outputFlag = m_msgOutputValidationDirection ?  dir == int(m_validationDirection) : true;

  // no material update below or above a certain cut value
  if (p > m_momentumCut && p < m_momentumMax) {
  
    // the updatedParameters - first a copy
    AmgVector(5) updatedParameters(parm.parameters());
  
    // get the delta of the Energy
    EnergyLoss* energyLoss = (m_doEloss) ? 
      m_eLossUpdator->energyLoss(matprop, updateMomentum, pathcorrection, dir, particle, m_useMostProbableEloss) :
      0;
    // update for mean energy loss
    double deltaE      = energyLoss ? energyLoss->deltaE() : 0;
    double sigmaDeltaE = energyLoss ? energyLoss->sigmaDeltaE() : 0;
    delete energyLoss;
    if(m_landauMode && m_accumulatedElossSigma != 0 && sigmaDeltaE != 0){
      if(dir == Trk::oppositeMomentum) deltaE += sigmaDeltaE*log(1+m_accumulatedElossSigma/sigmaDeltaE)
					 + m_accumulatedElossSigma*log(1+sigmaDeltaE/m_accumulatedElossSigma);
      else deltaE -= sigmaDeltaE*log(1+m_accumulatedElossSigma/sigmaDeltaE)
	     + m_accumulatedElossSigma*log(1+sigmaDeltaE/m_accumulatedElossSigma);
      
      m_accumulatedElossSigma += sigmaDeltaE;
    }else if(m_landauMode){
      m_accumulatedElossSigma += sigmaDeltaE;    
    }
    double newP2       = (E+deltaE)*(E+deltaE)-m*m;
    if (E+deltaE < -m) return 0; // protect against flip in correction
    if(newP2 < m_momentumCut*m_momentumCut) return 0; // protect against FPE
    double deltaP      = sqrt(newP2)-p;
    double sigmaQoverP = sigmaDeltaE/std::pow(beta*p,2);
    
    updatedParameters[Trk::qOverP] = parm.charge()/(p+deltaP); 

    // check if Parameters are measured parameters
    AmgSymMatrix(5)* updatedCovariance = 0;
    if (parm.covariance() || (m_validationMode && !m_validationIgnoreUnmeasured) ){
      // the new CovarianceMatrix - a copy first
      updatedCovariance = new AmgSymMatrix(5)(*parm.covariance());
      // only update if msUpdator exists
      double angularVariation = (m_doMs) ? m_msUpdator->sigmaSquare(matprop, updateMomentum, pathcorrection, particle) : 0.;  
      // update the covariance entries - angular variation in phi has dependency on theta direction
      // sign of the noise adding ----------------------------------------------------------------    
      int sign = int(matupmode);
      // checks will only be done in the removeNoise mode  
      
      (*updatedCovariance)(Trk::phi,Trk::phi)       += sign*angularVariation/(sin(parm.parameters()[Trk::theta])*sin(parm.parameters()[Trk::theta])); 
      (*updatedCovariance)(Trk::theta,Trk::theta)   += sign*angularVariation; 
       if (!m_xKalmanStraggling && !m_landauMode)
          (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*sigmaQoverP*sigmaQoverP;
       else if(m_xKalmanStraggling)
           { /* to be filled in*/  }
       else if(m_landauMode){
         //subtract what we added up till now and add what we should add up till now
        //Landau's 68% limit is best modeled by 1.6*sigmaParameter
	     (*updatedCovariance)(Trk::qOverP,Trk::qOverP) -= sign*std::pow(1.6*(m_accumulatedElossSigma-p*p*sigmaQoverP)/(p*p),2);
	     (*updatedCovariance)(Trk::qOverP,Trk::qOverP) += sign*std::pow(1.6*m_accumulatedElossSigma/((p+deltaP)*(p+deltaP)),2);
       }
      
      // the checks for the remove Noise mode -----------------------------------------------------
       if (matupmode == Trk::removeNoise && !checkCovariance(*updatedCovariance)){
          // the covariance is invalid      
          delete updatedCovariance; return 0;
       }  
      
       // create the ErrorMatrix         // -------------------------------------- screen output --------------------------------------
       if (outputFlag && m_msgOutputCorrections ){
              double sigmaAngle = sqrt(angularVariation);
              ATH_MSG_VERBOSE( "    sigma(phi) / sigma(theta) = " << sigmaAngle/sin(parm.parameters()[Trk::theta]) << " / " << sigmaAngle );
              ATH_MSG_VERBOSE( "    deltaP / sigmaQoverP      = " << deltaP << " / " << sigmaQoverP );
       }
      //----------------------------------------- validation section ----------------------------------
      // validation if configured
      if (m_validationMode 
          && dir==Trk::PropDirection(m_validationDirection)
          && m_validationLayer)
       {
        // all you have from MaterialProperties        
        double pathInX0 = pathcorrection*matprop.thicknessInX0();
        double A = 0.;
        double Z = 0.;
        double rho = 0.;
        double l0  = 0.;
        // or better take the extended version for more information
        const Trk::MaterialProperties* extProperties
              = dynamic_cast<const Trk::MaterialProperties*>(&matprop);

         if (extProperties){
             A   = extProperties->averageA();
             Z   = extProperties->averageZ();
             rho = extProperties->averageRho();
             l0  = extProperties->l0();
         }

        Trk::AssociatedMaterial assMatHit(parm.position(),
                                          pathInX0,matprop.x0(),
                                          l0,
                                          A,Z,rho,pathcorrection,
                                          m_validationLayer->enclosingTrackingVolume(),
                                          m_validationLayer);


         // record the Material hit ----------------------------------------------------------------
         m_materialMapper->recordMaterialHit(assMatHit,
                                             parm.position());



         // the steps
         m_validationSteps++;
         m_validationPhi += parm.position().phi();
         m_validationEta += parm.position().eta();
         // reset the validation layer
         m_validationLayer = 0;           

       }
      //----------------------------------------- validation section ----------------------------------

     }
//    return parm.cloneToNew(updatedParameters, updatedCovariance);
    
     return parm.associatedSurface().createTrackParameters(updatedParameters[Trk::loc1],updatedParameters[Trk::loc2],
                                                    updatedParameters[Trk::phi],updatedParameters[Trk::theta],
                                                    updatedParameters[Trk::qOverP],updatedCovariance);
  }
  return parm.clone();  
}


void Trk::MaterialEffectsUpdator::validationAction() const
{
    
745
746
  //if (m_validationMode && m_validationSteps)
  //      m_materialMapper->finalizeEvent(m_validationEta/m_validationSteps, m_validationPhi/m_validationSteps);
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

     m_validationEta   = 0.;
     m_validationPhi   = 0.;
     m_validationSteps = 0;

}

void Trk::MaterialEffectsUpdator::modelAction(const Trk::TrackParameters* /*parm*/) const
{
  //  if(!m_landauMode || parm == 0){
  m_accumulatedElossSigma = 0;
  return;
    //}
  /*  const Trk::MeasuredTrackParameters* mpars = dynamic_cast<const Trk::MeasuredTrackParameters*>(parm);
  // initialize ErrorMatrix pointer
  Trk::ErrorMatrix* updatedError      = 0;
  double p = parm->momentum().mag();
  Trk::DefinedParameter qOverPmod(parm->charge()/p, Trk::qOverP); 
  if (mpars){
    // the new CovarianceMatrix - a copy first
    Trk::CovarianceMatrix* updatedCovariance = new Trk::CovarianceMatrix(mpars->localErrorMatrix().covariance());
    // update the covariance entries - angular variation in phi has dependency on theta direction
    (*updatedCovariance)[Trk::qOverP][Trk::qOverP] += m_accumulatedElossSigma*m_accumulatedElossSigma/(p*p*p*p);
    updatedError = new Trk::ErrorMatrix(updatedCovariance);

    Trk::TrkParametersManipulator::manipulateParameter(parm, qOverPmod, updatedError);
    }*/
}


bool Trk::MaterialEffectsUpdator::checkCovariance(AmgSymMatrix(5)& updated) const
{
   if ( updated(Trk::phi,Trk::phi) > 0. && updated(Trk::theta,Trk::theta) > 0. && updated(Trk::qOverP,Trk::qOverP) > 0.)
     return true;
   
   // given an update 
   ATH_MSG_DEBUG( "  [-] update material with 'removeNoise' results in negative covariance entries. Skipping update." );
   return false;
}