TRT_ToT_dEdx.cxx 67.9 KB
Newer Older
1
2
3
4
/*
  Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/

5
6
7
//
//  !!!!!! Problem with calibration constants for mean ToT on the tracks (norm_ ...) !!!!!!!
//
8
9
10
11
12
13
14
15
16
17
18
19
#include "TRT_ToT_Tools/TRT_ToT_dEdx.h"
#include "TRT_ToT_Tools/TRT_ToT_Corrections.h"


#include "GaudiKernel/MsgStream.h"
#include "GaudiKernel/AlgFactory.h"
#include "GaudiKernel/IToolSvc.h"
#include "StoreGate/StoreGateSvc.h"

#include "InDetIdentifier/TRT_ID.h"
#include "InDetRIO_OnTrack/TRT_DriftCircleOnTrack.h"
#include "InDetReadoutGeometry/TRT_DetectorManager.h"
20
#include "xAODEventInfo/EventInfo.h"
21
22
23
24
25

#include "GaudiKernel/IChronoStatSvc.h"

#include "TF1.h"

26
27
28
29
30
31
#include "AthenaPoolUtilities/CondAttrListCollection.h"
#include "AthenaPoolUtilities/AthenaAttributeList.h"
#include "CoralBase/AttributeListSpecification.h"
#include "AthenaPoolUtilities/CondAttrListVec.h"
#include "StoreGate/DataHandle.h"

32

33
// constructor
34
35
36
37
TRT_ToT_dEdx::TRT_ToT_dEdx(const std::string& t, const std::string& n, const IInterface* p)
  :
  AthAlgTool(t,n,p),
  m_TRTStrawSummarySvc("InDetTRTStrawStatusSummarySvc",n)
38
{
39
40
41
42
43
44
45
	declareInterface<ITRT_ToT_dEdx>(this);
	declareProperty("TRTStrawSummarySvc",    m_TRTStrawSummarySvc);

	SetDefaultConfiguration();

	m_isData  = true;
	m_gasTypeInStraw = kUnset;
46
47
48
}


49
50
51
52
53
54

void TRT_ToT_dEdx::SetDefaultConfiguration()
{
	declareProperty("TRT_dEdx_divideByL",m_divideByL=true);
	declareProperty("TRT_dEdx_useHThits",m_useHThits=true);
	declareProperty("TRT_dEdx_corrected",m_corrected=true);
55
	declareProperty("TRT_dEdx_whichToTEstimatorAlgo",m_whichToTEstimatorAlgo=kToTLargerIsland);
56
	declareProperty("TRT_dEdx_useTrackPartWithGasType",m_useTrackPartWithGasType=kUnset);
57
58
59
60
	declareProperty("TRT_dEdx_toolScenario",m_toolScenario=kAlgReweightTrunkOne);
	declareProperty("TRT_dEdx_applyMimicToXeCorrection",m_applyMimicToXeCorrection=false);
	declareProperty("TRT_dEdx_trackConfig_maxRtrack",m_trackConfig_maxRtrack=1.85);
	declareProperty("TRT_dEdx_trackConfig_minRtrack",m_trackConfig_minRtrack=0.15);
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
	declareProperty("TRT_dEdx_useZeroRHitCut",m_useZeroRHitCut=true);
}



void TRT_ToT_dEdx::ShowDEDXSetup() const
{
	ATH_MSG_DEBUG("//////////////////////////////////////////////////////////////////");
	ATH_MSG_DEBUG("///              TRT_ToT_Tool setup configuration              ///");
	ATH_MSG_DEBUG(" ");
	ATH_MSG_DEBUG("m_divideByL                     ="<<m_divideByL<<"");
	ATH_MSG_DEBUG("m_useHThits                     ="<<m_useHThits<<"");
	ATH_MSG_DEBUG("m_corrected                     ="<<m_corrected<<"");
	ATH_MSG_DEBUG("m_whichToTEstimatorAlgo         ="<<m_whichToTEstimatorAlgo<<"");
	ATH_MSG_DEBUG("m_useTrackPartWithGasType       ="<<m_useTrackPartWithGasType<<"");
	ATH_MSG_DEBUG("m_toolScenario                  ="<<m_toolScenario<<"");
	ATH_MSG_DEBUG("m_applyMimicToXeCorrection      ="<<m_applyMimicToXeCorrection<<"");
	ATH_MSG_DEBUG(" ");
	ATH_MSG_DEBUG("m_trackConfig_minRtrack         ="<<m_trackConfig_minRtrack<<"");
	ATH_MSG_DEBUG("m_trackConfig_maxRtrack         ="<<m_trackConfig_maxRtrack<<"");
	ATH_MSG_DEBUG("m_useZeroRHitCut                ="<<m_useZeroRHitCut<<"");
	ATH_MSG_DEBUG(" ");
	ATH_MSG_DEBUG("//////////////////////////////////////////////////////////////////");
}



88
89
90
91
// destructor
TRT_ToT_dEdx::~TRT_ToT_dEdx() {}


92

93
// initialize
94
95
StatusCode TRT_ToT_dEdx::initialize() 
{
96
97
98
99
100
101
102

  MsgStream log(msgSvc(), name());
  
  // retrieve TRT-ID helper
  StoreGateSvc* detStore = 0;
  StatusCode sc = service( "DetectorStore", detStore );
  if (sc.isFailure()){
103
    ATH_MSG_ERROR ( "Could not get DetectorStore" );
104
105
    return sc;
  }
106
  
107
108
  sc = detStore->retrieve(m_trtId, "TRT_ID");
  if (sc.isFailure()){
109
    ATH_MSG_ERROR ( "Could not get TRT_ID helper !" );
110
111
112
113
114
    return StatusCode::FAILURE;
  }

  sc = detStore->retrieve(m_trtman, "TRT");
  if (sc.isFailure()){
115
    ATH_MSG_ERROR ( "Could not get TRT detector manager !" );
116
117
118
119
120
121
    return StatusCode::FAILURE;
  }

  m_timingProfile=0;
  sc = service("ChronoStatSvc", m_timingProfile);
  if ( sc.isFailure() || 0 == m_timingProfile) {
122
    ATH_MSG_DEBUG ("Can not find ChronoStatSvc name="<<m_timingProfile );
123
  }
124
125
126
127
 
  const DataHandle<CondAttrListVec> aptr;
  std::string folderName = {"/TRT/Calib/ToT/ToTVectors"};
  if (StatusCode::SUCCESS == detStore->regFcn(&TRT_ToT_dEdx::update,this,aptr,folderName)){
128
    ATH_MSG_DEBUG ("Registered callback for ToT");
129
  }else{
130
	ATH_MSG_ERROR ("Callback registration failed for /TRT/Calib/ToT/ToTVectors ");
131
  }
132

133
134
135
136
137
138
139
  const DataHandle<CondAttrListCollection> affectedRegionH;
  if (detStore->regFcn(&TRT_ToT_dEdx::update2,this,affectedRegionH,"/TRT/Calib/ToT/ToTValue").isSuccess()){
	ATH_MSG_DEBUG ( "Registered callback for  /TRT/Calib/ToT/ToTValue " );
  }else{
	ATH_MSG_WARNING ( "Cannot register callback for /TRT/Calib/ToT/ToTValue " );
  }

140
141
142
143
144
145
146
147
 
 //|-TRTStrawSummarySvc     = ServiceHandle('InDetTRTStrawStatusSummarySvc')
 sc = m_TRTStrawSummarySvc.retrieve();
  if (StatusCode::SUCCESS!= sc ){
    ATH_MSG_ERROR ("Failed to retrieve StrawStatus Summary " << m_TRTStrawSummarySvc);
    ATH_MSG_ERROR ("configure as 'None' to avoid its loading.");
    return sc;
  } else {
148
149
    if ( !m_TRTStrawSummarySvc.empty() ) 
      ATH_MSG_INFO ( "Retrieved tool " << m_TRTStrawSummarySvc );
150
151
  }

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
  ATH_MSG_INFO("//////////////////////////////////////////////////////////////////");
  ATH_MSG_INFO("///              TRT_ToT_Tool setup configuration              ///");
  ATH_MSG_INFO(" ");
  ATH_MSG_INFO("m_divideByL                     ="<<m_divideByL<<"");
  ATH_MSG_INFO("m_useHThits                     ="<<m_useHThits<<"");
  ATH_MSG_INFO("m_corrected                     ="<<m_corrected<<"");
  ATH_MSG_INFO("m_whichToTEstimatorAlgo         ="<<m_whichToTEstimatorAlgo<<"");
  ATH_MSG_INFO("m_useTrackPartWithGasType       ="<<m_useTrackPartWithGasType<<"");
  ATH_MSG_INFO("m_toolScenario                  ="<<m_toolScenario<<"");
  ATH_MSG_INFO("m_applyMimicToXeCorrection      ="<<m_applyMimicToXeCorrection<<"");
  ATH_MSG_INFO(" ");
  ATH_MSG_INFO("m_trackConfig_minRtrack         ="<<m_trackConfig_minRtrack<<"");
  ATH_MSG_INFO("m_trackConfig_maxRtrack         ="<<m_trackConfig_maxRtrack<<"");
  ATH_MSG_INFO("m_useZeroRHitCut                ="<<m_useZeroRHitCut<<"");
  ATH_MSG_INFO(" ");
  ATH_MSG_INFO("//////////////////////////////////////////////////////////////////");

  ATH_MSG_INFO ( name() << " initialize() successful" );    
170
171
172
  return StatusCode::SUCCESS;
}

173
174
175
176


StatusCode TRT_ToT_dEdx::finalize() 
{
177
  MsgStream log(msgSvc(), name());
178
  ATH_MSG_DEBUG ( "... in finalize() ..." );
179
180
181
182
183
  if(m_timingProfile)m_timingProfile->chronoPrint("TRT_ToT_dEdx"); //MJ
  return StatusCode::SUCCESS;
}


184
185
186

// callback for DB for arrays
StatusCode TRT_ToT_dEdx::update(int& /*i*/ , std::list<std::string>& /*l*/) 
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
	StoreGateSvc* detStore = 0;
	StatusCode sc = service( "DetectorStore", detStore );

	std::vector<std::string>  dict_names = {"para_end_corrRZLXe","para_end_corrRZ_Xe","para_end_mimicToXeXe","para_long_corrRZLXe","para_long_corrRZ_Xe","para_long_mimicToXeXe","para_short_corrRZLXe","para_short_corrRZ_Xe","para_short_mimicToXeXe","resolution_Xe","resolution_e_Xe","para_end_corrRZLAr","para_end_corrRZ_Ar","para_end_mimicToXeAr","para_long_corrRZLAr","para_long_corrRZ_Ar","para_long_mimicToXeAr","para_short_corrRZLAr","para_short_corrRZ_Ar","para_short_mimicToXeAr","resolution_Ar","resolution_e_Ar","para_end_corrRZLKr","para_end_corrRZ_Kr","para_end_mimicToXeKr","para_long_corrRZLKr","para_long_corrRZ_Kr","para_long_mimicToXeKr","para_short_corrRZLKr","para_short_corrRZ_Kr","para_short_mimicToXeKr","resolution_Kr","resolution_e_Kr"};
	std::map<std::string,std::vector<float> > result_dict;

	const DataHandle<CondAttrListVec> channel_values;

	if (StatusCode::SUCCESS == detStore->retrieve(channel_values, "/TRT/Calib/ToT/ToTVectors" ))
	{
		int dataBaseType = kNewDB;
		ATH_MSG_DEBUG("update():: dict_names[]="<<dict_names.size()<<", channel_values[]="<<channel_values->size()<<"");
		if(channel_values->size()<19695) 
			dataBaseType = kOldDB; 

		if(dataBaseType==kNewDB) 
		{
			CondAttrListVec::const_iterator first_channel = channel_values->begin();
			CondAttrListVec::const_iterator last_channel  = channel_values->end();

			unsigned int current_channel = 0;
			std::vector<float> current_array_values = {};

			for (; first_channel != last_channel; ++first_channel) {
				if (current_channel != first_channel->first){
					result_dict[dict_names[current_channel]] = current_array_values;
					current_channel = first_channel->first;      
					current_array_values.clear();
				}
				current_array_values.push_back(first_channel->second["array_value"].data<float>());		
			}
			
220
221
222
223
224
			// protection for longer vectors present in newer DB tags
			if (current_channel < dict_names.size()) {
			  result_dict[dict_names[current_channel]] = current_array_values;
			}

225
226
227
228
229
230
231
232
233
			update_New(result_dict);
			ATH_MSG_DEBUG ("update():: Reading new database is done!");

			return StatusCode::SUCCESS;
		
		} else 
		if(dataBaseType==kOldDB) 
		{
			ATH_MSG_WARNING ("update():: Old COOL database tag!");
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
			std::vector<std::string>  dict_names_old = {"resolution","resolution_e","para_long_corrRZ_MC","para_short_corrRZ_MC","para_end_corrRZ_MC","para_long_corrRZL_MC","para_short_corrRZL_MC","para_end_corrRZL_MC"};
	
			CondAttrListVec::const_iterator first_channel = channel_values->begin();
			CondAttrListVec::const_iterator last_channel  = channel_values->end();

			unsigned int current_channel = 0;
			std::vector<float> current_array_values = {};

			for (; first_channel != last_channel; ++first_channel) 
			{
				if (current_channel != first_channel->first)
				{
					result_dict[dict_names_old[current_channel]] = current_array_values;
					current_channel = first_channel->first;      
					current_array_values.clear();
				}
				current_array_values.push_back(first_channel->second["array_value"].data<float>());		
			}
			
			result_dict[dict_names_old[current_channel]] = current_array_values;

			update_Old(result_dict);
			ATH_MSG_DEBUG ("update():: Reading old database is done!");

			return StatusCode::SUCCESS;
		}
		else {
			ATH_MSG_ERROR ("Problem reading condDB object. dataBaseType="<<dataBaseType<<"");
	    return StatusCode::FAILURE;
		}
	}
	else {
		ATH_MSG_ERROR ("Problem reading condDB object. -");
		return StatusCode::FAILURE;
	}

	return StatusCode::SUCCESS;
}



