Bug Summary

File:libraries/TRACKING/DReferenceTrajectory.cc
Location:line 667, column 2
Description:Access to field 'Ro' results in a dereference of a null pointer (loaded from variable 'step')

Annotated Source Code

1// $Id$
2//
3// File: DReferenceTrajectory.cc
4// Created: Wed Jul 19 13:42:58 EDT 2006
5// Creator: davidl (on Darwin swire-b241.jlab.org 8.7.0 powerpc)
6//
7
8#include <memory>
9
10#include <DVector3.h>
11using namespace std;
12#include <math.h>
13
14#include "DReferenceTrajectory.h"
15#include "DTrackCandidate.h"
16#include "DMagneticFieldStepper.h"
17#include "HDGEOMETRY/DRootGeom.h"
18#define ONE_THIRD0.33333333333333333 0.33333333333333333
19#define TWO_THIRD0.66666666666666667 0.66666666666666667
20#define EPS1e-8 1e-8
21#define NaNstd::numeric_limits<double>::quiet_NaN() std::numeric_limits<double>::quiet_NaN()
22
23struct StepStruct {DReferenceTrajectory::swim_step_t steps[256];};
24
25//---------------------------------
26// DReferenceTrajectory (Constructor)
27//---------------------------------
28DReferenceTrajectory::DReferenceTrajectory(const DMagneticFieldMap *bfield
29 , double q
30 , swim_step_t *swim_steps
31 , int max_swim_steps
32 , double step_size)
33{
34 // Copy some values into data members
35 this->q = q;
36 this->step_size = step_size;
37 this->bfield = bfield;
38 this->Nswim_steps = 0;
39 this->dist_to_rt_depth = 0;
40 this->mass = 0.13957; // assume pion mass until otherwise specified
41 this->hit_cdc_endplate = false;
42 this->RootGeom=NULL__null;
43 this->geom = NULL__null;
44 this->ploss_direction = kForward;
45 this->check_material_boundaries = true;
46
47 this->last_phi = 0.0;
48 this->last_swim_step = NULL__null;
49 this->last_dist_along_wire = 0.0;
50 this->last_dz_dphi = 0.0;
51
52 this->debug_level = 0;
53
54 // Initialize some values from configuration parameters
55 BOUNDARY_STEP_FRACTION = 0.80;
56 MIN_STEP_SIZE = 0.05; // cm
57 MAX_STEP_SIZE = 3.0; // cm
58 int MAX_SWIM_STEPS = 10000;
59
60 gPARMS->SetDefaultParameter("TRK:BOUNDARY_STEP_FRACTION" , BOUNDARY_STEP_FRACTION, "Fraction of estimated distance to boundary to use as step size");
61 gPARMS->SetDefaultParameter("TRK:MIN_STEP_SIZE" , MIN_STEP_SIZE, "Minimum step size in cm to take when swimming a track with adaptive step sizes");
62 gPARMS->SetDefaultParameter("TRK:MAX_STEP_SIZE" , MAX_STEP_SIZE, "Maximum step size in cm to take when swimming a track with adaptive step sizes");
63 gPARMS->SetDefaultParameter("TRK:MAX_SWIM_STEPS" , MAX_SWIM_STEPS, "Number of swim steps for DReferenceTrajectory to allocate memory for (when not using external buffer)");
64
65 // It turns out that the greatest bottleneck in speed here comes from
66 // allocating/deallocating the large block of memory required to hold
67 // all of the trajectory info. The preferred way of calling this is
68 // with a pointer allocated once at program startup. This code block
69 // though allows it to be allocated here if necessary.
70 if(!swim_steps){
71 own_swim_steps = true;
72 this->max_swim_steps = MAX_SWIM_STEPS;
73 this->swim_steps = new swim_step_t[this->max_swim_steps];
74 }else{
75 own_swim_steps = false;
76 this->max_swim_steps = max_swim_steps;
77 this->swim_steps = swim_steps;
78 }
79}
80
81//---------------------------------
82// DReferenceTrajectory (Copy Constructor)
83//---------------------------------
84DReferenceTrajectory::DReferenceTrajectory(const DReferenceTrajectory& rt)
85{
86 /// The copy constructor will always allocate its own memory for the
87 /// swim steps and set its internal flag to indicate that is owns them
88 /// regardless of the owner of the source trajectory's.
89
90 this->Nswim_steps = rt.Nswim_steps;
91 this->q = rt.q;
92 this->max_swim_steps = rt.max_swim_steps;
93 this->own_swim_steps = true;
94 this->step_size = rt.step_size;
95 this->bfield = rt.bfield;
96 this->last_phi = rt.last_phi;
97 this->last_dist_along_wire = rt.last_dist_along_wire;
98 this->last_dz_dphi = rt.last_dz_dphi;
99 this->RootGeom = rt.RootGeom;
100 this->geom = rt.geom;
101 this->dist_to_rt_depth = 0;
102 this->mass = rt.GetMass();
103 this->ploss_direction = rt.ploss_direction;
104 this->check_material_boundaries = rt.GetCheckMaterialBoundaries();
105 this->BOUNDARY_STEP_FRACTION = rt.GetBoundaryStepFraction();
106 this->MIN_STEP_SIZE = rt.GetMinStepSize();
107 this->MAX_STEP_SIZE = rt.GetMaxStepSize();
108 this->debug_level=rt.debug_level;
109
110 this->swim_steps = new swim_step_t[this->max_swim_steps];
111 this->last_swim_step = NULL__null;
112 for(int i=0; i<Nswim_steps; i++)
113 {
114 swim_steps[i] = rt.swim_steps[i];
115 if(&(rt.swim_steps[i]) == rt.last_swim_step)
116 this->last_swim_step = &(swim_steps[i]);
117 }
118
119}
120
121//---------------------------------
122// operator= (Assignment operator)
123//---------------------------------
124DReferenceTrajectory& DReferenceTrajectory::operator=(const DReferenceTrajectory& rt)
125{
126 /// The assignment operator will always make sure the memory allocated
127 /// for the swim_steps is owned by the object being copied into.
128 /// If it already owns memory of sufficient size, then it will be
129 /// reused. If it owns memory that is too small, it will be freed and
130 /// a new block allocated. If it does not own its swim_steps coming
131 /// in, then it will allocate memory so that it does own it on the
132 /// way out.
133
134 if(&rt == this)return *this; // protect against self copies
135
136 // Free memory if block is too small
137 if(own_swim_steps==true && max_swim_steps<rt.Nswim_steps){
138 delete[] swim_steps;
139 swim_steps=NULL__null;
140 }
141
142 // Forget memory block if we don't currently own it
143 if(!own_swim_steps){
144 swim_steps=NULL__null;
145 }
146
147 this->Nswim_steps = rt.Nswim_steps;
148 this->q = rt.q;
149 this->max_swim_steps = rt.max_swim_steps;
150 this->own_swim_steps = true;
151 this->step_size = rt.step_size;
152 this->bfield = rt.bfield;
153 this->last_phi = rt.last_phi;
154 this->last_dist_along_wire = rt.last_dist_along_wire;
155 this->last_dz_dphi = rt.last_dz_dphi;
156 this->RootGeom = rt.RootGeom;
157 this->geom = rt.geom;
158 this->dist_to_rt_depth = rt.dist_to_rt_depth;
159 this->mass = rt.GetMass();
160 this->ploss_direction = rt.ploss_direction;
161 this->check_material_boundaries = rt.GetCheckMaterialBoundaries();
162 this->BOUNDARY_STEP_FRACTION = rt.GetBoundaryStepFraction();
163 this->MIN_STEP_SIZE = rt.GetMinStepSize();
164 this->MAX_STEP_SIZE = rt.GetMaxStepSize();
165
166 // Allocate memory if needed
167 if(swim_steps==NULL__null)this->swim_steps = new swim_step_t[this->max_swim_steps];
168
169 // Copy swim steps
170 this->last_swim_step = NULL__null;
171 for(int i=0; i<Nswim_steps; i++)
172 {
173 swim_steps[i] = rt.swim_steps[i];
174 if(&(rt.swim_steps[i]) == rt.last_swim_step)
175 this->last_swim_step = &(swim_steps[i]);
176 }
177
178
179 return *this;
180}
181
182//---------------------------------
183// ~DReferenceTrajectory (Destructor)
184//---------------------------------
185DReferenceTrajectory::~DReferenceTrajectory()
186{
187 if(own_swim_steps){
188 delete[] swim_steps;
189 }
190}
191
192//---------------------------------
193// CopyWithShift
194//---------------------------------
195void DReferenceTrajectory::CopyWithShift(const DReferenceTrajectory *rt, DVector3 shift)
196{
197 // First, do a straight copy
198 *this = *rt;
199
200 // Second, shift all positions
201 for(int i=0; i<Nswim_steps; i++)swim_steps[i].origin += shift;
202}
203
204
205//---------------------------------
206// Reset
207//---------------------------------
208void DReferenceTrajectory::Reset(void){
209 //reset DReferenceTrajectory for re-use
210 this->Nswim_steps = 0;
211 this->ploss_direction = kForward;
212 this->mass = 0.13957; // assume pion mass until otherwise specified
213 this->hit_cdc_endplate = false;
214 this->last_phi = 0.0;
215 this->last_swim_step = NULL__null;
216 this->last_dist_along_wire = 0.0;
217 this->last_dz_dphi = 0.0;
218 //do not reset "swim_steps" array: "ought" be ok as long as "Nswim_steps" is accurate
219}
220
221//---------------------------------
222// FastSwim -- light-weight swim to a wire that does not treat multiple
223// scattering but does handle energy loss.
224// No checks for distance to boundaries are done.
225//---------------------------------
226void DReferenceTrajectory::FastSwim(const DVector3 &pos, const DVector3 &mom,
227 DVector3 &last_pos,DVector3 &last_mom,
228 double q,double smax,
229 const DCoordinateSystem *wire){
230 DVector3 mypos(pos);
231 DVector3 mymom(mom);
232
233 // Initialize the stepper
234 DMagneticFieldStepper stepper(bfield, q, &pos, &mom);
235 double s=0,doca=1000.,old_doca=1000.,dP_dx=0.;
236 double mass=GetMass();
237 while (s<smax){
238 // Save old value of doca
239 old_doca=doca;
240
241 // Adjust step size to take smaller steps in regions of high momentum loss
242 if(mass>0. && step_size<0.0 && geom){
243 double KrhoZ_overA=0.0;
244 double rhoZ_overA=0.0;
245 double LogI=0.0;
246 double X0=0.0;
247 if (geom->FindMatALT1(mypos,mymom,KrhoZ_overA,rhoZ_overA,LogI,X0)
248 ==NOERROR){
249 // Calculate momentum loss due to ionization
250 dP_dx = dPdx(mymom.Mag(), KrhoZ_overA, rhoZ_overA,LogI);
251 double my_step_size = 0.0001/fabs(dP_dx);
252
253 if(my_step_size>MAX_STEP_SIZE)my_step_size=MAX_STEP_SIZE; // maximum step size in cm
254 if(my_step_size<MIN_STEP_SIZE)my_step_size=MIN_STEP_SIZE; // minimum step size in cm
255
256 stepper.SetStepSize(my_step_size);
257 }
258 }
259 // Swim to next
260 double ds=stepper.Step(NULL__null);
261 s+=ds;
262
263 stepper.GetPosMom(mypos,mymom);
264 if (mass>0 && dP_dx<0.){
265 double ptot=mymom.Mag();
266 if (ploss_direction==kForward) ptot+=dP_dx*ds;
267 else ptot-=dP_dx*ds;
268 mymom.SetMag(ptot);
269 stepper.SetStartingParams(q, &mypos, &mymom);
270 }
271
272 // Break if we have passed the wire
273 DVector3 wirepos=wire->origin;
274 if (fabs(wire->udir.z())>0.){ // for CDC wires
275 wirepos+=((mypos.z()-wire->origin.z())/wire->udir.z())*wire->udir;
276 }
277 doca=(wirepos-mypos).Mag();
278 if (doca>old_doca) break;
279
280 // Store the position and momentum for this step
281 last_pos=mypos;
282 last_mom=mymom;
283 }
284}
285
286//---------------------------------
287// Swim
288//---------------------------------
289void DReferenceTrajectory::Swim(const DVector3 &pos, const DVector3 &mom, double q, double smax, const DCoordinateSystem *wire)
290{
291 /// (Re)Swim the trajectory starting from pos with momentum mom.
292 /// This will use the charge and step size (if given) passed to
293 /// the constructor when the object was created. It will also
294 /// (re)use the sim_step buffer, replacing it's contents.
295
296 // If the charged passed to us is greater that 10, it means use the charge
297 // already stored in the class. Otherwise, use what was passed to us.
298 if(fabs(q)>10)
299 q = this->q;
300 else
301 this->q = q;
302
303 DMagneticFieldStepper stepper(bfield, q, &pos, &mom);
304 if(step_size>0.0)stepper.SetStepSize(step_size);
305
306 // Step until we hit a boundary (don't track more than 20 meters)
307 swim_step_t *swim_step = this->swim_steps;
308 double t=0.;
309 Nswim_steps = 0;
310 double itheta02 = 0.0;
311 double itheta02s = 0.0;
312 double itheta02s2 = 0.0;
313 swim_step_t *last_step=NULL__null;
314 // Magnetic field
315 double Bz_old=0;
316
317 // Reset flag indicating whether we hit the CDC endplate
318 // and get the parameters of the endplate so we can check
319 // if we hit it while swimming.
320 hit_cdc_endplate = false;
321#if 0 // The GetCDCEndplate call goes all the way back to the XML and slows down
322 // overall tracking by a factor of 20. Therefore, we skip finding it
323 // and just hard-code the values instead. 1/28/2011 DL
324 double cdc_endplate_z=150+17; // roughly, from memory
325 double cdc_endplate_dz=5.0; // roughly, from memory
326 double cdc_endplate_rmin=10.0; // roughly, from memory
327 double cdc_endplate_rmax=55.0; // roughly, from memory
328 if(geom)geom->GetCDCEndplate(cdc_endplate_z, cdc_endplate_dz, cdc_endplate_rmin, cdc_endplate_rmax);
329 double cdc_endplate_zmin = cdc_endplate_z - cdc_endplate_dz/2.0;
330 double cdc_endplate_zmax = cdc_endplate_zmin + cdc_endplate_dz;
331#else
332 double cdc_endplate_rmin=10.0; // roughly, from memory
333 double cdc_endplate_rmax=55.0; // roughly, from memory
334 double cdc_endplate_zmin = 167.6;
335 double cdc_endplate_zmax = 168.2;
336#endif
337
338 // Get Bfield from stepper to initialize Bz_old
339 DVector3 B;
340 stepper.GetBField(B);
341 Bz_old = B.z();
342
343 for(double s=0; fabs(s)<smax; Nswim_steps++, swim_step++){
344
345
346 if(Nswim_steps>=this->max_swim_steps){
347 jerr<<__FILE__"DReferenceTrajectory.cc"<<":"<<__LINE__347<<" Too many steps in trajectory. Truncating..."<<endl;
348 break;
349 }
350
351 stepper.GetDirs(swim_step->sdir, swim_step->tdir, swim_step->udir);
352 stepper.GetPosMom(swim_step->origin, swim_step->mom);
353 swim_step->Ro = stepper.GetRo();
354 swim_step->s = s;
355 swim_step->t = t;
356
357 //magnitude of momentum and beta
358 double p_sq=swim_step->mom.Mag2();
359 double one_over_beta=sqrt(1.+mass*mass/p_sq);
360
361 // Add material if geom or RootGeom is not NULL
362 // If both are non-NULL, then use RootGeom
363 double dP = 0.0;
364 double dP_dx=0.0;
365 double s_to_boundary=1.0E6; // initialize to "infinity" in case we don't set this below
366 if(RootGeom || geom){
367 double KrhoZ_overA=0.0;
368 double rhoZ_overA=0.0;
369 double LogI=0.0;
370 double X0=0.0;
371 jerror_t err;
372 if(RootGeom){
373 double rhoZ_overA,rhoZ_overA_logI;
374 err = RootGeom->FindMatLL(swim_step->origin,
375 rhoZ_overA,
376 rhoZ_overA_logI,
377 X0);
378 KrhoZ_overA=0.1535e-3*rhoZ_overA;
379 LogI=rhoZ_overA_logI/rhoZ_overA;
380 }else{
381 if(check_material_boundaries){
382 err = geom->FindMatALT1(swim_step->origin, swim_step->mom, KrhoZ_overA, rhoZ_overA,LogI, X0, &s_to_boundary);
383 }else{
384 err = geom->FindMatALT1(swim_step->origin, swim_step->mom, KrhoZ_overA, rhoZ_overA,LogI, X0);
385 }
386
387 // Check if we hit the CDC endplate
388 double z = swim_step->origin.Z();
389 if(z>=cdc_endplate_zmin && z<=cdc_endplate_zmax){
390 double r = swim_step->origin.Perp();
391 if(r>=cdc_endplate_rmin && r<=cdc_endplate_rmax){
392 hit_cdc_endplate = true;
393 }
394 }
395 }
396
397 if(err == NOERROR){
398 if(X0>0.0){
399 double p=sqrt(p_sq);
400 double delta_s = s;
401 if(last_step)delta_s -= last_step->s;
402 double radlen = delta_s/X0;
403
404 if(radlen>1.0E-5){ // PDG 2008 pg 271, second to last paragraph
405
406 double theta0 = 0.0136*one_over_beta/p*sqrt(radlen)*(1.0+0.038*log(radlen)); // From PDG 2008 eq 27.12
407 double theta02 = theta0*theta0;
408 itheta02 += theta02;
409 itheta02s += s*theta02;
410 itheta02s2 += s*s*theta02;
411 }
412
413 // Calculate momentum loss due to ionization
414 dP_dx = dPdx(p, KrhoZ_overA, rhoZ_overA,LogI);
415 }
416 }
417 last_step = swim_step;
418 }
419 swim_step->itheta02 = itheta02;
420 swim_step->itheta02s = itheta02s;
421 swim_step->itheta02s2 = itheta02s2;
422
423 // Adjust step size to take smaller steps in regions of high momentum loss or field gradient
424 if(step_size<0.0){ // step_size<0 indicates auto-calculated step size
425 // Take step so as to change momentum by 100keV
426 //double my_step_size=p/fabs(dP_dx)*0.01;
427 double my_step_size = 0.0001/fabs(dP_dx);
428
429 // Now check the field gradient
430#if 0
431 stepper.GetBField(B);
432 double Bz = B.z();
433 if (fabs(Bz-Bz_old)>EPS1e-8){
434 double my_step_size_B=0.01*my_step_size
435 *fabs(Bz/(Bz_old-Bz));
436 if (my_step_size_B<my_step_size)
437 my_step_size=my_step_size_B;
438 }
439 Bz_old=Bz; // Save old z-component of B-field
440#endif
441 // Use the estimated distance to the boundary to make sure we don't overstep
442 // into a high density region and miss some material. Use half the estimated
443 // distance since it's only an estimate. Note that even though this would lead
444 // to infinitely small steps, there is a minimum step size imposed below to
445 // ensure the step size is reasonable.
446 double step_size_to_boundary = BOUNDARY_STEP_FRACTION*s_to_boundary;
447 if(step_size_to_boundary < my_step_size)my_step_size = step_size_to_boundary;
448
449 if(my_step_size>MAX_STEP_SIZE)my_step_size=MAX_STEP_SIZE; // maximum step size in cm
450 if(my_step_size<MIN_STEP_SIZE)my_step_size=MIN_STEP_SIZE; // minimum step size in cm
451
452 stepper.SetStepSize(my_step_size);
453 }
454
455 // Swim to next
456 double ds=stepper.Step(NULL__null);
457
458 // Calculate momentum loss due to the step we're about to take
459 dP = ds*dP_dx;
460 swim_step->dP = dP; // n.b. stepper has been updated for next round but we're still on present step
461
462 // Adjust momentum due to ionization losses
463 if(dP!=0.0){
464 DVector3 pos, mom;
465 stepper.GetPosMom(pos, mom);
466 double ptot = mom.Mag() - dP; // correct for energy loss
467 bool ranged_out = false;
468 if(ptot<0.0)ranged_out=true;
469 if(dP<0.0 && ploss_direction==kForward)ranged_out=true;
470 if(dP>0.0 && ploss_direction==kBackward)ranged_out=true;
471 if(mom.Mag()==0.0)ranged_out=true;
472 if(ranged_out){
473 Nswim_steps++; // This will at least allow for very low momentum particles to have 1 swim step
474 break;
475 }
476 mom.SetMag(ptot);
477 stepper.SetStartingParams(q, &pos, &mom);
478 }
479
480 // update flight time
481 t+=ds*one_over_beta/SPEED_OF_LIGHT29.9792;
482 s += ds;
483
484
485 // Exit loop if we leave the tracking volume
486 if(swim_step->origin.Perp()>88.0
487 && swim_step->origin.Z()<407.0){Nswim_steps++; break;} // ran into BCAL
488 if (swim_step->origin.X()>129. || swim_step->origin.Y()>129.)
489 {Nswim_steps++; break;} // left extent of TOF
490 if(swim_step->origin.Z()>670.0){Nswim_steps++; break;} // ran into FCAL
491 if(swim_step->origin.Z()<-100.0){Nswim_steps++; break;} // exit upstream
492 if(wire && Nswim_steps>0){ // optionally check if we passed a wire we're supposed to be swimming to
493 swim_step_t *closest_step = FindClosestSwimStep(wire);
494 if(++closest_step!=swim_step){Nswim_steps++; break;}
495 }
496 }
497
498 // OK. At this point the positions of the trajectory in the lab
499 // frame have been recorded along with the momentum of the
500 // particle and the directions of reference trajectory
501 // coordinate system at each point.
502}
503
504
505// Routine to find position on the trajectory where the track crosses a radial
506// position R. Also returns the path length to this position.
507jerror_t DReferenceTrajectory::GetIntersectionWithRadius(double R,
508 DVector3 &mypos,
509 double *s,
510 double *t) const{
511 if(Nswim_steps<1){
512 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
512<<" "
<<"No swim steps! You must \"Swim\" the track before calling GetIntersectionWithRadius(...)"<<endl;
513 }
514 // Loop over swim steps and find the one that crosses the radius
515 swim_step_t *swim_step = swim_steps;
516 swim_step_t *step=NULL__null;
517 swim_step_t *last_step=NULL__null;
518 for(int i=0; i<Nswim_steps; i++, swim_step++){
519 if (swim_step->origin.Perp()>R){
520 step=swim_step;
521 break;
522 }
523 if (swim_step->origin.Z()>407.0) return VALUE_OUT_OF_RANGE;
524 last_step=swim_step;
525 }
526 if (step==NULL__null||last_step==NULL__null) return VALUE_OUT_OF_RANGE;
527
528 // At this point, the location where the track intersects the cyclinder
529 // is somewhere between last_step and step. For simplicity, we're going
530 // to just find the intersection of the cylinder with the line that joins
531 // the 2 positions. We do this by working in the X/Y plane only and
532 // finding the value of "alpha" which is the fractional distance the
533 // intersection point is between last_pos and mypos. We'll then apply
534 // the alpha found in the 2D X/Y space to the 3D x/y/Z space to find
535 // the actual intersection point.
536 DVector2 x1(last_step->origin.X(), last_step->origin.Y());
537 DVector2 x2(step->origin.X(), step->origin.Y());
538 DVector2 dx = x2-x1;
539 double A = dx.Mod2();
540 double B = 2.0*(x1.X()*dx.X() + x1.Y()*dx.Y());
541 double C = x1.Mod2() - R*R;
542
543 double sqrt_D=sqrt(B*B-4.0*A*C);
544 double one_over_denom=0.5/A;
545 double alpha1 = (-B + sqrt_D)*one_over_denom;
546 double alpha2 = (-B - sqrt_D)*one_over_denom;
547 double alpha = alpha1;
548 if(alpha1<0.0 || alpha1>1.0)alpha=alpha2;
549 if(!finite(alpha))return VALUE_OUT_OF_RANGE;
550
551 DVector3 delta = step->origin - last_step->origin;
552 mypos = last_step->origin + alpha*delta;
553
554 // The value of s actually represents the pathlength
555 // to the outside point. Adjust it back to the
556 // intersection point (approximately).
557 if (s) *s = step->s-(1.0-alpha)*delta.Mag();
558
559 // flight time
560 if (t){
561 double p_sq=step->mom.Mag2();
562 double one_over_beta=sqrt(1.+mass*mass/p_sq);
563 *t = step->t-(1.0-alpha)*delta.Mag()*one_over_beta/SPEED_OF_LIGHT29.9792;
564 }
565
566 return NOERROR;
567}
568
569//---------------------------------
570// GetIntersectionWithPlane
571//---------------------------------
572void DReferenceTrajectory::GetIntersectionWithPlane(const DVector3 &origin, const DVector3 &norm, DVector3 &pos, double *s,double *t) const{
573 DVector3 dir;
574 GetIntersectionWithPlane(origin,norm,pos,dir,s,t);
575}
576void DReferenceTrajectory::GetIntersectionWithPlane(const DVector3 &origin, const DVector3 &norm, DVector3 &pos, DVector3 &dir, double *s,double *t) const
577{
578 /// Get the intersection point of this trajectory with a plane.
579 /// The plane is specified by <i>origin</i> and <i>norm</i>. The
580 /// <i>origin</i> vector should give the coordinates of any point
581 /// on the plane and <i>norm</i> should give a vector normal to
582 /// the plane. The <i>norm</i> vector will be copied and normalized
583 /// so it can be of any magnitude upon entry.
584 ///
585 /// The coordinates of the intersection point will copied into
586 /// the supplied <i>pos</i> vector. If a non-NULL pointer for <i>s</i>
587 /// is passed in, the pathlength of the trajectory from its begining
588 /// to the intersection point is copied into location pointed to.
589
590 // Set reasonable defaults
591 pos.SetXYZ(0,0,0);
592 if(s)*s=0.0;
1
Taking false branch
593
594 // Find the closest swim step to the position where the track crosses
595 // the plane
596 swim_step_t *step = FindPlaneCrossing(origin,norm);
597 // Kludge for tracking to forward detectors assuming that the planes
598 // are perpendicular to the beam line
599 if (step && step->origin.Z()>600.
600 ){
601 double p_sq=step->mom.Mag2();
602 //double ds=(origin.z()-step->origin.z())*p/step->mom.z();
603 double dz_over_pz=(origin.z()-step->origin.z())/step->mom.z();
604 double ds=sqrt(p_sq)*dz_over_pz;
605 pos.SetXYZ(step->origin.x()+dz_over_pz*step->mom.x(),
606 step->origin.y()+dz_over_pz*step->mom.y(),
607 origin.z());
608 dir=step->mom;
609 dir.SetMag(1.0);
610 if (s){
611 *s=step->s+ds;
612 }
613 // flight time
614 if (t){
615 double one_over_beta=sqrt(1.+mass*mass/p_sq);
616 *t = step->t+ds*one_over_beta/SPEED_OF_LIGHT29.9792;
617 }
618
619 return;
620 }
621
622 if(!step){
2
Taking false branch
623 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
623<<" "
<<"Could not find closest swim step!"<<endl;
624 return;
625 }
626
627 // Here we follow a scheme described in more detail in the
628 // DistToRT(DVector3 hit) method below. The basic idea is to
629 // express a point on the helix in terms of a single variable
630 // and then solve for that variable by setting the distance
631 // to zero.
632 //
633 // x = Ro*(cos(phi) - 1)
634 // y = Ro*sin(phi)
635 // z = phi*(dz/dphi)
636 //
637 // As is done below, we work in the RT coordinate system. Well,
638 // sort of. The distance to the plane is given by:
639 //
640 // d = ( x - c ).n
641 //
642 // where x is a point on the helix, c is the "origin" point
643 // which lies somewhere in the plane and n is the "norm"
644 // vector. Since we want a point in the plane, we set d=0
645 // and solve for phi (with the components of x expressed in
646 // terms of phi as given in the DistToRT method below).
647 //
648 // Thus, the equation we need to solve is:
649 //
650 // x.n - c.n = 0
651 //
652 // notice that "c" only gets dotted into "n" so that
653 // dot product can occur in any coordinate system. Therefore,
654 // we do that in the lab coordinate system to avoid the
655 // overhead of transforming "c" to the RT system. The "n"
656 // vector, however, still must be transformed.
657 //
658 // Expanding the trig functions to 2nd order in phi, performing
659 // the x.n dot product, and gathering equal powers of phi
660 // leads us to he following:
661 //
662 // (-Ro*nx/2)*phi^2 + (Ro*ny+dz_dphi*nz)*phi - c.n = 0
663 //
664 // which is quadratic in phi. We solve for both roots, but use
665 // the one with the smller absolute value (if both are finite).
666
667 double &Ro = step->Ro;
3
Access to field 'Ro' results in a dereference of a null pointer (loaded from variable 'step')
668
669 // OK, having said all of that, it turns out that the above
670 // mechanism will tend to fail in regions of low or no
671 // field because the value of Ro is very large. Thus, we need to
672 // use a straight line projection in such cases. We also
673 // want to use a straight line projection if the helical intersection
674 // fails for some other reason.
675 //
676 // The algorthim is then to only try the helical calculation
677 // for small (<10m) values of Ro and then do the straight line
678 // if R is larger than that OR the helical calculation fails.
679
680 // Try helical calculation
681 if(Ro<1000.0){
682 double nx = norm.Dot(step->sdir);
683 double ny = norm.Dot(step->tdir);
684 double nz = norm.Dot(step->udir);
685
686 double delta_z = step->mom.Dot(step->udir);
687 double delta_phi = step->mom.Dot(step->tdir)/Ro;
688 double dz_dphi = delta_z/delta_phi;
689
690 double A = -Ro*nx/2.0;
691 double B = Ro*ny + dz_dphi*nz;
692 double C = norm.Dot(step->origin-origin);
693 double sqroot=sqrt(B*B-4.0*A*C);
694 double twoA=2.0*A;
695
696 double phi_1 = (-B + sqroot)/(twoA);
697 double phi_2 = (-B - sqroot)/(twoA);
698
699 double phi = fabs(phi_1)<fabs(phi_2) ? phi_1:phi_2;
700 if(!finite(phi_1))phi = phi_2;
701 if(!finite(phi_2))phi = phi_1;
702 if(finite(phi)){
703
704 double my_s = -Ro/2.0 * phi*phi;
705 double my_t = Ro * phi;
706 double my_u = dz_dphi * phi;
707
708 pos = step->origin + my_s*step->sdir + my_t*step->tdir + my_u*step->udir;
709 dir = step->mom;
710 dir.SetMag(1.0);
711 if(s){
712 double delta_s = sqrt(my_t*my_t + my_u*my_u);
713 *s = step->s + (phi>0 ? +delta_s:-delta_s);
714 }
715 // flight time
716 if (t){
717 double delta_s = sqrt(my_t*my_t + my_u*my_u);
718 double ds=(phi>0 ? +delta_s:-delta_s);
719 double p_sq=step->mom.Mag2();
720 double one_over_beta=sqrt(1.+mass*mass/p_sq);
721 *t = step->t+ds*one_over_beta/SPEED_OF_LIGHT29.9792;
722 }
723
724 // Success. Go ahead and return
725 return;
726 }
727 }
728
729 // If we got here then we need to try a straight line calculation
730 double alpha = norm.Dot(origin)/norm.Dot(step->mom);
731 pos = alpha*step->mom;
732 dir = step->mom;
733 dir.SetMag(1.0);
734 if(s){
735 double delta_s = alpha*step->mom.Mag();
736 *s = step->s + delta_s;
737 }
738 // flight time
739 if (t){
740 double p_sq=step->mom.Mag2();
741 double one_over_beta=sqrt(1.+mass*mass/p_sq);
742 *t = step->t+alpha*sqrt(p_sq)*one_over_beta/SPEED_OF_LIGHT29.9792;
743 }
744}
745
746//---------------------------------
747// InsertSteps
748//---------------------------------
749int DReferenceTrajectory::InsertSteps(const swim_step_t *start_step, double delta_s, double step_size)
750{
751 /// Insert additional steps into the reference trajectory starting
752 /// at start_step and swimming for at least delta_s by step_size
753 /// sized steps. Both delta_s and step_size are in centimeters.
754 /// If the value of delta_s is negative then the particle's momentum
755 /// and charge are reversed before swimming. This could be a problem
756 /// if energy loss is implemented.
757
758 if(!start_step)return -1;
759
760 // We do this by creating another, temporary DReferenceTrajectory object
761 // on the stack and swimming it.
762 DVector3 pos = start_step->origin;
763 DVector3 mom = start_step->mom;
764 double my_q = q;
765 int direction = +1;
766 if(delta_s<0.0){
767 mom *= -1.0;
768 my_q = -q;
769 direction = -1;
770 }
771
772 // Here I allocate the steps using an auto_ptr so I don't have to mess with
773 // deleting them at all of the possible exits. The problem with auto_ptr
774 // is it can't handle arrays so it has to be wrapped in a struct.
775 auto_ptr<StepStruct> steps_aptr(new StepStruct);
776 DReferenceTrajectory::swim_step_t *steps = steps_aptr->steps;
777 DReferenceTrajectory rt(bfield , my_q , steps , 256);
778 rt.SetStepSize(step_size);
779 rt.Swim(pos, mom, my_q, fabs(delta_s));
780 if(rt.Nswim_steps==0)return 1;
781
782 // Check that there is enough space to add these points
783 if((Nswim_steps+rt.Nswim_steps)>max_swim_steps){
784 //_DBG_<<"Not enough swim steps available to add new ones! Max="<<max_swim_steps<<" had="<<Nswim_steps<<" new="<<rt.Nswim_steps<<endl;
785 return 2;
786 }
787
788 // At this point, we may have swum forward or backwards so the points
789 // will need to be added either before start_step or after it. We also
790 // may want to replace an old step that overlaps our high density steps
791 // since they are presumably more accurate. Find the indexes of the
792 // existing steps that the new steps will be inserted between.
793 double sdiff = rt.swim_steps[rt.Nswim_steps-1].s;
794 double s1 = start_step->s;
795 double s2 = start_step->s + (double)direction*sdiff;
796 double smin = s1<s2 ? s1:s2;
797 double smax = s1<s2 ? s2:s1;
798 int istep_start = 0;
799 int istep_end = 0;
800 for(int i=0; i<Nswim_steps; i++){
801 if(swim_steps[i].s < smin)istep_start = i;
802 if(swim_steps[i].s <= smax)istep_end = i+1;
803 }
804
805 // istep_start and istep_end now point to the steps we want to keep.
806 // All steps between them (exclusive) will be overwritten. Note that
807 // the original start_step should be in the "overwrite" range since
808 // it is included already in the new trajectory.
809 int steps_to_overwrite = istep_end - istep_start - 1;
810 int steps_to_shift = rt.Nswim_steps - steps_to_overwrite;
811
812 // Shift the steps down (or is it up?) starting with istep_end.
813 for(int i=Nswim_steps-1; i>=istep_end; i--)swim_steps[i+steps_to_shift] = swim_steps[i];
814
815 // Copy the new steps into this object
816 double s_0 = start_step->s;
817 double itheta02_0 = start_step->itheta02;
818 double itheta02s_0 = start_step->itheta02s;
819 double itheta02s2_0 = start_step->itheta02s2;
820 for(int i=0; i<rt.Nswim_steps; i++){
821 int index = direction>0 ? (istep_start+1+i):(istep_start+1+rt.Nswim_steps-1-i);
822 swim_steps[index] = rt.swim_steps[i];
823 swim_steps[index].s = s_0 + (double)direction*swim_steps[index].s;
824 swim_steps[index].itheta02 = itheta02_0 + (double)direction*swim_steps[index].itheta02;
825 swim_steps[index].itheta02s = itheta02s_0 + (double)direction*swim_steps[index].itheta02s;
826 swim_steps[index].itheta02s2 = itheta02s2_0 + (double)direction*swim_steps[index].itheta02s2;
827 if(direction<0.0){
828 swim_steps[index].sdir *= -1.0;
829 swim_steps[index].tdir *= -1.0;
830 }
831 }
832 Nswim_steps += rt.Nswim_steps-steps_to_overwrite;
833
834 // Note that the above procedure may leave us with "kinks" in the itheta0
835 // variables. It may be that we need to recalculate those for all of the
836 // new points and the ones after them by making one more pass. I'm hoping
837 // it is a realitively small correction though so we can skip it here.
838 return 0;
839}
840
841//---------------------------------
842// DistToRTwithTime
843//---------------------------------
844double DReferenceTrajectory::DistToRTwithTime(DVector3 hit, double *s,double *t) const{
845 double dist=DistToRT(hit,s);
846 if (s!=NULL__null && t!=NULL__null && last_swim_step!=NULL__null){
847 double p_sq=last_swim_step->mom.Mag2();
848 double one_over_beta=sqrt(1.+mass*mass/p_sq);
849 *t=last_swim_step->t+(*s-last_swim_step->s)*one_over_beta/SPEED_OF_LIGHT29.9792;
850 }
851 return dist;
852}
853
854//---------------------------------
855// DistToRT
856//---------------------------------
857double DReferenceTrajectory::DistToRT(DVector3 hit, double *s) const
858{
859 last_swim_step=NULL__null;
860 if(Nswim_steps<1)_DBG__std::cerr<<"DReferenceTrajectory.cc"<<":"<<
860<<std::endl
;
861
862 // First, find closest step to point
863 swim_step_t *swim_step = swim_steps;
864 swim_step_t *step=NULL__null;
865 //double min_delta2 = 1.0E6;
866 double old_delta2=10.e6,delta2=1.0e6;
867 for(int i=0; i<Nswim_steps; i++, swim_step++){
868
869 DVector3 pos_diff = swim_step->origin - hit;
870 delta2 = pos_diff.Mag2();
871 if (delta2>old_delta2) break;
872
873 //if(delta2 < min_delta2){
874 //min_delta2 = delta2;
875
876 step = swim_step;
877 old_delta2=delta2;
878 //}
879 }
880 if(step==NULL__null){
881 // It seems to occasionally occur that we have 1 swim step
882 // and it's values are invalid. Supress warning messages
883 // for these as they are "known" (even if not fully understood!)
884 if(Nswim_steps>1){
885 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
885<<" "
<<"\"hit\" passed to DistToRT(DVector3) out of range!"<<endl;
886 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
886<<" "
<<"hit x,y,z = "<<hit.x()<<", "<<hit.y()<<", "<<hit.z()<<" Nswim_steps="<<Nswim_steps<<" min_delta2="<<delta2<<endl;
887 }
888 return 1.0E6;
889 }
890
891 // store last step
892 last_swim_step=step;
893
894
895 // Next, define a point on the helical segment defined by the
896 // swim step it the RT coordinate system. The directions of
897 // the RT coordinate system are defined by step->xdir, step->ydir,
898 // and step->zdir. The coordinates of a point on the helix
899 // in this coordinate system are:
900 //
901 // x = Ro*(cos(phi) - 1)
902 // y = Ro*sin(phi)
903 // z = phi*(dz/dphi)
904 //
905 // where phi is the phi angle of the point in this coordinate system.
906 // phi=0 corresponds to the swim step point itself
907 //
908 // Transform the given coordinates to the RT coordinate system
909 // and call these x0,y0,z0. Then, the distance of point to a
910 // point on the helical segment is given by:
911 //
912 // d^2 = (x0-x)^2 + (y0-y)^2 + (z0-z)^2
913 //
914 // where x,y,z are all functions of phi as given above.
915 //
916 // writing out d^2 in terms of phi, but using the small angle
917 // approximation for the trig functions, an equation for the
918 // distance in only phi is obtained. Taking the derivative
919 // and setting it equal to zero leaves a 3rd order polynomial
920 // in phi whose root corresponds to the minimum distance.
921 // Skipping some math, this equation has the form:
922 //
923 // d(d^2)/dphi = 0 = Ro^2*phi^3 + 2*alpha*phi + beta
924 //
925 // where:
926 // alpha = x0*Ro + Ro^2 + (dz/dphi)^2
927 //
928 // beta = -2*y0*Ro - 2*z0*(dz/dphi)
929 //
930 // The above 3rd order poly is convenient in that it does not
931 // contain a phi^2 term. This means we can skip the step
932 // done in the general case where a change of variables is
933 // made such that the 2nd order term disappears.
934 //
935 // In general, an equation of the form
936 //
937 // w^3 + 3.0*b*w + 2*c = 0
938 //
939 // has one real root:
940 //
941 // w0 = q - p
942 //
943 // where:
944 // q^3 = d - c
945 // p^3 = d + c
946 // d^2 = b^3 + c^2 (don't confuse with d^2 above!)
947 //
948 // So for us ...
949 //
950 // 3b = 2*alpha/(Ro^2)
951 // 2c = beta/(Ro^2)
952
953 hit -= step->origin;
954 double x0 = hit.Dot(step->sdir);
955 double y0 = hit.Dot(step->tdir);
956 double z0 = hit.Dot(step->udir);
957 double &Ro = step->Ro;
958 double Ro2 = Ro*Ro;
959 double delta_z = step->mom.Dot(step->udir);
960 double delta_phi = step->mom.Dot(step->tdir)/Ro;
961 double dz_dphi = delta_z/delta_phi;
962
963 // double alpha = x0*Ro + Ro2 + pow(dz_dphi,2.0);
964 double alpha=x0*Ro + Ro2 +dz_dphi*dz_dphi;
965 // double beta = -2.0*y0*Ro - 2.0*z0*dz_dphi;
966 double beta = -2.0*(y0*Ro + z0*dz_dphi);
967 // double b = (2.0*alpha/Ro2)/3.0;
968 double b= TWO_THIRD0.66666666666666667*alpha/Ro2;
969 // double c = (beta/Ro2)/2.0;
970 double c = 0.5*(beta/Ro2);
971 // double d = sqrt(pow(b,3.0) + pow(c,2.0));
972 double d2=b*b*b+c*c;
973 double phi=0.,dist2=1e8;
974 if (d2>=0){
975 double d=sqrt(d2);
976 //double q = pow(d-c, ONE_THIRD);
977 //double p = pow(d+c, ONE_THIRD);
978 double p=cbrt(d+c);
979 double q=cbrt(d-c);
980 phi = q - p;
981 double phisq=phi*phi;
982
983 dist2 = 0.25*Ro2*phisq*phisq + alpha*phisq + beta*phi
984 + x0*x0 + y0*y0 + z0*z0;
985 }
986 else{
987 // Use DeMoivre's theorem to find the cube root of a complex
988 // number. In this case there are three real solutions.
989 double d=sqrt(-d2);
990 c*=-1.;
991 double temp=sqrt(cbrt(c*c+d*d));
992 double theta1=ONE_THIRD0.33333333333333333*atan2(d,c);
993 double sum_over_2=temp*cos(theta1);
994 double diff_over_2=-temp*sin(theta1);
995
996 double phi0=2.*sum_over_2;
997 double phi0sq=phi0*phi0;
998 double phi1=-sum_over_2+sqrt(3)*diff_over_2;
999 double phi1sq=phi1*phi1;
1000 double phi2=-sum_over_2-sqrt(3)*diff_over_2;
1001 double phi2sq=phi2*phi2;
1002 double d2_2 = 0.25*Ro2*phi2sq*phi2sq + alpha*phi2sq + beta*phi2 + x0*x0 + y0*y0 + z0*z0;
1003 double d2_1 = 0.25*Ro2*phi1sq*phi1sq + alpha*phi1sq + beta*phi1 + x0*x0 + y0*y0 + z0*z0;
1004 double d2_0 = 0.25*Ro2*phi0sq*phi0sq + alpha*phi0sq + beta*phi0 + x0*x0 + y0*y0 + z0*z0;
1005
1006 if (d2_0<d2_1 && d2_0<d2_2){
1007 phi=phi0;
1008 dist2=d2_0;
1009 }
1010 else if (d2_1<d2_0 && d2_1<d2_2){
1011 phi=phi1;
1012 dist2=d2_1;
1013 }
1014 else{
1015 phi=phi2;
1016 dist2=d2_2;
1017 }
1018
1019 if (isnan(Ro))
1020 {
1021 }
1022 }
1023
1024
1025
1026 // Calculate distance along track ("s")
1027 if(s!=NULL__null){
1028 double dz = dz_dphi*phi;
1029 double Rodphi = Ro*phi;
1030 double ds = sqrt(dz*dz + Rodphi*Rodphi);
1031 *s = step->s + (phi>0.0 ? ds:-ds);
1032 }
1033
1034 this->last_phi = phi;
1035 this->last_swim_step = step;
1036 this->last_dz_dphi = dz_dphi;
1037
1038 return sqrt(dist2);
1039}
1040
1041//---------------------------------
1042// FindClosestSwimStep
1043//---------------------------------
1044DReferenceTrajectory::swim_step_t* DReferenceTrajectory::FindClosestSwimStep(const DCoordinateSystem *wire, int *istep_ptr) const
1045{
1046 /// Find the closest swim step to the given wire. The value of
1047 /// "L" should be the active wire length. The coordinate system
1048 /// defined by "wire" should have its origin at the center of
1049 /// the wire with the wire running in the direction of udir.
1050
1051 if(istep_ptr)*istep_ptr=-1;
1052
1053 if(Nswim_steps<1){
1054 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1054<<" "
<<"No swim steps! You must \"Swim\" the track before calling FindClosestSwimStep(...)"<<endl;
1055 }
1056
1057 // Make sure we have a wire first!
1058 if(!wire)return NULL__null;
1059
1060 // Loop over swim steps and find the one closest to the wire
1061 swim_step_t *swim_step = swim_steps;
1062 swim_step_t *step=NULL__null;
1063 //double min_delta2 = 1.0E6;
1064 double old_delta2=1.0e6;
1065 double L_over_2 = wire->L/2.0; // half-length of wire in cm
1066 int istep=-1;
1067
1068 double dx, dy, dz;
1069
1070 // w is a vector to the origin of the wire
1071 // u is a unit vector along the wire
1072
1073 double wx, wy, wz;
1074 double ux, uy, uz;
1075
1076 wx = wire->origin.X();
1077 wy = wire->origin.Y();
1078 wz = wire->origin.Z();
1079
1080 ux = wire->udir.X();
1081 uy = wire->udir.Y();
1082 uz = wire->udir.Z();
1083
1084 int i;
1085 for(i=0; i<Nswim_steps; i++, swim_step++){
1086 // Find the point's position along the wire. If the point
1087 // is past the end of the wire, calculate the distance
1088 // from the end of the wire.
1089 // DVector3 pos_diff = swim_step->origin - wire->origin;
1090
1091 dx = swim_step->origin.X() - wx;
1092 dy = swim_step->origin.Y() - wy;
1093 dz = swim_step->origin.Z() - wz;
1094
1095 // double u = wire->udir.Dot(pos_diff);
1096 double u = ux * dx + uy * dy + uz * dz;
1097
1098 // Find distance perpendicular to wire
1099 // double delta2 = pos_diff.Mag2() - u*u;
1100 double delta2 = dx*dx + dy*dy + dz*dz - u*u;
1101
1102 // If point is past end of wire, calculate distance
1103 // from wire's end by adding on distance along wire direction.
1104 if( fabs(u)>L_over_2){
1105 // delta2 += pow(fabs(u)-L_over_2, 2.0);
1106 double u_minus_L_over_2=fabs(u)-L_over_2;
1107 delta2 += ( u_minus_L_over_2*u_minus_L_over_2 );
1108 // printf("step %d\n",i);
1109 }
1110
1111 if(debug_level>3)_DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1111<<" "
<<"delta2="<<delta2<<" old_delta2="<<old_delta2<<endl;
1112 if (delta2>old_delta2) break;
1113
1114 //if(delta2 < min_delta2){
1115 // min_delta2 = delta2;
1116 step = swim_step;
1117 istep=i;
1118
1119 //}
1120 //printf("%d delta %f min %f\n",i,delta2,min_delta2);
1121 old_delta2=delta2;
1122 }
1123
1124 if(istep_ptr)*istep_ptr=istep;
1125
1126 if(debug_level>3)_DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1126<<" "
<<"found closest step at i="<<i<<" istep_ptr="<<istep_ptr<<endl;
1127
1128 return step;
1129}
1130
1131//---------------------------------
1132// FindClosestSwimStep
1133//---------------------------------
1134DReferenceTrajectory::swim_step_t* DReferenceTrajectory::FindClosestSwimStep(const DVector3 &origin, DVector3 norm, int *istep_ptr) const
1135{
1136 /// Find the closest swim step to the plane specified by origin
1137 /// and norm. origin should indicate any point in the plane and
1138 /// norm a vector normal to the plane.
1139 if(istep_ptr)*istep_ptr=-1;
1140
1141 if(Nswim_steps<1){
1142 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1142<<" "
<<"No swim steps! You must \"Swim\" the track before calling FindClosestSwimStep(...)"<<endl;
1143 }
1144
1145 // Make sure normal vector is unit lenght
1146 norm.SetMag(1.0);
1147
1148 // Loop over swim steps and find the one closest to the plane
1149 swim_step_t *swim_step = swim_steps;
1150 swim_step_t *step=NULL__null;
1151 //double min_dist = 1.0E6;
1152 double old_dist=1.0e6;
1153 int istep=-1;
1154
1155 for(int i=0; i<Nswim_steps; i++, swim_step++){
1156
1157 // Distance to plane is dot product of normal vector with any
1158 // vector pointing from the current step to a point in the plane
1159 double dist = fabs(norm.Dot(swim_step->origin-origin));
1160
1161 if (dist>old_dist) break;
1162
1163 // Check if we're the closest step
1164 //if(dist < min_dist){
1165 //min_dist = dist;
1166
1167 step = swim_step;
1168 istep=i;
1169 //}
1170 old_dist=dist;
1171
1172 // We should probably have a break condition here so we don't
1173 // waste time looking all the way to the end of the track after
1174 // we've passed the plane.
1175 }
1176
1177 if(istep_ptr)*istep_ptr=istep;
1178
1179 return step;
1180}
1181
1182
1183//---------------------------------
1184// FindPlaneCrossing
1185//---------------------------------
1186DReferenceTrajectory::swim_step_t* DReferenceTrajectory::FindPlaneCrossing(const DVector3 &origin, DVector3 norm, int *istep_ptr) const
1187{
1188 /// Find the closest swim step to the position where the track crosses
1189 /// the plane specified by origin
1190 /// and norm. origin should indicate any point in the plane and
1191 /// norm a vector normal to the plane.
1192 if(istep_ptr)*istep_ptr=-1;
1193
1194 if(Nswim_steps<1){
1195 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1195<<" "
<<"No swim steps! You must \"Swim\" the track before calling FindPlaneCrossing(...)"<<endl;
1196*((int*)NULL__null) = 1; // force seg. fault
1197 }
1198
1199 // Make sure normal vector is unit lenght
1200 norm.SetMag(1.0);
1201
1202 // Loop over swim steps and find the one closest to the plane
1203 swim_step_t *swim_step = swim_steps;
1204 swim_step_t *step=NULL__null;
1205 //double min_dist = 1.0E6;
1206 int istep=-1;
1207 double old_dist=1.0e6;
1208
1209 for(int i=0; i<Nswim_steps; i++, swim_step++){
1210
1211 // Distance to plane is dot product of normal vector with any
1212 // vector pointing from the current step to a point in the plane
1213 //double dist = fabs(norm.Dot(swim_step->origin-origin));
1214 double dist = norm.Dot(swim_step->origin-origin);
1215
1216 // We've crossed the plane when the sign of dist changes
1217 if (dist*old_dist<0 && i>0) {
1218 if (fabs(dist)<fabs(old_dist)){
1219 step=swim_step;
1220 istep=i;
1221 }
1222 break;
1223 }
1224 step = swim_step;
1225 istep=i;
1226 old_dist=dist;
1227 }
1228
1229 if(istep_ptr)*istep_ptr=istep;
1230
1231 return step;
1232}
1233
1234
1235
1236
1237//---------------------------------
1238// DistToRT
1239//---------------------------------
1240double DReferenceTrajectory::DistToRT(const DCoordinateSystem *wire, double *s) const
1241{
1242 /// Find the closest distance to the given wire in cm. The value of
1243 /// "L" should be the active wire length (in cm). The coordinate system
1244 /// defined by "wire" should have its origin at the center of
1245 /// the wire with the wire running in the direction of udir.
1246 swim_step_t *step=FindClosestSwimStep(wire);
1247
1248 return (step && step->s>0) ? DistToRT(wire, step, s):std::numeric_limits<double>::quiet_NaN();
1249}
1250
1251//---------------------------------
1252// DistToRTBruteForce
1253//---------------------------------
1254double DReferenceTrajectory::DistToRTBruteForce(const DCoordinateSystem *wire, double *s) const
1255{
1256 /// Find the closest distance to the given wire in cm. The value of
1257 /// "L" should be the active wire length (in cm). The coordinate system
1258 /// defined by "wire" should have its origin at the center of
1259 /// the wire with the wire running in the direction of udir.
1260 swim_step_t *step=FindClosestSwimStep(wire);
1261
1262 return step ? DistToRTBruteForce(wire, step, s):std::numeric_limits<double>::quiet_NaN();
1263}
1264
1265//------------------
1266// DistToRT
1267//------------------
1268double DReferenceTrajectory::DistToRT(const DCoordinateSystem *wire, const swim_step_t *step, double *s) const
1269{
1270 /// Calculate the distance of the given wire(in the lab
1271 /// reference frame) to the Reference Trajectory which the
1272 /// given swim step belongs to. This uses the momentum directions
1273 /// and positions of the swim step
1274 /// to define a curve and calculate the distance of the hit
1275 /// from it. The swim step should be the closest one to the wire.
1276 /// IMPORTANT: This approximates the helix locally by a parabola.
1277 /// This means the swim step should be fairly close
1278 /// to the wire so that this approximation is valid. If the
1279 /// reference trajectory from which the swim step came is too
1280 /// sparse, the results will not be nearly as good.
1281
1282 // Interestingly enough, this is one of the harder things to figure
1283 // out in the tracking code which is why the explanations may be
1284 // a bit long.
1285
1286 // The general idea is to define the helix in a coordinate system
1287 // in which the wire runs along the z-axis. The distance to the
1288 // wire is then defined just in the X/Y plane of this coord. system.
1289 // The distance is expressed as a function of the phi angle in the
1290 // natural coordinate system of the helix. This way, phi=0 corresponds
1291 // to the swim step point itself and the DOCA point should be
1292 // at a small phi angle.
1293 //
1294 // The minimum distance between the helical segment and the wire
1295 // will be a function of sin(phi), cos(phi) and phi. Approximating
1296 // sin(phi) by phi and cos(phi) by (1-phi^2) leaves a 4th order
1297 // polynomial in phi. Taking the derivative leaves a 3rd order
1298 // polynomial whose root is the phi corresponding to the
1299 // Distance Of Closest Approach(DOCA) point on the helix. Plugging
1300 // that value of phi back into the distance formula gives
1301 // us the minimum distance between the track and the wire.
1302
1303 // First, we need to define the coordinate system in which the
1304 // wire runs along the z-axis. This is actually done already
1305 // in the CDC package for each wire once, at program start.
1306 // The directions of the axes are defined in wire->sdir,
1307 // wire->tdir, and wire->udir.
1308
1309 // Next, define a point on the helical segment defined by the
1310 // swim step it the RT coordinate system. The directions of
1311 // the RT coordinate system are defined by step->xdir, step->ydir,
1312 // and step->zdir. The coordinates of a point on the helix
1313 // in this coordinate system are:
1314 //
1315 // x = Ro*(cos(phi) - 1)
1316 // y = Ro*sin(phi)
1317 // z = phi*(dz/dphi)
1318 //
1319 // where phi is the phi angle of the point in this coordinate system.
1320
1321 // Now, a vector describing the helical point in the LAB coordinate
1322 // system is:
1323 //
1324 // h = x*xdir + y*ydir + z*zdir + pos
1325 //
1326 // where h,xdir,ydir,zdir and pos are all 3-vectors.
1327 // xdir,ydir,zdir are unit vectors defining the directions
1328 // of the RT coord. system axes in the lab coord. system.
1329 // pos is a vector defining the position of the swim step
1330 // in the lab coord.system
1331
1332 // Now we just need to find the extent of "h" in the wire's
1333 // coordinate system (period . means dot product):
1334 //
1335 // s = (h-wpos).sdir
1336 // t = (h-wpos).tdir
1337 // u = (h-wpos).udir
1338 //
1339 // where wpos is the position of the center of the wire in
1340 // the lab coord. system and is given by wire->wpos.
1341
1342 // At this point, the values of s,t, and u repesent a point
1343 // on the helix in the coord. system of the wire with the
1344 // wire in the "u" direction and positioned at the origin.
1345 // The distance(squared) from the wire to the point on the helix
1346 // is given by:
1347 //
1348 // d^2 = s^2 + t^2
1349 //
1350 // where s and t are both functions of phi.
1351
1352 // So, we'll define the values of "s" and "t" above as:
1353 //
1354 // s = A*x + B*y + C*z + D
1355 // t = E*x + F*y + G*z + H
1356 //
1357 // where A,B,C,D,E,F,G, and H are constants defined below
1358 // and x,y,z are all functions of phi defined above.
1359 // (period . means dot product)
1360 //
1361 // A = sdir.xdir
1362 // B = sdir.ydir
1363 // C = sdir.zdir
1364 // D = sdir.(pos-wpos)
1365 //
1366 // E = tdir.xdir
1367 // F = tdir.ydir
1368 // G = tdir.zdir
1369 // H = tdir.(pos-wpos)
1370 const DVector3 &xdir = step->sdir;
1371 const DVector3 &ydir = step->tdir;
1372 const DVector3 &zdir = step->udir;
1373 const DVector3 &sdir = wire->sdir;
1374 const DVector3 &tdir = wire->tdir;
1375 const DVector3 &udir = wire->udir;
1376 DVector3 pos_diff = step->origin - wire->origin;
1377
1378 double A = sdir.Dot(xdir);
1379 double B = sdir.Dot(ydir);
1380 double C = sdir.Dot(zdir);
1381 double D = sdir.Dot(pos_diff);
1382
1383 double E = tdir.Dot(xdir);
1384 double F = tdir.Dot(ydir);
1385 double G = tdir.Dot(zdir);
1386 double H = tdir.Dot(pos_diff);
1387
1388 // OK, here is the dirty part. Using the approximations given above
1389 // to write the x and y functions in terms of phi^2 and phi (instead
1390 // of cos and sin) we put them into the equations for s and t above.
1391 // Then, inserting those into the equation for d^2 above that, we
1392 // get a very long equation in terms of the constants A,...H and
1393 // phi up to 4th order. Combining coefficients for similar powers
1394 // of phi yields an equation of the form:
1395 //
1396 // d^2 = Q*phi^4 + R*phi^3 + S*phi^2 + T*phi + U
1397 //
1398 // The dirty part is that it takes the better part of a sheet of
1399 // paper to work out the relations for Q,...U in terms of
1400 // A,...H, and Ro, dz/dphi. You can work it out yourself on
1401 // paper to verify that the equations below are correct.
1402 double Ro = step->Ro;
1403 double Ro2 = Ro*Ro;
1404 double delta_z = step->mom.Dot(step->udir);
1405 double delta_phi = step->mom.Dot(step->tdir)/Ro;
1406 double dz_dphi = delta_z/delta_phi;
1407 double dz_dphi2=dz_dphi*dz_dphi;
1408 double Ro_dz_dphi=Ro*dz_dphi;
1409
1410 // double Q = pow(A*Ro/2.0, 2.0) + pow(E*Ro/2.0, 2.0);
1411 double Q=0.25*Ro2*(A*A+E*E);
1412 // double R = -(2.0*A*B*Ro2 + 2.0*A*C*Ro_dz_dphi + 2.0*E*F*Ro2 + 2.0*E*G*Ro_dz_dphi)/2.0;
1413 double R = -((A*B+E*F)*Ro2 + (A*C+E*G)*Ro_dz_dphi);
1414 // double S = pow(B*Ro, 2.0) + pow(C*dz_dphi,2.0) + 2.0*B*C*Ro_dz_dphi - 2.0*A*D*Ro/2.0
1415 //+ pow(F*Ro, 2.0) + pow(G*dz_dphi,2.0) + 2.0*F*G*Ro_dz_dphi - 2.0*E*H*Ro/2.0;
1416 double S= (B*B+F*F)*Ro2+(C*C+G*G)*dz_dphi2+2.0*(B*C+F*G)*Ro_dz_dphi
1417 -(A*D+E*H)*Ro;
1418 // double T = 2.0*B*D*Ro + 2.0*C*D*dz_dphi + 2.0*F*H*Ro + 2.0*G*H*dz_dphi;
1419 double T = 2.0*((B*D+F*H)*Ro + (C*D+G*H)*dz_dphi);
1420 double U = D*D + H*H;
1421
1422 // Aaarghh! my fingers hurt just from typing all of that!
1423 //
1424 // OK, now we differentiate the above equation for d^2 to get:
1425 //
1426 // d(d^2)/dphi = 4*Q*phi^3 + 3*R*phi^2 + 2*S*phi + T
1427 //
1428 // NOTE: don't confuse "R" with "Ro" in the above equations!
1429 //
1430 // Now we have to solve the 3rd order polynomial for the phi value of
1431 // the point of closest approach on the RT. This is a well documented
1432 // procedure. Essentially, when you have an equation of the form:
1433 //
1434 // x^3 + a2*x^2 + a1*x + a0 = 0;
1435 //
1436 // a change of variables is made such that w = x + a2/3 which leads
1437 // to a third order poly with no w^2 term:
1438 //
1439 // w^3 + 3.0*b*w + 2*c = 0
1440 //
1441 // where:
1442 // b = a1/3 - (a2^2)/9
1443 // c = a0/2 - a1*a2/6 + (a2^3)/27
1444 //
1445 // The one real root of this is:
1446 //
1447 // w0 = q - p
1448 //
1449 // where:
1450 // q^3 = d - c
1451 // p^3 = d + c
1452 // d^2 = b^3 + c^2 (don't confuse with d^2 above!)
1453 //
1454 // For us this means that:
1455 // a2 = 3*R/(4*Q)
1456 // a1 = 2*S/(4*Q)
1457 // a0 = T/(4*Q)
1458 //
1459 // A potential problem could occur if Q is at or very close to zero.
1460 // This situation occurs when both A and E are zero. This would mean
1461 // that both sdir and tdir are perpendicular to xdir which means
1462 // xdir is in the same direction as udir (got that?). Physically,
1463 // this corresponds to the situation when both the momentum and
1464 // the magnetic field are perpendicular to the wire (though not
1465 // necessarily perpendicular to each other). This situation can't
1466 // really occur in the CDC detector where the chambers are well
1467 // contained in a region where the field is essentially along z as
1468 // are the wires.
1469 //
1470 // Just to be safe, we check that Q is greater than
1471 // some minimum before solving for phi. If it is too small, we fall
1472 // back to solving the quadratic equation for phi.
1473 double phi =0.0;
1474 if(fabs(Q)>1.0E-6){
1475 /*
1476 double fourQ = 4.0*Q;
1477 double a2 = 3.0*R/fourQ;
1478 double a1 = 2.0*S/fourQ;
1479 double a0 = T/fourQ;
1480 */
1481 double one_over_fourQ=0.25/Q;
1482 double a2=3.0*R*one_over_fourQ;
1483 double a1=2.0*S*one_over_fourQ;
1484 double a0=T*one_over_fourQ;
1485 double a2sq=a2*a2;
1486 /*
1487 double b = a1/3.0 - a2*a2/9.0;
1488 double c = a0/2.0 - a1*a2/6.0 + a2*a2*a2/27.0;
1489 */
1490 double b=ONE_THIRD0.33333333333333333*(a1-ONE_THIRD0.33333333333333333*a2sq);
1491 double c=0.5*(a0-ONE_THIRD0.33333333333333333*a1*a2)+a2*a2sq/27.0;
1492 double my_d2=b*b*b+c*c;
1493 if (my_d2>0){
1494 //double d = sqrt(pow(b, 3.0) + pow(c, 2.0)); // occasionally, this is zero. See below
1495 double d=sqrt(my_d2);
1496 //double q = pow(d - c, ONE_THIRD);
1497 //double p = pow(d + c, ONE_THIRD);
1498 double q=cbrt(d-c);
1499 double p=cbrt(d+c);
1500
1501 double w0 = q - p;
1502 //phi = w0 - a2/3.0;
1503 phi = w0 - ONE_THIRD0.33333333333333333*a2;
1504 }
1505 else{
1506 // Use DeMoivre's theorem to find the cube root of a complex
1507 // number. In this case there are three real solutions.
1508 double d=sqrt(-my_d2);
1509 c*=-1.;
1510 double temp=sqrt(cbrt(c*c+d*d));
1511 double theta1=ONE_THIRD0.33333333333333333*atan2(d,c);
1512 double sum_over_2=temp*cos(theta1);
1513 double diff_over_2=-temp*sin(theta1);
1514
1515 double phi0=-a2/3+2.*sum_over_2;
1516 double phi1=-a2/3-sum_over_2+sqrt(3)*diff_over_2;
1517 double phi2=-a2/3-sum_over_2-sqrt(3)*diff_over_2;
1518
1519 double d2_0 = U + phi0*(T + phi0*(S + phi0*(R + phi0*Q)));
1520 double d2_1 = U + phi1*(T + phi1*(S + phi1*(R + phi1*Q)));
1521 double d2_2 = U + phi2*(T + phi2*(S + phi2*(R + phi2*Q)));
1522
1523 if (d2_0<d2_1 && d2_0<d2_2){
1524 phi=phi0;
1525 }
1526 else if (d2_1<d2_0 && d2_1<d2_2){
1527 phi=phi1;
1528 }
1529 else{
1530 phi=phi2;
1531 }
1532 }
1533 }
1534
1535 if(fabs(Q)<=1.0E-6 || !finite(phi)){
1536 double a = 3.0*R;
1537 double b = 2.0*S;
1538 double c = 1.0*T;
1539 phi = (-b + sqrt(b*b - 4.0*a*c))/(2.0*a);
1540 }
1541
1542 // The accuracy of this method is limited by how close the step is to the
1543 // actual minimum. If the value of phi is large then the step size is
1544 // not too close and we should add another couple of steps in the right
1545 // place in order to get a more accurate value. Note that while this will
1546 // increase the time it takes this round, presumably the fitter will be
1547 // calling this often for each wire and having a high density of points
1548 // near the wires will just make subsequent calls go quicker. This also
1549 // allows larger initial step sizes with the high density regions getting
1550 // filled in as needed leading to overall faster tracking.
1551#if 0
1552 if(finite(phi) && fabs(phi)>2.0E-4){
1553 if(dist_to_rt_depth>=3){
1554 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1554<<" "
<<"3 or more recursive calls to DistToRT(). Something is wrong! bailing ..."<<endl;
1555 //for(int k=0; k<Nswim_steps; k++){
1556 // DVector3 &v = swim_steps[k].origin;
1557 // _DBG_<<" "<<k<<": "<<v.X()<<", "<<v.Y()<<", "<<v.Z()<<endl;
1558 //}
1559 //exit(-1);
1560 return std::numeric_limits<double>::quiet_NaN();
1561 }
1562 double scale_step = 1.0;
1563 double s_range = 1.0*scale_step;
1564 double step_size = 0.02*scale_step;
1565 int err = InsertSteps(step, phi>0.0 ? +s_range:-s_range, step_size); // Add new steps near this step by swimming in the direction of phi
1566 if(!err){
1567 step=FindClosestSwimStep(wire); // Find the new closest step
1568 if(!step)return std::numeric_limits<double>::quiet_NaN();
1569 dist_to_rt_depth++;
1570 double doca = DistToRT(wire, step, s); // re-call ourself with the new step
1571 dist_to_rt_depth--;
1572 return doca;
1573 }else{
1574 if(err<0)return std::numeric_limits<double>::quiet_NaN();
1575
1576 // If InsertSteps() returns an error > 0 then it indicates that it
1577 // was unable to add additional steps (perhaps because there
1578 // aren't enough spaces available). In that case, we just go ahead
1579 // and use the phi we have and make the best estimate possible.
1580 }
1581 }
1582#endif
1583
1584 // It is possible at this point that the value of phi corresponds to
1585 // a point past the end of the wire. We should check for this here and
1586 // recalculate, if necessary, the DOCA at the end of the wire. First,
1587 // calculate h (the vector defined way up above) and dot it into the
1588 // wire's u-direction to get the position of the DOCA point along the
1589 // wire.
1590 double x = -0.5*Ro*phi*phi;
1591 double y = Ro*phi;
1592 double z = dz_dphi*phi;
1593 DVector3 h = pos_diff + x*xdir + y*ydir + z*zdir;
1594 double u = h.Dot(udir);
1595 if(fabs(u) > wire->L/2.0){
1596 // Looks like our DOCA point is past the end of the wire.
1597 // Find phi corresponding to the end of the wire.
1598 double L_over_2 = u>0.0 ? wire->L/2.0:-wire->L/2.0;
1599 double a = -0.5*Ro*udir.Dot(xdir);
1600 double b = Ro*udir.Dot(ydir) + dz_dphi*udir.Dot(zdir);
1601 double c = udir.Dot(pos_diff) - L_over_2;
1602 double twoa=2.0*a;
1603 double sqroot=sqrt(b*b-4.0*a*c);
1604 double phi1 = (-b + sqroot)/(twoa);
1605 double phi2 = (-b - sqroot)/(twoa);
1606 phi = fabs(phi1)<fabs(phi2) ? phi1:phi2;
1607 u=L_over_2;
1608 }
1609 this->last_dist_along_wire = u;
1610
1611 // Use phi to calculate DOCA
1612 double d2 = U + phi*(T + phi*(S + phi*(R + phi*Q)));
1613 double d = sqrt(d2);
1614
1615 // Calculate distance along track ("s")
1616 double dz = dz_dphi*phi;
1617 double Rodphi = Ro*phi;
1618 double ds = sqrt(dz*dz + Rodphi*Rodphi);
1619 if(s)*s=step->s + (phi>0.0 ? ds:-ds);
1620 if(debug_level>3){
1621 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1621<<" "
<<"distance to rt: "<<*s<<" from step at "<<step->s<<" with ds="<<ds<<" d="<<d<<" dz="<<dz<<" Rodphi="<<Rodphi<<endl;
1622 _DBG_std::cerr<<"DReferenceTrajectory.cc"<<":"<<
1622<<" "
<<"phi="<<phi<<" U="<<U<<" u="<<u<<endl;
1623 }
1624
1625 // Remember phi and step so additional info on the point can be obtained
1626 this->last_phi = phi;
1627 this->last_swim_step = step;
1628 this->last_dz_dphi = dz_dphi;
1629
1630 return d; // WARNING: This could return nan!
1631}
1632
1633//------------------
1634// DistToRTBruteForce
1635//------------------
1636double DReferenceTrajectory::DistToRTBruteForce(const DCoordinateSystem *wire, const swim_step_t *step, double *s) const
1637{
1638 /// Calculate the distance of the given wire(in the lab
1639 /// reference frame) to the Reference Trajectory which the
1640 /// given swim step belongs to. This uses the momentum directions
1641 /// and positions of the swim step
1642 /// to define a curve and calculate the distance of the hit
1643 /// from it. The swim step should be the closest one to the wire.
1644 /// IMPORTANT: This calculates the distance using a "brute force"
1645 /// method of taking tiny swim steps to find the minimum distance.
1646 /// It is vey SLOW and you should be using DistToRT(...) instead.
1647 /// This is only here to provide an independent check of DistToRT(...).
1648
1649 const DVector3 &xdir = step->sdir;
1650 const DVector3 &ydir = step->tdir;
1651 const DVector3 &zdir = step->udir;
1652 const DVector3 &sdir = wire->sdir;
1653 const DVector3 &tdir = wire->tdir;
1654 DVector3 pos_diff = step->origin - wire->origin;
1655
1656 double Ro = step->Ro;
1657 double delta_z = step->mom.Dot(step->udir);
1658 double delta_phi = step->mom.Dot(step->tdir)/Ro;
1659 double dz_dphi = delta_z/delta_phi;
1660
1661 // Brute force
1662 double min_d2 = 1.0E6;
1663 double phi=M_PI3.14159265358979323846;
1664 for(int i=-2000; i<2000; i++){
1665 double myphi=(double)i*0.000005;
1666 DVector3 d = Ro*(cos(myphi)-1.0)*xdir
1667 + Ro*sin(myphi)*ydir
1668 + dz_dphi*myphi*zdir
1669 + pos_diff;
1670
1671 double d2 = pow(d.Dot(sdir),2.0) + pow(d.Dot(tdir),2.0);
1672 if(d2<min_d2){
1673 min_d2 = d2;
1674 phi = myphi;
1675 this->last_phi = myphi;
1676 }
1677 }
1678 double d2 = min_d2;
1679 double d = sqrt(d2);
1680 this->last_phi = phi;
1681 this->last_swim_step = step;
1682 this->last_dz_dphi = dz_dphi;
1683
1684 // Calculate distance along track ("s")
1685 double dz = dz_dphi*phi;
1686 double Rodphi = Ro*phi;
1687 double ds = sqrt(dz*dz + Rodphi*Rodphi);
1688 if(s)*s=step->s + (phi>0.0 ? ds:-ds);
1689
1690 return d;
1691}
1692
1693//------------------
1694// Straw_dx
1695//------------------
1696double DReferenceTrajectory::Straw_dx(const DCoordinateSystem *wire, double radius)
1697{
1698 /// Find the distance traveled within the specified radius of the
1699 /// specified wire. This will give the "dx" component of a dE/dx
1700 /// measurement for cylindrical geometry as we have with straw tubes.
1701 ///
1702 /// At this point, the estimate is done using a simple linear
1703 /// extrapolation from the DOCA point in the direction of the momentum
1704 /// to the 2 points at which it itersects the given radius. Segments
1705 /// which extend past the end of the wire will be clipped to the end
1706 /// of the wire before calculating the total dx.
1707
1708 // First, find the DOCA point for this wire
1709 double s;
1710 double doca = DistToRT(wire, &s);
1711 if(!finite(doca))
1712 return 0.0;
1713
1714 // If doca is outside of the given radius, then we're done
1715 if(doca>=radius)return 0.0;
1716
1717 // Get the location and momentum direction of the DOCA point
1718 DVector3 pos, momdir;
1719 GetLastDOCAPoint(pos, momdir);
1720 if(momdir.Mag()!=0.0)momdir.SetMag(1.0);
1721
1722 // Get wire direction
1723 const DVector3 &udir = wire->udir;
1724
1725 // Calculate vectors used to form quadratic equation for "alpha"
1726 // the distance along the mometum direction from the DOCA point
1727 // to the intersection with a cylinder of the given radius.
1728 DVector3 A = udir.Cross(pos-wire->origin);
1729 DVector3 B = udir.Cross(momdir);
1730
1731 // If the magnitude of B is zero at this point, it means the momentum
1732 // direction is parallel to the wire. In this case, this method will
1733 // not work. Return NaN.
1734 if(B.Mag()<1.0E-10)return std::numeric_limits<double>::quiet_NaN();
1735
1736 double a = B.Mag();
1737 double b = A.Dot(B);
1738 double c = A.Mag() - radius;
1739 double d = sqrt(b*b - 4.0*a*c);
1740
1741 // The 2 roots should correspond to the 2 intersection points.
1742 double alpha1 = (-b + d)/(2.0*a);
1743 double alpha2 = (-b - d)/(2.0*a);
1744
1745 DVector3 int1 = pos + alpha1*momdir;
1746 DVector3 int2 = pos + alpha2*momdir;
1747
1748 // Check if point1 is past the end of the wire
1749 double q = udir.Dot(int1 - wire->origin);
1750 if(fabs(q) > wire->L/2.0){
1751 double gamma = udir.Dot(wire->origin - pos) + (q>0.0 ? +1.0:-1.0)*wire->L/2.0;
1752 gamma /= momdir.Dot(udir);
1753 int1 = pos + gamma*momdir;
1754 }
1755
1756 // Check if point2 is past the end of the wire
1757 q = udir.Dot(int2 - wire->origin);
1758 if(fabs(q) > wire->L/2.0){
1759 double gamma = udir.Dot(wire->origin - pos) + (q>0.0 ? +1.0:-1.0)*wire->L/2.0;
1760 gamma /= momdir.Dot(udir);
1761 int2 = pos + gamma*momdir;
1762 }
1763
1764 // Calculate distance
1765 DVector3 delta = int1 - int2;
1766
1767 return delta.Mag();
1768}
1769
1770//------------------
1771// GetLastDOCAPoint
1772//------------------
1773void DReferenceTrajectory::GetLastDOCAPoint(DVector3 &pos, DVector3 &mom) const
1774{
1775 /// Use values saved by the last call to one of the DistToRT functions
1776 /// to calculate the 3-D DOCA position in lab coordinates and momentum
1777 /// in GeV/c.
1778
1779 if(last_swim_step==NULL__null){
1780 if(Nswim_steps>0){
1781 last_swim_step = &swim_steps[0];
1782 last_phi = 0.0;
1783 }else{
1784 pos.SetXYZ(NaNstd::numeric_limits<double>::quiet_NaN(),NaNstd::numeric_limits<double>::quiet_NaN(),NaNstd::numeric_limits<double>::quiet_NaN());
1785 mom.SetXYZ(NaNstd::numeric_limits<double>::quiet_NaN(),NaNstd::numeric_limits<double>::quiet_NaN(),NaNstd::numeric_limits<double>::quiet_NaN());
1786 return;
1787 }
1788 }
1789
1790 // If last_phi is not finite, set it to 0 as a last resort
1791 if(!finite(last_phi))last_phi = 0.0;
1792
1793 const DVector3 &xdir = last_swim_step->sdir;
1794 const DVector3 &ydir = last_swim_step->tdir;
1795 const DVector3 &zdir = last_swim_step->udir;
1796
1797 double x = -(last_swim_step->Ro/2.0)*last_phi*last_phi;
1798 double y = last_swim_step->Ro*last_phi;
1799 double z = last_dz_dphi*last_phi;
1800
1801 pos = last_swim_step->origin + x*xdir + y*ydir + z*zdir;
1802 mom = last_swim_step->mom;
1803
1804 mom.Rotate(-last_phi, zdir);
1805}
1806
1807//------------------
1808// GetLastDOCAPoint
1809//------------------
1810DVector3 DReferenceTrajectory::GetLastDOCAPoint(void) const
1811{
1812 /// Use values saved by the last call to one of the DistToRT functions
1813 /// to calculate the 3-D DOCA position in lab coordinates. This is
1814 /// mainly intended for debugging.
1815 if(last_swim_step==NULL__null){
1816 if(Nswim_steps>0){
1817 last_swim_step = &swim_steps[0];
1818 last_phi = 0.0;
1819 }else{
1820 return DVector3(NaNstd::numeric_limits<double>::quiet_NaN(),NaNstd::numeric_limits<double>::quiet_NaN(),NaNstd::numeric_limits<double>::quiet_NaN());
1821 }
1822 }
1823 const DVector3 &xdir = last_swim_step->sdir;
1824 const DVector3 &ydir = last_swim_step->tdir;
1825 const DVector3 &zdir = last_swim_step->udir;
1826 double Ro = last_swim_step->Ro;
1827 double delta_z = last_swim_step->mom.Dot(zdir);
1828 double delta_phi = last_swim_step->mom.Dot(ydir)/Ro;
1829 double dz_dphi = delta_z/delta_phi;
1830
1831 double x = -(Ro/2.0)*last_phi*last_phi;
1832 double y = Ro*last_phi;
1833 double z = dz_dphi*last_phi;
1834
1835 return last_swim_step->origin + x*xdir + y*ydir + z*zdir;
1836}
1837
1838//------------------
1839// dPdx
1840//------------------
1841double DReferenceTrajectory::dPdx_from_A_Z_rho(double ptot, double A, double Z, double density) const
1842{
1843 double I = (Z*12.0 + 7.0)*1.0E-9; // From Leo 2nd ed. pg 25.
1844 if (Z>=13) I=(9.76*Z+58.8*pow(Z,-0.19))*1.0e-9;
1845 double rhoZ_overA=density*Z/A;
1846 double KrhoZ_overA = 0.1535e-3*rhoZ_overA;
1847
1848 return dPdx(ptot, KrhoZ_overA,rhoZ_overA,log(I));
1849}
1850
1851//------------------
1852// dPdx
1853//------------------
1854double DReferenceTrajectory::dPdx(double ptot, double KrhoZ_overA,
1855 double rhoZ_overA,double LogI) const
1856{
1857 /// Calculate the momentum loss per unit distance traversed of the material with
1858 /// the given A, Z, and density. Value returned is in GeV/c per cm
1859 /// This follows the July 2008 PDG section 27.2 ppg 268-270.
1860 if(mass==0.0)return 0.0; // no ionization losses for neutrals
1861
1862 double gammabeta = ptot/mass;
1863 double gammabeta2=gammabeta*gammabeta;
1864 double gamma = sqrt(gammabeta2+1);
1865 double beta = gammabeta/gamma;
1866 double beta2=beta*beta;
1867 double me = 0.511E-3;
1868 double m_ratio=me/mass;
1869 double two_me_gammabeta2=2.*me*gammabeta2;
1870
1871 double Tmax = two_me_gammabeta2/(1.0+2.0*gamma*m_ratio+m_ratio*m_ratio);
1872 //double K = 0.307075E-3; // GeV gm^-1 cm^2
1873 // Density effect
1874 double delta=0.;
1875 double X=log10(gammabeta);
1876 double X0,X1;
1877 double Cbar=2.*(LogI-log(28.816e-9*sqrt(rhoZ_overA)))+1.;
1878 if (rhoZ_overA>0.01){ // not a gas
1879 if (LogI<-1.6118){ // I<100
1880 if (Cbar<=3.681) X0=0.2;
1881 else X0=0.326*Cbar-1.;
1882 X1=2.;
1883 }
1884 else{
1885 if (Cbar<=5.215) X0=0.2;
1886 else X0=0.326*Cbar-1.5;
1887 X1=3.;
1888 }
1889 }
1890 else { // gases
1891 X1=4.;
1892 if (Cbar<=9.5) X0=1.6;
1893 else if (Cbar>9.5 && Cbar<=10.) X0=1.7;
1894 else if (Cbar>10 && Cbar<=10.5) X0=1.8;
1895 else if (Cbar>10.5 && Cbar<=11.) X0=1.9;
1896 else if (Cbar>11.0 && Cbar<=12.25) X0=2.;
1897 else if (Cbar>12.25 && Cbar<=13.804){
1898 X0=2.;
1899 X1=5.;
1900 }
1901 else {
1902 X0=0.326*Cbar-2.5;
1903 X1=5.;
1904 }
1905 }
1906 if (X>=X0 && X<X1)
1907 delta=4.606*X-Cbar+(Cbar-4.606*X0)*pow((X1-X)/(X1-X0),3.);
1908 else if (X>=X1)
1909 delta= 4.606*X-Cbar;
1910
1911 double dEdx = KrhoZ_overA/beta2*(log(two_me_gammabeta2*Tmax)
1912 -2.*LogI - 2.0*beta2 -delta);
1913
1914 double dP_dx = dEdx/beta;
1915
1916 double g = 0.350/sqrt(-log(0.06));
1917 dP_dx *= 1.0 + exp(-pow(ptot/g,2.0)); // empirical for really low momentum particles
1918
1919 if(ploss_direction==kBackward)dP_dx = -dP_dx;
1920
1921 return dP_dx;
1922}
1923
1924//------------------
1925// Dump
1926//------------------
1927void DReferenceTrajectory::Dump(double zmin, double zmax)
1928{
1929 swim_step_t *step = swim_steps;
1930 for(int i=0; i<Nswim_steps; i++, step++){
1931 vector<pair<string,string> > item;
1932 double x = step->origin.X();
1933 double y = step->origin.Y();
1934 double z = step->origin.Z();
1935 if(z<zmin || z>zmax)continue;
1936
1937 double px = step->mom.X();
1938 double py = step->mom.Y();
1939 double pz = step->mom.Z();
1940
1941 cout<<i<<": ";
1942 cout<<"(x,y,z)=("<<x<<","<<y<<","<<z<<") ";
1943 cout<<"(px,py,pz)=("<<px<<","<<py<<","<<pz<<") ";
1944 cout<<"(Ro,s,t)=("<<step->Ro<<","<<step->s<<","<<step->t<<") ";
1945 cout<<endl;
1946 }
1947
1948}
1949
1950// Propagate the covariance matrix for {px,py,pz,x,y,z,t} along the step ds
1951jerror_t DReferenceTrajectory::PropagateCovariance(double ds,double q,
1952 double mass,
1953 const DVector3 &mom,
1954 const DVector3 &pos,
1955 DMatrixDSym &C) const{
1956 DMatrix J(7,7);
1957
1958 double one_over_p_sq=1./mom.Mag2();
1959 double one_over_p=sqrt(one_over_p_sq);
1960 double px=mom.X();
1961 double py=mom.Y();
1962 double pz=mom.Z();
1963 double Bx,By,Bz;
1964 this->bfield->GetField(pos.x(),pos.y(),pos.z(),Bx,By,Bz);
1965
1966 double ds_over_p=ds*one_over_p;
1967 double factor=0.003*q*ds_over_p;
1968 double temp=(Bz*py-Bx*pz)*one_over_p_sq;
1969 J(0,0)=1-factor*px*temp;
1970 J(0,1)=factor*(Bz-py*temp);
1971 J(0,2)=-factor*(By+pz*temp);
1972
1973 temp=(Bx*pz-Bz*px)*one_over_p_sq;
1974 J(1,0)=-factor*(Bz+px*temp);
1975 J(1,1)=1-factor*py*temp;
1976 J(1,2)=factor*(Bx-pz*temp);
1977
1978 temp=(By*px-Bx*py)*one_over_p_sq;
1979 J(2,0)=factor*(By-px*temp);
1980 J(2,1)=-factor*(Bx+py*temp);
1981 J(2,2)=1-factor*pz*temp;
1982
1983 J(3,3)=1.;
1984 double ds_over_p3=one_over_p_sq*ds_over_p;
1985 J(3,0)=ds_over_p*(1-px*px*one_over_p_sq);
1986 J(3,1)=-px*py*ds_over_p3;
1987 J(3,2)=-px*pz*ds_over_p3;
1988
1989 J(4,4)=1.;
1990 J(4,0)=J(3,1);
1991 J(4,1)=ds_over_p*(1-py*py*one_over_p_sq);
1992 J(4,2)=-py*pz*ds_over_p3;
1993
1994 J(5,5)=1.;
1995 J(5,0)=J(3,2);
1996 J(5,1)=J(4,2);
1997 J(5,2)=ds_over_p*(1-pz*pz*one_over_p_sq);
1998
1999 J(6,6)=1.;
2000 double m_sq=mass*mass;
2001 double fac2=(-ds/SPEED_OF_LIGHT29.9792)*m_sq*one_over_p_sq*one_over_p_sq
2002 /sqrt(1.+m_sq*one_over_p_sq);
2003 J(6,0)=fac2*px;
2004 J(6,1)=fac2*py;
2005 J(6,2)=fac2*pz;
2006
2007 C=C.Similarity(J);
2008
2009 return NOERROR;
2010}
2011
2012
2013// Find the mid-point of the line connecting the points of closest approach of the
2014// trajectories of two tracks. Return the positions, momenta, and error matrices
2015// at these points for the two tracks.
2016jerror_t
2017DReferenceTrajectory::IntersectTracks( const DReferenceTrajectory *rt2,
2018 DKinematicData *track1_kd,
2019 DKinematicData *track2_kd,
2020 DVector3 &pos, double &doca, double &var_doca) const{
2021 const swim_step_t *swim_step1=this->swim_steps;
2022 const swim_step_t *swim_step2=rt2->swim_steps;
2023
2024 DMatrixDSym cov1=track1_kd->errorMatrix();
2025 DMatrixDSym cov2=track2_kd->errorMatrix();
2026 double q1=this->q;
2027 double q2=rt2->q;
2028 double mass1=this->mass;
2029 double mass2=rt2->mass;
2030
2031 // Initialize the doca and traverse both particles' trajectories
2032 doca=1000.;
2033 DVector3 oldpos1,oldpos2,oldmom1,oldmom2;
2034 double tflight1=0.,tflight2=0.;
2035 for (int i=0;i<this->Nswim_steps-1&&i<rt2->Nswim_steps-1;
2036 i++, swim_step1++, swim_step2++){
2037 DVector3 pos1=swim_step1->origin;
2038 DVector3 pos2=swim_step2->origin;
2039 DVector3 diff=pos1-pos2;
2040 double new_doca=diff.Mag();
2041
2042 if (new_doca>doca){
2043 if (i==1){ // backtrack to find the true doca
2044 tflight1=tflight2=0.;
2045
2046 swim_step1=this->swim_steps;
2047 swim_step2=rt2->swim_steps;
2048
2049 cov1=track1_kd->errorMatrix();
2050 cov2=track2_kd->errorMatrix();
2051
2052 pos1=swim_step1->origin;
2053 DVector3 mom1=swim_step1->mom;
2054 DMagneticFieldStepper stepper1(this->bfield, this->q, &pos1, &mom1);
2055
2056 pos2=swim_step2->origin;
2057 DVector3 mom2=swim_step2->mom;
2058 DMagneticFieldStepper stepper2(this->bfield, rt2->q, &pos2, &mom2);
2059
2060 int inew=0;
2061 while (inew<100){
2062 double ds1=stepper1.Step(&pos1,-0.5);
2063 double ds2=stepper2.Step(&pos2,-0.5);
2064
2065 // Compute the revised estimate for the doca
2066 diff=pos1-pos2;
2067 new_doca=diff.Mag();
2068
2069 if (new_doca>doca){
2070 break;
2071 }
2072
2073 // Propagate the covariance matrices along the trajectories
2074 this->PropagateCovariance(ds1,q1,mass1,mom1,oldpos1,cov1);
2075 rt2->PropagateCovariance(ds2,q2,mass2,mom2,oldpos2,cov2);
2076
2077 // Store the current positions, doca and adjust flight times
2078 oldpos1=pos1;
2079 oldpos2=pos2;
2080 doca=new_doca;
2081
2082 double one_over_p1_sq=1./mom1.Mag2();
2083 tflight1+=ds1*sqrt(1.+mass1*mass1*one_over_p1_sq)/SPEED_OF_LIGHT29.9792;
2084
2085 double one_over_p2_sq=1./mom2.Mag2();
2086 tflight2+=ds2*sqrt(1.+mass2*mass2*one_over_p2_sq)/SPEED_OF_LIGHT29.9792;
2087
2088 // New momenta
2089 stepper1.GetMomentum(mom1);
2090 stepper2.GetMomentum(mom2);
2091
2092 oldmom1=/*(-1.)*/mom1;
2093 oldmom2=/*(-1.)*/mom2;
2094
2095 inew++;
2096 }
2097 }
2098
2099 // "Vertex" is mid-point of line connecting the positions of closest
2100 // approach of the two tracks
2101 pos=0.5*(oldpos1+oldpos2);
2102
2103 track1_kd->setErrorMatrix(cov1);
2104 track1_kd->setMomentum(oldmom1);
2105 track1_kd->setPosition(oldpos1);
2106 double err_t0=track1_kd->t0_err();
2107 track1_kd->setT0(track1_kd->t0()+tflight1,sqrt(err_t0*err_t0+cov1(6,6)),track1_kd->t0_detector());
2108
2109 track2_kd->setErrorMatrix(cov2);
2110 track2_kd->setMomentum(oldmom2);
2111 track2_kd->setPosition(oldpos2);
2112 err_t0=track2_kd->t0_err();
2113 track2_kd->setT0(track2_kd->t0()+tflight2,sqrt(err_t0*err_t0+cov2(6,6)),track2_kd->t0_detector());
2114
2115 // Compute the variance on the doca
2116 diff=oldpos1-oldpos2;
2117 double dx=diff.x();
2118 double dy=diff.y();
2119 double dz=diff.z();
2120 var_doca=(dx*dx*(cov1(3,3)+cov2(3,3))+dy*dy*(cov1(4,4)+cov2(4,4))
2121 +dz*dz*(cov1(5,5)+cov2(5,5))+2.*dx*dy*(cov1(3,4)+cov2(3,4))
2122 +2.*dx*dz*(cov1(3,5)+cov2(3,5))+2.*dy*dz*(cov1(4,5)+cov2(4,5)))
2123 /(doca*doca);
2124
2125 break;
2126 }
2127
2128 // Propagate the covariance matrices along the trajectories
2129 this->PropagateCovariance(this->swim_steps[i+1].s-swim_step1->s,q1,mass1,
2130 swim_step1->mom,swim_step1->origin,cov1);
2131 rt2->PropagateCovariance(rt2->swim_steps[i+1].s-swim_step2->s,q2,mass2,
2132 swim_step2->mom,swim_step2->origin,cov2);
2133
2134 // Store the current positions and doca
2135 oldpos1=pos1;
2136 oldpos2=pos2;
2137 oldmom1=swim_step1->mom;
2138 oldmom2=swim_step2->mom;
2139 tflight1=swim_step1->t;
2140 tflight2=swim_step2->t;
2141 doca=new_doca;
2142 }
2143
2144 return NOERROR;
2145}
2146
2147
2148