void TRT_ToT_dEdx::update_New(std::map<std::string,std::vector<float> > &result_dict) 
{
	//	fill Xenon +++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
	for (unsigned int ind=0; ind < 4; ++ind) {
		Dedxcorrection::resolution[0][ind]=result_dict["resolution_Xe"][ind];
	}

	for (unsigned int ind=0; ind < 4; ++ind) {
		Dedxcorrection::resolution_e[0][ind]=result_dict["resolution_e_Xe"][ind];
	}

	for (unsigned int ind=0; ind < 3240; ++ind) {
		Dedxcorrection::para_long_corrRZ_MC[0][ind]=result_dict["para_long_corrRZ_Xe"][ind];
	}

	for (unsigned int ind=0; ind < 216; ++ind) {
		Dedxcorrection::para_short_corrRZ_MC[0][ind]=result_dict["para_short_corrRZ_Xe"][ind];
	}

	for (unsigned int ind=0; ind < 630; ++ind) {
		Dedxcorrection::para_long_corrRZL_MC[0][ind]=result_dict["para_long_corrRZLXe"][ind];
	}

	for (unsigned int ind=0; ind < 63; ++ind) {
		Dedxcorrection::para_short_corrRZL_MC[0][ind]=result_dict["para_short_corrRZLXe"][ind];
	}

	for (unsigned int ind=0; ind < 252; ++ind) {
		Dedxcorrection::para_end_corrRZL_MC[0][ind]=result_dict["para_end_corrRZLXe"][ind];
	}
306

307
308
309
	for (unsigned int ind=0; ind < 3240; ++ind) {
		Dedxcorrection::para_long_corrRZ[0][ind]=result_dict["para_long_corrRZ_Xe"][ind];
	}
310

311
312
313
	for (unsigned int ind=0; ind < 216; ++ind) {
		Dedxcorrection::para_short_corrRZ[0][ind]=result_dict["para_short_corrRZ_Xe"][ind];
	}
314

315
316
317
	for (unsigned int ind=0; ind < 630; ++ind) {
		Dedxcorrection::para_long_corrRZL_DATA[0][ind]=result_dict["para_long_corrRZLXe"][ind];
	}
318

319
320
321
	for (unsigned int ind=0; ind < 63; ++ind) {
		Dedxcorrection::para_short_corrRZL_DATA[0][ind]=result_dict["para_short_corrRZLXe"][ind];
	}
322

323
324
325
326
327
328
329
330
331
332
333
	for (unsigned int ind=0; ind < 252; ++ind) {
		Dedxcorrection::para_end_corrRZL_DATA[0][ind]=result_dict["para_end_corrRZLXe"][ind];
	}

	for (unsigned int ind=0; ind < 336; ++ind) {
		Dedxcorrection::para_end_corrRZ[0][ind]=result_dict["para_end_corrRZ_Xe"][ind];
	}

	for (unsigned int ind=0; ind < 336; ++ind) {
		Dedxcorrection::para_end_corrRZ_MC[0][ind]=result_dict["para_end_corrRZ_Xe"][ind];
	}
334
335

	
336
337
338
339
340
341
342
343
344
345
346
347
348
		
	for (unsigned int ind=0; ind < 560; ++ind) {
		Dedxcorrection::para_end_mimicToXe_DATA[0][ind]=result_dict["para_end_mimicToXeXe"][ind];
	}
	for (unsigned int ind=0; ind < 560; ++ind) {
		Dedxcorrection::para_end_mimicToXe_MC[0][ind]=result_dict["para_end_mimicToXeXe"][ind];
	}
	for (unsigned int ind=0; ind < 180; ++ind) {
		Dedxcorrection::para_short_mimicToXe_DATA[0][ind]=result_dict["para_short_mimicToXeXe"][ind];
	}
	for (unsigned int ind=0; ind < 180; ++ind) {
		Dedxcorrection::para_short_mimicToXe_MC[0][ind]=result_dict["para_short_mimicToXeXe"][ind];
	}
349
	for (unsigned int ind=0; ind < 1080; ++ind) {
350
351
		Dedxcorrection::para_long_mimicToXe_DATA[0][ind]=result_dict["para_long_mimicToXeXe"][ind];
	}
352
	for (unsigned int ind=0; ind < 1080; ++ind) {
353
354
		Dedxcorrection::para_long_mimicToXe_MC[0][ind]=result_dict["para_long_mimicToXeXe"][ind];
	}
355

356
357
358
	//	fill Argon +++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
	for (unsigned int ind=0; ind < 4; ++ind) {
		Dedxcorrection::resolution[1][ind]=result_dict["resolution_Ar"][ind];
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

	for (unsigned int ind=0; ind < 4; ++ind) {
		Dedxcorrection::resolution_e[1][ind]=result_dict["resolution_e_Ar"][ind];
	}

	for (unsigned int ind=0; ind < 3240; ++ind) {
		Dedxcorrection::para_long_corrRZ_MC[1][ind]=result_dict["para_long_corrRZ_Ar"][ind];
	}

	for (unsigned int ind=0; ind < 216; ++ind) {
		Dedxcorrection::para_short_corrRZ_MC[1][ind]=result_dict["para_short_corrRZ_Ar"][ind];
	}

	for (unsigned int ind=0; ind < 630; ++ind) {
		Dedxcorrection::para_long_corrRZL_MC[1][ind]=result_dict["para_long_corrRZLAr"][ind];
	}

	for (unsigned int ind=0; ind < 63; ++ind) {
		Dedxcorrection::para_short_corrRZL_MC[1][ind]=result_dict["para_short_corrRZLAr"][ind];
	}

	for (unsigned int ind=0; ind < 252; ++ind) {
		Dedxcorrection::para_end_corrRZL_MC[1][ind]=result_dict["para_end_corrRZLAr"][ind];
	}

	for (unsigned int ind=0; ind < 3240; ++ind) {
		Dedxcorrection::para_long_corrRZ[1][ind]=result_dict["para_long_corrRZ_Ar"][ind];
	}

	for (unsigned int ind=0; ind < 216; ++ind) {
		Dedxcorrection::para_short_corrRZ[1][ind]=result_dict["para_short_corrRZ_Ar"][ind];
	}

	for (unsigned int ind=0; ind < 630; ++ind) {
		Dedxcorrection::para_long_corrRZL_DATA[1][ind]=result_dict["para_long_corrRZLAr"][ind];
	}

	for (unsigned int ind=0; ind < 63; ++ind) {
		Dedxcorrection::para_short_corrRZL_DATA[1][ind]=result_dict["para_short_corrRZLAr"][ind];
	}

	for (unsigned int ind=0; ind < 252; ++ind) {
		Dedxcorrection::para_end_corrRZL_DATA[1][ind]=result_dict["para_end_corrRZLAr"][ind];
	}

	for (unsigned int ind=0; ind < 336; ++ind) {
		Dedxcorrection::para_end_corrRZ[1][ind]=result_dict["para_end_corrRZ_Ar"][ind];
	}

	for (unsigned int ind=0; ind < 336; ++ind) {
		Dedxcorrection::para_end_corrRZ_MC[1][ind]=result_dict["para_end_corrRZ_Ar"][ind];
	}

	
414
		
415
416
417
418
419
420
421
422
423
424
425
426
	for (unsigned int ind=0; ind < 560; ++ind) {
		Dedxcorrection::para_end_mimicToXe_DATA[1][ind]=result_dict["para_end_mimicToXeAr"][ind];
	}
	for (unsigned int ind=0; ind < 560; ++ind) {
		Dedxcorrection::para_end_mimicToXe_MC[1][ind]=result_dict["para_end_mimicToXeAr"][ind];
	}
	for (unsigned int ind=0; ind < 180; ++ind) {
		Dedxcorrection::para_short_mimicToXe_DATA[1][ind]=result_dict["para_short_mimicToXeAr"][ind];
	}
	for (unsigned int ind=0; ind < 180; ++ind) {
		Dedxcorrection::para_short_mimicToXe_MC[1][ind]=result_dict["para_short_mimicToXeAr"][ind];
	}
427
	for (unsigned int ind=0; ind < 1080; ++ind) {
428
429
		Dedxcorrection::para_long_mimicToXe_DATA[1][ind]=result_dict["para_long_mimicToXeAr"][ind];
	}
430
	for (unsigned int ind=0; ind < 1080; ++ind) {
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
		Dedxcorrection::para_long_mimicToXe_MC[1][ind]=result_dict["para_long_mimicToXeAr"][ind];
	}

	//	fill Krypton +++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
	for (unsigned int ind=0; ind < 4; ++ind) {
		Dedxcorrection::resolution[2][ind]=result_dict["resolution_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 4; ++ind) {
		Dedxcorrection::resolution_e[2][ind]=result_dict["resolution_e_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 3240; ++ind) {
		Dedxcorrection::para_long_corrRZ_MC[2][ind]=result_dict["para_long_corrRZ_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 216; ++ind) {
		Dedxcorrection::para_short_corrRZ_MC[2][ind]=result_dict["para_short_corrRZ_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 630; ++ind) {
		Dedxcorrection::para_long_corrRZL_MC[2][ind]=result_dict["para_long_corrRZLKr"][ind];
	}

	for (unsigned int ind=0; ind < 63; ++ind) {
		Dedxcorrection::para_short_corrRZL_MC[2][ind]=result_dict["para_short_corrRZLKr"][ind];
	}

	for (unsigned int ind=0; ind < 252; ++ind) {
		Dedxcorrection::para_end_corrRZL_MC[2][ind]=result_dict["para_end_corrRZLKr"][ind];
	}

	for (unsigned int ind=0; ind < 3240; ++ind) {
		Dedxcorrection::para_long_corrRZ[2][ind]=result_dict["para_long_corrRZ_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 216; ++ind) {
		Dedxcorrection::para_short_corrRZ[2][ind]=result_dict["para_short_corrRZ_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 630; ++ind) {
		Dedxcorrection::para_long_corrRZL_DATA[2][ind]=result_dict["para_long_corrRZLKr"][ind];
	}

	for (unsigned int ind=0; ind < 63; ++ind) {
		Dedxcorrection::para_short_corrRZL_DATA[2][ind]=result_dict["para_short_corrRZLKr"][ind];
	}

	for (unsigned int ind=0; ind < 252; ++ind) {
		Dedxcorrection::para_end_corrRZL_DATA[2][ind]=result_dict["para_end_corrRZLKr"][ind];
	}

	for (unsigned int ind=0; ind < 336; ++ind) {
		Dedxcorrection::para_end_corrRZ[2][ind]=result_dict["para_end_corrRZ_Kr"][ind];
	}

	for (unsigned int ind=0; ind < 336; ++ind) {
		Dedxcorrection::para_end_corrRZ_MC[2][ind]=result_dict["para_end_corrRZ_Kr"][ind];
	}

	
		
	for (unsigned int ind=0; ind < 560; ++ind) {
		Dedxcorrection::para_end_mimicToXe_DATA[2][ind]=result_dict["para_end_mimicToXeKr"][ind];
	}
	for (unsigned int ind=0; ind < 560; ++ind) {
		Dedxcorrection::para_end_mimicToXe_MC[2][ind]=result_dict["para_end_mimicToXeKr"][ind];
	}
	for (unsigned int ind=0; ind < 180; ++ind) {
		Dedxcorrection::para_short_mimicToXe_DATA[2][ind]=result_dict["para_short_mimicToXeKr"][ind];
	}
	for (unsigned int ind=0; ind < 180; ++ind) {
		Dedxcorrection::para_short_mimicToXe_MC[2][ind]=result_dict["para_short_mimicToXeKr"][ind];
	}
505
	for (unsigned int ind=0; ind < 1080; ++ind) {
506
507
		Dedxcorrection::para_long_mimicToXe_DATA[2][ind]=result_dict["para_long_mimicToXeKr"][ind];
	}
508
	for (unsigned int ind=0; ind < 1080; ++ind) {
509
510
511
512
513
514
515
516
517
518
519
520
521
		Dedxcorrection::para_long_mimicToXe_MC[2][ind]=result_dict["para_long_mimicToXeKr"][ind];
	}
}



void TRT_ToT_dEdx::update_Old(std::map<std::string,std::vector<float> > &result_dict)
{
	for(int gasType = 0; gasType<3; gasType++) { // loop over gas types
		for (unsigned int ind=0; ind < 4; ++ind) {
			Dedxcorrection::resolution[gasType][ind]=result_dict["resolution"][ind];
		}

522
		for (unsigned int ind=0; ind < 4; ++ind) {
523
			Dedxcorrection::resolution_e[gasType][ind]=result_dict["resolution_e"][ind];
524
525
526
		}

		for (unsigned int ind=0; ind < 3240; ++ind) {
527
			Dedxcorrection::para_long_corrRZ_MC[gasType][ind]=result_dict["para_long_corrRZ_MC"][ind];
528
		}
529

530
		for (unsigned int ind=0; ind < 216; ++ind) {
531
			Dedxcorrection::para_short_corrRZ_MC[gasType][ind]=result_dict["para_short_corrRZ_MC"][ind];
532
533
534
		}

		for (unsigned int ind=0; ind < 630; ++ind) {
535
				Dedxcorrection::para_long_corrRZL_MC[gasType][ind]=result_dict["para_long_corrRZL_MC"][ind];
536
537
538
		}

		for (unsigned int ind=0; ind < 63; ++ind) {
539
			Dedxcorrection::para_short_corrRZL_MC[gasType][ind]=result_dict["para_short_corrRZL_MC"][ind];
540
		}
541

542
		for (unsigned int ind=0; ind < 252; ++ind) {
543
			Dedxcorrection::para_end_corrRZL_MC[gasType][ind]=result_dict["para_end_corrRZL_MC"][ind];
544
545
546
		}

		for (unsigned int ind=0; ind < 3240; ++ind) {
547
			Dedxcorrection::para_long_corrRZ[gasType][ind]=result_dict["para_long_corrRZ_MC"][ind];
548
549
550
		}

		for (unsigned int ind=0; ind < 216; ++ind) {
551
			Dedxcorrection::para_short_corrRZ[gasType][ind]=result_dict["para_short_corrRZ_MC"][ind];
552
553
554
		}

		for (unsigned int ind=0; ind < 630; ++ind) {
555
			Dedxcorrection::para_long_corrRZL_DATA[gasType][ind]=result_dict["para_long_corrRZL_MC"][ind];
556
557
558
		}

		for (unsigned int ind=0; ind < 63; ++ind) {
559
			Dedxcorrection::para_short_corrRZL_DATA[gasType][ind]=result_dict["para_short_corrRZL_MC"][ind];
560
561
562
		}

		for (unsigned int ind=0; ind < 252; ++ind) {
563
			Dedxcorrection::para_end_corrRZL_DATA[gasType][ind]=result_dict["para_end_corrRZL_MC"][ind];
564
565
		}

566
567
568
		for (unsigned int ind=0; ind < 336; ++ind) {
			Dedxcorrection::para_end_corrRZ[gasType][ind]=result_dict["para_end_corrRZ_MC"][ind];
		}
569

570
571
572
		for (unsigned int ind=0; ind < 336; ++ind) {
			Dedxcorrection::para_end_corrRZ_MC[gasType][ind]=result_dict["para_end_corrRZ_MC"][ind];
		}
573

574
575
576
577
578
		// Setting aditional corrections
		for (unsigned int ind=0; ind < 560; ++ind) {
			Dedxcorrection::para_end_mimicToXe_MC[gasType][ind]   = 1.;
	  	Dedxcorrection::para_end_mimicToXe_DATA[gasType][ind] = 1.;
		}
579

580
581
582
583
		for (unsigned int ind=0; ind < 180; ++ind) {
			Dedxcorrection::para_short_mimicToXe_MC[gasType][ind]   = 1.;
			Dedxcorrection::para_short_mimicToXe_DATA[gasType][ind] = 1.;
		}
584

585
		for (unsigned int ind=0; ind < 1080; ++ind) {
586
587
588
589
590
			Dedxcorrection::para_long_mimicToXe_MC[gasType][ind]   = 1.;
		  Dedxcorrection::para_long_mimicToXe_DATA[gasType][ind] = 1.;
		}
	}
}
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
// callback for DB for scalar values
StatusCode TRT_ToT_dEdx::update2(int& /*i*/, std::list<std::string>& /*l*/ )
{
	const CondAttrListCollection* attrListColl = 0;
	StoreGateSvc* detStore = 0;
	StatusCode sc = service( "DetectorStore", detStore );

	if (StatusCode::SUCCESS == detStore->retrieve(attrListColl, "/TRT/Calib/ToT/ToTValue" ))
	{
		int dataBaseType = kNewDB;
		if(attrListColl->size() < 2) dataBaseType = kOldDB;

		CondAttrListCollection::const_iterator first = attrListColl->begin();
		CondAttrListCollection::const_iterator last  = attrListColl->end();

		if(dataBaseType==kNewDB) 
		{
			for (int index=0; first != last; ++first,++index) 
			{
			 	const coral::AttributeList& attrList = (*first).second;
				Dedxcorrection::paraL_dEdx_p1[index] = attrList["paraL_dEdx_p1"].data<float>();
				Dedxcorrection::paraL_dEdx_p2[index] = attrList["paraL_dEdx_p2"].data<float>();
				Dedxcorrection::paraL_dEdx_p3[index] = attrList["paraL_dEdx_p3"].data<float>();
				Dedxcorrection::paraL_dEdx_p4[index] = attrList["paraL_dEdx_p4"].data<float>();
				Dedxcorrection::paraL_dEdx_p5[index] = attrList["paraL_dEdx_p5"].data<float>();

				Dedxcorrection::para_dEdx_p1[index] = attrList["para_dEdx_p1"].data<float>();
				Dedxcorrection::para_dEdx_p2[index] = attrList["para_dEdx_p2"].data<float>();
				Dedxcorrection::para_dEdx_p3[index] = attrList["para_dEdx_p3"].data<float>();
				Dedxcorrection::para_dEdx_p4[index] = attrList["para_dEdx_p4"].data<float>();
				Dedxcorrection::para_dEdx_p5[index] = attrList["para_dEdx_p5"].data<float>();
				  
				Dedxcorrection::norm_offset_data[index] = attrList["norm_offset_data"].data<float>();
				Dedxcorrection::norm_slope_tot[index] = attrList["norm_slope_tot"].data<float>();  
				Dedxcorrection::norm_slope_totl[index] = attrList["norm_slope_totl"].data<float>(); 
				Dedxcorrection::norm_offset_tot[index] = attrList["norm_offset_tot"].data<float>(); 
				Dedxcorrection::norm_offset_totl[index] = attrList["norm_offset_totl"].data<float>();		
			  Dedxcorrection::norm_nzero[index]=attrList["norm_nzero"].data<int>();
	  	}
		} 
		else 
		{
			ATH_MSG_WARNING ("update2():: Old COOL database tag!");
			// return update2_Old();
			for (; first != last; ++first) {  
				const coral::AttributeList& attrList = (*first).second;
				for(int gasType=0; gasType<3; gasType++)
				{
					Dedxcorrection::paraL_dEdx_p1[gasType] = attrList["paraL_dEdx_p1"].data<float>();
					Dedxcorrection::paraL_dEdx_p2[gasType] = attrList["paraL_dEdx_p2"].data<float>();
					Dedxcorrection::paraL_dEdx_p3[gasType] = attrList["paraL_dEdx_p3"].data<float>();
					Dedxcorrection::paraL_dEdx_p4[gasType] = attrList["paraL_dEdx_p4"].data<float>();
					Dedxcorrection::paraL_dEdx_p5[gasType] = attrList["paraL_dEdx_p5"].data<float>();

					Dedxcorrection::para_dEdx_p1[gasType] = attrList["para_dEdx_p1"].data<float>();
					Dedxcorrection::para_dEdx_p2[gasType] = attrList["para_dEdx_p2"].data<float>();
					Dedxcorrection::para_dEdx_p3[gasType] = attrList["para_dEdx_p3"].data<float>();
					Dedxcorrection::para_dEdx_p4[gasType] = attrList["para_dEdx_p4"].data<float>();
					Dedxcorrection::para_dEdx_p5[gasType] = attrList["para_dEdx_p5"].data<float>();

					Dedxcorrection::norm_offset_data[gasType] = attrList["norm_offset_data"].data<float>();
					Dedxcorrection::norm_slope_tot[gasType] = attrList["norm_slope_tot"].data<float>();  
					Dedxcorrection::norm_slope_totl[gasType] = attrList["norm_slope_totl"].data<float>(); 
					Dedxcorrection::norm_offset_tot[gasType] = attrList["norm_offset_tot"].data<float>(); 
					Dedxcorrection::norm_offset_totl[gasType] = attrList["norm_offset_totl"].data<float>();		
					Dedxcorrection::norm_nzero[gasType]=attrList["norm_nzero"].data<int>(); 
				}
	  	}
		}
	} else {
		ATH_MSG_ERROR ("Problem reading condDB object. -");
		return StatusCode::FAILURE;
	}

	return StatusCode::SUCCESS;
669
670
671
}


672
673

bool TRT_ToT_dEdx::isGood_Hit(const Trk::TrackStateOnSurface *itr) const
674
675
676
677
678
679
680
681
682
683
{
  const Trk::MeasurementBase* trkM = itr->measurementOnTrack();
  if (!trkM)  return false;   
  const InDet::TRT_DriftCircleOnTrack *driftcircle = dynamic_cast<const InDet::TRT_DriftCircleOnTrack*>(trkM);  
  if (!driftcircle) return false;

  const Trk::TrackParameters* trkP = itr->trackParameters();
  if(trkP==0)return false; 
  double Trt_Rtrack = fabs(trkP->parameters()[Trk::locR]);
  double Trt_RHit = fabs(driftcircle->localParameters()[Trk::driftRadius]);
684
685
686
687
688
689
690
691
692
  double Trt_HitTheta = trkP->parameters()[Trk::theta];
  double Trt_HitPhi = trkP->parameters()[Trk::phi];
  double error2 = 2*driftcircle->localCovariance()(Trk::driftRadius,Trk::driftRadius);
  double distance2 = (Trt_Rtrack - Trt_RHit)*(Trt_Rtrack - Trt_RHit);
  Identifier DCId = driftcircle->identify();
  int HitPart =  m_trtId->barrel_ec(DCId);
  const InDetDD::TRT_BaseElement* element = m_trtman->getElement(DCId);
  double strawphi = element->center(DCId).phi();

693
694
  if ( m_useZeroRHitCut && Trt_RHit==0) return false;                                     // tube hit
  if ( (Trt_Rtrack >= m_trackConfig_maxRtrack) || (Trt_Rtrack <= m_trackConfig_minRtrack) )return false;    // drift radius close to wire or wall
695
696
697
698
699
700
701
702
703
704
705
  if (distance2 > error2) return false; // Select precision hit only

  L = 0;
  if (std::abs(HitPart)==1) { //Barrel
    L = 2*sqrt(4-Trt_Rtrack*Trt_Rtrack)*1./fabs(sin(Trt_HitTheta));
  }
  if (std::abs(HitPart)==2) { //EndCap
    L = 2*sqrt(4-Trt_Rtrack*Trt_Rtrack)*1./sqrt(1-sin(Trt_HitTheta)*sin(Trt_HitTheta)*cos(Trt_HitPhi-strawphi)*cos(Trt_HitPhi-strawphi));
  }
  if(m_divideByL)
    if ( L < 1.7 ) return false; // Length in the straw
706
  if(!m_useHThits){
707
708
709
    int TrtHl = driftcircle->highLevel();
    if (TrtHl==1) return false; 
  }
710
711
712
713
714
715
716
717
718
719
720
721

  if(m_useTrackPartWithGasType!=kUnset) // don't preselect hits
  {
  	if(m_useTrackPartWithGasType!=gasTypeInStraw(itr))
  		return false;
  }

  unsigned int BitPattern = driftcircle->prepRawData()->getWord();
  double ToT = getToT(BitPattern);

  if(ToT==0) return false; // If ToT for this hit equal 0, skip it.
  
722
723
724
  return true;
}

725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744


double TRT_ToT_dEdx::dEdx(const Trk::Track* track, bool DivideByL, bool useHThits, bool corrected)
{

	if(corrected) SwitchOnRSCorrection();
	else SwitchOffRSCorrection();

	if(DivideByL) SwitchOnDivideByL();
	else SwitchOffDivideByL();

	if(useHThits) SwitchOnUseHThits();
	else SwitchOffUseHThits();

	return dEdx(track);
}



double TRT_ToT_dEdx::dEdx(const Trk::Track* track)
745
{
746
747
748
	ATH_MSG_DEBUG("dEdx()");
	ShowDEDXSetup();  

749
  double nVtx=-1.;
750

751
752
753
754
755
  // Event information 
  const xAOD::EventInfo* eventInfo = 0;
  ATH_CHECK( evtStore()->retrieve( eventInfo) );
  
 // check if data or MC 
756
  m_isData = true;
757
  if(eventInfo->eventType(xAOD::EventInfo::IS_SIMULATION ) ){
758
		m_isData=false;
759
  }
760
  
761
  // 	Average interactions per crossing for the current BCID
762
763
764
765
766
767
768
769
  double mu = -1.;
  mu = eventInfo->averageInteractionsPerCrossing();
  if(m_isData) {
    nVtx = 1.3129 + 0.716194*mu + (-0.00475074)*mu*mu;
  }
  else
    nVtx = 1.0897 + 0.748287*mu + (-0.00421788)*mu*mu;

770
771
772
773
774
775
776
777

  if (!track) {
    return 0;
  }
  const DataVector<const Trk::TrackStateOnSurface>* vtsos = track->trackStateOnSurfaces(); 
  if (!vtsos) {
    return 0;
  }
778
  
779
  DataVector<const Trk::TrackStateOnSurface>::const_iterator itr  = vtsos->begin();
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
	DataVector<const Trk::TrackStateOnSurface>::const_iterator itre = vtsos->end();  

  if(m_toolScenario==kAlgStandard || m_toolScenario==kAlgScalingToXe)
  {
  	std::vector<double> vecToT;
  	double ToTsum = 0;

 	  for ( ; itr!=itre ; ++itr) {
	    if ( isGood_Hit((*itr))) {
			vecToT.push_back(correctToT_corrRZ(*itr));
	    }
	  } 
	  
	  sort(vecToT.begin(), vecToT.end());
	  int nhits = (int)vecToT.size();
795

796
797
798
799
800
	  int ntrunk = 1;
	  if(m_divideByL) nhits-=ntrunk;

	  // Boost speed
	  if(nhits<1)return 0.0;
801

802
803
804
805
806
807
	  for (int i = 0; i < nhits;i++){
	    ToTsum+=vecToT.at(i);
	  } 
	  ToTsum*=correctNormalization(m_divideByL, m_isData, nVtx);

	  return ToTsum/nhits;
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
  else
  if(m_toolScenario==kAlgReweight || m_toolScenario==kAlgReweightTrunkOne)
  {
  	std::vector<double> vecToT_Xe;
  	std::vector<double> vecToT_Ar;
  	std::vector<double> vecToT_Kr;

  	int gasTypeForCorrectNormalization = m_useTrackPartWithGasType;
  	if(m_useTrackPartWithGasType!=kUnset)
  	{
  		ATH_MSG_WARNING("dEdX_Estimator():: Using m_toolScenario="<<m_toolScenario<<" scenario m_useTrackPartWithGasType is set to"<<m_useTrackPartWithGasType<<", but kUnset is requiered. Setting that to kUnset. Check you tool configuration.");
  		m_useTrackPartWithGasType=kUnset;
  	}

	  for ( ; itr!=itre ; ++itr) {
	    if ( isGood_Hit((*itr))) {
	    	m_gasTypeInStraw=gasTypeInStraw(*itr);
		    if(m_gasTypeInStraw==kXenon)
		    	vecToT_Xe.push_back(correctToT_corrRZ(*itr));
		    else
		    if(m_gasTypeInStraw==kArgon)
		    	vecToT_Ar.push_back(correctToT_corrRZ(*itr));
		    else
		    if(m_gasTypeInStraw==kKrypton)
		    	vecToT_Kr.push_back(correctToT_corrRZ(*itr));
		    else
		    ATH_MSG_ERROR("dEdX_Estimator():: During scenario kAlgReweight variable m_gasTypeInStraw got value kUnset.");
	    }
	  } 

	  sort(vecToT_Xe.begin(), vecToT_Xe.end());
	  sort(vecToT_Ar.begin(), vecToT_Ar.end());
	  sort(vecToT_Kr.begin(), vecToT_Kr.end());

	  int nhitsXe = (int)vecToT_Xe.size();
	  int nhitsAr = (int)vecToT_Ar.size();
	  int nhitsKr = (int)vecToT_Kr.size();


	  int ntrunk = 1;
	  if(m_divideByL)
	  {
		  if(m_toolScenario==kAlgReweight){
				if(nhitsXe>0) nhitsXe-=ntrunk;
				if(nhitsAr>0) nhitsAr-=ntrunk;
				if(nhitsKr>0) nhitsKr-=ntrunk;
		  }
		  else // kAlgReweightTrunkOne
		  {
		  	int trunkGas = kUnset;
		  	double maxToT = 0.;
		  	if(nhitsXe>0 && vecToT_Xe.at(nhitsXe-1)>maxToT) trunkGas = kXenon;
		  	if(nhitsAr>0 && vecToT_Ar.at(nhitsAr-1)>maxToT) trunkGas = kArgon;
		  	if(nhitsKr>0 && vecToT_Kr.at(nhitsKr-1)>maxToT) trunkGas = kKrypton;

		  	if(trunkGas==kXenon)   nhitsXe-=ntrunk;
		  	else
		  	if(trunkGas==kArgon)   nhitsAr-=ntrunk;
		  	else
		  	if(trunkGas==kKrypton) nhitsKr-=ntrunk;
		  }
		}

		m_useTrackPartWithGasType = gasTypeForCorrectNormalization;

		// Boost speed.
		int nhits  = nhitsXe + nhitsAr + nhitsKr;
		if(nhits<1) return 0.0;

		double ToTsumXe = 0;
  	double ToTsumAr = 0;
  	double ToTsumKr = 0;
	  for (int i = 0; i < nhitsXe;i++){
	    ToTsumXe+=vecToT_Xe.at(i);
	  } 
	  for (int i = 0; i < nhitsAr;i++){
	    ToTsumAr+=vecToT_Ar.at(i);
	  } 
	  for (int i = 0; i < nhitsKr;i++){
	    ToTsumKr+=vecToT_Kr.at(i);
	  } 

	  if(nhitsXe>0) ToTsumXe/=nhitsXe;
	  else ToTsumXe = 0;
	  if(nhitsAr>0) ToTsumAr/=nhitsAr;
	  else ToTsumAr = 0;
	  if(nhitsKr>0) ToTsumKr/=nhitsKr;
	  else ToTsumKr = 0;


	  double ToTsum = ToTsumXe*nhitsXe + ToTsumAr*nhitsAr + ToTsumKr*nhitsKr;
900

901
	  ToTsum*=correctNormalization(m_divideByL, m_isData, nVtx);
902

903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
	  return ToTsum/nhits;
  }
  

  ATH_MSG_ERROR("dEdX_Estimator():: m_toolScenario has wrong value "<<m_toolScenario<<"");
	return 0.;
}



double TRT_ToT_dEdx::usedHits(const Trk::Track* track, bool DivideByL, bool useHThits)
{
	if(DivideByL) 	SwitchOnDivideByL();
	else			SwitchOffDivideByL();

	if(useHThits) 	SwitchOnUseHThits();
	else			SwitchOffUseHThits();

	return usedHits(track);
922
923
}

924
925
926


double TRT_ToT_dEdx::usedHits(const Trk::Track* track)
927
{
928
929
930
	ATH_MSG_DEBUG("usedHits()");
	ShowDEDXSetup();  

931
932
933
934
935
936
937
  if (!track) {
    return 0;
  }
  const DataVector<const Trk::TrackStateOnSurface>* vtsos = track->trackStateOnSurfaces(); 
  if (!vtsos) {
    return 0;
  }
938

939
940
  DataVector<const Trk::TrackStateOnSurface>::const_iterator itr  = vtsos->begin();
  DataVector<const Trk::TrackStateOnSurface>::const_iterator itre = vtsos->end();  
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
  

  if(m_toolScenario==kAlgStandard || m_toolScenario==kAlgScalingToXe)
  {
  	int nhits =0;

 	  for ( ; itr!=itre ; ++itr) {
	    if ( isGood_Hit((*itr))) {
			nhits++;
	    }
	  } 

	  int ntrunk = 1;
	  if(m_divideByL) nhits-=ntrunk;

	  return nhits;
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
  else
  if(m_toolScenario==kAlgReweight || m_toolScenario==kAlgReweightTrunkOne)
  {
		int nhits = 0;
		int nhitsXe = 0;
		int nhitsAr = 0;
		int nhitsKr = 0;

  	int gasTypeForCorrectNormalization = m_useTrackPartWithGasType;
  	if(m_useTrackPartWithGasType!=kUnset)
  	{
  		ATH_MSG_WARNING("usedHits_Estimator():: Using m_toolScenario="<<m_toolScenario<<" scenario m_useTrackPartWithGasType is set to "<<m_useTrackPartWithGasType<<", but kUnset is requiered. Setting that to kUnset. Check you tool configuration.");
  		m_useTrackPartWithGasType=kUnset;
  	}

		for ( ; itr!=itre ; ++itr) {
			if ( isGood_Hit((*itr))) {
				m_gasTypeInStraw=gasTypeInStraw(*itr);
				if(m_gasTypeInStraw==kXenon)
					nhitsXe++;
				else
				if(m_gasTypeInStraw==kArgon)
					nhitsAr++;
				else
				if(m_gasTypeInStraw==kKrypton)
					nhitsKr++;
				else
					ATH_MSG_ERROR("usedHits_Estimator():: During scenario kAlgReweight variable m_gasTypeInStraw got value kUnset.");
			}
		} 

		m_useTrackPartWithGasType = gasTypeForCorrectNormalization;

	  int ntrunk = 1;
	  if(m_divideByL) {
		  if(m_toolScenario==kAlgReweight){
				if(nhitsXe>0) nhitsXe-=ntrunk;
				if(nhitsAr>0) nhitsAr-=ntrunk;
				if(nhitsKr>0) nhitsKr-=ntrunk;
		  }
		  else { // kAlgReweightTrunkOne
		  	if(nhitsXe>0 || nhitsAr>0 || nhitsKr>0)
		  		nhitsXe -= ntrunk;
		  }
		}

		nhits  = nhitsXe + nhitsAr + nhitsKr;
1005

1006
	  return nhits;
1007
1008
  }

1009
1010
1011
1012
1013
  ATH_MSG_ERROR("usedHits_Estimator():: m_toolScenario has wrong value "<<m_toolScenario<<"");
	return 0;
}


1014

1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
double TRT_ToT_dEdx::getProb(const double dEdx_obs, const double pTrk, Trk::ParticleHypothesis hypothesis, int nUsedHits, bool dividebyL)
{
	if(dividebyL) 	SwitchOnDivideByL();
	else			SwitchOffDivideByL();

	return getProb(dEdx_obs, pTrk, hypothesis, nUsedHits);
}



double TRT_ToT_dEdx::getProb(const double dEdx_obs, const double pTrk, Trk::ParticleHypothesis hypothesis, int nUsedHits) const
{
	
	ATH_MSG_DEBUG("getProb():: m_gasTypeInStraw = "<<m_gasTypeInStraw<<"");
1029

1030
1031
1032
1033
1034
1035
	if(m_gasTypeInStraw==kUnset)
	{
		ATH_MSG_WARNING("getProb():: m_gasTypeInStraw set kUnset that is not allowed! Use gasTypeInStraw(*itr) to get gas type info for that hit first!");
		ATH_MSG_WARNING("getProb():: Now m_gasTypeInStraw sets to kXenon.");
		m_gasTypeInStraw = kXenon;
	}
1036

1037
  double dEdx_pred = predictdEdx(pTrk, hypothesis); 
1038
1039
1040
1041
1042
1043
1044
1045
  if(dEdx_pred==0)return 0.0;
  if(hypothesis==Trk::electron){
    // correction for pTrk in [MeV]
    double factor = 1;
    double correct = 1+factor*(0.045*log10(pTrk)+0.885-1);
    dEdx_pred= dEdx_pred/correct;
  }

1046
  double Resolution = Dedxcorrection::resolution[m_gasTypeInStraw][0]+Dedxcorrection::resolution[m_gasTypeInStraw][1]*(nUsedHits+0.5)+Dedxcorrection::resolution[m_gasTypeInStraw][2]*(nUsedHits+0.5)*(nUsedHits+0.5)+Dedxcorrection::resolution[m_gasTypeInStraw][3]*(nUsedHits+0.5)*(nUsedHits+0.5)*(nUsedHits+0.5);
1047
  if(hypothesis==Trk::electron){
1048
    Resolution = Dedxcorrection::resolution_e[m_gasTypeInStraw][0]+Dedxcorrection::resolution_e[m_gasTypeInStraw][1]*(nUsedHits+0.5)+Dedxcorrection::resolution_e[m_gasTypeInStraw][2]*(nUsedHits+0.5)*(nUsedHits+0.5)+Dedxcorrection::resolution_e[m_gasTypeInStraw][3]*(nUsedHits+0.5)*(nUsedHits+0.5)*(nUsedHits+0.5);
1049
1050
1051
1052
1053
  }

  double prob =exp( -0.5 * ( ( ( dEdx_obs - dEdx_pred ) / (Resolution*dEdx_pred) ) * 
			     ( ( dEdx_obs - dEdx_pred ) / (Resolution*dEdx_pred) ) ))  ; 

1054
  ATH_MSG_DEBUG("getProb():: return "<<prob<<"");
1055
  return prob;
1056
1057
1058
1059
1060
1061
1062
1063
}



double TRT_ToT_dEdx::getTest(const double dEdx_obs, const double pTrk, Trk::ParticleHypothesis hypothesis, Trk::ParticleHypothesis antihypothesis, int nUsedHits, bool dividebyL)
{
	if(dividebyL) 	SwitchOnDivideByL();
	else			SwitchOffDivideByL();
1064

1065
	return getTest(dEdx_obs, pTrk, hypothesis, antihypothesis, nUsedHits);
1066
1067
1068
}


1069
1070
1071
1072
1073
1074
1075
1076
1077

double TRT_ToT_dEdx::getTest(const double dEdx_obs, const double pTrk, Trk::ParticleHypothesis hypothesis, Trk::ParticleHypothesis antihypothesis, int nUsedHits) const
{
  ATH_MSG_DEBUG("getTest()");
	
  if ( dEdx_obs<=0. || pTrk<=0. || nUsedHits<=0 ) return 0.5;
  
  double Pone = getProb(dEdx_obs,pTrk,hypothesis,nUsedHits);
  double Ptwo = getProb(dEdx_obs,pTrk,antihypothesis,nUsedHits);
1078
  if( (Pone+Ptwo) != 0){
1079
  	ATH_MSG_DEBUG("getTest():: return "<<Pone/(Pone+Ptwo)<<"");
1080
1081
1082
    return Pone/(Pone+Ptwo);
  }else
    return 0.5;
1083
1084
1085
}


1086

1087
1088
1089
1090
1091
1092
double TRT_ToT_dEdx::predictdEdx(const double pTrk, Trk::ParticleHypothesis hypothesis, bool dividebyL)
{
	if(dividebyL) 	SwitchOnDivideByL();
	else			SwitchOffDivideByL();

	return predictdEdx(pTrk, hypothesis);
1093
1094
}

1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107


double TRT_ToT_dEdx::predictdEdx(const double pTrk, Trk::ParticleHypothesis hypothesis) const
{
	ATH_MSG_DEBUG("predictdEdx(): m_gasTypeInStraw = "<<m_gasTypeInStraw<<"");

	if(m_gasTypeInStraw==kUnset)
	{
		ATH_MSG_WARNING("predictdEdx():: m_gasTypeInStraw set kUnset that is not allowed! Use gasTypeInStraw(*itr) to get gas type info for that hit first!");
		ATH_MSG_WARNING("predictdEdx():: Now m_gasTypeInStraw sets to kXenon.");
		m_gasTypeInStraw = kXenon;
	}

1108
1109
1110
1111
1112
1113
1114
1115
  double mass = m_particlemasses.mass[hypothesis];

  double betaGamma = pTrk/mass;
  /** @todo why is it possible that a 20 MeV particle reaches this point? (see Savannah bug 94644) */
  // low momentum particle can create floating point error 
  // do we need the check in the log parameter in addition? will create CPU increase
  // do we want to throw an assertion here?
  if(pTrk<100)return 0; 
1116
1117
1118
1119
1120
  if(m_divideByL){    
    if(Dedxcorrection::paraL_dEdx_p3[m_gasTypeInStraw]+1./( std::pow( betaGamma, Dedxcorrection::paraL_dEdx_p5[m_gasTypeInStraw]))<=0) return 0;
    return Dedxcorrection::paraL_dEdx_p1[m_gasTypeInStraw]/std::pow( sqrt( (betaGamma*betaGamma)/(1.+(betaGamma*betaGamma)) ), Dedxcorrection::paraL_dEdx_p4[m_gasTypeInStraw])  * 
      (Dedxcorrection::paraL_dEdx_p2[m_gasTypeInStraw] - std::pow( sqrt( (betaGamma*betaGamma)/(1.+(betaGamma*betaGamma)) ), Dedxcorrection::paraL_dEdx_p4[m_gasTypeInStraw] ) 
      	- log(Dedxcorrection::paraL_dEdx_p3[m_gasTypeInStraw]+1./( std::pow( betaGamma, Dedxcorrection::paraL_dEdx_p5[m_gasTypeInStraw]) ) ) );
1121
  }else {
1122
1123
1124
1125
    if(Dedxcorrection::para_dEdx_p3[m_gasTypeInStraw]+1./( std::pow( betaGamma, Dedxcorrection::para_dEdx_p5[m_gasTypeInStraw]) )<=0)return 0; 
    return Dedxcorrection::para_dEdx_p1[m_gasTypeInStraw]/std::pow( sqrt( (betaGamma*betaGamma)/(1.+(betaGamma*betaGamma)) ), Dedxcorrection::para_dEdx_p4[m_gasTypeInStraw])  * 
      (Dedxcorrection::para_dEdx_p2[m_gasTypeInStraw] - std::pow( sqrt( (betaGamma*betaGamma)/(1.+(betaGamma*betaGamma)) ), Dedxcorrection::para_dEdx_p4[m_gasTypeInStraw] ) 
      	- log(Dedxcorrection::para_dEdx_p3[m_gasTypeInStraw]+1./( std::pow( betaGamma, Dedxcorrection::para_dEdx_p5[m_gasTypeInStraw]) ) ) );
1126
  }
1127
  //return 0;  
1128
1129
}

1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141


double TRT_ToT_dEdx::mass(const double pTrk, double dEdx ) const
{
	ATH_MSG_DEBUG("mass(): m_gasTypeInStraw = "<<m_gasTypeInStraw<<"");

	if(m_gasTypeInStraw==kUnset)
	{
		ATH_MSG_WARNING("mass():: m_gasTypeInStraw set kUnset that is not allowed! Use gasTypeInStraw(*itr) to get gas type info for that hit first!");
		ATH_MSG_WARNING("mass():: Now m_gasTypeInStraw sets to kXenon.");
		m_gasTypeInStraw = kXenon;
	}
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
  // only for testing purposes!!!!
  // note that dE/dx has to be corrected on track level first before value can be transferred to mass
  // this has to be tuned on user level
  /** @todo make failsafe */
  static const double bg_min = 0.001;
  static const double bg_max = 3;   // maximal allowed bg
  
  static const std::string blumRolandiFunction = "( [0]/sqrt( (x*x/([5]*[5]))/(1.+(x*x/([5]*[5]))) )^[3] ) * ([1] - sqrt( (x*x/([5]*[5]))/(1.+(x*x/([5]*[5]))) )^[3] - log([2]+1./((x/[5])^[4]) ) )";
  
  TF1 blumRolandi( "BR", blumRolandiFunction.c_str(), 0.7, 100000);

1153
  blumRolandi.SetParameters(Dedxcorrection::para_dEdx_p1[m_gasTypeInStraw],Dedxcorrection::para_dEdx_p2[m_gasTypeInStraw],Dedxcorrection::para_dEdx_p3[m_gasTypeInStraw],Dedxcorrection::para_dEdx_p4[m_gasTypeInStraw],Dedxcorrection::para_dEdx_p5[m_gasTypeInStraw], 1. ); 
1154
1155
1156
  //blumRolandi.SetParameters(&Dedxcorrection::para_dEdx_BB);
  double betaGamma = blumRolandi.GetX(dEdx, bg_min, bg_max); 
  
1157
1158
  ATH_MSG_DEBUG("mass():: return "<<pTrk/betaGamma<<"");
	
1159
1160
1161
1162
1163
  return pTrk/betaGamma;
}



1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
/* returns gas type for given straw */
int TRT_ToT_dEdx::gasTypeInStraw(const Trk::TrackStateOnSurface *itr) const
{
	const Trk::MeasurementBase* trkM = itr->measurementOnTrack();
  if (!trkM)  return kUnset;   
  const InDet::TRT_DriftCircleOnTrack *driftcircle = dynamic_cast<const InDet::TRT_DriftCircleOnTrack*>(trkM);  
  if (!driftcircle) return kUnset;

  return gasTypeInStraw(driftcircle);
}



int TRT_ToT_dEdx::gasTypeInStraw(const InDet::TRT_DriftCircleOnTrack *driftcircle) const
{
  Identifier DCid = driftcircle->identify();  
  
  // getStatusHT returns enum {Undefined, Dead, Good, Xenon, Argon, Krypton, EmulatedArgon, EmulatedKrypton}.
  // Our representation of 'GasType' is 0:Xenon, 1:Argon, 2:Krypton
  int GasType=0; // Xenon is default
  if (!m_TRTStrawSummarySvc.empty()) {
    int stat = m_TRTStrawSummarySvc->getStatusHT(DCid);
    if       ( stat==2 || stat==3 ) { GasType = kXenon; } // Xe
    else if  ( stat==1 || stat==4 ) { GasType = kArgon; } // Ar
    else if  ( stat==5 )            { GasType = kKrypton; } // Kr
    else if  ( stat==6 )            { GasType = kArgon; } // Emulated Ar
    else if  ( stat==7 )            { GasType = kKrypton; } // Emulated Kr
    else { ATH_MSG_FATAL ("getStatusHT = " << stat << ", must be 'Good(2)||Xenon(3)' or 'Dead(1)||Argon(4)' or 'Krypton(5)' or 'EmulatedArgon(6)' or 'EmulatedKr(7)'!");
           throw std::exception();
         }
  }
  if(GasType > kKrypton || GasType < kXenon) return kUnset; 

  return GasType;
}



double TRT_ToT_dEdx::getToT(unsigned int BitPattern) const
{
	if(m_whichToTEstimatorAlgo==kToTLargerIsland) 
		return getToTlargerIsland(BitPattern);
	else
	if(m_whichToTEstimatorAlgo==kToTHighOccupancy) 
		return getToTHighOccupancy(BitPattern);
	else
	if(m_whichToTEstimatorAlgo==kToTHighOccupancySmart)
		return getToTHighOccupancySmart(BitPattern);

	ATH_MSG_FATAL("getToT():: No ToT estimator case for m_whichToTEstimatorAlgo"<<m_whichToTEstimatorAlgo<<"");
	throw std::exception();

	return 0;
}


/////////////////////////////////
// Corrections
/////////////////////////////////

double TRT_ToT_dEdx::correctNormalization(bool divideLength,bool scaledata, double nVtx) const
{
	int gasType = m_useTrackPartWithGasType;
	if(m_useTrackPartWithGasType==kUnset)
		gasType=kXenon;
	if(nVtx<=0)nVtx=Dedxcorrection::norm_nzero[gasType];
	double slope = Dedxcorrection::norm_slope_tot[gasType];
	double offset = Dedxcorrection::norm_offset_tot[gasType];
	if(divideLength){
		slope = Dedxcorrection::norm_slope_tot[gasType];
		offset = Dedxcorrection::norm_offset_tot[gasType];
	} 
	double shift = Dedxcorrection::norm_offset_data[gasType];
	if(!scaledata)shift = 0;
	return (slope*Dedxcorrection::norm_nzero[gasType]+offset)/(slope*nVtx+offset+shift);
}



double TRT_ToT_dEdx::correctToT_corrRZ(const Trk::TrackStateOnSurface *itr)
{
1245
1246
1247
1248
1249
1250
1251
1252
1253
  const Trk::MeasurementBase* trkM = itr->measurementOnTrack();
  const Trk::TrackParameters* trkP = itr->trackParameters();
  const InDet::TRT_DriftCircleOnTrack *driftcircle = dynamic_cast<const InDet::TRT_DriftCircleOnTrack*>(trkM);

  if (!driftcircle) return 0;
  if (driftcircle->prepRawData()==0) return 0;

  Identifier DCId = driftcircle->identify();
  unsigned int BitPattern = driftcircle->prepRawData()->getWord();
1254
1255
1256
1257
1258
  double ToT = getToT(BitPattern);
  if(ToT==0) {
  	ATH_MSG_WARNING("correctToT_corrRZ(const Trk::TrackStateOnSurface *itr):: ToT="<<ToT<<". We must cut that hit in isGood_Hit() !");
  	return 0;
  }
1259
  int HitPart =  m_trtId->barrel_ec(DCId);
1260
1261
1262
  int StrawLayer = m_trtId->straw_layer(DCId);
  int Layer = m_trtId->layer_or_wheel(DCId);
  double HitRtrack = fabs(trkP->parameters()[Trk::locR]);
1263
1264
1265
1266
1267
  m_gasTypeInStraw = gasTypeInStraw(itr);  
  if(m_gasTypeInStraw==kUnset) {
  	ATH_MSG_ERROR("correctToT_corrRZ(const Trk::TrackStateOnSurface *itr):: Gas type in straw is kUnset! Return ToT = 0");
  	return 0;
  }  
1268
  
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
  if(m_applyMimicToXeCorrection==true || m_toolScenario==kAlgScalingToXe)
  {
  	if(m_gasTypeInStraw!=kXenon) // mimic to Xenon ToT, so we skip Xenon hits
	  {	
	  	double mimicCorr = 0.;
			if (abs(HitPart)==1) // Barrel
				mimicCorr=mimicToXeHit_Barrel(HitRtrack, Layer, StrawLayer);
			else // End-cap
				mimicCorr=mimicToXeHit_Endcap(HitRtrack, Layer, HitPart); 

			if(mimicCorr==0.)
		  {
		  	ATH_MSG_FATAL("correctToT_corrRZ():: mimicCorr = "<<mimicCorr<<"");
		  	throw std::exception();
		  }
			ToT/=mimicCorr;

			if(m_whichToTEstimatorAlgo==kToTLargerIsland){
				if(ToT<3.125) ToT = 3.125;
				if(ToT>75)    ToT = 75;
			}else{
				if(ToT<3.125) ToT = 3.125;
				if(ToT>62.5)  ToT = 62.5;
			}

			m_gasTypeInStraw=kXenon; // After mimic correction we work with that hit as Xenon hit.
	  }  
1296
  }
1297
1298
1299
 
  if(m_divideByL) ToT = ToT/L;
  if(!m_corrected) return ToT;
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
  /* else correct */
	   
  double HitZ = driftcircle->globalPosition().z();
  double trackx =  driftcircle->globalPosition().x();
  double tracky =  driftcircle->globalPosition().y();
  double HitRpos = sqrt(trackx*trackx+tracky*tracky);
  
  /** @todo implement possiblity to set the scaling factor run-by-run from database, 
      should probably be done later on track- level */
  double ToTmip = 1;
  double valToT = 0;
1311
  if(m_divideByL){
1312
    if (abs(HitPart)==1) // Barrel
1313
      valToT = fitFuncBarrel_corrRZL(HitRtrack,HitZ, Layer, StrawLayer);
1314
    else // End-cap
1315
      valToT = fitFuncEndcap_corrRZL(HitRtrack,HitRpos,Layer, HitZ>0?1:(HitZ<0?-1:0));   
1316
1317
  }else{
    if (abs(HitPart)==1) // Barrel
1318
      valToT = fitFuncBarrel_corrRZ(HitRtrack,HitZ, Layer, StrawLayer);
1319
    else // End-cap
1320
      valToT = fitFuncEndcap_corrRZ(HitRtrack,HitRpos,Layer, HitZ>0?1:(HitZ<0?-1:0));
1321
1322
  } 

1323
  return ToTmip*ToT/valToT;
1324
1325
}

1326
1327
1328
1329
1330
1331
1332
1333
1334
1335


double TRT_ToT_dEdx::correctToT_corrRZL(const Trk::TrackParameters* trkP,const InDet::TRT_DriftCircleOnTrack *driftcircle, int HitPart,int Layer,int StrawLayer, bool isData)
{
	m_isData = isData;
	
 	if(trkP==0)return false; 
 	if (!driftcircle) return false;
 	if (driftcircle->prepRawData()==0) return 0;
  double HitRtrack = fabs(trkP->parameters()[Trk::locR]);
1336
  double Trt_RHit = fabs(driftcircle->localParameters()[Trk::driftRadius]);
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
  if ( m_useZeroRHitCut && Trt_RHit==0) return false;                                     // tube hit
  if ( (HitRtrack >= m_trackConfig_maxRtrack) || (HitRtrack <= m_trackConfig_minRtrack) )return false;    // drift radius close to wire or wall
  if(!m_useHThits){
    int TrtHl = driftcircle->highLevel();
    if (TrtHl==1) return false; 
  }

  m_gasTypeInStraw = gasTypeInStraw(driftcircle);  
  if(m_useTrackPartWithGasType!=kUnset) // don't preselect hits
  {
  	if(m_useTrackPartWithGasType!=m_gasTypeInStraw)
  		return false;
  }
1350
1351

  unsigned int BitPattern = driftcircle->prepRawData()->getWord();
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
  double ToT = getToT(BitPattern);
  if(ToT==0) return false; // If ToT for this hit equal 0, skip it.

  if(m_applyMimicToXeCorrection==true || m_toolScenario==kAlgScalingToXe)
  {
  	if(m_gasTypeInStraw!=kXenon) // mimic to Xenon ToT, so we skip Xenon hits
	  {	
			if (abs(HitPart)==1) // Barrel
				ToT/=mimicToXeHit_Barrel(HitRtrack, Layer, StrawLayer);
			else // End-cap
				ToT/=mimicToXeHit_Endcap(HitRtrack, Layer, HitPart); 

			if(m_whichToTEstimatorAlgo==kToTLargerIsland){
				if(ToT<3.125) ToT = 3.125;
				if(ToT>75)    ToT = 75;
			}else{
				if(ToT<3.125) ToT = 3.125;
				if(ToT>62.5)  ToT = 62.5;
			}

			m_gasTypeInStraw=kXenon; // After mimic correction we work with that hit as Xenon hit.
	  }  
  }

1376
  ToT = ToT/L;
1377

1378
1379
1380
1381
  const Amg::Vector3D& gp = driftcircle->globalPosition();
  double HitR = sqrt( gp.x() * gp.x() + gp.y() * gp.y() );
  double HitZ = gp.z();
  double ToTmip = 1;
1382
  double valToT = 1;
1383
1384

  if (abs(HitPart)==1) // Barrel
1385
    valToT = fitFuncBarrel_corrRZL(HitRtrack,HitZ, Layer, StrawLayer);
1386
  else // End-cap
1387
    valToT = fitFuncEndcap_corrRZL(HitRtrack ,HitR,Layer, HitZ>0?1:(HitZ<0?-1:0));
1388
1389
1390
1391
  return ToTmip*ToT/valToT;
}


1392
1393
1394
1395
1396
1397
1398
1399
1400

double TRT_ToT_dEdx::correctToT_corrRZ(const Trk::TrackParameters* trkP,const InDet::TRT_DriftCircleOnTrack *driftcircle, int HitPart,int Layer,int StrawLayer, bool isData)
{
	m_isData = isData;

  if(trkP==0)return false; 
 	if (!driftcircle) return false;
 	if (driftcircle->prepRawData()==0) return 0;
  double HitRtrack = fabs(trkP->parameters()[Trk::locR]);
1401
  double Trt_RHit = fabs(driftcircle->localParameters()[Trk::driftRadius]);
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
  if ( m_useZeroRHitCut && Trt_RHit==0) return false;                                     // tube hit
  if ( (HitRtrack >= m_trackConfig_maxRtrack) || (HitRtrack <= m_trackConfig_minRtrack) )return false;    // drift radius close to wire or wall
  if(!m_useHThits){
    int TrtHl = driftcircle->highLevel();
    if (TrtHl==1) return false; 
  }            

 	m_gasTypeInStraw = gasTypeInStraw(driftcircle);  
  if(m_useTrackPartWithGasType!=kUnset) // don't preselect hits
  {
  	if(m_useTrackPartWithGasType!=m_gasTypeInStraw)
  		return false;
  }
1415
1416

  unsigned int BitPattern = driftcircle->prepRawData()->getWord();
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
  double ToT = getToT(BitPattern);
  if(ToT==0) return false; // If ToT for this hit equal 0, skip it.
  
  if(m_applyMimicToXeCorrection==true || m_toolScenario==kAlgScalingToXe)
  {
  	if(m_gasTypeInStraw!=kXenon) // mimic to Xenon ToT, so we skip Xenon hits
	  {	
			if (abs(HitPart)==1) // Barrel
				ToT/=mimicToXeHit_Barrel(HitRtrack, Layer, StrawLayer);
			else // End-cap
				ToT/=mimicToXeHit_Endcap(HitRtrack, Layer, HitPart); 

			if(m_whichToTEstimatorAlgo==kToTLargerIsland){
				if(ToT<3.125) ToT = 3.125;
				if(ToT>75)    ToT = 75;
			}else{
				if(ToT<3.125) ToT = 3.125;
				if(ToT>62.5)  ToT = 62.5;
			}

			m_gasTypeInStraw=kXenon; // After mimic correction we work with that hit as Xenon hit.
	  }  
  }

1441
1442
1443
1444
  const Amg::Vector3D& gp = driftcircle->globalPosition();
  double HitR = sqrt( gp.x() * gp.x() + gp.y() * gp.y() );
  double HitZ = gp.z();
  double ToTmip = 1;
1445
  double valToT = 1;
1446
1447

  if (abs(HitPart)==1) // Barrel
1448
    valToT = fitFuncBarrel_corrRZ(HitRtrack,HitZ, Layer, StrawLayer);
1449
  else // End-cap
1450
    valToT = fitFuncEndcap_corrRZ(HitRtrack ,HitR,Layer, HitZ>0?1:(HitZ<0?-1:0));
1451
1452
1453
1454
  return ToTmip*ToT/valToT;
}


1455
1456
1457

double TRT_ToT_dEdx::fitFuncBarrel_corrRZ(double driftRadius,double zPosition, int Layer, int StrawLayer) const
{
1458
  if(Layer==0 && StrawLayer<9)
1459
    return fitFuncBarrelShort_corrRZ(driftRadius,zPosition, StrawLayer);
1460
  else
1461
    return fitFuncBarrelLong_corrRZ(driftRadius,zPosition,Layer, StrawLayer);
1462
  //return 0;
1463
1464
1465
}


1466
1467
1468

double TRT_ToT_dEdx::fitFuncEndcap_corrRZ(double driftRadius,double radialPosition, int Layer, int sign) const 
{
1469
1470
1471
  /**
   * T(r,R) = T0(r)+ a(r)*R
   */
1472
1473
  double T0 =  fitFuncPol_corrRZ(0,driftRadius,Layer,0,sign,2);
  double a  =  fitFuncPol_corrRZ(1,driftRadius,Layer,0,sign,2);
1474
1475
1476
1477
  return T0+a*radialPosition;
}


1478
1479
1480

double TRT_ToT_dEdx::fitFuncBarrelLong_corrRZ(double driftRadius,double zPosition, int Layer, int StrawLayer) const
{
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
  /**
   *                   |z|       /|z| - l  \
   * T(r,z) = T0(r) +   ---  exp|----------|
   *                    v(r)     \  s(r)   /
   */ 
  double z = fabs(zPosition);
  int sign=1;
  if(zPosition<0)sign=-1;
  double l = 704.6;
  // define set of parameters for negative and positive z positions
1491
1492
1493