icemc.cc
1 #include <iostream>
2 #include <fstream>
3 #include <sstream>
4 #include <ctype.h>
5 #include <string>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <vector>
9 #include <array>
10 #include <time.h>
11 #include "TTreeIndex.h"
12 #include "TChain.h"
13 #include "TH1.h"
14 #include "TH2.h"
15 #include "TF1.h"
16 #include "TF2.h"
17 #include "TFile.h"
18 #include "TObject.h"
19 #include "icemc_random.h"
20 #include "TTree.h"
21 #include "TLegend.h"
22 #include "TLine.h"
23 #include "TROOT.h"
24 #include "TPostScript.h"
25 #include "TCanvas.h"
26 #include "TH2F.h"
27 #include "TText.h"
28 #include "TProfile.h"
29 #include "TGraph.h"
30 #include "TGraphErrors.h"
31 #include "TGraphAsymmErrors.h"
32 #include "TStyle.h"
33 #include "TMath.h"
34 #include "TMarker.h"
35 #include <unistd.h>
36 #include "TVector3.h"
37 #include "TRotation.h"
38 #include "TSpline.h"
39 #include "Math/InterpolationTypes.h"
40 #include "Math/Interpolator.h"
41 #include "signal.h"
42 #include <cmath>
43 
44 
45 //#include "rx.hpp"
46 #include "Constants.h"
47 #include "Settings.h"
48 #include "position.hh"
49 
50 #include "earthmodel.hh"
51 #include "Tools.h"
52 #include "vector.hh"
53 #include "roughness.hh"
54 #include "anita.hh"
55 #include "balloon.hh"
56 #include "icemodel.hh"
57 // #include "trigger.hh"
58 #include "Spectra.h"
59 #include "signal.hh"
60 #include "secondaries.hh"
61 #include "ray.hh"
62 #include "counting.hh"
63 #include "Primaries.h"
64 #include "Taumodel.hh"
65 #include "screen.hh"
66 #include "GlobalTrigger.h"
67 #include "ChanTrigger.h"
68 #include "SimulatedSignal.h"
69 #include "EnvironmentVariable.h"
70 #include "source.hh"
71 #include <typeinfo>
72 #include <string>
73 #include <sstream>
74 
75 #if __cplusplus > 199711L
76 #define isnan std::isnan
77 #include <type_traits>
78 #endif
79 
80 #include <typeinfo>
81 
82 #include <fenv.h>
83 
84 #ifdef ANITA_UTIL_EXISTS
85 #include "UsefulAnitaEvent.h"
86 #ifdef ANITA3_EVENTCORRELATOR
87 #include "SkyMap.h"
88 #endif
89 #include "AnitaGeomTool.h"
90 #include "AnitaConventions.h"
91 #include "RawAnitaHeader.h"
92 #include "Adu5Pat.h"
93 #include "FFTtools.h"
94 #include "UsefulAdu5Pat.h"
95 UsefulAnitaEvent* realEvPtr = NULL;
96 RawAnitaHeader* rawHeaderPtr = NULL;
97 Adu5Pat* Adu5PatPtr = NULL;
98 #ifdef ANITA3_EVENTREADER
99 #include "TruthAnitaEvent.h"
100 TruthAnitaEvent* truthEvPtr = NULL;
101 #endif
102 #endif
103 
104 Taumodel* TauPtr = NULL;
105 
106 const string ICEMC_SRC_DIR = EnvironmentVariable::ICEMC_SRC_DIR();
107 
108 ClassImp(RX);
109 //ClassImp(Settings);
110 
111 using namespace std;
112 
113 class EarthModel;
114 class Position;
115 class Settings;
116 
117 /************MOVED FROM shared.hh and shared.cc*****************/
118 // These need to be moved elsewhere.
119 // They were all global variables inside of shared.hh.
120 // Most of these should not be global variables.
121 const int NVIEWANGLE=100; // number of viewing angles to look at the signal, on Seckel's request
122 // int irays; // counts rays (for roughness) // LC: commented out because not used
123 
124 int inu; // counts neutrinos as they are generated
125 double eventsfound_beforetrigger=0.;
126 double eventsfound_crust=0; //number of events that only traverse the crust
127 double eventsfound_weightgt01=0; // summing weights > 0.1
128 double eventsfound_belowhorizon=0; // how many are below horizon
129 double eventsfound=0; // how many events found
130 double eventsfound_prob=0; // how many events found, probabilities
131 double sum[3]; // sum of weight for events found for 3 flavors
132 double sum_prob[3]; // sum of weight for events found for 3 flavors
133 // These numbers are from Feldman and Cousins wonderful paper: physics/9711021
134 double poissonerror_minus[21] = {0.-0.00, 1.-0.37, 2.-0.74, 3.-1.10, 4.-2.34, 5.-2.75, 6.-3.82, 7.-4.25, 8.-5.30, 9.-6.33, 10.-6.78, 11.-7.81, 12.-8.83, 13.-9.28, 14.-10.30, 15.-11.32, 16.-12.33, 17.-12.79, 18.-13.81, 19.-14.82, 20.-15.83};
135 double poissonerror_plus[21] = {1.29-0., 2.75-1., 4.25-2., 5.30-3., 6.78-4., 7.81-5., 9.28-6., 10.30-7., 11.32-8., 12.79-9., 13.81-10., 14.82-11., 16.29-12., 17.30-13., 18.32-14., 19.32-15., 20.80-16., 21.81-17., 22.82-18., 23.82-19., 25.30-20.};
136 const int NBINS=10; // keep track of the number of events found, binned
137 // by weights
138 double MIN_LOGWEIGHT=-3;
139 double MAX_LOGWEIGHT=-1;
140 int index_weights=0; // which bin the weight falls into
141 double eventsfound_binned[NBINS];
142 double eventsfound_binned_e[NBINS];
143 double eventsfound_binned_mu[NBINS];
144 double eventsfound_binned_tau[NBINS];
145 double km3sr = 0; // total km3sr
146 double km3sr_e=0; // to calculate km3sr for electrons
147 double km3sr_mu=0; // to calculate km3sr for muons
148 double km3sr_tau=0; // to calculate km3sr for taus
149 double error_plus=0; // keeping track of asymmetric error bars
150 double error_e_plus=0;
151 double error_mu_plus=0;
152 double error_tau_plus=0;
153 double error_minus=0;
154 double error_e_minus=0;
155 double error_mu_minus=0;
156 double error_tau_minus=0;
157 int ierr=0; // integer for returning error from functions.
158 double gain_dipole=2.15; // antenna gain (nominal value for dipole is 2.15)
159 double changle_deg=0; // same, in degrees.
160 // inputs
161 int NNU; // number of neutrinos
162 int whichray=0; // indexes the rays that we look at (actually just used for ice but we use it in GetNuFlavor so keep it here)
163 double RANDOMISEPOL=0.;
164 /************MOVED FROM shared.hh and shared.cc*****************/
165 
166 
167 std::vector<int> NNU_per_source;
168 std::vector<double> eventsfound_per_source;
169 std::vector<double> eventsfound_prob_per_source;
170 
171 double volume_thishorizon; // for plotting volume within the horizon of the balloon
172 double realtime_this; // for plotting real unix time
173 double longitude_this; // for plotting longitude
174 double latitude_this; // for plotting latitude
175 double altitude_this; // for plotting altitude
176 double heading_this=0.;// for plotting heading
177 double gps_offset=0;
178 
179 // inputs
180 
181 double pnu=pow(10., 20);
182 
183 double MEANX=0;
184 double MEANY=0.;
185 
186 double SIGNALRADIUS=2.; // in degrees
187 
188 // frequency binning
189 const double FREQ_LOW_DISCONES=120.E6; // min frequency for discones
190 const double FREQ_HIGH_DISCONES=1000.E6; // max frequency for discones
191 
192 double bwslice_vnoise_thislayer[4];// for filling tree6b, noise for each bandwidth on each layer
193 int passes_thisevent=0; // this event passes
194 int unmasked_thisevent=0; // this event is unmasked
195 
196 int discones_passing; // number of discones that pass
197 int NDISCONES=8;
198 double heff_discone=0; // effective height of a discone antenna
199 double polarfactor_discone=0.;// factor to account for antenna beam pattern.
200 double thislambda=0;// for finding wavelength at each frequency
201 double volts_discone=0.;// for finding voltage at each discone
202 double vnoise_discone=0.; // noise on each discone
203 
204 
205 double BW_DISCONES=300.E6-120.E6; // bandwidth of the discones
206 
207 // ray tracing
208 double fresnel1=0;
209 double fresnel1_eachboresight[Anita::NLAYERS_MAX][Anita::NPHI_MAX]; // for slac simulation
210 double fresnel2=0;
211 double mag1=0; // magnification factor on field at ice-firn interface
212 double mag1_eachboresight[Anita::NLAYERS_MAX][Anita::NPHI_MAX];// for slac simulation
213 double mag2=0; // magnification factor on field in firn-air
214 double t_coeff_pokey, t_coeff_slappy;
215 double rflength=0; // distance from interaction to ice-air exit point
216 
217 double e_comp_max1=0;
218 double h_comp_max1=0;
219 double e_comp_max2=0;
220 double h_comp_max2=0;
221 double e_comp_max3=0;
222 double h_comp_max3=0;
223 
224 double diffexit=0; // checking exit point between_MAX interations
225 double diff_3tries=0;
226 double diffnorm=0; // checking angle of surf normal between iterations
227 double diffrefr=0; // checking angle of refr between iterations
228 double costheta_inc=0; // cos angle of incidence wrt surface normal
229 double costheta_exit=0; // theta of exit point wrt earth (costheta=1 at south pole)
230 double theta_rf_atbn; // polar angle of the signal as seen by perfect eyes at the balloon.
231 double theta_rf_atbn_measured; //polar angle of the signal as measured at the balloon (just the above variable smeared by 0.5 degrees)
232 double theta_nnu_atbn;
233 double theta_nnu_rf_diff_atbn;
234 
235 double phi_rf_atbn;
236 double phi_nnu_atbn;
237 double phi_nnu_rf_diff_atbn;
238 
239 
240 Vector nnu_xy;
241 Vector r_bn_xy;
242 Vector rf_xy;
243 
244 
245 double costhetanu=-1000; // costheta of neutrino direction wrt earth (costheta=1 at south pole)
246 
247 // neutrino path
248 double theta_in=0; // theta where neutrino enters earth (radians, south pole=0)
249 double lat_in=0; // latitude where neutrino enters earth (degrees, south pole=-90)
250 double nearthlayers=0; // how many layers (core, mantle, crust) does nnu traverse
251 double weight_prob=0.;//event weight, including probability it interacts somewhere in ice along its path
252 double weight1=0; // event weight, just based on absorption in earth, see note
253 double weight=0.; // total event weight (product of the previous 2)
254 double logweight=0.;// log of the previous number
255 double len_int=0;// interaction length in m
256 double pieceofkm2sr=0; // Use this for making plots comparing different cross sections. The integral of a plot from a run will be the total Area*sr of the detector. That way it is proportional to the cross section and the integral is something meaningful to people.
257 
258 // counting variables
259 int count_inthisloop1=0; // for debugging
260 int count_inthisloop2=0;
261 int count_inthisloop3=0;
262 double averaging_thetas1=0; // for debugging
263 double averaging_thetas2=0;
264 double averaging_thetas3=0;
265 int count_total=0; // number of neutrinos looped over. should always equal inu
266 
267 // i.e., is theoretically visible by balloon
268 
269 int count_asktrigger=0;
270 int count_asktrigger_nfb=0;
271 int count_pass=0; // how many total trigger channels pass (4 bandwidth slices*2 pol * nrx)
272 
273 double count_passestrigger_w=0; // same as above, but sum weights
274 int passestrigger=0; // 1=this event passes trigger, 0=does not
275 // so that we know to increment count_passestrigger_w at the end of the event
276 int allcuts[2]={0, 0}; // index is which ray (upward or downward)
277 // 1=this ray for this event passes all cuts, 0=does not
278 double allcuts_weighted[2]={0, 0}; // same as above but weighted
279 double allcuts_weighted_polarization[3]={0, 0, 0}; // same as above but divided into [0] vpol, [1] hpol, [2] both vpol and hpol
280 
281 
282 //signal has a chance to pass after accounting for 1/r
283 int count_chanceofsurviving=0; // based on neutrino direction, has a chance of making it through earth.
284 
285 int count_chanceinhell0=0; // based on 1/r, and best case attenuation
286 // (after 2nd guess at rf exit point)
287 // signal has a chance of passing
288 
289 double count_chanceinhell2_w=0; //same as above, but sum weights
290 int chanceinhell2=0; // 1=this event has chance to pass, 0=does not-
291 // so that we know to increment count_chanceinhell2_w by weight1 at the end.
292 
293 int count_chordgoodlength=0; // Incremented if neutrino path through earth is more than 1m
294 int count_d2goodlength=0; // neutrino path through ice is more than 1m
295 int count_rx=0; // counting antennas we loop through them
296 
297 double sum_frac[3]; // fraction of passing events that are e, mu, tau adding weights
298 double sum_frac_db[3]; // same for double bangs
299 
300 const int NBINS_DISTANCE=28; // keep track of number that pass as a function of distance to make Peter's plot
301 double eventsfound_binned_distance[NBINS_DISTANCE] = {0.}; // binning cumulative events found vs. distance
302 int index_distance=0; // index for filling array above
303 double km3sr_distance[NBINS_DISTANCE] = {0.}; // result of conversion of events to sensitivity
304 double error_distance_plus[NBINS_DISTANCE] = {0.}; // errors on above
305 double error_distance_minus[NBINS_DISTANCE] = {0.};
306 int eventsfound_binned_distance_forerror[NBINS_DISTANCE][NBINS] = {{0}}; // for propagation of errors
307 
308 //taus
309 double km3sr_db = 0;
310 double km3sr_nfb=0;
311 double ptau=0;
312 int count_passestrigger_nfb=0;
313 double percent_increase_db=0;
314 double percent_increase_nfb=0;
315 double percent_increase_total=0;
316 double error_nfb=0;
317 double error_km3sr_nfb=0;
318 double error_percent_increase_nfb=0;
319 
320 Vector n_exit2bn_db[5];
321 Vector nrf_iceside_db[5]; // direction of rf [tries][3d]
322 double n_exit_phi; //phi angle of the ray from the surface to the balloon
323 int count_dbexitsice=0;
324 
325 // int count_interacts_in_earth=0;
326 double eventsfound_nfb_binned[NBINS]; // counting events without first bang
327 
328 // rf parameters
329 double heff_max=0.62639; // maximum value of the effective height based on antenna specs
330 
331 // event geometry
332 double scalefactor_distance=0; // 1/r scalefactor
333 double scalefactor_attenuation=0; //scalefactor due to attenuation in ice
334 double MAX_ATTENLENGTH=1671;
335 double maxtaper=0; // this is just for plotting - maximum you are ever off cerenkov cone while
336 //an event is detectable
337 double dviewangle_deg=0;
338 
339 double forseckel[NVIEWANGLE][Anita::NFREQ];// Per Seckel's request, get strength of signal across frequencies for different viewing angles.
340 double viewangles[NVIEWANGLE];
341 double GetAirDistance(double altitude_bn, double beta); // given beta=angle wrt horizontal that the ray hits the balloon, calculate distance that the ray traveled in air, including curvature of earth
342 
343 //Input files
344 int err = 1; // errors from GetDirection function
345 
346 double djunk; // junk variable
347 
348 //For verification plots - added by Stephen
349 int max_antenna0 = -1; //antenna with the peak voltage, top layer
350 int max_antenna1 = -1; //antenna with the peak voltage, middle layer
351 int max_antenna2 = -1; //antenna with the peak voltage, bottom layer
352 double max_antenna_volts0 = 0; //Voltage on the antenna with maximum signal, top layer
353 double max_antenna_volts0_em = 0; //Component of voltage from em shower on the antenna with maximum signal, top layer
354 
355 double max_antenna_volts1 = 0; //Voltage on the antenna with maximum signal, middle layer
356 double max_antenna_volts2 = 0; //Voltage on the antenna with maximum signal, bottom layer
357 
358 double rx0_signal_eachband[2][5];
359 double rx0_threshold_eachband[2][5];
360 double rx0_noise_eachband[2][5];
361 int rx0_passes_eachband[2][5];
362 
363 double voltagearray[Anita::NLAYERS_MAX*Anita::NPHI_MAX]; //Records max voltages on each antenna for one neutrino
364 
365 Vector ant_max_normal0; //Vector normal to the face of the antenna with the maximum signal for a single neutrino, top layer
366 Vector ant_max_normal1; //Vector normal to the face of the antenna with the maximum signal for a single neutrino, middle layer
367 Vector ant_max_normal2; //Vector normal to the face of the antenna with the maximum signal for a single neutrino, bottom layer
368 double vmmhz1m_visible = 0; //Actual V/m/Mhz at 1m
369 int freq_bins = Anita::NFREQ; //Because the compiler objected to using the const directly
370 double total_kgm2 = 0; // output of Getchord
371 double nnu_array[3];
372 double r_in_array[3];
373 double nsurf_rfexit_array[3];
374 double nsurf_rfexit_db_array[3];
375 double r_bn_array[3];
376 double n_bn_array[3];
377 double posnu_array[3];
378 double nrf_iceside_array[5][3];
379 double nrf_iceside_db_array[5][3];
380 double ant_max_normal0_array[3];
381 double ant_max_normal1_array[3];
382 double ant_max_normal2_array[3];
383 double n_pol_array[3];
384 double n_exit2bn_array[5][3];
385 double r_enterice_array[3];
386 double n_exit2bn_db_array[5][3];
387 double rfexit_array[5][3];
388 double rfexit_db_array[5][3];
389 
390 int times_crust_entered_det=0; //Counter for total times each Earth layer is entered for detected neutrinos only
391 int times_mantle_entered_det=0;
392 int times_core_entered_det=0;
393 int crust_entered=0;
394 int mantle_entered=0;
395 int core_entered=0;
396 int neutrinos_passing_all_cuts=0;
397 double sum_weights=0;
398 //End verification plot block
399 
400 int xsecParam_nutype = 0; // neutrino = 0, antineutrino = 1;
401 int xsecParam_nuint = 1; // NC = 0, CC = 1;
402 
403 
404 double justNoise_trig[2][48][512];
405 double justSignal_trig[2][48][512];
406 double justNoise_dig[2][48][512];
407 double justSignal_dig[2][48][512];
408 
409 // functions
410 
411 // set up array of viewing angles for making plots for seckel
412 void SetupViewangles(Signal *sig1);
413 
414 void GetAir(double *col1); // get air column as a function of theta- only important for black hole studies
415 double GetThisAirColumn(Settings*, Position r_in, Vector nnu, Position posnu, double *col1, double& cosalpha, double& mytheta, double& cosbeta0, double& mybeta);
416 
417 double ScaleVmMHz(double vmmhz1m_max, const Position &posnu1, const Position &r_bn, const Position &rfexit);
418 
419 
420 double IsItDoubleBang(double exitlength, double plepton);
421 
422 int WhereIsSecondBang(const Position& posnu, const Vector& nnu, double nuexitlength, double pnu, IceModel *antarctica1, const Position& r_bn, Position &posnu2, Position &rfexit_db, Vector &n_exit2bn_db);
423 void GetCurrent(string& current);
424 
425 
426 double GetAverageVoltageFromAntennasHit(Settings *settings1, int *nchannels_perrx_triggered, double *voltagearray, double& volts_rx_sum);
427 
428 
429 Vector GetPolarization(const Vector &nnu, const Vector &nrf2_iceside);
430 
431 void Attenuate(IceModel *antartica1, Settings *settings1, double& vmmhz_max, double rflength, const Position &posnu);
432 
433 void Attenuate_down(IceModel *antarctica1, Settings *settings1, double& vmmhz_max, const Position &rfexit2, const Position &posnu, const Position &posnu_down);
434 
435 void IsAbsorbed(double chord_kgm2, double len_int_kgm2, double& weight);
436 
437 void GetBalloonLocation(Interaction *interaction1,Ray *ray1,Balloon *bn1,IceModel *antarctica);
438 
439 int GetRayIceSide(const Vector &n_exit2rx, const Vector &nsurf_rfexit, double nexit, double nenter, Vector &nrf2_iceside);
440 
441 int GetDirection(Settings *settings1, Interaction *interaction1, const Vector &refr, double deltheta_em, double deltheta_had, double emfrac, double hadfrac, double vmmhz1m_max, double r_fromballoon, Ray *ray1, Signal *sig1, Position posnu, Anita *anita1, Balloon *bn1, Vector &nnu, double& costhetanu, double& theta_threshold);
442 
443 void GetFresnel(Roughness *rough1, int ROUGHNESS_SETTING, const Vector &nsurf_rfexit, const Vector &n_exit2rx, Vector &n_pol, const Vector &nrf2_iceside, double efield, double emfrac, double hadfrac, double deltheta_em, double deltheta_had, double &t_coeff_pokey, double &t_coeff_slappy, double &fresnel, double &mag);
444 
445 double GetViewAngle(const Vector &nrf2_iceside, const Vector &nnu);
446 
447 int TIR(const Vector &n_surf, const Vector &nrf2_iceside, double N_IN, double N_OUT);
448 
449 void IntegrateBands(Anita *anita1, int k, Screen *panel1, double *freq, double scalefactor, double *sumsignal);
450 
451 void Integrate(Anita *anita1, int j, int k, double *vmmhz, double *freq, double scalefactor, double sumsignal);
452 
453 void interrupt_signal_handler(int); // This catches the Control-C interrupt, SIGINT
454 
455 bool ABORT_EARLY = false; // This flag is set to true when interrupt_signal_handler() is called
456 
457 void Summarize(Settings *settings1, Anita* anita1, Counting *count1, Spectra *spectra1, Signal *sig1, Primaries *primary1, double, double eventsfound, double, double, double, double*, double, double, double&, double&, double&, double&, ofstream&, ofstream&, TString, Balloon*, SourceModel * src_model);
458 
459 void WriteNeutrinoInfo(Position&, Vector&, Position&, double, string, string, double, ofstream &nu_out);
460 
461 void CloseTFile(TFile *hfile);
462 
463 int Getmine(double*, double*, double*, double*);
464 
465 void Getearth(double*, double*, double*, double*);
466 
467 
468 #ifdef ANITA_UTIL_EXISTS
469 int GetIceMCAntfromUsefulEventAnt(Settings *settings1, int UsefulEventAnt);
470 #ifdef R_EARTH
471 #undef R_EARTH
472 #endif
473 #endif
474 
475 
476 double thresholdsAnt[48][2][5];
477 double thresholdsAntPass[48][2][5];
478 
479 
480 //do a threshold scan
481 double threshold_start=-1.;
482 double threshold_end=-6.;
483 const int NTHRESHOLDS=20;
484 double threshold_step=(threshold_end-threshold_start)/(double)NTHRESHOLDS;
485 
486 double npass_v_thresh[NTHRESHOLDS]={0.};
487 double denom_v_thresh[NTHRESHOLDS]={0.};
488 double npass_h_thresh[NTHRESHOLDS]={0.};
489 double denom_h_thresh[NTHRESHOLDS]={0.};
490 double thresholds[NTHRESHOLDS];
491 
492 int main(int argc, char **argv) {
493  //--------------------------------------------------------------
494  // MC Anita
495  //
496  // 12/01/03
497  //
498  //--------------------------------------------------------------
499 
500  //floating point exceptions
501  //
502  //
503  #ifdef ICEMC_FEEXCEPT
504  feenableexcept(FE_INVALID | FE_DIVBYZERO);
505 #endif
506 
507  // for comparing with peter
508  double sumsignal[5]={0.};
509  double sumsignal_aftertaper[5]={0.};
510 
511  string stemp;
512 
513  Settings* settings1 = new Settings();
514 
515  string input= ICEMC_SRC_DIR + "/inputs.conf";
516  string run_num;//current run number as string
517  int run_no = 0;//current run number as integer
518 
519  if( (argc%3!=1)&&(argc%2!=1)) {
520  cout << "Syntax for options: -i inputfile -o outputdir -r run_number\n";
521  return 0;
522  }
523  int nnu_tmp=0;
524  double exp_tmp=0;
525  double trig_thresh=0.;
526  int startNu=0;
527  TString outputdir;
528  char clswitch; // command line switch
529  if (argc>1) {
530  while ((clswitch = getopt(argc, argv, "t:i:o:r:n:e:x:")) != EOF) {
531  switch(clswitch) {
532  case 'n':
533  nnu_tmp=atoi(optarg);
534  cout << "Changed number of simulated neutrinos to " << nnu_tmp << endl;
535  break;
536  case 't':
537  trig_thresh=atof(optarg);
538  break;
539  case 'i':
540  input=optarg;
541  cout << "Changed input file to: " << input << endl;
542  break;
543  case 'o':
544  outputdir=optarg;
545  cout << "Changed output directory to: " << string(outputdir.Data()) << endl;
546  stemp="mkdir -p " + string(outputdir.Data());
547  system(stemp.c_str());
548  break;
549  case 'e':
550  exp_tmp=atof(optarg);
551  cout << "Changed neutrino energy exponent to " << exp_tmp << endl;
552  break;
553  case 'x':
554  startNu=atoi(optarg);
555  cout << "Running icemc for just 1 event with eventNumber : " << startNu << endl;
556  break;
557  case 'r':
558  run_num=optarg;
559  stringstream convert(run_num);
560  convert>>run_no;
561  break;
562  } // end switch
563  } // end while
564  } // end if arg>1
565 
566  settings1->SEED=settings1->SEED +run_no;
567  cout << "seed is " << settings1->SEED << endl;
568 
569 
570  stemp=string(outputdir.Data())+"/nu_position"+run_num+".txt";
571  ofstream nu_out(stemp.c_str(), ios::app); //Positions, direction of momentum, and neutrino type for Ryan.
572 
573  stemp=string(outputdir.Data())+"/veff"+run_num+".txt";
574  ofstream veff_out(stemp.c_str(), ios::app);//to output only energy and effective volume to veff.txt
575 
576  stemp=string(outputdir.Data())+"/distance"+run_num+".txt";
577  ofstream distanceout(stemp.c_str());
578 
579  stemp=string(outputdir.Data())+"/debug"+run_num+".txt";
580  fstream outfile(stemp.c_str(), ios::out);
581 
582  stemp=string(outputdir.Data())+"/forbrian"+run_num+".txt";
583  fstream forbrian(stemp.c_str(), ios::out);
584 
585  stemp=string(outputdir.Data())+"/al_voltages_direct"+run_num+".dat";
586  fstream al_voltages_direct(stemp.c_str(), ios::out); //added djg ------provide anita-lite voltages and noise from MC for anita-lite analysis
587 
588  stemp=string(outputdir.Data())+"/events"+run_num+".txt";
589  ofstream eventsthatpassfile(stemp.c_str());
590 
591  stemp=string(outputdir.Data())+"/numbers"+run_num+".txt";
592  ofstream fnumbers(stemp.c_str()); // debugging
593 
594  stemp=string(outputdir.Data())+"/output"+run_num+".txt";
595  ofstream foutput(stemp.c_str(), ios::app);
596 
597  stemp=string(outputdir.Data())+"/slacviewangles"+run_num+".dat";
598  ofstream fslac_viewangles(stemp.c_str()); // this outputs numbers that we need for analyzing slac data
599 
600  stemp=string(outputdir.Data())+"/slac_hitangles"+run_num+".dat";
601  ofstream fslac_hitangles(stemp.c_str()); // this outputs numbers that we need for analyzing slac data
602 
603  Balloon *bn1=new Balloon(); // instance of the balloon
604  Anita *anita1=new Anita();// right now this constructor gets banding info
605  Secondaries *sec1=new Secondaries();
606  Primaries *primary1=new Primaries();
607  Signal *sig1=new Signal();
608  Ray *ray1=new Ray(); // create new instance of the ray class
609  Counting *count1=new Counting();
610  GlobalTrigger *globaltrig1;
611  Taumodel *taus1 = new Taumodel();
612  // input parameters
613  settings1->ReadInputs(input.c_str(), foutput, NNU, RANDOMISEPOL);
614  settings1->ApplyInputs(anita1, sec1, sig1, bn1, ray1);
615 
616  // Signal needs to be initialize with Askaryan parametrisation info
617  // After the inputs are read
618  sig1->Initialize();
619 
620  settings1->SEED=settings1->SEED + run_no;
621  setSeed(settings1->SEED);
622 
623  bn1->InitializeBalloon();
624  anita1->Initialize(settings1, foutput, inu, outputdir);
625 
626  if (startNu>0){
627  run_no = 0;
628  nnu_tmp = startNu+1;
629  }
630 
631  if (trig_thresh!=0)
632  anita1->powerthreshold[4]=trig_thresh;
633  if (nnu_tmp!=0)
634  NNU=nnu_tmp;
635  if (exp_tmp!=0)
636  settings1->EXPONENT=exp_tmp;
637 
638  SourceModel *src_model = 0;
639  if (!strcasecmp(settings1->SOURCE.c_str(),"CUSTOM"))
640  {
641  src_model = new SourceModel("custom");
642 
643  src_model->addSource( new Source("Custom Source", (settings1->CUSTOM_RA)/15, settings1->CUSTOM_DEC,
644  new ConstantExponentialSourceFlux(settings1->CUSTOM_GAMMA, 1e-10,1e6)));
645 
646  }
647  else if(strcasecmp(settings1->SOURCE.c_str(),"NONE"))
648  {
649  src_model = SourceModel::getSourceModel(settings1->SOURCE.c_str(),
650  SourceModel::Restriction( settings1->DEC_CUT, settings1->WHICH_SOURCES.c_str(), settings1->WHICH_SUBTYPE.c_str(),
651  SourceModel::Restriction::fromString(settings1->WHICH_START_TIME.c_str()),
652  SourceModel::Restriction::fromString(settings1->WHICH_END_TIME.c_str())));
653  }
654 
655  if (settings1->SOURCE_USE_EXPONENT && settings1->EXPONENT < 22)
656  {
657  settings1->SOURCE_MIN_E=settings1->EXPONENT;
658  settings1->SOURCE_MAX_E=settings1->EXPONENT;
659  }
660 
661 
662  double src_min = TMath::Power(10,settings1->SOURCE_MIN_E-9); //since source model takes things in GeV
663  double src_max = TMath::Power(10,settings1->SOURCE_MAX_E-9); //since source model takes things in GeV
664 
665  Spectra *spectra1 = new Spectra((int)settings1->EXPONENT);
666  Interaction *interaction1=new Interaction("nu", primary1, settings1, 0, count1);
667  Interaction *int_banana=new Interaction("banana", primary1, settings1, 0, count1);
668 
669  if (src_model) {
670  printf("Using Source Model %s\n", src_model->getName());
671  printf("Setting up weights: %g %g %g %g\n", bn1->min_time, bn1->max_time, src_min, src_max);
672  src_model->setUpWeights(bn1->min_time, bn1->max_time , src_min, src_max);
673  }
674 
675 
676 
677  Roughness *rough1 = new Roughness(settings1); // create new instance of the roughness class
678  rough1->SetRoughScale(settings1->ROUGHSIZE);
679 
680  Screen *panel1 = new Screen(0); // create new instance of the screen class
681 
682  if(!src_model && spectra1->IsSpectrum())
683  {
684  cout << "Using an energy spectrum" << endl;
685  }
686 
687  else if (src_model)
688  {
689  cout<< "Source Model Bounds are 10^" << settings1->SOURCE_MIN_E << "eV to 10^" << settings1->SOURCE_MAX_E << "eV" << endl;
690  }
691 
692  else if (!src_model && spectra1->IsMonoenergetic())
693  {
694  cout << "Using a monoenergetic exponent of: " << settings1->EXPONENT << endl;
695  }
696 
697  std::cout << "----------------------" << std::endl;
698 
699  // declare instance of trigger class.
700  // this constructor reads from files with info to parameterize the
701  // signal efficiency curves.
702  // and reads in scalar vs. threshold scans
703 
704  time_t raw_start_time = time(NULL);
705  struct tm * start_time = localtime(&raw_start_time);
706 
707  cout << "Date and time at start of run are: " << asctime (start_time) << "\n";
708 
709  if (settings1->FORSECKEL)
710  SetupViewangles(sig1);// set up viewing angles for testing against jaime's parameterizations
711 
712  // for attenuation of neutrino in atmosphere
713  // only important for black hole studies
714  double col1[900];
715  GetAir(col1);
716  double myair = 0.;//air column density, kg/m^2
717 
718  // zeroing global variables.
719  Tools::Zero(sum_frac, 3);
720  Tools::Zero(sum_frac_db, 3);
721  Tools::Zero(anita1->NRX_PHI, Anita::NLAYERS_MAX);
722  for (int i=0;i<Anita::NLAYERS_MAX;i++) {
723  Tools::Zero(anita1->PHI_EACHLAYER[i], Anita::NPHI_MAX);
724  }
725  Tools::Zero(anita1->PHI_OFFSET, Anita::NLAYERS_MAX);
726  Tools::Zero(anita1->THETA_ZENITH, Anita::NLAYERS_MAX);
727  Tools::Zero(anita1->LAYER_VPOSITION, Anita::NLAYERS_MAX);
728  Tools::Zero(anita1->RRX, Anita::NLAYERS_MAX);
729 
730  //added djg ////////////////////////////////////////////////////////
731  al_voltages_direct<<"antenna #"<<" "<<"volts chan 1"<<" "<<"volts chan 2"<<" "<<"volts chan 3"<<" "<<"volts chan 4"<<" "<<"noise chan 1"<<" "<<"noise chan 2"<<" "<<"noise chan 3"<<" "<<"noise chan 4"<<" "<<"weight"<<endl;
733 
734  // ray tracing
735  double viewangle=0;
736  double viewangle_temp=0; // angle of ray in ice relative to neutrino direction
737  double viewangle_deg=0; // viewing angle in degrees.
738  double cosviewangle=0; // cosine of viewing angle
739  double offaxis=0; // viewangle-changle, for plotting
740  double nsigma_offaxis=0;// offaxis, relative to deltheta_had, for plotting
741  double theta_threshold=0; // maximum angle you can be away from the cerenkov angle and still have a chance of seeing the event.
742  double theta_threshold_deg=0; // maximum angle you can be away from the cerenkov angle and still have a chance of seeing the event.
743 
744  double nsigma_em_threshold=0; //number of sigma away theta_threshold is.
745  double nsigma_had_threshold=0;// just for plotting
746  double slopeyangle=0; // angle between nominal surface normal and the surface normal after slopeyness is applied
747  //-------------------
748  int beyondhorizon = 0; //Switch tells if neutrino interacts beyond the balloon's horizon. (0: inside horizon, 1: outside horizon)
749 
750  // frequency binning
751  double vmmhz1m_max=0; // maximum V/m/MHz at 1m from Jaime (highest frequency)
752  double vmmhz_lowfreq=0.; // V/m/MHz after 1/r, attenuation at the lowest freq.
753  double bestcase_atten=0;// attenuation factor, best case
754  double vmmhz1m_fresneledonce=0; // above, after fresnel factor applied for ice-air interface
755  double vmmhz1m_fresneledtwice=0; // above, after fresnel factor applied for firn
756  double vmmhz[Anita::NFREQ]; // V/m/MHz at balloon (after all steps)
757 
758  // given the angle you are off the Cerenkov cone, the fraction of the observed e field that comes from the em shower
759  double vmmhz_em[Anita::NFREQ];
760  double vmmhz_temp=1.;
761  double vmmhz_min_thatpasses=1000;
762  double vmmhz_min=0; // minimum of the above array
763  double vmmhz_max=0; // maximum of the above array
764  double deltheta_em[Anita::NFREQ], deltheta_had[Anita::NFREQ]; // for ch angular distribution
765  double deltheta_em_max, deltheta_had_max; // maximum value of above array angular distribution
766  double deltheta_em_mid2, deltheta_had_mid2; // widths of cones for the mid2 band
767 
768  // shower properties
769  double emfrac, hadfrac, sumfrac; // em and had fractions
770  int n_interactions=1; // count number of interactions for this event, including secondaries.
771  double emfrac_db, hadfrac_db;
772  int nuflavorint2=interaction1->nuflavorint;
773  double costheta_nutraject2=interaction1->costheta_nutraject;
774  double phi_nutraject2=interaction1->phi_nutraject;
775  double altitude_int2=interaction1->altitude_int;
776  int currentint2=interaction1->currentint;
777  double d12=interaction1->d1;
778  double d22=interaction1->d2;
779  double dtryingdirection2=interaction1->dtryingdirection;
780  double logchord2=interaction1->logchord;
781  double r_fromballoon2=interaction1->r_fromballoon[0];
782  double chord_kgm2_bestcase2=interaction1->chord_kgm2_bestcase;
783  double chord_kgm2_ice2=interaction1->chord_kgm2_ice;
784  double weight_bestcase2=interaction1->weight_bestcase;
785  double r_exit2bn2=interaction1->r_exit2bn;
786  double r_exit2bn_measured2=interaction1->r_exit2bn_measured;
787 
788  string taudecay; // tau decay type: e, m, h
789 
790  double elast_y=0; // inelasticity
791  double volts_rx_0=0; // voltage on an individual antenna, lc polarization
792  double volts_rx_1=0; // voltage on an individual antenna, rc polarization
793  double volts_rx_max=0; // max voltage seen on an antenna - just for debugging purposes
794  double volts_rx_ave=0; // ave voltage seen on an antenna, among hit antennas
795  double volts_rx_sum=0; // ave voltage seen on an antenna, among hit antennas
796 
797  double volts_rx_max_highband; // max voltage seen on an antenna - just for debugging purposes
798  double volts_rx_max_lowband; // max voltage seen on an antenna - just for debugging purposes
799  double volts_rx_rfcm_lab_e_all[48][512];
800  double volts_rx_rfcm_lab_h_all[48][512];
801 
802  // variable declarations for functions GetEcompHcompEvector and GetEcompHcompkvector - oindree
803  static double e_component[Anita::NANTENNAS_MAX]={0}; // E comp along polarization
804  static double h_component[Anita::NANTENNAS_MAX]={0}; // H comp along polarization
805  static double n_component[Anita::NANTENNAS_MAX]={0}; // normal comp along polarization
806 
807  static double e_component_kvector[Anita::NANTENNAS_MAX]={0}; // component of e-field along the rx e-plane
808  static double h_component_kvector[Anita::NANTENNAS_MAX]={0}; // component of the e-field along the rx h-plane
809  static double n_component_kvector[Anita::NANTENNAS_MAX]={0}; // component of the e-field along the normal
810 
811  Vector n_eplane = const_z;
812  Vector n_hplane = -const_y;
813  Vector n_normal = const_x;
814 
815  double chengji = 0;
816  Vector ant_normal; //Vector normal to the face of the antenna
817 
818  double hitangle_e, hitangle_h; // angle the ray hits the antenna wrt e-plane, h-plane
819  double hitangle_e_all[Anita::NANTENNAS_MAX]; // hit angles rel. to e plane stored for each antenna
820  double hitangle_h_all[Anita::NANTENNAS_MAX]; // hit angles rel. to h plane stored for each antenna
821 
822  double sigma = 0; // for cross section
823  double len_int_kgm2=0; // interaction length in kg/m^2
824  double eventsfound_db=0; // same, for double bang
825  double eventsfound_nfb=0; // for taus
826 
827  // positions in earth frame
828  double horizcoord=0; // x component of interaction position
829  double vertcoord=0; // y component of interaction position
830 
831  double dist_int_bn_2d=0; // 2-d (surface) distance between interaction and balloon
832  double dist_int_bn_2d_chord=0; //chord distance between interaction and balloon (between surface points)
833 
834  double viewangle_eachboresight[Anita::NLAYERS_MAX][Anita::NPHI_MAX]; // viewing angle for each antenna
835 
836  double cosalpha; // angle between nu momentum and surface normal at earth entrance point
837  double mytheta;
838  double cosbeta0; // angle between nu momentum and surface normal at interaction point.
839  double mybeta;
840  double nuexitlength=0; // distance from interaction to where neutrino would leave
841  double nuexitice=0;
842  double nuentrancelength=0; // for taus
843  double taulength=0; // distance tau travels in ice before decaying
844  double icethickness=0; // for taus
845  double theta_pol_measured; // theta of the polarization as measured at the payload (for now we don't correct for the 10 degree cant)
846 
847  double ptaui=0;
848  double ptauf =0;
849  double tauweight=0;
850  double nutauweightsum=0;
851  double tauweightsum=0;
852  double nutauweight=0;
853  int tautrigger=0;
854  int tauweighttrigger=0;
855  double sample_x=0, sample_y = 0;
856 
857  bool isDead;
858 
859  double sourceLon;
860  double sourceAlt;
861  double sourceLat;
862  double sourceMag;
863 
864  //double payloadTheta;
865  //double payloadPhi;
866 
867  Vector n_nutraject_ontheground; //direction of the neutrino from the person standing on the ground just below the balloon.
868  Vector n_pol; // direction of polarization
869  Vector n_pol_eachboresight[Anita::NLAYERS_MAX][Anita::NPHI_MAX]; // direction of polarization of signal seen at each antenna
870  Vector n_pol_db; // same, double bangs
871 
872  int l3trig[Anita::NPOL]; // 16 bit number which says which phi sectors pass L3 V-POL
873  int l3trignoise[Anita::NPOL]; // 16 bit number which says which phi sectors pass L3 V-POL
874  // For each trigger layer, which "clumps" pass L2. 16 bit, 16 bit and 8 bit for layers 1 & 2 and nadirs
875  int l2trig[Anita::NPOL][Anita::NTRIGGERLAYERS_MAX];
876  //For each trigger layer, which antennas pass L1. 16 bit, 16 bit and 8 bit and layers 1, 2 and nadirs
877  int l1trig[Anita::NPOL][Anita::NTRIGGERLAYERS_MAX];
878 
879  // these are declared here so that they can be stuck into trees
880  int loctrig[Anita::NPOL][Anita::NLAYERS_MAX][Anita::NPHI_MAX]; //counting how many pass trigger requirement
881 
882  int loctrig_nadironly[Anita::NPOL][Anita::NPHI_MAX]; //counting how many pass trigger requirement
883 
884  int nchannels_triggered = 0; // total number of channels triggered
885  int nchannels_perrx_triggered[48]; // total number of channels triggered
886 
887  // zeroing
888  interaction1->dnutries=0;
889  eventsfound=0.; // sums weights for events that pass
890 
891  Tools::Zero(count1->npass, 2); // sums events that pass, without weights
892  Tools::Zero(sum, 3);
893  eventsfound_db=0;
894  eventsfound_nfb=0;
895 
896  Tools::Zero(eventsfound_binned, NBINS);
897  Tools::Zero(eventsfound_binned_e, NBINS);
898  Tools::Zero(eventsfound_binned_mu, NBINS);
899  Tools::Zero(eventsfound_binned_tau, NBINS);
900  Tools::Zero(eventsfound_nfb_binned, NBINS);
901 
902  //we pick both the interaction point and its corresponding mirror point
903 
904  //for drawing the events on the events map
905  TH2F *ref_int_coord=new TH2F("ref_int_coord", "", 600, -3000, 3000, 500, -2500, 2500);
906  ref_int_coord->SetMarkerSize(0.7);;
907  ref_int_coord->SetMarkerStyle(30);
908  ref_int_coord->SetMarkerColor(kBlue);
909 
910  TH2F *dir_int_coord=new TH2F("dir_int_coord", "", 600, -3000, 3000, 500, -2500, 2500);
911  dir_int_coord->SetMarkerSize(0.7);
912  dir_int_coord->SetMarkerStyle(30);
913 
914  TH1F *prob_eachphi_bn=new TH1F("prob_eachphi_bn", "prob_eachphi_bn", 100, 0., 6.3);
915  TH1F *prob_eachilon_bn=new TH1F("prob_eachilon_bn", "prob_eachilon_bn", 180, 0., 180.);
916  TH2F *h6=new TH2F("theta_vs_hitangle_h", "theta_vs_hitangle_h", 100, -3.14, 3.14, 100, -1.1, 1.1);
917  TH1F *h10=new TH1F("hitangle_e", "hitangle_e", 20, -1.6, 1.6);
918  TH1F *hy=new TH1F("hy", "hy", 100, 0., 1.);
919  TH1F *fraction_sec_muons = new TH1F("fraction_sec_muons", "fraction_sec_muons", 100, 0., 1.);
920  TH1F *fraction_sec_taus=new TH1F("fraction_sec_taus", "fraction_sec_taus", 100, 0., 1.);
921  TH1F *n_sec_muons= new TH1F("n_sec_muons", "n_sec_muons", 100, 0., 10.);
922  TH1F *n_sec_taus= new TH1F("n_sec_taus", "n_sec_taus", 100, 0., 10.);
923  TH1F *sampleweights=new TH1F("sampleweights", "sampleweights", 100, -5., 0.); // we sample weights for early events and save
924  //them in this histogram,
925 
926  //to determine where the cut should be.
927  stemp=string(outputdir.Data())+"/icefinal"+run_num+".root";
928  TFile *hfile = new TFile(stemp.c_str(), "RECREATE", "ice");
929  TTree *tree2 = new TTree("h2000", "h2000"); // tree2 filled for each event that is beyond the horizon.
930 
931  tree2->Branch("inu", &inu, "inu/I");
932  tree2->Branch("horizcoord", &horizcoord, "horizcoord/D");
933  tree2->Branch("vertcoord", &vertcoord, "vertcoord/D");
934  tree2->Branch("scalefactor_distance", &scalefactor_distance, "scalefactor_distance/D");
935  tree2->Branch("scalefactor_attenuation", &scalefactor_attenuation, "scalefactor_attenuation/D");
936 
937  TTree *tree3 = new TTree("h3000", "h3000"); // tree3 if signal is detectable.
938  tree3->Branch("deltheta_em_max", &deltheta_em_max, "deltheta_em_max/D");
939  tree3->Branch("deltheta_had_max", &deltheta_had_max, "deltheta_had_max/D");
940  tree3->Branch("theta_threshold_deg", &theta_threshold_deg, "theta_threshold_deg/D");
941  tree3->Branch("nsigma_em_threshold", &nsigma_em_threshold, "nsigma_em_threshold/D");
942  tree3->Branch("nsigma_had_threshold", &nsigma_had_threshold, "nsigma_had_threshold/D");
943  tree3->Branch("horizcoord", &horizcoord, "horizcoord/D");
944  tree3->Branch("vertcoord", &vertcoord, "vertcoord/D");
945  tree3->Branch("vmmhz_max", &vmmhz_max, "vmmhz_max/D");
946  tree3->Branch("vmmhz_min", &vmmhz_min, "vmmhz_min/D");
947  tree3->Branch("dviewangle_deg", &dviewangle_deg, "dviewangle_deg/D");
948  tree3->Branch("viewangle_deg", &viewangle_deg, "viewangle_deg/D");
949  tree3->Branch("changle_deg", &changle_deg, "changle_deg/D");
950  tree3->Branch("cosviewangle", &cosviewangle, "cosviewangle/D");
951  tree3->Branch("emfrac", &emfrac, "emfrac/D");
952  tree3->Branch("hadfrac", &hadfrac, "hadfrac/D");
953 
954  TTree *tree5 = new TTree("h5000", "h5000"); // tree5 filled for each nutau.
955  tree5->Branch("vmmhz1m_max", &vmmhz1m_max, "vmmhz1m_max/D");
956  tree5->Branch("inu", &inu, "inu/I");
957  tree5->Branch("nuexitlength", &nuexitlength, "nuexitlength/D");
958  tree5->Branch("nuexitice", &nuexitice, "nuexitice");
959  tree5->Branch("vmmhz_max", &vmmhz_max, "vmmhz_max");
960  tree5->Branch("maxtaper", &maxtaper, "maxtaper");
961  tree5->Branch("inu", &inu, "inu/I");
962  tree5->Branch("whichray", &whichray, "whichray/I");
963  tree5->Branch("pnu", &pnu, "pnu/D");
964  tree5->Branch("costhetanu", &costhetanu, "costhetanu/D");
965  tree5->Branch("viewangle", &viewangle, "viewangle/D");
966  tree5->Branch("offaxis", &offaxis, "offaxis/D");
967  tree5->Branch("nsigma_offaxis", &nsigma_offaxis, "nsigma_offaxis/D");
968  tree5->Branch("hadfrac", &hadfrac, "hadfrac/D");
969  tree5->Branch("emfrac", &emfrac, "emfrac/D");
970  tree5->Branch("sumfrac", &sumfrac, "sumfrac/D");
971  tree5->Branch("horizcoord", &horizcoord, "horizcoord/D");
972  tree5->Branch("vertcoord", &vertcoord, "vertcoord/D");
973  tree5->Branch("weight1", &weight1, "weight1/D");
974  tree5->Branch("nearthlayers", &nearthlayers, "nearthlayers/D");
975  tree5->Branch("logchord", &logchord2, "interaction1->logchord/D");
976  tree5->Branch("diff_3tries", &diff_3tries, "diff_3tries/D");
977  tree5->Branch("fresnel2", &fresnel2, "fresnel2/D");
978  tree5->Branch("costheta_inc", &costheta_inc, "costheta_inc/D");
979  tree5->Branch("costheta_exit", &costheta_exit, "costheta_exit/D");
980  tree5->Branch("deltheta_em", &deltheta_em[0], "deltheta_em/D");
981  tree5->Branch("deltheta_had", &deltheta_had[0], "deltheta_had/F");
982  tree5->Branch("r_fromballoon", &interaction1->r_fromballoon[0], "r_fromballoon/F");
983  tree5->Branch("theta_in", &theta_in, "theta_in/D");
984  tree5->Branch("lat_in", &lat_in, "lat_in/D");
985 
986 
987  TTree *tree6 = new TTree("h6000", "h6000"); // tree6 filled for neutrinos that enter S of 60 deg S latitude.
988  tree6->Branch("volts_rx_0", &volts_rx_0, "volts_rx_0/D");
989  tree6->Branch("volts_rx_1", &volts_rx_1, "volts_rx_1/D");
990  tree6->Branch("horizcoord", &horizcoord, "horizcoord/D");
991  tree6->Branch("vertcoord", &vertcoord, "vertcoord/D");
992  tree6->Branch("theta_in", &theta_in, "theta_in/D");
993  tree6->Branch("chord_kgm2_bestcase", &chord_kgm2_bestcase2, "chord_kgm2_bestcase/D");
994  tree6->Branch("chord_kgm2_ice", &interaction1->chord_kgm2_ice, "chord_kgm2_ice/D");
995  tree6->Branch("costheta_nutraject", &interaction1->costheta_nutraject, "costheta_nutraject/D");
996  tree6->Branch("weight1", &weight1, "weight1/D");
997  tree6->Branch("weight_bestcase", &weight_bestcase2, "weight_bestcase/D");
998  tree6->Branch("whichray", &whichray, "whichray/I");
999  tree6->Branch("mybeta", &mybeta, "mybeta/D");
1000  tree6->Branch("longitude", &longitude_this, "longitude/D");
1001 
1002 
1003  TTree *tree6b = new TTree("h6001", "h6001"); // tree6b filled for the closest antenna to the interaction
1004  tree6b->Branch("bwslice_vnoise", bwslice_vnoise_thislayer, "bwslice_vnoise_thislayer[4]/D");
1005 
1006  TTree *tree7 = new TTree("h7000", "h7000"); // tree6 filled just after flavor is set
1007  tree7->Branch("emfrac", &emfrac, "emfrac/D");
1008  tree7->Branch("hadfrac", &hadfrac, "hadfrac/D");
1009  tree7->Branch("current", &interaction1->currentint, "currentint/I");
1010  tree7->Branch("nuflavor", &interaction1->nuflavorint, "nuflavorint/I");
1011  tree7->Branch("sumfrac", &sumfrac, "sumfrac/D");
1012  tree7->Branch("slopeyangle", &slopeyangle, "slopeyangle/D");
1013 
1014  TTree *jaimetree=new TTree("jaimetree", "jaimetree"); // signal as it is produced at the interaction
1015  jaimetree->Branch("vmmhz1m_max", &vmmhz1m_max, "vmmhz1m_max/D");
1016  jaimetree->Branch("emfrac", &emfrac, "emfrac/D");
1017  jaimetree->Branch("hadfrac", &hadfrac, "hadfrac/D");
1018  jaimetree->Branch("deltheta_em_max", &deltheta_em_max, "deltheta_em_max/D");
1019  jaimetree->Branch("deltheta_had_max", &deltheta_had_max, "deltheta_had_max/D");
1020  jaimetree->Branch("sumfrac", &sumfrac, "sumfrac/D");
1021  jaimetree->Branch("vmmhz1m_visible", &vmmhz1m_visible, "vmmhz1m_visible/D");
1022 
1023  TTree *viewangletree=new TTree("viewangletree", "viewangletree"); // signal as it is produced at the interaction
1024  viewangletree->Branch("dviewangle_deg", &dviewangle_deg, "dviewangle_deg/D");
1025  viewangletree->Branch("emfrac", &emfrac, "emfrac/D");
1026  viewangletree->Branch("hadfrac", &hadfrac, "hadfrac/D");
1027  viewangletree->Branch("deltheta_em_max", &deltheta_em_max, "deltheta_em_max/D");
1028  viewangletree->Branch("deltheta_had_max", &deltheta_had_max, "deltheta_had_max/D");
1029  viewangletree->Branch("theta_threshold_deg", &theta_threshold_deg, "theta_threshold_deg/D");
1030  viewangletree->Branch("dnutries", &interaction1->dnutries, "dnutries/D");
1031  viewangletree->Branch("viewangle", &viewangle, "viewangle/D");
1032  viewangletree->Branch("chord", &interaction1->chord, "dnutries/D");
1033 
1034  TTree *neutrino_positiontree=new TTree("neutrino_positiontree", "neutrino_positiontree");
1035  neutrino_positiontree->Branch("nnu", &interaction1->nnu, "nnu[3]/D");
1036  neutrino_positiontree->Branch("dtryingdirection", &interaction1->dtryingdirection, "dtryingdirection/D");
1037  neutrino_positiontree->Branch("bn1->dtryingposition", &bn1->dtryingposition, "bn1->dtryingposition/D");
1038 
1039  //Filled just after Getchord, where we find the neutrino's path through the Earth
1040  TTree *nupathtree=new TTree("nupathtree", "nupathtree");
1041  nupathtree->Branch("total_kgm2", &total_kgm2, "total_kgm2/D");
1042  nupathtree->Branch("chord", &interaction1->chord, "chord/D");
1043  nupathtree->Branch("crust_entered", &crust_entered, "crust_entered/I");
1044  nupathtree->Branch("mantle_entered", &mantle_entered, "mantle_entered/I");
1045  nupathtree->Branch("core_entered", &core_entered, "core_entered/I");
1046  nupathtree->Branch("mybeta", &mybeta, "mybeta/D");
1047  nupathtree->Branch("costheta_nutraject", &interaction1->costheta_nutraject, "costheta_nutraject/D");
1048 
1049  TTree *finaltree = new TTree("passing_events", "passing_events"); // finaltree filled for all events that pass
1050  finaltree->Branch("inu", &inu, "inu/I");
1051  finaltree->Branch("sample_x", &sample_x, "sample_x/D");
1052  finaltree->Branch("sample_y", &sample_y, "sample_y/D");
1053  finaltree->Branch("vmmhz_min", &vmmhz_min, "vmmhz_min/D");
1054  finaltree->Branch("vmmhz_max", &vmmhz_max, "vmmhz_max/D");
1055  finaltree->Branch("thresholdsAnt", &thresholdsAnt, "thresholdsAnt[48][2][5]/D");
1056  finaltree->Branch("thresholdsAntPass", &thresholdsAntPass, "thresholdsAntPass[48][2][5]/D");
1057  finaltree->Branch("deadTime", &anita1->deadTime, "deadTime/D");
1058  finaltree->Branch("horizcoord", &horizcoord, "horizcoord/D");
1059  finaltree->Branch("vertcoord", &vertcoord, "vertcoord/D");
1060  finaltree->Branch("horizcoord_bn", &bn1->horizcoord_bn, "horizcoord_bn/D");
1061  finaltree->Branch("vertcoord_bn", &bn1->vertcoord_bn, "vertcoord_bn/D");
1062  finaltree->Branch("r_bn", &r_bn_array, "r_bn_array[3]/D");
1063  finaltree->Branch("n_bn", &n_bn_array, "n_bn_array[3]/D");
1064  finaltree->Branch("longitude_bn", &longitude_this, "longitude_bn/D");
1065  finaltree->Branch("heading_bn", &heading_this, "heading_bn/D");
1066  finaltree->Branch("gps_offset", &gps_offset, "gps_offset/D");
1067  // this one is just weight due to earth absorption
1068  finaltree->Branch("weight1", &weight1, "weight1/D");
1069  // this is the total weight - the one you want to use!
1070  finaltree->Branch("weight", &weight, "weight/D");
1071  finaltree->Branch("logweight", &logweight, "logweight/D");
1072  finaltree->Branch("posnu", &posnu_array, "posnu_array[3]/D");
1073  finaltree->Branch("costheta_nutraject", &costheta_nutraject2, "costheta_nutraject/D");
1074  finaltree->Branch("chord_kgm2_ice", &chord_kgm2_ice2, "chord_kgm2_ice/D");
1075  finaltree->Branch("phi_nutraject", &phi_nutraject2, "phi_nutraject/D");
1076  finaltree->Branch("altitude_int", &altitude_int2, "altitude_int/D");
1077  finaltree->Branch("nnu", &nnu_array, "nnu_array[3]/D");
1078  finaltree->Branch("n_exit2bn", &n_exit2bn_array, "n_exit2bn_array[5][3]/D");
1079  finaltree->Branch("n_exit_phi", &n_exit_phi, "n_exit_phi/D");
1080  finaltree->Branch("rfexit", &rfexit_array, "rfexit_array[5][3]/D");
1081 
1082  finaltree->Branch("pnu", &pnu, "pnu/D");
1083  finaltree->Branch("elast_y", &elast_y, "elast_y/D");
1084  finaltree->Branch("emfrac", &emfrac, "emfrac/D");
1085  finaltree->Branch("hadfrac", &hadfrac, "hadfrac/D");
1086  finaltree->Branch("sumfrac", &sumfrac, "sumfrac/D");
1087  finaltree->Branch("nuflavor", &nuflavorint2, "nuflavorint/I");//1=electron, 2=muon, 3=tau
1088  finaltree->Branch("current", &currentint2, "currentint/I");//0=charged current, 1=neutral current
1089  finaltree->Branch("logchord", &logchord2, "logchord/D");
1090  finaltree->Branch("nuexitice", &nuexitice, "nuexitice/D");
1091  finaltree->Branch("weight_bestcase", &weight_bestcase2, "weight_bestcase/D");
1092  finaltree->Branch("chord_kgm2_bestcase", &chord_kgm2_bestcase2, "chord_kgm2_bestcase/D");
1093  finaltree->Branch("dtryingdirection", &dtryingdirection2, "dtryingdirection/D");
1094  finaltree->Branch("l3trig", &l3trig, "l3trig[2]/I");
1095  finaltree->Branch("l2trig", &l2trig, "l2trig[2][3]/I");
1096  finaltree->Branch("l1trig", &l1trig, "l1trig[2][3]/I");
1097  finaltree->Branch("phiTrigMask", &anita1->phiTrigMask, "phiTrigMask/s");
1098  finaltree->Branch("phiTrigMaskH", &anita1->phiTrigMaskH, "phiTrigMaskH/s");
1099  finaltree->Branch("l1TrigMask", &anita1->l1TrigMask, "l1TrigMask/s");
1100  finaltree->Branch("l1TrigMaskH", &anita1->l1TrigMaskH, "l1TrigMaskH/s");
1101  finaltree->Branch("max_antenna0", &max_antenna0, "max_antenna0/I");
1102  finaltree->Branch("max_antenna1", &max_antenna1, "max_antenna1/I");
1103  finaltree->Branch("max_antenna2", &max_antenna2, "max_antenna2/I");
1104 
1105  finaltree->Branch("viewangle", &viewangle, "viewangle/D");
1106  finaltree->Branch("offaxis", &offaxis, "offaxis/D");
1107  finaltree->Branch("rx0_signal_eachband", &rx0_signal_eachband, "rx0_signal_eachband[2][5]/D");
1108  finaltree->Branch("rx0_threshold_eachband", &rx0_threshold_eachband, "rx0_threshold_eachband[2][5]/D");
1109  finaltree->Branch("rx0_noise_eachband", &rx0_noise_eachband, "rx0_noise_eachband[2][5]/D");
1110  finaltree->Branch("rx0_passes_eachband", &rx0_passes_eachband, "rx0_passes_eachband[2][5]/I");
1111  finaltree->Branch("e_component", &e_component, "e_component[48]/D");
1112  finaltree->Branch("h_component", &h_component, "h_component[48]/D");
1113  finaltree->Branch("dist_int_bn_2d", &dist_int_bn_2d, "dist_int_bn_2d/D");
1114  finaltree->Branch("d1", &d12, "d1/D");
1115 
1116  finaltree->Branch("cosalpha", &cosalpha, "cosalpha/D");
1117  finaltree->Branch("mytheta", &mytheta, "mytheta/D");
1118  finaltree->Branch("cosbeta0", &cosbeta0, "cosbeta0/D");
1119  finaltree->Branch("mybeta", &mybeta, "mybeta/D");
1120  finaltree->Branch("d1", &d12, "d1/D");
1121  finaltree->Branch("d2", &d22, "d2/D");
1122 
1123  //Begin block added by Stephen for verification plots
1124  finaltree->Branch("fresnel1", &fresnel1, "fresnel1/D");
1125  finaltree->Branch("fresnel2", &fresnel2, "fresnel2/D");
1126  finaltree->Branch("mag1", &mag1, "mag1/D");
1127  finaltree->Branch("mag2", &mag2, "mag2/D");
1128  finaltree->Branch("t_coeff_pokey", &t_coeff_pokey, "t_coeff_pokey/D");
1129  finaltree->Branch("t_coeff_slappy", &t_coeff_slappy, "t_coeff_slappy/D");
1130  finaltree->Branch("exponent", &settings1->EXPONENT, "EXPONENT/D");
1131 
1132  finaltree->Branch("hitangle_e_all", &hitangle_e_all, "hitangle_e_all[48]/D");
1133  finaltree->Branch("hitangle_h_all", &hitangle_h_all, "hitangle_h_all[48]/D");
1134 
1135  finaltree->Branch("e_comp_max1", &e_comp_max1, "e_comp_max1/D");
1136  finaltree->Branch("h_comp_max1", &h_comp_max1, "h_comp_max1/D");
1137  finaltree->Branch("e_comp_max2", &e_comp_max2, "e_comp_max2/D");
1138  finaltree->Branch("h_comp_max2", &h_comp_max2, "h_comp_max2/D");
1139  finaltree->Branch("e_comp_max3", &e_comp_max3, "e_comp_max3/D");
1140  finaltree->Branch("h_comp_max3", &h_comp_max3, "h_comp_max3/D");
1141  finaltree->Branch("max_antenna_volts0", &max_antenna_volts0, "max_antenna_volts0/D");
1142  finaltree->Branch("max_antenna_volts0_em", &max_antenna_volts0_em, "max_antenna_volts0_em/D");
1143  finaltree->Branch("max_antenna_volts1", &max_antenna_volts1, "max_antenna_volts1/D");
1144  finaltree->Branch("max_antenna_volts2", &max_antenna_volts2, "max_antenna_volts2/D");
1145  finaltree->Branch("triggers", &nchannels_perrx_triggered, "nchannels_perrx_triggered[48]/I");
1146  finaltree->Branch("nchannels_triggered", &nchannels_triggered, "nchannels_triggered/I");
1147  finaltree->Branch("volts_rx_max", &volts_rx_max, "volts_rx_max/D");
1148  finaltree->Branch("volts_rx_ave", &volts_rx_ave, "volts_rx_ave/D");
1149  finaltree->Branch("volts_rx_sum", &volts_rx_sum, "volts_rx_sum/D");
1150 
1151  finaltree->Branch("volts_rx_max_highband", &volts_rx_max_highband, "volts_rx_max_highband/D");
1152  finaltree->Branch("volts_rx_max_lowband", &volts_rx_max_lowband, "volts_rx_max_lowband/D");
1153  finaltree->Branch("theta_pol_measured", &theta_pol_measured, "theta_pol_measured/D");
1154  finaltree->Branch("theta_rf_atbn", &theta_rf_atbn, "theta_rf_atbn/D");
1155  finaltree->Branch("theta_rf_atbn_measured", &theta_rf_atbn_measured, "theta_rf_atbn_measured/D");
1156  finaltree->Branch("theta_nnu_atbn",&theta_nnu_atbn,"theta_nnu_atbn/D");
1157  finaltree->Branch("theta_nnu_rf_diff_atbn",&theta_nnu_rf_diff_atbn,"theta_nnu_rf_diff_atbn/D");
1158  finaltree->Branch("phi_nnu_atbn",&phi_nnu_atbn,"phi_nnu_atbn/D");
1159  finaltree->Branch("phi_rf_atbn",&phi_rf_atbn,"phi_rf_atbn/D");
1160  finaltree->Branch("phi_nnu_rf_diff_atbn",&phi_nnu_rf_diff_atbn,"phi_nnu_rf_diff_atbn/D");
1161  finaltree->Branch("voltage", &voltagearray, "voltagearray[48]/D");
1162  finaltree->Branch("nlayers", &settings1->NLAYERS, "settings1->NLAYERS/I");
1163 
1164  finaltree->Branch("vmmhz1m_max", &vmmhz1m_max, "vmmhz1m_max/D");
1165  finaltree->Branch("vmmhz_lowfreq", &vmmhz_lowfreq, "vmmhz_lowfreq/D");
1166 
1167  finaltree->Branch("deltheta_em_max", &deltheta_em_max, "deltheta_em_max/D");
1168  finaltree->Branch("deltheta_had_max", &deltheta_had_max, "deltheta_had_max/D");
1169  finaltree->Branch("r_enterice", &r_enterice_array, "r_enterice_array[3]/D");
1170  finaltree->Branch("n_exit2bn_db", &n_exit2bn_db_array, "n_exit2bn_db_array[5][3]/D");
1171 
1172  finaltree->Branch("rfexit_db", &rfexit_db_array, "rfexit_db_array[5][3]/D");
1173  finaltree->Branch("r_in", &r_in_array, "r_in_array[3]/D");
1174  finaltree->Branch("nsurf_rfexit", &nsurf_rfexit_array, "nsurf_rfexit_array[3]/D");
1175  finaltree->Branch("nsurf_rfexit_db", &nsurf_rfexit_db_array, "nsurf_rfexit_db_array[3]/D");
1176  finaltree->Branch("r_fromballoon", &r_fromballoon2, "r_fromballoon/D");
1177  finaltree->Branch("r_fromballoon_db", &interaction1->r_fromballoon_db, "r_fromballoon_db/D");
1178 
1179  finaltree->Branch("nuexitlength", &nuexitlength, "nuexitlength/D");
1180  finaltree->Branch("nuentrancelength", &nuentrancelength, "nuentrancelength/D");
1181  finaltree->Branch("taulength", &taulength, "taulength/D");
1182  finaltree->Branch("icethickness", &icethickness, "icethickness/D");
1183  finaltree->Branch("nrf_iceside", &nrf_iceside_array, "nrf_iceside_array[5][3]/D");
1184  finaltree->Branch("nrf_iceside_db", &nrf_iceside_db_array, "nrf_iceside_db_array[5][3]/D");
1185  finaltree->Branch("ant_normal0", &ant_max_normal0_array, "ant_max_normal0_array[3]/D");
1186  finaltree->Branch("ant_normal1", &ant_max_normal1_array, "ant_max_normal1_array[3]/D");
1187  finaltree->Branch("ant_normal2", &ant_max_normal2_array, "ant_max_normal2_array[3]/D");
1188  finaltree->Branch("vmmhz1m_visible", &vmmhz1m_visible, "vmmhz1m_visible/D");
1189  finaltree->Branch("freq_bins", &freq_bins, "freq_bins/I");
1190  finaltree->Branch("vmmhz", &vmmhz, "vmmhz[freq_bins]/D");
1191 
1192  finaltree->Branch("dist_int_bn_2d_chord", &dist_int_bn_2d_chord, "dist_int_bn_2d_chord/D");
1193 
1194  finaltree->Branch("dviewangle_deg", &dviewangle_deg, "dviewangle_deg/D");
1195  finaltree->Branch("theta_threshold_deg", &theta_threshold_deg, "theta_threshold_deg/D");
1196  finaltree->Branch("total_kgm2", &total_kgm2, "total_kgm2/D");
1197  finaltree->Branch("chord", &interaction1->chord, "chord/D");
1198  finaltree->Branch("crust_entered", &crust_entered, "crust_entered/I");
1199  finaltree->Branch("mantle_entered", &mantle_entered, "mantle_entered/I");
1200  finaltree->Branch("core_entered", &core_entered, "core_entered/I");
1201  finaltree->Branch("n_pol", &n_pol_array, "n_pol_array[3]/D");
1202  finaltree->Branch("vmmhz_min_thatpasses", &vmmhz_min_thatpasses, "vmmhz_min_thatpasses/D");
1203 
1204  finaltree->Branch("pieceofkm2sr", &pieceofkm2sr, "pieceofkm2sr/D");
1205  //finaltree->Branch("volts_original", &volts_original, "volts_original[10][20][2]/D");
1206  finaltree->Branch("r_exit2bn", &r_exit2bn2, "r_exit2bn/D");
1207  finaltree->Branch("r_exit2bn_measured", &r_exit2bn_measured2, "r_exit2bn_measured/D");
1208  finaltree->Branch("scalefactor_attenuation", &scalefactor_attenuation, "scalefactor_attenuation/D");
1209  finaltree->Branch("anita1->PHI_OFFSET", &anita1->PHI_OFFSET, "anita1->PHI_OFFSET/D");
1210  finaltree->Branch("igps", &bn1->igps, "igyps/I");
1211  finaltree->Branch("volts_rx_rfcm_lab_e_all", &volts_rx_rfcm_lab_e_all, "volts_rx_rfcm_lab_e_all[48][512]/D");
1212  finaltree->Branch("volts_rx_rfcm_lab_h_all", &volts_rx_rfcm_lab_h_all, "volts_rx_rfcm_lab_h_all[48][512]/D");
1213  finaltree->Branch("ptaui", &ptaui, "ptaui/D");
1214  finaltree->Branch("ptauf", &ptauf, "ptauf/D");
1215  finaltree->Branch("sourceLon", &sourceLon, "sourceLon/D");
1216  finaltree->Branch("sourceLat", &sourceLat, "sourceLat/D");
1217  finaltree->Branch("sourceAlt", &sourceAlt, "sourceAlt/D");
1218  finaltree->Branch("sourceMag", &sourceMag, "sourceMag/D");
1219  //finaltree->Branch("payloadTheta", &payloadTheta, "payloadTheta/D");
1220  //finaltree->Branch("payloadPhi", &payloadPhi, "payloadPhi/D");
1221 
1222  TTree *mytaus_tree = new TTree("mytaus", "mytaus");
1223  mytaus_tree->Branch("taus", &TauPtr);
1224 
1225 
1226 
1227  double rms_rfcm_e;
1228  double rms_rfcm_h;
1229  double rms_lab_e;
1230  double rms_lab_h;
1231 
1232  double avgfreq_rfcm[Anita::NFREQ];
1233  double avgfreq_rfcm_lab[Anita::NFREQ];
1234  double freq[Anita::NFREQ];
1235 
1236  TTree *summarytree = new TTree("summarytree", "summarytree"); // finaltree filled for all events that pass
1237  summarytree->Branch("NNU", &NNU, "NNU/I");
1238  summarytree->Branch("EXPONENT", &settings1->EXPONENT, "EXPONENT/D");
1239  summarytree->Branch("eventsfound_beforetrigger", &eventsfound_beforetrigger, "eventsfound_beforetrigger/D");
1240  summarytree->Branch("rms_rfcm_e", &rms_rfcm_e, "rms_rfcm_e/D");
1241  summarytree->Branch("rms_rfcm_h", &rms_rfcm_h, "rms_rfcm_h/D");
1242  summarytree->Branch("rms_lab_e", &rms_lab_e, "rms_lab_e/D");
1243  summarytree->Branch("rms_lab_h", &rms_lab_h, "rms_lab_h/D");
1244  summarytree->Branch("avgfreq_rfcm", &avgfreq_rfcm, "avgfreq_rfcm[128]/D");
1245  summarytree->Branch("avgfreq_rfcm_lab", &avgfreq_rfcm_lab, "avgfreq_rfcm_lab[128]/D");
1246  summarytree->Branch("freq", &freq, "freq[128]/D");
1247 
1248  TTree *banana_tree = new TTree("banana_tree", "banana_tree"); //To record banana plot info - Stephen
1249  banana_tree->Branch("r_bn", &bn1->r_bn, "r_bn[3]/D");
1250 
1251  TTree *ytree = new TTree("ytree", "ytree"); //To record y distributions
1252  ytree->Branch("elast_y", &elast_y, "elast_y/D");
1253 
1254  double icethck;
1255  double elev;
1256  double lon_ground;
1257  double lat_ground;
1258  double lon_ice;
1259  double lat_ice;
1260  double h20_depth;
1261  double lon_water;
1262  double lat_water;
1263 
1264  TTree *icetree = new TTree("icetree", "icetree");
1265  icetree->Branch("icethck", &icethck, "icethck/D");
1266  icetree->Branch("lon_ice", &lon_ice, "lon_ice/D");
1267  icetree->Branch("lat_ice", &lat_ice, "lat_ice/D");
1268  icetree->Branch("lon_water", &lon_water, "lon_water/D");
1269  icetree->Branch("lat_water", &lat_water, "lat_water/D");
1270  icetree->Branch("h20_depth", &h20_depth, "h20_depth/D");
1271 
1272  TTree *groundtree = new TTree("groundtree", "groundtree");
1273  groundtree->Branch("elev", &elev, "elev/D");
1274  groundtree->Branch("lon_ground", &lon_ground, "lon_ground/D");
1275  groundtree->Branch("lat_ground", &lat_ground, "lat_ground/D");
1276 
1277  //End block added by Stephen
1278 
1279  TTree *tree11 = new TTree("h11000", "h11000"); // tree11
1280  tree11->Branch("loctrig00", &loctrig[0][0], "loctrig0/D");
1281  tree11->Branch("loctrig10", &loctrig[1][0], "loctrig0/D");
1282  tree11->Branch("loctrig20", &loctrig[2][0], "loctrig0/D");
1283  tree11->Branch("loctrig_nadironly0", &loctrig_nadironly[0], "loctrig_nadironly0/D");
1284  tree11->Branch("loctrig01", &loctrig[0][1], "loctrig1/D");
1285  tree11->Branch("loctrig11", &loctrig[1][1], "loctrig1/D");
1286  tree11->Branch("loctrig21", &loctrig[2][1], "loctrig1/D");
1287  tree11->Branch("loctrig_nadironly1", &loctrig_nadironly[1], "loctrig0/D");
1288 
1289  TTree *tree16 = new TTree("h16000", "h16000");
1290  tree16->Branch("pnu", &pnu, "pnu/D");
1291  tree16->Branch("ptau", &ptau, "ptau/D");
1292  tree16->Branch("taulength", &taulength, "taulength/D");
1293  tree16->Branch("weight1", &weight1, "weight1/D");
1294  tree16->Branch("emfrac", &emfrac, "emfrac/D");
1295  tree16->Branch("hadfrac", &hadfrac, "hadfrac/D");
1296  tree16->Branch("nuentrancelength", &nuentrancelength, "nuentrancelength/D");
1297 
1298  int pdgcode;
1299 
1300  TTree *tree18 = new TTree("h18000", "h18000");
1301  tree18->Branch("emfrac", &emfrac, "emfrac/D");
1302  tree18->Branch("hadfrac", &hadfrac, "hadfrac/D");
1303  tree18->Branch("pdgcode", &pdgcode, "pdgcode/I");
1304 
1305 
1306  TH1D *h1mybeta = new TH1D("betaforall", "betaforall(deg)", 180, -15, 15);
1307  TH1D *h1mytheta= new TH1D("mytheta", "mytheta(deg)", 180, -90, 90);//90-incidentangle when neutrinos enter the Earth.
1308  TH1F *hundogaintoheight_e=new TH1F("undogaintoheight_e", "undogaintoheight_e", 100, 0., 1.);
1309  TH1F *hundogaintoheight_h=new TH1F("undogaintoheight_h", "undogaintoheight_h", 100, 0., 1.);
1310  TH1F *rec_diff=new TH1F("rec_diff", "rec_diff", 100, -1., 1.);
1311  TH1F *recsum_diff=new TH1F("recsum_diff", "recsum_diff", 100, -1., 1.);
1312  TH1F *rec_diff0=new TH1F("rec_diff0", "rec_diff0", 100, -1., 1.);
1313  TH1F *rec_diff1=new TH1F("rec_diff1", "rec_diff1", 100, -1., 1.);
1314  TH1F *rec_diff2=new TH1F("rec_diff2", "rec_diff2", 100, -1., 1.);
1315  TH1F *rec_diff3=new TH1F("rec_diff3", "rec_diff3", 100, -1., 1.);
1316 
1317  TTree *vmmhz_tree = new TTree("vmmhz_tree", "vmmhz_tree"); //To record frequency spread at point where it is first filled
1318  vmmhz_tree->Branch("freq_bins", &freq_bins, "freq_bins/I");
1319  vmmhz_tree->Branch("vmmhz", &vmmhz, "vmmhz[freq_bins]/D");
1320 
1321  TTree *tree1 = new TTree("h1000", "h1000"); // tree1 filled for each neutrino
1322  tree1->Branch("inu", &inu, "inu/I");
1323  tree1->Branch("diffexit", &diffexit, "diffexit/D");
1324  tree1->Branch("diffrefr", &diffrefr, "diffrefr/D");
1325  tree1->Branch("horizcoord", &horizcoord, "horizcoord/D");
1326  tree1->Branch("vertcoord", &vertcoord, "vertcoord/D");
1327  tree1->Branch("costhetanu", &costhetanu, "costhetanu/D");
1328  tree1->Branch("vmmhz1m_max", &vmmhz1m_max, "vmmhz1m_max/D");
1329  tree1->Branch("volume_thishorizon", &volume_thishorizon, "volume_thishorizon/D");
1330  tree1->Branch("realtime", &realtime_this, "realtime/D");
1331  tree1->Branch("longitude", &longitude_this, "longitude/D");
1332  tree1->Branch("latitude", &latitude_this, "latitude/D");
1333  tree1->Branch("MAXHORIZON", &bn1->MAXHORIZON, "MAXHORIZON/D");
1334  tree1->Branch("igps", &bn1->igps, "igps/I");
1335  tree1->Branch("passes_thisevent", &passes_thisevent, "passes_thisevent/I");
1336  tree1->Branch("igps", &bn1->igps, "igps/I");
1337  tree1->Branch("weight", &weight, "weight/D");
1338  tree1->Branch("r_exit2bn", &interaction1->r_exit2bn, "r_exit2bn/D");
1339  tree1->Branch("bn1->igps", &bn1->igps, "bn1->igps/I");
1340 
1341  // set up balloontree
1342 
1343  TTree *balloontree = new TTree("balloon", "balloon"); //filled for all events
1344  balloontree->Branch("heading", &bn1->heading, "heading/D");
1345  balloontree->Branch("pitch", &bn1->pitch, "pitch/D");
1346  balloontree->Branch("roll", &bn1->roll, "roll/D");
1347  balloontree->Branch("realTime_flightdata", &bn1->realTime_flightdata, "realTime_flightdata/I");
1348  balloontree->Branch("latitude", &bn1->latitude, "latitude/D");
1349  balloontree->Branch("longitude", &bn1->longitude, "longitude/D");
1350  balloontree->Branch("altitude", &bn1->altitude, "altitude/D");
1351  balloontree->Branch("horizcoord_bn", &bn1->horizcoord_bn, "horizcoord_bn/D");
1352  balloontree->Branch("vertcoord_bn", &bn1->vertcoord_bn, "vertcoord_bn/D");
1353 
1354  // these variables are for energy reconstruction studies
1355  double undogaintoheight_e=0;
1356  double undogaintoheight_h=0;
1357 
1358  double undogaintoheight_e_array[4];
1359  double undogaintoheight_h_array[4];
1360 
1361  double nbins_array[4];
1362 
1363  double rec_efield=0;
1364  double true_efield=0;
1365 
1366  double rec_efield_array[4];
1367  double true_efield_array[4];
1368  // end energy reconstruction variables
1369 
1370  //ofstream oindree_file;
1371  //oindree_file.open("oindree_file_taper.txt",std::ios_base::app);
1372 
1373  IceModel *antarctica = new IceModel(settings1->ICE_MODEL + settings1->NOFZ*10, settings1->CONSTANTICETHICKNESS * 1000 + settings1->CONSTANTCRUST * 100 + settings1->FIXEDELEVATION * 10 + 0, settings1->WEIGHTABSORPTION);
1374  cout << "area of the earth's surface covered by antarctic ice is " << antarctica->ice_area << "\n";
1375 
1376  ULong_t eventNumber;
1377 #ifdef ANITA_UTIL_EXISTS
1378 
1379  string outputAnitaFile =string(outputdir.Data())+"/SimulatedAnitaEventFile"+run_num+".root";
1380  TFile *anitafileEvent = new TFile(outputAnitaFile.c_str(), "RECREATE");
1381 
1382  TTree *eventTree = new TTree("eventTree", "eventTree");
1383  eventTree->Branch("event", &realEvPtr );
1384  eventTree->Branch("run", &run_no, "run/I" );
1385  eventTree->Branch("weight", &weight, "weight/D");
1386 
1387  outputAnitaFile =string(outputdir.Data())+"/SimulatedAnitaHeadFile"+run_num+".root";
1388  TFile *anitafileHead = new TFile(outputAnitaFile.c_str(), "RECREATE");
1389 
1390  TTree *headTree = new TTree("headTree", "headTree");
1391  headTree->Branch("header", &rawHeaderPtr );
1392  headTree->Branch("weight", &weight, "weight/D");
1393 
1394  outputAnitaFile =string(outputdir.Data())+"/SimulatedAnitaGpsFile"+run_num+".root";
1395  TFile *anitafileGps = new TFile(outputAnitaFile.c_str(), "RECREATE");
1396 
1397  TTree *adu5PatTree = new TTree("adu5PatTree", "adu5PatTree");
1398  adu5PatTree->Branch("pat", &Adu5PatPtr );
1399  adu5PatTree->Branch("eventNumber", &eventNumber, "eventNumber/L");
1400  adu5PatTree->Branch("weight", &weight, "weight/D" );
1401 
1402 #ifdef ANITA3_EVENTREADER
1403 
1404  // Set AnitaVersion so that the right payload geometry is used
1405  AnitaVersion::set(settings1->ANITAVERSION);
1406 
1407  outputAnitaFile =string(outputdir.Data())+"/SimulatedAnitaTruthFile"+run_num+".root";
1408  TFile *anitafileTruth = new TFile(outputAnitaFile.c_str(), "RECREATE");
1409 
1410 
1411  TString icemcgitversion( EnvironmentVariable::ICEMC_VERSION(outputdir));
1412  printf("ICEMC GIT Repository Version: %s\n", icemcgitversion.Data());
1413  unsigned int timenow = time(NULL);
1414 
1415  TTree *configAnitaTree = new TTree("configIcemcTree", "Config file and settings information");
1416  configAnitaTree->Branch("gitversion", &icemcgitversion );
1417  configAnitaTree->Branch("nnu", &NNU );
1418  configAnitaTree->Branch("startTime", &timenow );
1419  // configAnitaTree->Branch("icemcSettings", &settings1 );
1420  configAnitaTree->Fill();
1421 
1422  TTree *triggerSettingsTree = new TTree("triggerSettingsTree", "Trigger settings");
1423  triggerSettingsTree->Branch("dioderms", anita1->bwslice_dioderms_fullband_allchan, "dioderms[2][48][7]/D" );
1424  triggerSettingsTree->Branch("diodemean", anita1->bwslice_diodemean_fullband_allchan, "diodemean[2][48][7]/D");
1425  triggerSettingsTree->Fill();
1426 
1427 
1428  TTree *summaryAnitaTree = new TTree("summaryAnitaTree", "summaryAnitaTree"); // finaltree filled for all events that pass
1429  summaryAnitaTree->Branch("EXPONENT", &settings1->EXPONENT, "EXPONENT/D" );
1430  summaryAnitaTree->Branch("SELECTION_MODE", &settings1->UNBIASED_SELECTION, "SELECTION_MODE/I" );
1431  summaryAnitaTree->Branch("totalnu_per_source", &NNU_per_source);
1432  summaryAnitaTree->Branch("weighted_nu_per_source", &eventsfound_per_source);
1433  summaryAnitaTree->Branch("weighted_prob_nu_per_source", &eventsfound_prob_per_source);
1434  summaryAnitaTree->Branch("total_nu", &NNU, "total_nu/I" );
1435  summaryAnitaTree->Branch("total_nue", &count1->nnu_e, "total_nue/I" );
1436  summaryAnitaTree->Branch("total_numu", &count1->nnu_mu, "total_numu/I" );
1437  summaryAnitaTree->Branch("total_nutau", &count1->nnu_tau, "total_nutau/I" );
1438  summaryAnitaTree->Branch("pass_nu", &count1->npass[0], "pass_nu/I" );
1439 
1440 
1441  summaryAnitaTree->Branch("weighted_nu", &eventsfound, "weighted_nu/D" );
1442  summaryAnitaTree->Branch("weighted_nue", &sum[0], "weighted_nue/D" );
1443  summaryAnitaTree->Branch("weighted_numu", &sum[1], "weighted_numu/D" );
1444  summaryAnitaTree->Branch("weighted_nutau", &sum[2], "weighted_nutau/D" );
1445 
1446  summaryAnitaTree->Branch("weighted_prob_nu", &eventsfound_prob, "weighted_prob_nu/D" );
1447  summaryAnitaTree->Branch("weighted_prob_nue", &sum_prob[0], "weighted_prob_nue/D" );
1448  summaryAnitaTree->Branch("weighted_prob_numu", &sum_prob[1], "weighted_prob_numu/D" );
1449  summaryAnitaTree->Branch("weighted_prob_nutau", &sum_prob[2], "weighted_prob_nutau/D" );
1450 
1451 
1452  summaryAnitaTree->Branch("int_length", &len_int_kgm2, "int_length/D");
1453  summaryAnitaTree->Branch("total_volume", &antarctica->volume, "total_volume/D");
1454  summaryAnitaTree->Branch("rho_medium", &sig1->RHOMEDIUM, "rho_medium/D");
1455  summaryAnitaTree->Branch("selection_box_half_length", &settings1->UNBIASED_PS_MAX_DISTANCE_KM, "selection_box_half_length/D");
1456  // summaryAnitaTree->Branch("rho_h20", &(sig1->RHOH20), "rho_water/D");
1457 
1458  summaryAnitaTree->Branch("effVol_nu", &km3sr, "effVol_nu/D" );
1459 // summaryAnitaTree->Branch("effArea_nu", &km2sr, "effArea_nu/D");
1460 
1461  TTree *truthAnitaTree = new TTree("truthAnitaTree", "Truth Anita Tree");
1462  truthAnitaTree->Branch("truth", &truthEvPtr );
1463 
1464  TruthAnitaNeutrino * truthNuPtr = settings1->SAVE_TRUTH_NU_TREE ? new TruthAnitaNeutrino : 0;
1465  TTree* truthAnitaNuTree = settings1->SAVE_TRUTH_NU_TREE ? new TTree("truthAnitaNuTree","Truth ANITA Neutrino Tree (all nus)") : 0;
1466  if (settings1->SAVE_TRUTH_NU_TREE)
1467  {
1468  truthAnitaNuTree->SetAutoFlush(10000);
1469  truthAnitaNuTree->Branch("truth_neutrino", &truthNuPtr );
1470  }
1471 
1472 #endif
1473 
1474  AnitaGeomTool *AnitaGeom1 = AnitaGeomTool::Instance();
1475 
1476 #endif
1477  //end ROOT variable definitions
1479 
1480 #ifdef ANITA3_EVENTCORRELATOR
1481  const int skyMapLat = 90;
1482  TMarker *astroObject = new TMarker();
1483  SkyMap *skyMapOut = new SkyMap(skyMapLat);
1484 #endif
1485 
1486  if (bn1->WHICHPATH==3) {
1487  settings1->CONSTANTCRUST = 1; //Set ice depths and elevations all the same
1488  settings1->CONSTANTICETHICKNESS = 1;
1489  settings1->FIXEDELEVATION = 1;
1490  }
1491 
1492 
1493  for (int i=0;i<antarctica->nRows_ice;i++) {
1494  for (int j=0;j<antarctica->nCols_ice;j++) {
1495  antarctica->IceENtoLonLat(j, i, lon_ice, lat_ice);
1496  icethck=antarctica->IceThickness(lon_ice, lat_ice);
1497  lon_water=lon_ice; //redundant?
1498  lat_water=lat_ice;
1499  h20_depth=antarctica->h_water_depth.GetBinContent(j+1,i+1);
1500  if (settings1->HIST) icetree->Fill();
1501  }
1502  }
1503  for (int i=0;i<antarctica->nRows_ground;i++) {
1504  for (int j=0;j<antarctica->nCols_ground;j++) {
1505  antarctica->GroundENtoLonLat(j, i, lon_ground, lat_ground);
1506  elev=antarctica->SurfaceAboveGeoid(lon_ground, lat_ground);
1507  if (settings1->HIST) groundtree->Fill();
1508  }
1509  }
1510 
1511  // fills arrays according to antenna specs
1512  anita1->GetBeamWidths(settings1); // this is used if GAINS set to 0
1513  // Antenna measured gain vs. frequency
1514  anita1->ReadGains(); // this is used if GAINS set to 1
1515  anita1->Set_gain_angle(settings1, sig1->NMEDIUM_RECEIVER);
1516  if(settings1->WHICH == 2 || settings1->WHICH == 6) anita1->SetDiffraction(); // for the upper ring
1517 
1518  TCanvas *cgains=new TCanvas("cgains", "cgains", 880, 800);
1519  TGraph *ggains=new TGraph(anita1->NPOINTS_GAIN, anita1->frequency_forgain_measured, anita1->vvGaintoHeight);
1520  ggains->Draw("al");
1521  stemp=string(outputdir.Data())+"/gains.eps";
1522  cgains->Print((TString)stemp);
1523 
1524  // sets position of balloon and related quantities
1525  // these are all passed as pointers
1526  // theta, phi, altitude of balloon
1527  // position of balloon, altitude and position of surface of earth (relative to the center of the earth) under balloon
1528  bn1->SetDefaultBalloonPosition(antarctica);
1529 
1530  anita1->SetNoise(settings1, bn1, antarctica);
1531  //pathtree->Fill(); //Added by Stephen for verification of path
1532 
1533  // find the maximum distance the interaction could be from the balloon and still be within the horizon.
1534  antarctica->GetMAXHORIZON(bn1);
1535 
1536  // calculate the volume of ice seen by the balloon for all balloon positions
1537  antarctica->CreateHorizons(settings1, bn1, bn1->theta_bn, bn1->phi_bn, bn1->altitude_bn, foutput);
1538  cout << "Done with CreateHorizons.\n";
1539 
1540  // sets neutrino energy
1541  if (! src_model && spectra1->IsMonoenergetic() ){
1542  pnu=pow(10., settings1->EXPONENT);
1543  primary1->GetSigma(pnu, sigma, len_int_kgm2, settings1, xsecParam_nutype, xsecParam_nuint); // get cross section and interaction length.
1544  cout << "pnu, sigma and len_int_kgm2 (for nu CC) are " << pnu << " " << sigma << " " << len_int_kgm2 << "\n";
1545  }
1546 
1547  if (settings1->WRITEPOSFILE==1) {
1548  nu_out << "Neutrinos with energy " << pnu << "\n\n"; //Write header to file of neutrino positions
1549  nu_out << "nu #, position of nu interaction, depth of int., Direction of nu momentum, Position of balloon, nu flavour, current type, elasticity\n\n\n\n";
1550  }
1551 
1552  if (bn1->WHICHPATH==3) { //Force certain parameters if we're doing a banana plot
1553  NNU = settings1->horizontal_banana_points*settings1->vertical_banana_points; //Total number of points to look at
1554  anita1->maxthreshold = Interaction::banana_sigma;
1555  settings1->SIGNAL_FLUCT = Interaction::banana_signal_fluct;
1556  settings1->CONSTANTCRUST=1; //Set ice depths and elevations all the same
1557  settings1->CONSTANTICETHICKNESS=1;
1558  settings1->FIXEDELEVATION=1;
1559  pnu=Interaction::pnu_banana;
1560  int_banana->surface_over_banana_nu=antarctica->Surface(int_banana->nu_banana);
1561  int_banana->nu_banana_surface=(int_banana->surface_over_banana_nu) * (int_banana->nu_banana);
1562  } //Done setting parameters for banana plot
1563 
1564  cout << "reminder that I took out ChangeCoord.\n";
1565 
1566  // builds payload based on read inputs
1567  anita1->GetPayload(settings1, bn1);
1568 
1569  if (settings1->TRIGGERSCHEME == 3 || settings1->TRIGGERSCHEME == 4 || settings1->TRIGGERSCHEME==5) {
1570  Vector plusz(0., 0., 1.);
1571  bn1->PickBalloonPosition(plusz, antarctica, settings1, anita1);
1572  anita1->calculate_all_offsets();
1573  double angle_theta=16.;
1574  double angle_phi=0.;
1575  Vector x = Vector(cos(angle_theta * RADDEG) * cos((angle_phi+11.25) * RADDEG),
1576  cos(angle_theta * RADDEG) * sin((angle_phi+11.25) * RADDEG),
1577  sin(angle_theta * RADDEG));
1578  anita1->GetArrivalTimes(x,bn1,settings1);
1579  cout << "end of getarrivaltimes\n";
1580  }
1581 
1582  // get positions of the anita payload during the slac test
1583  if (settings1->SLAC)
1584  bn1->GetSlacPositions(anita1);
1585 
1586  switch (settings1->WHICHRAYS){
1587  case 1:
1588  settings1->MINRAY=0;
1589  settings1->MAXRAY=0;
1590  break;
1591  case 2:
1592  settings1->MINRAY=0;
1593  settings1->MAXRAY=1;
1594  break;
1595  case 3:
1596  settings1->MINRAY=1;
1597  settings1->MAXRAY=1;
1598  break;
1599  }
1600 
1601 
1602  time_t raw_loop_start_time = time(NULL);
1603  cout<<"Starting loop over events. Time required for setup is "<<(int)((raw_loop_start_time - raw_start_time)/60)<<":"<< ((raw_loop_start_time - raw_start_time)%60)<<endl;
1604 
1605  //CD TODO: Do something analogous for sources
1606  TCanvas *ctest1 = new TCanvas("ctest1", "", 880, 800);
1607 
1608  // Surely we only want this if there's a spectrum...
1609  if ( spectra1->IsSpectrum() ){
1610  spectra1->GetGEdNdEdAdt()->Draw("al");
1611  spectra1->GetGEdNdEdAdt()->GetHistogram()->SetMinimum(-0.2*spectra1->Getmaxflux());
1612  spectra1->GetSEdNdEdAdt()->SetLineColor(2);
1613  spectra1->GetSEdNdEdAdt()->Draw("l same");
1614 
1615  stemp=string(outputdir.Data())+"/GetG_test1.pdf";
1616  ctest1->Print((TString)stemp);
1617  }
1618 
1619  // for averaging balloon altitude and distance from center of earth
1620  // for comparing with Peter
1621  double average_altitude=0.;
1622  double average_rbn=0.;
1623 
1624  //if using energy spectrum
1625  if ( spectra1->IsSpectrum() ){
1626  TCanvas *ctemp = new TCanvas("ctemp");
1627 
1628  TFile *out = new TFile("Temp.root", "recreate");
1629  TGraph *g1 = spectra1->GetGEdNdEdAdt();
1630  g1->Draw("Al");
1631  ctemp->Print("Temp1.png");
1632  int n = g1->GetN();
1633  double *x = g1->GetX();
1634  double x2[20];
1635  for (int i=0;i<n;i++) x2[i] = TMath::Power(10., x[i]);
1636  TGraph *g2 = new TGraph(n, x2, g1->GetY());
1637  g2->Draw("Al");
1638  ctemp->SetLogy();
1639  ctemp->SetLogx();
1640  cout << g2->Integral() << " " << g2->Integral(1, n) << endl;
1641  ctemp->Print("Temp2.png");
1642  g1->Write();
1643  g2->Write();
1644  out->Close();
1645  }
1646 
1647 
1648  signal(SIGINT, interrupt_signal_handler); // This function call allows icemc to gracefully abort and write files as usual rather than stopping abruptly.
1649 
1650  TString objName = "noObject";
1651 
1652  // Setting gps offset for plotting direction wrt north
1653  if (settings1->WHICH==7){
1654  gps_offset=atan2(-0.7042,0.71)*DEGRAD;
1655  } else if(settings1->WHICH==8){
1656  gps_offset=atan2(-0.7085,0.7056)*DEGRAD;
1657  } else if (settings1->WHICH==9 || settings1->WHICH==10){
1658  gps_offset=45;
1659  } else gps_offset=0;
1660 
1661  int antNum;
1662 
1663  // begin looping over NNU neutrinos doing the things
1664  for (inu = startNu; inu < NNU; inu++) {
1665 
1666  if (NNU >= 100) {
1667  if (inu % (NNU / 100) == 0)
1668  cout << inu << " neutrinos. " << (double(inu)/double(NNU)) * 100 << "% complete.\n";
1669  }
1670  else
1671  cout << inu << " neutrinos. " << (double(inu) / double(NNU)) * 100 << "% complete.\n";
1672 
1673  eventNumber=(ULong_t)(run_no)*NNU+inu;
1674 //cerr<<inu<<endl;
1675 //if( !((inu==246) || (inu==2579) || (inu==5522) || (inu==11235) || (inu==11815) || (inu==19723) || (inu==21264) || (inu==28442) || (inu==36789) || (inu==36894) || (inu==38424) || (inu==45829) || (inu==45880) || (inu==52929) || (inu==56821) || (inu==64933) || (inu==73569) || (inu==73707) || (inu==78717) || (inu==92717) || (inu==99750)) ) continue;
1676 //
1677  // Set seed of all random number generators to be dependent on eventNumber
1678  setSeed(eventNumber);
1679 
1680  //reset screen parameters (even for no roughness) for the new event
1681  panel1->ResetParameters();
1682  anita1->inu=inu;
1683 
1684  std::string nunum = Form("%d",inu);
1685 
1686  double time_weight = 1; //this is the sum of all source time weights for the time
1687  double src_time_weight = 1; //this is the time weight for the selected source
1688 
1689  for (whichray = settings1->MINRAY; whichray <= settings1->MAXRAY; whichray++) {
1690  anita1->passglobtrig[0]=0;
1691  anita1->passglobtrig[1]=0;
1692  passes_thisevent=0;
1693  unmasked_thisevent=1;
1694  vmmhz_min_thatpasses=1000; // initializing. want to find the minumum voltage that passes a
1695 
1696 
1697  Vector force_dir;
1698  double RA = 0;
1699  double dec = 0;
1700  int which_source = -1;
1701  if (!src_model && spectra1->IsSpectrum() ){//if using energy spectrum
1702 
1703  if(settings1->USEDARTBOARD) pnu=spectra1->GetNuEnergy();
1704  else pnu=spectra1->GetCDFEnergy();
1705 
1706  } // end IsSpectrum
1707 
1708  ierr=primary1->GetSigma(pnu, sigma, len_int_kgm2, settings1, xsecParam_nutype, interaction1->currentint); // given neutrino momentum, cross section and interaction length of neutrino.
1709  // ierr=0 if the energy is too low for the parameterization
1710  // ierr=1 otherwise
1711  len_int=1.0/(sigma*sig1->RHOH20*(1./M_NUCL)*1000); // in km (interaction length is in water equivalent)
1712 
1713  n_interactions=1;
1714  count_pass=0;
1715  passestrigger=0;
1716  chanceinhell2=0;
1717  sec1->secondbang=false;
1718  count_total++;
1719  // initializing the voltage seen by each polarization of each antenna
1720  interaction1->dtryingdirection=0;
1721  bn1->dtryingposition=0;
1722  for (int i=0; i<Anita::NFREQ;i++) {
1723  vmmhz[i] = 0.; // the full signal with all factors accounted for (1/r, atten. etc.)
1724  vmmhz_em[i]=0.; // for keeping track of just the em component of the shower
1725  } //Zero the vmmhz array - helpful for banana plots, shouldn't affect anything else - Stephen
1726 
1727  int got_a_good_position = 0;
1728 
1729  do // loop for forcing a good position with sources if that option is enabled
1730  {
1731  // Picks the balloon position and at the same time sets the masks and thresholds
1732  bn1->PickBalloonPosition(antarctica, settings1, inu, anita1, getRNG(RNG_BALLOON_POSITION)->Rndm());
1733 
1734 
1735  // find average balloon altitude and distance from center of earth for
1736  // making comparisons with Peter
1737  average_altitude+=bn1->altitude_bn/(double)NNU;
1738  average_rbn+=bn1->r_bn.Mag()/(double)NNU;
1739 
1740  realtime_this=bn1->realTime_flightdata;
1741  longitude_this=bn1->longitude;
1742  latitude_this=bn1->latitude;
1743  altitude_this=bn1->altitude;
1744  heading_this=bn1->heading;
1745 
1746  if (src_model)
1747  {
1748  time_weight = src_model->getTimeWeight(realtime_this);
1749 
1750  which_source = time_weight > 0 ? src_model->getDirectionAndEnergy(&force_dir, realtime_this, pnu, src_min, src_max) : -1;
1751  if(which_source >= 0) {
1752  got_a_good_position = 1;
1753  src_time_weight = src_model->getPerSourceTimeWeight(realtime_this, which_source);
1754 
1755  if (NNU_per_source.size() < which_source+1)
1756  {
1757  NNU_per_source.resize(which_source+1);
1758  eventsfound_per_source.resize(which_source+1);
1759  eventsfound_prob_per_source.resize(which_source+1);
1760  }
1761 
1762  NNU_per_source[which_source]++;
1763 
1764  const Source * src = src_model->getSource(which_source);
1765  RA = src->getRA();
1766  dec= src->getDec()* TMath::RadToDeg(); // Get it make in deg
1767  objName = src->getName();
1768  pnu*=1e9; //GeV -> eV
1769  ierr=primary1->GetSigma(pnu, sigma, len_int_kgm2, settings1, xsecParam_nutype, interaction1->currentint); // given neutrino momentum, cross section and interaction length of neutrino.
1770  len_int=1.0/(sigma*sig1->RHOH20*(1./M_NUCL)*1000); // in km (why interaction length in water?) //EH
1771  }
1772 
1773 
1774  //std::cout << "pnu = " << pnu << std::endl;
1775  //std::cout << "RA = " << RA << std::endl;
1776  //std::cout << "dec = " << dec << std::endl;
1777  //std::cout << "objName = " << objName << std::endl;
1778  }
1779  else
1780  {
1781  got_a_good_position = 1;
1782 
1783  if (settings1->HORIZON_OFFSET > -999)
1784  {
1785  double horizon_angle = acos(bn1->r_bn_shadow.Mag()/bn1->r_bn.Mag());
1786  double alt = -horizon_angle + TMath::DegToRad() * settings1->HORIZON_OFFSET;
1787  double Az = 0; //for now always sough
1788  double lat = bn1->latitude*TMath::DegToRad();
1789  double sin_lat = sin(lat);
1790  double cos_lat = cos(lat);
1791  double sindec = sin_lat *sin(alt) - cos_lat*cos(alt) *cos(Az);
1792  double cosdec = sqrt(1-sindec*sindec);
1793  double h = atan2(sin(Az),-sin_lat*cos(Az) + cos_lat*tan(alt));
1794  force_dir = Vector(cos(h)*cosdec,sin(h)*cosdec,sindec);
1795  }
1796  }
1797 
1798  } while(!got_a_good_position && settings1->SOURCE_SKIP_WHEN_NONE) ;
1799 
1800  if (settings1->HIST && !settings1->ONLYFINAL
1801  && prob_eachphi_bn->GetEntries() < settings1->HIST_MAX_ENTRIES) {
1802  prob_eachphi_bn->Fill(bn1->phi_bn);
1803  prob_eachilon_bn->Fill(bn1->r_bn.Lon());
1804  balloontree->Fill();
1805  }
1806 
1807  if (bn1->WHICHPATH==3) { // for banana plot
1808  //Set observation location
1809  bn1->setObservationLocation(int_banana, inu, antarctica, settings1);
1810  } //End else if (WHICHPATH==3) : Banana plot locations
1811 
1812  // No sources were turned on, so we have no neutrino. So we should try again.
1813  if (!got_a_good_position)
1814  {
1815 #ifdef ANITA3_EVENTREADER
1816 
1817  if (truthNuPtr) truthNuPtr->setNoNu(bn1->r_bn.GetX(), bn1->r_bn.GetY(), bn1->r_bn.GetZ(), realtime_this);
1818 // truthAnitaNuTree->Fill();
1819 #endif
1820  continue;
1821  }
1822 
1823  // pick random point in ice.
1824  // also get initial guess shower exit position
1825  // unit vector from shower exit to balloon.
1826  // get both positions of interaction point and its mirror point.
1827  //-------------------------------------------------------
1828  beyondhorizon = 0;
1829 
1830 
1831  //Use placement new instead of deleting and recreating so that branch pointers don't go away
1832  interaction1 = new (interaction1) Interaction("nu", primary1, settings1, whichray, count1);
1833 
1834  if(taus1)
1835  delete taus1;
1836  taus1 = new Taumodel();
1837 
1838  int taumodes = settings1->taumodes;
1839  tauweighttrigger=0;
1840  interaction1->weight_nu=0;
1841  interaction1->weight_nu_prob=0;
1842  taus1->weight_tau_prob=0;
1843 
1844  if (taumodes==1 && interaction1->nuflavor=="nutau" && interaction1->current=="cc")
1845  tautrigger=1;
1846  else
1847  tautrigger=0;
1848 
1849  bn1->PickDownwardInteractionPoint(interaction1, anita1, settings1, antarctica, ray1, beyondhorizon, len_int_kgm2, (src_model || settings1->HORIZON_OFFSET > -999) ? &force_dir : 0);
1850 
1851  bool havent_set_frac = true;
1852  bool havent_set_weights = true;
1853  bool havent_set_dir = true;
1854 
1855 #ifdef ANITA3_EVENTREADER
1856 
1857  if (settings1->UNBIASED_SELECTION > 0 || src_model || settings1->HORIZON_OFFSET) //in this case, we have already picked the direction
1858  {
1859  havent_set_dir = false;
1860  if (truthNuPtr) truthNuPtr->setDir(interaction1->nnu.GetX(), interaction1->nnu.GetY(), interaction1->nnu.GetZ());
1861  }
1862 
1863  //FILL TruthAnitaNeutrino here (in case we don't get to fill it later)
1864  if (truthNuPtr)
1865  {
1866  truthNuPtr->setPos(interaction1->posnu.GetX(), interaction1->posnu.GetY(), interaction1->posnu.GetZ(),
1867  bn1->r_bn.GetX(), bn1->r_bn.GetY(), bn1->r_bn.GetZ(), realtime_this);
1868  truthNuPtr->setNu(pnu,pdgcode);
1869  }
1870 #endif
1871 
1872 #ifdef ANITA3_EVENTREADER
1873 #define DO_SKIP { if (truthNuPtr) {truthNuPtr->setSkipped(true,havent_set_frac,havent_set_weights,havent_set_dir); truthAnitaNuTree->Fill();} continue; }
1874 #else
1875 #define DO_SKIP continue ;
1876 #endif
1877 
1878  //BELOW HERE, WE NO LONGER HAVE EVERY EVENT
1879  //
1880  if (interaction1->noway)
1881  {
1882  DO_SKIP
1883  }
1884  count1->noway[whichray]++;
1885 
1886  if (interaction1->wheredoesitleave_err)
1887  {
1888  DO_SKIP
1889  }
1890  count1->wheredoesitleave_err[whichray]++;
1891 
1892  if (interaction1->neverseesice)
1893  {
1894  DO_SKIP
1895  }
1896  count1->neverseesice[whichray]++;
1897 
1898  if (interaction1->wheredoesitenterice_err)
1899  {
1900  DO_SKIP
1901  }
1902  count1->wheredoesitenterice_err[whichray]++;
1903 
1904  if (interaction1->toohigh)
1905  {
1906  DO_SKIP
1907  }
1908  count1->toohigh[whichray]++;
1909 
1910  if (interaction1->toolow)
1911  {
1912  DO_SKIP
1913  }
1914  count1->toolow[whichray]++;
1915 
1916  if (bn1->WHICHPATH==3)
1917  interaction1=int_banana;
1918 
1919  if (!interaction1->iceinteraction)
1920  {
1921  DO_SKIP
1922  }
1923  count1->iceinteraction[whichray]++;
1924 
1925  if (beyondhorizon) {
1926  DO_SKIP
1927  }
1928  count1->inhorizon[whichray]++;
1929  // cerenkov angle depends on depth because index of refraction depends on depth.
1930  //if(!settings1->ROUGHNESS){
1931  if (settings1->FIRN) {
1932  sig1->SetNDepth(antarctica->GetN(interaction1->altitude_int));
1933  // changle = acos(1/N_DEPTH);
1934  changle_deg=sig1->changle*DEGRAD;
1935  }
1936  //}
1937 
1938  if (settings1->FORSECKEL==1)
1939  sig1->SetChangle(acos(1/sig1->NICE));
1940 
1941  // x and y components of interaction in km.
1942  horizcoord=interaction1->posnu[0]/1000;
1943  vertcoord=interaction1->posnu[1]/1000;
1944 
1945  ray1->GetSurfaceNormal(settings1, antarctica, interaction1->posnu, slopeyangle, 0);
1946 
1947  // *** warning **** for Snell's law, I call the ray on the air-side
1948  // the incident angle and the ice-side ray the refracted
1949 
1950  // ray's angle of incidence (in the air) onto ice
1951  costheta_inc=ray1->n_exit2bn[0]*ray1->nsurf_rfexit; // just for plotting
1952 
1953  // just for plotting
1954  costheta_exit=cos(ray1->rfexit[0].Theta()); // just for plotting
1955 
1956 
1957  if (!ray1->TraceRay(settings1, anita1, 1, sig1->N_DEPTH)) {
1958  DO_SKIP
1959  }
1960 
1961  // // use snell's law to get the first guess at the
1962  // // direction of the rf as it leaves ice surface.
1963  // // 0th guess was simply radially outward from interaction position
1964  // // this now takes into account balloon position and surface normal.
1965  ray1->GetRFExit(settings1, anita1, whichray, interaction1->posnu, interaction1->posnu_down, bn1->r_bn, bn1->r_boresights, 1, antarctica); // fills ray1->n_exit2bn[1]
1966 
1967  ray1->GetSurfaceNormal(settings1, antarctica, interaction1->posnu, slopeyangle, 1);
1968 
1969  if (!ray1->TraceRay(settings1, anita1, 2, sig1->N_DEPTH)) {; // trace ray, 2nd iteration.
1970  DO_SKIP
1971  }
1972 
1973 
1974 
1975  // fills ray1->n_exit2bn[2] ?
1976  ray1->GetRFExit(settings1, anita1, whichray, interaction1->posnu, interaction1->posnu_down, bn1->r_bn, bn1->r_boresights, 2, antarctica);
1977 
1978  ray1->GetSurfaceNormal(settings1, antarctica, interaction1->posnu, slopeyangle, 2);
1979 
1980  if (bn1->WHICHPATH==4) // if this is for comparison with Peter, print angles of incidence
1981  ray1->PrintAnglesofIncidence();
1982 
1983  // intermediate counter
1984  count1->nraypointsup1[whichray]++;
1985 
1986  sec1->GetTauDecay(interaction1->nuflavor, interaction1->current, taudecay, emfrac_db, hadfrac_db);
1987 
1988  // pick elasticity (for now is done for neutrinos only)
1989  elast_y=primary1->pickY(settings1, pnu, xsecParam_nutype, interaction1->currentint);
1990  if (settings1->CONSTANTY==1) { // if we ask to make y a constant=0.2
1991  elast_y=0.2;
1992  interaction1->nuflavor="nue";
1993  interaction1->current="cc";
1994  }
1995  else if (settings1->CONSTANTY==2)
1996  {
1997  if (settings1->SHOWERTYPE == 0)
1998  {
1999  elast_y = 1;
2000  interaction1->nuflavor="nue";
2001  interaction1->current="cc";
2002  }
2003  else
2004  {
2005  elast_y = 0;
2006  interaction1->nuflavor="nue";
2007  interaction1->current="cc";
2008  }
2009  }
2010  if (bn1->WHICHPATH==3)
2011  elast_y = Interaction::banana_y;
2012  if (bn1->WHICHPATH==4)
2013  elast_y=1.;
2014  if (settings1->FORSECKEL==1) {
2015  if (settings1->SHOWERTYPE==0) // all hadronic shower
2016  elast_y=1.;
2017  if (settings1->SHOWERTYPE==1) // all em shower
2018  elast_y=0.;
2019  } //if (settings1->FORSECKEL)
2020 
2021  if (ytree->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2022  ytree->Fill();
2023 
2024 
2025  //TAU STUFF. Pick whether it will stay as a neutrino or create tau
2026  if ( tautrigger == 1 ) {
2027  if ( ( !settings1->UNBIASED_SELECTION ) && ( !settings1->SLAC ) && !src_model ) {
2028  err = GetDirection(settings1, interaction1, ray1->nrf_iceside[4], deltheta_em_max, deltheta_had_max, emfrac, hadfrac, vmmhz1m_max*bestcase_atten, interaction1->r_fromballoon[whichray], ray1, sig1, interaction1->posnu, anita1, bn1, interaction1->nnu, costhetanu, theta_threshold);
2029  //cout<<"UNBIASED_SELECTION IS "<<settings1->UNBIASED_SELECTION<<"\n";
2030  }
2031  else if (src_model || settings1->HORIZON_OFFSET > -999)
2032  {
2033  interaction1->nnu = force_dir;
2034  interaction1->dtryingdirection = 1; //ugh
2035  costhetanu = cos(force_dir.Theta());
2036  theta_threshold = 1;
2037  err = 1;
2038  }
2039  else if ( settings1->SLAC ) {
2040  Vector xaxis(1., 0., 0.);
2041  //nnu=(rfexit[0].Unit()).Rotate(-10.*RADDEG, interaction1->posnu.Cross(zaxis));
2042  interaction1->nnu = xaxis.RotateY(bn1->theta_bn-settings1->SLAC_HORIZDIST/EarthModel::R_EARTH); //direction of neutrino- for slac, that's the direction of the beam
2043  interaction1->nnu = interaction1->nnu.RotateZ(bn1->phi_bn);
2044  costhetanu=cos(interaction1->nnu.Theta());
2045  theta_threshold=1.; // this is a bogus theta_threshold but it is only used for plotting anyway
2046  if (settings1->BORESIGHTS) {
2047  fslac_viewangles << bn1->sslacpositions[bn1->islacposition] << "\n";
2048  for(int ilayer=0;ilayer<settings1->NLAYERS;ilayer++) { // loop over layers on the payload
2049  for(int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) {
2050  viewangle_eachboresight[ilayer][ifold]=acos(interaction1->nnu.Dot(ray1->nrf_iceside_eachboresight[4][ilayer][ifold]));
2051  fslac_viewangles << ilayer << "\t" << ifold << "\t" << (viewangle_eachboresight[ilayer][ifold]-sig1->changle)*DEGRAD << "\n";
2052  }//end for ifold
2053  }//end for ilayer
2054  }//end if boresights
2055  err = 1; // everything is a-okay
2056  }// end else if slac
2057 
2058  if ( err == 0 )
2059  {
2060  DO_SKIP//bad stuff has happened.
2061  }
2062 
2063  interaction1->r_in = antarctica->WhereDoesItEnter(interaction1->posnu, interaction1->nnu);
2064 
2065  taus1->GetTauWeight(primary1, settings1, antarctica, interaction1, pnu, 1, ptauf, crust_entered);
2066 
2067  antarctica->Getchord(settings1, len_int_kgm2, interaction1->r_in, interaction1->pathlength_inice, settings1->UNBIASED_SELECTION == 0, interaction1->posnu, inu, interaction1->chord, interaction1->weight_nu_prob, interaction1->weight_nu, nearthlayers, myair, total_kgm2, crust_entered, mantle_entered, core_entered);
2068 
2069  nutauweight = interaction1->weight_nu_prob;
2070  tauweight = taus1->weight_tau_prob;
2071 
2072  nutauweightsum +=nutauweight;
2073  tauweightsum +=tauweight;
2074  double xrndm=getRNG(RNG_XRNDM)->Rndm();
2075 
2076  if(xrndm <=taus1->weight_tau_prob/(taus1->weight_tau_prob+interaction1->weight_nu_prob)){
2077  pnu=ptauf;//set the energy we are looking at to the final energy of the tau. cuts out alot of if-else statements
2078  tauweighttrigger=1;//From now on, signifies a tau particle
2079  }
2080  if(TauPtr)
2081  delete TauPtr;
2082 
2083  TauPtr = new Taumodel();
2084  TauPtr->inu = inu;
2085  TauPtr->ptauf = ptauf;
2086  TauPtr->weight_nu_prob = interaction1->weight_nu_prob;
2087  TauPtr->weight_tau_prob = taus1->weight_tau_prob;
2088 
2089  if (mytaus_tree->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2090  mytaus_tree->Fill();
2091 
2092  //delete TauPtr;
2093  }//end tautrigger ==1
2095 
2096  // get fraction of shower that is electromagnetic.
2097  // pi^0's are counted as hadronic.
2098  sec1->GetEMFrac(settings1, interaction1->nuflavor, interaction1->current, taudecay, elast_y, hy, pnu, inu,emfrac, hadfrac, n_interactions, tauweighttrigger);
2099  havent_set_frac = false;
2100 
2101 #ifdef ANITA3_EVENTREADER
2102  if (truthNuPtr) truthNuPtr->setFrac(hadfrac,emfrac);
2103 #endif
2104  if (emfrac+hadfrac>1.000001) {
2105  cout << "Warning: " << inu << " " << emfrac+hadfrac << "\n";
2106  }
2107 
2108 
2109  // for plotting
2110  sumfrac=emfrac+hadfrac;
2111  //cout << "tree7 check" <<interaction1->nuflavorint << endl;
2112  if (tree7->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2113  tree7->Fill();
2114 
2115  vmmhz1m_visible = (emfrac+hadfrac)*vmmhz1m_max; //Stephen - Record actual V/m/Mhz for display
2116 
2117  // plots for debugging.
2118  if (interaction1->nuflavor=="numu" && bn1->WHICHPATH != 3 && !settings1->ONLYFINAL && settings1->HIST==1 && fraction_sec_muons->GetEntries()<settings1->HIST_MAX_ENTRIES) {
2119  fraction_sec_muons->Fill(emfrac+hadfrac, weight);
2120  n_sec_muons->Fill((double)n_interactions);
2121  }
2122 
2123  if (interaction1->nuflavor=="nutau" && bn1->WHICHPATH != 3 && !settings1->ONLYFINAL && settings1->HIST==1 && fraction_sec_taus->GetEntries()<settings1->HIST_MAX_ENTRIES) {
2124  fraction_sec_taus->Fill(emfrac+hadfrac, weight);
2125  n_sec_taus->Fill((double)n_interactions);
2126  }
2127 
2128  // for double bangs
2129  if(sec1->secondbang && sec1->interestedintaus) {
2130  ptau=(1-elast_y)*pnu;
2131  emfrac=emfrac_db;
2132  hadfrac=hadfrac_db;
2133  }
2134 
2135  // Find the highest possible electric field emitted at this energy
2136  // (this corresponds to the electric field at the highest frequency
2137  // detectable by the antennas.
2138  // Also find the maximum width of Cerenkov cone (which is at lowest frequency)
2139  // These are used to find the maximum angular deviation from Cerenkov
2140  // cone where signal is still detectable.
2141  if(sec1->secondbang && sec1->interestedintaus) {
2142  vmmhz1m_max=sig1->GetVmMHz1m(ptau, anita1->FREQ_HIGH);
2143  sig1->GetSpread(ptau, emfrac, hadfrac, anita1->FREQ_LOW, deltheta_em_max, deltheta_had_max);
2144  } //if (secondbang && interestedintaus)
2145  else {// get peak signal at highest edge of frequency band because that is where it is highest
2146  vmmhz1m_max=sig1->GetVmMHz1m(pnu, anita1->FREQ_HIGH);
2147  sig1->GetSpread(pnu, emfrac, hadfrac, anita1->FREQ_LOW,
2148  deltheta_em_max, deltheta_had_max);
2149  } //end else (not secondbang or not interested in taus)
2150 
2151  if (jaimetree->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2152  jaimetree->Fill();
2153 
2154  // Using highest possible signal and minimum noise,
2155  // and accounting for distance from balloon,
2156  // and best case attenutation,
2157  // reject if signal is undetectable.
2158 
2159  if (whichray==0) // if we are looking at direct rays
2160  bestcase_atten=exp(interaction1->altitude_int/MAX_ATTENLENGTH); // the attenuation is obtained from the altitude of the interaction (shortest path is if the signal went straight up)
2161  if (whichray==1) // if we are looking at reflected rays
2162  bestcase_atten=exp(interaction1->altitude_int_mirror/MAX_ATTENLENGTH);//use the real path which seems from the mirror point.
2163 
2164  // let's keep this even in the roughness case, since it still represents an ceiling value
2165  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/((hadfrac+emfrac)*vmmhz1m_max*bestcase_atten/interaction1->r_fromballoon[whichray]*heff_max*anita1->bwmin/1.E6)>settings1->CHANCEINHELL_FACTOR && !settings1->SKIPCUTS) {
2166  DO_SKIP // by comparing highest possible signal to the lowest possible noise, reject if there is just no way we could detect this event.
2167  // vmmhz1m_max=signal at highest frequency
2168  // bestcase_atten=best case attenuation
2169  // r_fromballoon=distance from interaction to balloon
2170  //heff_max=maximum effective height over the frequency range
2171  }
2172 
2173  // intermediate counter
2174  count1->nnottoosmall[whichray]++;
2175 
2176  // pick neutrino direction.
2177  // This GetDirection() picks a neutrino direction such that its cerenkov cone
2178  // is close enough to the balloon line of sight that you have a chance in hell of seeing the signal.
2179  if (whichray==1) {
2180  chengji=ray1->nrf_iceside[4]*ray1->nrf_iceside[0];//the projection of nrf_iceside[2] on the direction of radius direction of interaction1->posnu
2181  //original nrf_iceside[4] is the upgoing direction of signals after being reflected.
2182  //now I get the corresponding downward direction of real signals in my case.
2183  //The two vectors are symmetric to the tangent plane of the Earth at interaction point
2184  ray1->nrf_iceside[4] = ray1->nrf_iceside[4] - 2*chengji*ray1->nrf_iceside[0];
2185  } //if whichray==1
2186 
2187  if ( tautrigger == 0 ) {//did this for cc- taus already, do again for all other particles
2188  if ( ! src_model && ( !settings1->UNBIASED_SELECTION ) && ( !settings1->SLAC ) ) {
2189  err = GetDirection(settings1, interaction1, ray1->nrf_iceside[4], deltheta_em_max, deltheta_had_max, emfrac, hadfrac, vmmhz1m_max*bestcase_atten, interaction1->r_fromballoon[whichray], ray1, sig1, interaction1->posnu, anita1, bn1, interaction1->nnu, costhetanu, theta_threshold);
2190  //cout << "costhetanu is " << costhetanu << endl;
2191  }
2192  else if (src_model || settings1->HORIZON_OFFSET > -999)
2193  {
2194  interaction1->nnu = force_dir;
2195  interaction1->dtryingdirection = 1; //ugh
2196  costhetanu = cos(force_dir.Theta());
2197  theta_threshold = 1;
2198  err = 1;
2199  }
2200  else if (settings1->SLAC) {
2201  Vector xaxis(1., 0., 0.);
2202  interaction1->nnu = xaxis.RotateY(bn1->theta_bn-settings1->SLAC_HORIZDIST/EarthModel::R_EARTH); //direction of neutrino- for slac, that's the direction of the beam
2203  interaction1->nnu = interaction1->nnu.RotateZ(bn1->phi_bn);
2204  costhetanu=cos(interaction1->nnu.Theta());
2205  theta_threshold=1.; // this is a bogus theta_threshold but it is only used for plotting anyway
2206  if (settings1->BORESIGHTS) {
2207  fslac_viewangles << bn1->sslacpositions[bn1->islacposition] << "\n";
2208  for(int ilayer=0;ilayer<settings1->NLAYERS;ilayer++) { // loop over layers on the payload
2209  for(int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) {
2210  viewangle_eachboresight[ilayer][ifold]=acos(interaction1->nnu.Dot(ray1->nrf_iceside_eachboresight[4][ilayer][ifold]));
2211  fslac_viewangles << ilayer << "\t" << ifold << "\t" << (viewangle_eachboresight[ilayer][ifold]-sig1->changle)*DEGRAD << "\n";
2212  }//end ifold
2213  }//end ilayer
2214  }//end boresight
2215  err = 1; // everything is a-okay
2216  }//end else if slac
2217  }//end tau trigger ==0
2218 
2219 
2220 #ifdef ANITA3_EVENTREADER
2221  if (havent_set_dir)
2222  {
2223  if (truthNuPtr) truthNuPtr->setDir(interaction1->nnu.GetX(), interaction1->nnu.GetY(), interaction1->nnu.GetZ());
2224  havent_set_dir = false;
2225  }
2226 #endif
2227 
2228  // gets angle between ray and neutrino direction
2229  viewangle = GetViewAngle(ray1->nrf_iceside[4], interaction1->nnu);
2230  if(viewangle>1.57 && !settings1->SKIPCUTS) { //discard the event if viewangle is greater than 90 degrees
2231  DO_SKIP
2232  }
2233  count1->nviewangle_lt_90[whichray]++; // add to counter
2234 
2235  if (!Ray::WhereDoesItLeave(interaction1->posnu, interaction1->nnu, antarctica, interaction1->nuexit))
2236  {
2237  DO_SKIP // doesn't give a real value from quadratic formula
2238  }
2239 
2240  GetBalloonLocation(interaction1, ray1, bn1, antarctica);
2241 
2242  nuexitlength=interaction1->posnu.Distance(interaction1->nuexit);
2243  // probability a tau would decay within this length at this
2244  // energy
2245  nuexitice=interaction1->posnu.Distance(interaction1->nuexitice);
2246  theta_threshold_deg=theta_threshold*DEGRAD;
2247 
2248  // neutrino direction in frame where balloon is up, 0=east, 1=north, 2=up
2249  n_nutraject_ontheground = Vector(bn1->n_east*interaction1->nnu, bn1->n_north*interaction1->nnu, bn1->n_bn*interaction1->nnu);
2250 
2251  cosviewangle=cos(viewangle); // cosine angle
2252  viewangle_deg=viewangle*DEGRAD; // same angle but in degrees
2253  dviewangle_deg=(sig1->changle-viewangle)*DEGRAD; // deviation from cerenkov angle
2254 
2255  if (viewangletree->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2256  viewangletree->Fill(); // fills variables related to viewing angle
2257 
2258  if (neutrino_positiontree->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2259  neutrino_positiontree->Fill(); // fills variables related to neutrino position
2260 
2261  if (whichray==1) {
2262  //return it to the upgoing direction that is after being reflected
2263  ray1->nrf_iceside[4] = ray1->nrf_iceside[4] + 2*chengji*ray1->nrf_iceside[0];
2264  }
2265 
2266  if ( err == 0 ) {
2267  count1->nbadfracs[whichray]++;
2268  cout<<"err==0, so leaving.\n";
2269  DO_SKIP
2270  }
2271  count1->ngoodfracs[whichray]++;
2272 
2273  // these variables are just for plotting
2274  nsigma_em_threshold=theta_threshold/deltheta_em_max;
2275  nsigma_had_threshold=theta_threshold/deltheta_had_max;
2276 
2277  // For each neutrino, multiply the number of tries
2278  // necessary to generate the appropriate direction,
2279  // and the number of tries necessary to generate
2280  // an appropriate position, and assume they are
2281  // independent.
2282  interaction1->dnutries=interaction1->dtryingdirection*bn1->dtryingposition;
2283 
2284  // for plotting aperture per ring radius from balloon
2285  index_distance=(int)(bn1->r_bn.SurfaceDistance(interaction1->posnu, bn1->surface_under_balloon) / (700000./(double)NBINS_DISTANCE));
2286 
2287  // where the neutrino enters the earth
2288  if (tautrigger==0){//did for cc-taus already, do for all other particles
2289  interaction1->r_in = antarctica->WhereDoesItEnter(interaction1->posnu, interaction1->nnu);
2290  antarctica->Getchord(settings1, len_int_kgm2, interaction1->r_in, interaction1->pathlength_inice, settings1->UNBIASED_SELECTION ==0, interaction1->posnu, inu, interaction1->chord, interaction1->weight_nu_prob,
2291  interaction1->weight_nu, nearthlayers, myair, total_kgm2, crust_entered, mantle_entered, core_entered);
2292  //cout << "interaction1->chord is " << interaction1->chord << "\n";
2293  }
2294 
2295  // total chord
2296  double chord_kgm2_test=interaction1->posnu.Distance(interaction1->r_in)*sig1->RHOMEDIUM;
2297 
2298  double weight_test=0; // weight if the whole chord from interaction to earth entrance is ice.
2299  // take best case scenario chord length and find corresponding weight
2300 
2301  IsAbsorbed(chord_kgm2_test, len_int_kgm2, weight_test);
2302 
2303 
2304 
2305  // if the probably the neutrino gets absorbed is almost 1, throw it out.
2306 
2307  //std::cout << "Cut on weights = " << settings1->CUTONWEIGHTS;
2308  //if ( bn1->WHICHPATH != 4 && settings1->FORSECKEL != 1 && !settings1->SKIPCUTS && !settings1->SOURCE) {
2309  if ( bn1->WHICHPATH != 4 && settings1->FORSECKEL != 1 && !settings1->SKIPCUTS) {
2310  if (weight_test < settings1->CUTONWEIGHTS) {
2311  DO_SKIP
2312  }
2313  }
2314  count_chanceofsurviving++;
2315 
2316  // theta of nu entrance point, in earth frame
2317  // and latitude
2318  theta_in=interaction1->r_in.Theta();
2319  lat_in=-90+theta_in*DEGRAD;
2320 
2321  // find quantities relevent for studying impact of atmosphere
2322  // for black hole studies
2323  // costheta and mytheta: theta of neutrino wrt surface normal where neutrino enters earth
2324  // cosbeta0, mybeta: theta of neutrino wrt surface normal for a person standing above the interaction point
2325  myair=GetThisAirColumn(settings1, interaction1->r_in, interaction1->nnu, interaction1->posnu, col1, cosalpha, mytheta, cosbeta0, mybeta);
2326 
2327  // where the neutrino enters the ice
2328  // reject if it enters beyond the borders of the continent.
2329  // step size is 1/10 of interaction length
2330  if (!settings1->FORSECKEL && !settings1->UNBIASED_SELECTION) {
2331  if (!antarctica->WhereDoesItEnterIce(interaction1->posnu, interaction1->nnu, len_int_kgm2/sig1->RHOMEDIUM/10., interaction1->r_enterice)) {
2332  //r_enterice.Print();
2333  if (antarctica->OutsideAntarctica(interaction1->r_enterice)) {
2334  cout<<"Warning! Neutrino enters beyond continent, program is rejecting neutrino! inu = "<<inu<<endl;
2335  if (bn1->WHICHPATH==3)
2336  cout<<"Warning! Neutrino enters beyond continent, program is rejecting neutrino!"<<endl;
2337  //
2338  DO_SKIP
2339  }// end outside antarctica
2340  }// end wheredoesitenterice
2341  }// end if !settings forseckel && unbiased
2342  // intermediate counter
2343  count1->nentersice[whichray]++;
2344 
2345  // d1=earth entrance to rock-ice interface
2346  // d2=rock-ice interface to position of neutrino interaction
2347  interaction1->d1=interaction1->r_enterice.Distance(interaction1->r_in);
2348  interaction1->d2=interaction1->r_enterice.Distance(interaction1->posnu);
2349 
2350 
2351  // get a lower limit on the chord that the neutrino traverses,
2352  // so that later we can see if the signal is detectable in
2353  // the best case scenario.
2354  if(sec1->secondbang && sec1->interestedintaus) {
2355  cout << "Need to bring back GetFirstBang before you can simulate taus.\n";
2356  cout << "I removed it because it required EarthModel and I wanted Secondaries to be a stand-alone class to use in the embedded simulation.\n";
2357  icethickness=interaction1->r_enterice.Distance(interaction1->nuexit);
2358  interaction1->chord_kgm2_bestcase=nuentrancelength*Tools::dMin(densities, 3);
2359  }
2360  else {
2361  // finds minimum chord (in kg/m^2) traversed by neutrino
2362  // only keeping events with weight > 10^-3
2363  // periodically need to make sure this is still valid
2364  // chord_kgm2_bestcase=(d1+d2)*sig1->RHOMEDIUM;
2365  interaction1->chord_kgm2_bestcase=(interaction1->d1+interaction1->d2)*Tools::dMin(densities, 3);
2366  }
2367 
2368  // chord just through ice.
2369  interaction1->chord_kgm2_ice=interaction1->d2*sig1->RHOMEDIUM;
2370 
2371  if (tree6->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
2372  tree6->Fill();
2373 
2374  //cout << "interaction1->chord_kgm2_bestcase = " << interaction1->chord_kgm2_bestcase << "\n";
2375  //cout << "len_int_kgm2 = " << len_int_kgm2 << "\n";
2376 
2377 
2378  // take best case scenario chord length and find corresponding weight
2379  IsAbsorbed(interaction1->chord_kgm2_bestcase, len_int_kgm2, interaction1->weight_bestcase);
2380 
2381 
2382  //cout << "interaction1->weight_bestcase = " << interaction1->weight_bestcase << "\n";
2383 
2384 
2385  // if the probability that the neutrino gets absorbed is almost 1, throw it out.
2386  //if (bn1->WHICHPATH!=4 && interaction1->weight_bestcase<settings1->CUTONWEIGHTS && !settings1->SKIPCUTS && !settings1->FORSECKEL && !settings1->SOURCE) {
2387  if (bn1->WHICHPATH!=4 && interaction1->weight_bestcase<settings1->CUTONWEIGHTS && !settings1->SKIPCUTS && !settings1->FORSECKEL) {
2388  if (bn1->WHICHPATH==3)
2389  cout<<"Neutrino is getting absorbed and thrown out!"<<endl;
2390  //
2391  DO_SKIP
2392  }
2393  //intermediate counter
2394  count1->nabsorbed[whichray]++;
2395 
2396  // intermediate counter
2397  count1->nraywithincontinent1[whichray]++;
2398 
2399  // now we have second guess for rf exit point, which is
2400  // pretty close to the right answer.
2401  // now get our best case attenuation again,
2402  // and see if we can reject the event.
2403  if (whichray==0)
2404  bestcase_atten=exp(-1*ray1->rfexit[1].Distance(interaction1->posnu)/MAX_ATTENLENGTH);
2405 
2406  if (whichray==1)
2407  bestcase_atten=exp(-1*ray1->rfexit[1].Distance(interaction1->posnu_down)/MAX_ATTENLENGTH);//use the real distance
2408 
2409  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/((hadfrac+emfrac)*vmmhz1m_max*bestcase_atten/interaction1->r_fromballoon[whichray]*heff_max*anita1->bwmin/1.E6)>settings1->CHANCEINHELL_FACTOR && !settings1->SKIPCUTS && !settings1->FORSECKEL) {
2410  if (bn1->WHICHPATH==3)
2411  cout<<"Event rejected. Check."<<endl;
2412  //
2413  DO_SKIP
2414  }
2415  count_chanceinhell0++;
2416 
2417  // intermediate counting
2418  count1->nraypointsup2[whichray]++;
2419 
2420  double nbelowsurface;
2421  // reject if it is totally internally reflected at the surface AND NOT CONSIDERING ROUGHNESS
2422  if (settings1->FIRN)
2423  nbelowsurface=NFIRN;
2424  else
2425  nbelowsurface=sig1->NICE;
2426  // this is purely a sanity check.
2427  // if everything is working, events should pass with 100% efficiency
2428  if (!settings1->ROUGHNESS && TIR(ray1->nsurf_rfexit, ray1->nrf_iceside[3], nbelowsurface, sig1->N_AIR)) {
2429  DO_SKIP
2430  }
2431  count1->nnottir[whichray]++;
2432 
2433  // this sets n_exit2bn[2] to the ray from the exit point to the balloon,
2434  // last iteration. Now we're ready to do some calculations!!!!
2435  ray1->GetRFExit(settings1, anita1, whichray, interaction1->posnu, interaction1->posnu_down, bn1->r_bn, bn1->r_boresights, 2, antarctica);
2436 
2437  count1->nraywithincontinent2[whichray]++;
2438 
2439  // for plotting- cos(theta) of neutrino direction standing on earth below balloon.
2440  interaction1->costheta_nutraject=(interaction1->nnu*bn1->r_bn)/sqrt(bn1->r_bn*bn1->r_bn);
2441 
2442  theta_nnu_atbn = interaction1->nnu.Angle(bn1->r_bn); // polar angle of neutrino direction as seen at the balloon.
2443 
2444  theta_rf_atbn = ray1->n_exit2bn[2].Angle(bn1->r_bn); // polar angle of the rf signal as seen at the balloon.
2445  // measured theta of the rf, which is actual smeared by SIGMA_THETA, whose default is 0.5 degrees.
2446  theta_rf_atbn_measured = theta_rf_atbn+getRNG(RNG_THETA_RF_RESOLUTION)->Gaus()*anita1->SIGMA_THETA;
2447  interaction1->r_exit2bn=bn1->r_bn.Distance(ray1->rfexit[2]);
2448  interaction1->r_exit2bn_measured=bn1->altitude_bn/cos(theta_rf_atbn_measured);
2449 
2450  theta_nnu_rf_diff_atbn = theta_nnu_atbn - theta_rf_atbn;
2451 
2452  //cout << "nnu : " << interaction1->nnu << " n_bn : " << bn1->n_bn << "\n";
2453  //cout << "acos of costheta nutraject " << DEGRAD*acos(interaction1->costheta_nutraject) << "\n";
2454  //cout << "Oindree: theta nnu, rf, diff at bn " << DEGRAD * theta_nnu_atbn << " " << DEGRAD * theta_rf_atbn << " " << DEGRAD * theta_nnu_rf_diff_atbn << "\n";
2455 
2456  nnu_xy.SetX((interaction1->nnu[0]) - (bn1->r_bn[0])*((interaction1->nnu*bn1->r_bn)/(bn1->r_bn*bn1->r_bn)));
2457  nnu_xy.SetY((interaction1->nnu[1]) - (bn1->r_bn[1])*((interaction1->nnu*bn1->r_bn)/(bn1->r_bn*bn1->r_bn)));
2458  nnu_xy.SetZ((interaction1->nnu[2]) - (bn1->r_bn[2])*((interaction1->nnu*bn1->r_bn)/(bn1->r_bn*bn1->r_bn)));
2459 
2460  rf_xy.SetX((ray1->n_exit2bn[2][0]) - (bn1->r_bn[0])*((ray1->n_exit2bn[2]*bn1->r_bn)/(bn1->r_bn*bn1->r_bn)));
2461  rf_xy.SetY((ray1->n_exit2bn[2][1]) - (bn1->r_bn[1])*((ray1->n_exit2bn[2]*bn1->r_bn)/(bn1->r_bn*bn1->r_bn)));
2462  rf_xy.SetZ((ray1->n_exit2bn[2][2]) - (bn1->r_bn[2])*((ray1->n_exit2bn[2]*bn1->r_bn)/(bn1->r_bn*bn1->r_bn)));
2463 
2464  r_bn_xy.SetX(bn1->r_bn[0]);
2465  r_bn_xy.SetY(bn1->r_bn[1]);
2466 
2467  phi_nnu_atbn = nnu_xy.Angle(r_bn_xy);
2468  phi_rf_atbn = rf_xy.Angle(r_bn_xy);
2469 
2470  //phi_nnu_rf_diff_atbn = nnu_xy.Angle(rf_xy);
2471 
2472  //cout << "phi diff between rf and nnu " << DEGRAD*phi_nnu_rf_diff_atbn << "\n";
2473 
2474  //phi_nnu_rf_diff_atbn = acos(nnu_xy*rf_xy/((sqrt(nnu_xy*nnu_xy))*(sqrt(rf_xy*rf_xy))));
2475 
2476  //cout << "phi diff between rf and nnu " << DEGRAD*phi_nnu_rf_diff_atbn << "\n";
2477 
2478  phi_nnu_rf_diff_atbn = phi_nnu_atbn - phi_rf_atbn;
2479 
2480  //if (phi_nnu_rf_diff_atbn < -180) phi_nnu_rf_diff_atbn += 360;
2481  //if (phi_nnu_rf_diff_atbn > 180) phi_nnu_rf_diff_atbn -= 360;
2482 
2483  //cout << "Oindree: phi nnu, rf, diff at bn " << DEGRAD * phi_nnu_atbn << " " << DEGRAD * phi_rf_atbn << " " << DEGRAD * phi_nnu_rf_diff_atbn << "\n";
2484 
2485  if((settings1->WHICH == 2 || settings1->WHICH == 6) && theta_rf_atbn < 0.3790091) {
2486  DO_SKIP // the deck will mess up the arrival times in the top ring
2487  }
2488  // reject if the rf leaves the ice where there is water, for example.
2489  if (!antarctica->AcceptableRfexit(ray1->nsurf_rfexit, ray1->rfexit[2], ray1->n_exit2bn[2])){
2490  if (bn1->WHICHPATH==3)
2491  cout<<"Should look at this. Not expecting to be here."<<endl;
2492  DO_SKIP
2493  }//end if acceptableRFexit
2494 
2495  // intermediate counting
2496  count1->nacceptablerf[whichray]++;
2497 
2498  // difference between exit points of 2nd and 3rd iterations.
2499  diff_3tries=ray1->rfexit[1].Distance(ray1->rfexit[2]);
2500 
2501  if (tree5->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1 && bn1->WHICHPATH != 3)
2502  tree5->Fill();
2503 
2504  // reject if 2nd and 3rd tries
2505  // don't converge within 10m.
2506  if (diff_3tries>10) {
2507  DO_SKIP
2508  }
2509  count1->nconverges[whichray]++;
2510  // Get Polarization vector. See Jackson, Cherenkov section.
2511  n_pol = GetPolarization(interaction1->nnu, ray1->nrf_iceside[4]);
2512 //cerr<<inu<<":(spec) v_nu "<<interaction1->nnu<<" : 2IP "<<ray1->nrf_iceside[4]<<" : inc npol"<<n_pol<< endl;
2513 //cerr<<inu<<" "<<ray1->rfexit[2]<<endl;
2514  if (settings1->BORESIGHTS) {
2515  for(int ilayer=0;ilayer<settings1->NLAYERS;ilayer++) { // loop over layers on the payload
2516  for(int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) {
2517  n_pol_eachboresight[ilayer][ifold]=GetPolarization(interaction1->nnu, ray1->nrf_iceside_eachboresight[4][ilayer][ifold]);
2518  } // end looping over antennas in phi
2519  } // end looping over layers
2520  } // if we are calculating for all boresights
2521 
2522  //if(!settings1->ROUGHNESS){
2523  if (settings1->FIRN){
2524  // now rotate that polarization vector according to ray paths in firn and air.
2525  // fresnel factor at ice-firn interface
2526  GetFresnel(rough1, settings1->ROUGHNESS, ray1->nsurf_rfexit, ray1->nrf_iceside[3], n_pol, ray1->nrf_iceside[4], vmmhz1m_max, emfrac, hadfrac, deltheta_em_max, deltheta_had_max, t_coeff_pokey, t_coeff_slappy, fresnel1, mag1);
2527  if (bn1->WHICHPATH==4)
2528  cout << "Lentenin factor is " << 1./mag1 << "\n";
2529 
2530  //The gradual transition in the firn means that there is no fresnel factor, only magnification
2531  // and the magnification factor is upside down compared to what it is
2532  // for the firn-air interface
2533  vmmhz1m_fresneledonce = vmmhz1m_max/mag1;
2534 
2535  // get fresnel factor at firn-air interface
2536  GetFresnel(rough1, settings1->ROUGHNESS, ray1->nsurf_rfexit, ray1->n_exit2bn[2], n_pol, ray1->nrf_iceside[3], vmmhz1m_fresneledonce, emfrac, hadfrac, deltheta_em_max, deltheta_had_max, t_coeff_pokey, t_coeff_slappy, fresnel2, mag2);
2537  // use both fresnel and magnification factors at firn-air interface. Notice that magnification factor is
2538  //upside-down compared to what it is in the firn.
2539  vmmhz1m_fresneledtwice=vmmhz1m_fresneledonce*fresnel2*mag2;
2540 
2541  if (settings1->BORESIGHTS) {
2542  for(int ilayer=0;ilayer<settings1->NLAYERS;ilayer++) { // loop over layers on the payload
2543  for(int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) {
2544  GetFresnel(rough1, settings1->ROUGHNESS, ray1->nsurf_rfexit, ray1->n_exit2bn_eachboresight[2][ilayer][ifold],
2545  n_pol_eachboresight[ilayer][ifold], ray1->nrf_iceside_eachboresight[3][ilayer][ifold],
2546  vmmhz1m_max, emfrac, hadfrac, deltheta_em_max, deltheta_had_max, t_coeff_pokey, t_coeff_slappy,
2547  fresnel1_eachboresight[ilayer][ifold], mag1_eachboresight[ilayer][ifold]);
2548  // std::cout << fresnel1_eachboresight[ilayer][ifold] << std::endl;
2549  } // end looping over phi sectors
2550  } // end looping over layers
2551  } // end if we are calculating for all boresights
2552 
2553 
2554  if (bn1->WHICHPATH==4)
2555  cout<<"firn-air interface: fresnel2, mag2 are "<<fresnel2<<" "<< mag2 <<"\n";
2556 
2557  }//end if firn
2558  else {
2559  sig1->GetSpread(pnu, emfrac, hadfrac, (anita1->bwslice_min[2]+anita1->bwslice_max[2])/2., deltheta_em_mid2, deltheta_had_mid2);
2560 
2561  GetFresnel(rough1, settings1->ROUGHNESS, ray1->nsurf_rfexit, ray1->n_exit2bn[2], n_pol, ray1->nrf_iceside[4], vmmhz1m_max, emfrac, hadfrac, deltheta_em_mid2, deltheta_had_mid2, t_coeff_pokey, t_coeff_slappy, fresnel1, mag1);
2562 
2563  vmmhz1m_fresneledtwice = vmmhz1m_max*fresnel1*mag1; // only the ice-air interface
2564 
2565  if (settings1->BORESIGHTS) {
2566  for(int ilayer=0;ilayer<settings1->NLAYERS;ilayer++) { // loop over layers on the payload
2567  for(int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) {
2568  GetFresnel(rough1, settings1->ROUGHNESS, ray1->nsurf_rfexit, ray1->n_exit2bn_eachboresight[2][ilayer][ifold], n_pol_eachboresight[ilayer][ifold], ray1->nrf_iceside_eachboresight[4][ilayer][ifold], vmmhz1m_max, emfrac, hadfrac, deltheta_em_max, deltheta_had_max, t_coeff_pokey, t_coeff_slappy, fresnel1_eachboresight[ilayer][ifold], mag1_eachboresight[ilayer][ifold]);
2569  } // end looping over phi sectors
2570  } // end looping over layers
2571  } // end if we are calculating for all boresights
2572  }//end else firn
2573 //cerr<<inu<<" -- here"<<endl; //}
2574  // OTHERWISE THERE IS ROUGHNESS SO DO MAGIC
2575  if(settings1->ROUGHNESS){//else{
2576  //(vector) ray1->nsurf_rfexit: surface normal at RFexit position
2577  //(pos) ->rfexit[2]: final iterated position of RF exit
2578  //(vector) ->n_exit2bn[2]: vector from RF exit position TO balloon
2579  //(pos) bn1->r_bn: position of balloon
2580  //(vector) n_pol: polarization vector
2581  //(pos) posnu: position of neutrino interaction
2582 
2583  int num_validscreenpoints = 0;
2584  Position pos_current;
2585  Vector vec_pos_current_to_balloon;
2586 
2587  Position pos_projectedImpactPoint;
2588  Vector vec_localnormal; //normalized, normal vector at projected ground point
2589  Vector vec_nnu_to_impactPoint; //normalized
2590  Vector vec_inc_perp; //normalized, vector perp. to incident and surface normal (out-of-inc place)
2591  Vector vec_inc_parl; //normalized, vector parl. to incident and surface normal (in-inc plane)
2592  double pol_perp_inc, pol_parl_inc; //component of incident polarization
2593  Vector vec_local_grnd_perp; //normalized, vector perp. to transmitted and surface normal (out-of-trans place)
2594  Vector vec_local_grnd_parl; //normalized, vector parl. to transmitted and surface normal (in-trans plane)
2595  double pol_perp_trans, pol_parl_trans; //component of transmitted polarization
2596  Vector vec_grndcomp2bln;
2597  Vector vec_grndcomp2IP;
2598 
2599  double time_reference_specular, time_reference_local;
2600  double pathlength_local; // set for each screen point
2601  double viewangle_local;
2602  double azimuth_local; // azimuthal angle between local surface normal and vector to balloon [radians]
2603  double theta_local; // polar angle between local surface normal and vector to balloon [radians]
2604  double theta_0_local; //angle between local surface normal and incident direction [radians]
2605  double tcoeff_perp_polperp, tcoeff_parl_polperp; //for perpendicular polarization (in-ground comp)
2606  double tcoeff_perp_polparl, tcoeff_parl_polparl; //for parallel polarization
2607  double power_perp_polperp, power_parl_polperp;
2608  double power_perp_polparl, power_parl_polparl;
2609  power_perp_polperp = power_parl_polperp = power_perp_polparl = power_parl_polparl = 0.;
2610  double fresnel_r, mag_r;
2611 
2612  Vector npol_local_inc, npol_local_trans;
2613  Vector temp_a;
2614 
2615  double Emag_local;
2616  double taperfactor;
2617 //cerr<<inu<<": "<<vmmhz1m_max<<endl;
2618 
2619  //double pathlength_specular = interaction1->posnu.Distance(ray1->rfexit[2]) + ray1->rfexit[2].Distance(bn1->r_bn);
2620  if (settings1->FIRN)
2621  time_reference_specular = (interaction1->posnu.Distance(ray1->rfexit[2])*NFIRN / CLIGHT) + (ray1->rfexit[2].Distance(bn1->r_bn)/CLIGHT);
2622  else
2623  time_reference_specular = (interaction1->posnu.Distance(ray1->rfexit[2])*NICE / CLIGHT) + (ray1->rfexit[2].Distance(bn1->r_bn)/CLIGHT);
2624 
2625  double slopeyx, slopeyy, slopeyz, rtemp;
2626  Vector ntemp2;
2627  Vector xaxis = Vector(1.,0.,0.);
2628  Vector yaxis = Vector(0.,1.,0.);
2629  Vector zaxis = Vector(0.,0.,1.);
2630 
2631  double basescreenedgelength = settings1->SCREENEDGELENGTH;
2632  double grd_stepsize = settings1->SCREENSTEPSIZE;
2633  int grd_nsteps;
2634  if(settings1->ROUGHSIZE>0)
2635  grd_nsteps = int(basescreenedgelength/2. / grd_stepsize);
2636  else
2637  grd_nsteps = 0;
2638 
2639  //#########
2640  //iterate points on the screen, get their position and project back to find ground impact
2641  //calculate incident and transmitted angles, look up power fraction, and add to running total
2642 
2643  //reset
2644  panel1->ResetParameters();
2645 
2646  panel1->SetNsamples( grd_nsteps );
2647  panel1->SetEdgeLength( grd_stepsize );
2648 
2649  panel1->SetCentralPoint( ray1->rfexit[2] );
2650  vec_localnormal = antarctica->GetSurfaceNormal(ray1->rfexit[2]).Unit();
2651  panel1->SetNormal( vec_localnormal );
2652  panel1->SetCosineProjectionFactor( 1. );
2653 
2654  panel1->SetUnitY( (vec_localnormal.Cross(ray1->n_exit2bn[2])).Unit() );
2655  panel1->SetUnitX( (panel1->GetUnitY().Cross(vec_localnormal)).Unit() );
2656 //cerr<<panel1->GetCentralPoint()<<" "<< bn1->r_bn<<endl;
2657  // loop over grid point on ground and see if it's valid
2658  for (int ii= -2*panel1->GetNsamples(); ii< 2*panel1->GetNsamples()+1; ii++){
2659  for (int jj= -2*panel1->GetNsamples(); jj< 2*panel1->GetNsamples()+1; jj++){
2660 //cerr<<"+++++++++++++"<<endl;
2661 //cerr<<inu<<": "<<ii<<" "<<jj<<endl;
2662  //cerr<<"+ seed point: "<<jj<<" / "<<panel1->GetNsamples()*panel1->GetNsamples()<<endl;
2663  Emag_local = vmmhz1m_max;
2664  taperfactor = fresnel_r = mag_r = 1.;
2665  tcoeff_perp_polparl = tcoeff_parl_polparl = 0.;
2666  tcoeff_perp_polperp = tcoeff_parl_polperp = 0.;
2667  pos_projectedImpactPoint = panel1->GetPosition(ii, jj); // this gets the new screen position
2668  vec_pos_current_to_balloon = Vector( bn1->r_bn[0] - pos_projectedImpactPoint[0], bn1->r_bn[1] - pos_projectedImpactPoint[1], bn1->r_bn[2] - pos_projectedImpactPoint[2] );
2669 
2670  // local angles of transmission and incidence in their respective planes
2671  vec_localnormal = antarctica->GetSurfaceNormal(pos_projectedImpactPoint).Unit();
2672  if (settings1->SLOPEY) {
2673  slopeyx=ray1->slopeyx;
2674  slopeyy=ray1->slopeyy;
2675  slopeyz=ray1->slopeyz;
2676  ntemp2 = vec_localnormal + slopeyx*xaxis + slopeyy*yaxis + slopeyz*zaxis;
2677  ntemp2 = ntemp2 / ntemp2.Mag();
2678  rtemp= ntemp2 * vec_localnormal;
2679  if (rtemp<=1) {
2680  vec_localnormal = ntemp2;
2681  }//if
2682  }//end local slopeyness
2683 //cerr<<inu<<" "<<pos_projectedImpactPoint<<endl;
2684  vec_nnu_to_impactPoint = Vector( pos_projectedImpactPoint[0]-interaction1->posnu[0], pos_projectedImpactPoint[1]-interaction1->posnu[1], pos_projectedImpactPoint[2]-interaction1->posnu[2] ).Unit();
2685 
2686  vec_grndcomp2IP = (vec_nnu_to_impactPoint - (vec_nnu_to_impactPoint.Dot(vec_localnormal)*vec_localnormal)).Unit();
2687  vec_grndcomp2bln = (vec_pos_current_to_balloon - (vec_pos_current_to_balloon.Dot(vec_localnormal)*vec_localnormal)).Unit();
2688  temp_a = vec_localnormal.Cross(vec_pos_current_to_balloon).Unit();
2689  azimuth_local = vec_grndcomp2IP.Angle(vec_grndcomp2bln); //[rad]
2690  if( temp_a.Dot(vec_nnu_to_impactPoint) < 0 )
2691  azimuth_local *= -1.;
2692  if( panel1->GetCentralPoint().Distance(pos_projectedImpactPoint)<0.75*grd_stepsize ){
2693  azimuth_local = 0.;
2694  }
2695 //cerr<<inu<<": "<<jj<<" "<<vec_grndcomp2IP<<" : "<<vec_grndcomp2bln<<" : "<<azimuth_local*180./PI<<endl;
2696  theta_local = vec_localnormal.Angle( (const Vector)vec_pos_current_to_balloon ); //[rad]
2697  theta_0_local = vec_localnormal.Angle(vec_nnu_to_impactPoint); //[rad]
2698 //cerr<<inu<<" "<<ii<<" "<<jj<<"; "<<panel1->GetCentralPoint()<<" : "<< pos_projectedImpactPoint<<" : "<<theta_local*180./PI<<" "<<theta_0_local*180./PI<<" "<< azimuth_local*180./PI<< endl;
2699 //cerr<< panel1->GetCentralPoint() - pos_projectedImpactPoint<<endl;
2700  if( isnan(theta_local) | isnan(theta_0_local) | isnan(azimuth_local) ){
2701  continue;
2702  }
2703  viewangle_local = GetViewAngle(vec_nnu_to_impactPoint, interaction1->nnu);
2704 
2705  // at this point, only figure out if taper will kill the geometry, but don't actually apply the factor
2706  deltheta_em[0]=deltheta_em_max*anita1->FREQ_LOW/anita1->freq[0];
2707  deltheta_had[0]=deltheta_had_max*anita1->FREQ_LOW/anita1->freq[0];
2708  sig1->TaperVmMHz(viewangle_local, deltheta_em[0], deltheta_had[0], emfrac, hadfrac, taperfactor, vmmhz_em[0]);// this applies the angular dependence.
2709  if(taperfactor==0)
2710  {
2711  continue;
2712  }
2713 //cerr<<inu<< ": past E=0"<<endl;
2715  // Field Magnitude
2716  #ifdef USE_HEALPIX
2717  if (settings1->FIRN)
2718  rough1->InterpolatePowerValue(power_perp_polperp, power_parl_polperp, power_perp_polparl, power_parl_polparl, theta_0_local*180./PI, theta_local*180./PI, azimuth_local *180./PI);
2719  else
2720  rough1->InterpolatePowerValue(power_perp_polperp, power_parl_polperp, power_perp_polparl, power_parl_polparl, theta_0_local*180./PI, theta_local*180./PI, azimuth_local *180./PI);
2721  #endif
2722 //cerr<<"P: "<<power_perp<<" "<<power_parl<<std::endl;
2723  if( (power_perp_polperp==0.)&(power_parl_polperp==0.)&(power_perp_polparl==0.)&(power_parl_polparl==0.) ){
2724  continue;
2725  }
2726 //cerr<<"survived power cut"<<endl;
2727  if (settings1->FIRN){
2728  tcoeff_perp_polparl = sqrt(power_perp_polparl);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2729  tcoeff_parl_polparl = sqrt(power_parl_polparl);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2730  tcoeff_perp_polperp = sqrt(power_perp_polperp);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2731  tcoeff_parl_polperp = sqrt(power_parl_polperp);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2732  }
2733  else{
2734  tcoeff_perp_polparl = sqrt(power_perp_polparl);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2735  tcoeff_parl_polparl = sqrt(power_parl_polparl);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2736  tcoeff_perp_polperp = sqrt(power_perp_polperp);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2737  tcoeff_parl_polperp = sqrt(power_parl_polperp);//*NFIRN*cos(theta_0_local)*cos(theta_local));
2738  }
2739  //
2740 //cerr<<"T: "<<tcoeff_perp<<" "<<tcoeff_parl<<std::endl;
2741 //cerr<<"T (spec): "<<t_coeff_slappy<<" "<<t_coeff_pokey<<std::endl;
2742  //Emag_local *= sqrt((tcoeff_perp*tcoeff_perp + tcoeff_parl*tcoeff_parl)) * mag_r;// * (antennalength*antennalength/(vec_pos_current_to_balloon.Mag()*vec_pos_current_to_balloon.Mag()))/HP_64_binarea);
2743 //cerr<<"E: "<<Emag_local<<std::endl;
2744  // account for 1/r for 1)interaction point to impact point and 2)impact point to balloon, and attenuation in ice
2745  pathlength_local = interaction1->posnu.Distance(pos_projectedImpactPoint) + pos_projectedImpactPoint.Distance(bn1->r_bn);
2746 //cerr<<"P: "<<pathlength_local<<std::endl;
2747  Emag_local /= pathlength_local ;
2748 //cerr<<"E: "<<Emag_local<<std::endl;
2749  Attenuate(antarctica, settings1, Emag_local, interaction1->posnu.Distance(pos_projectedImpactPoint), interaction1->posnu);
2750 //cerr<<"E: "<<Emag_local<<std::endl;
2752  // Incident and Transmitted Polarizations
2753  // set incident polarization
2754  npol_local_inc = GetPolarization(interaction1->nnu, vec_nnu_to_impactPoint).Unit();
2755  vec_inc_perp = (vec_localnormal.Cross(vec_nnu_to_impactPoint)).Unit();
2756  vec_inc_parl = (vec_nnu_to_impactPoint.Cross(vec_inc_perp)).Unit();
2757  pol_perp_inc = npol_local_inc * vec_inc_perp;
2758  pol_parl_inc = npol_local_inc * vec_inc_parl;
2759  //
2760  pol_perp_trans = pol_perp_inc * tcoeff_perp_polperp + pol_perp_inc * tcoeff_perp_polparl;
2761  pol_parl_trans = pol_parl_inc * tcoeff_parl_polparl + pol_parl_inc * tcoeff_parl_polperp;
2762  //
2763  vec_local_grnd_perp = (vec_localnormal.Cross(vec_pos_current_to_balloon)).Unit();
2764  vec_local_grnd_parl = (vec_pos_current_to_balloon.Cross(vec_local_grnd_perp)).Unit();
2765  //
2766  // set transmitted polarization
2767  npol_local_trans= (pol_perp_trans*vec_local_grnd_perp + pol_parl_trans*vec_local_grnd_parl).Unit();
2768 //cerr<<inu<<": v_nu "<<interaction1->nnu<<" : 2IP "<<vec_nnu_to_impactPoint<<" : npol "<<npol_local_trans<< endl;
2769  // check if transmitted polarization is undefined
2770  if( isnan(npol_local_trans[0]) ){
2771  continue;
2772  }
2773 //cerr<<"past pol cut"<<endl;
2774  //
2775  fresnel_r = sqrt( pow(vmmhz1m_max*pol_perp_trans,2) + pow(vmmhz1m_max*pol_parl_trans,2) ) / vmmhz1m_max;
2776  mag_r = sqrt( tan(theta_0_local) / tan(theta_local) );
2777  Emag_local *= fresnel_r * mag_r;
2778 //cerr<<"E: "<<Emag_local<<std::endl;
2779  if (settings1->FIRN)
2780  time_reference_local = (interaction1->posnu.Distance(pos_projectedImpactPoint)*NFIRN / CLIGHT) + (pos_projectedImpactPoint.Distance(bn1->r_bn)/CLIGHT);
2781  else
2782  time_reference_local = (interaction1->posnu.Distance(pos_projectedImpactPoint)*NICE / CLIGHT) + (pos_projectedImpactPoint.Distance(bn1->r_bn)/CLIGHT);
2783  // increment counter so we can track the size of the screen's vector arrays
2784  num_validscreenpoints++;
2785 
2786  //add the contribution to the running total
2787  panel1->AddVmmhz0(Emag_local); // pre-taper Efield
2788  panel1->AddVec2bln(vec_pos_current_to_balloon);
2789  panel1->AddPol(npol_local_trans);
2790  panel1->AddDelay( time_reference_specular - time_reference_local );
2791  panel1->AddImpactPt(pos_projectedImpactPoint);
2792  panel1->AddViewangle(viewangle_local);
2793  panel1->AddIncidenceAngle(theta_0_local);
2794  panel1->AddTransmissionAngle(theta_local);
2795  panel1->AddWeight( (panel1->GetEdgeLength() / panel1->GetNsamples()) * (panel1->GetEdgeLength() / panel1->GetNsamples()) );
2796  panel1->AddFacetLength(panel1->GetEdgeLength() / panel1->GetNsamples());
2797  panel1->AddTparallel_polParallel(tcoeff_parl_polparl);
2798  panel1->AddTperpendicular_polParallel(tcoeff_perp_polparl);
2799  panel1->AddTparallel_polPerpendicular(tcoeff_parl_polperp);
2800  panel1->AddTperpendicular_polPerpendicular(tcoeff_perp_polperp);
2801  //
2802  //cerr<<pos_current<<" "
2803  //<<Emag_local<<" "
2804  //<<npol_local_trans<<" "
2805  //<<(pathlength_specular-pathlength_local) / CLIGHT<<" "
2806  //<<pos_projectedImpactPoint<<" "
2807  //<<viewangle_local<<std::endl;
2808  }// end for jj
2809  }// end for ii
2810 
2811  panel1->SetNvalidPoints(num_validscreenpoints);
2812  //now construct the Screen's vmmhz array for all points, so it gets passed to the trigger object later to make the waveforms
2813  // here we get the array vmmhz by taking vmmhz1m_max (signal at lowest frequency bin) and vmmhz_max (signal at lowest frequency after applying 1/r factor and attenuation factor) and making an array across frequency bins by putting in frequency dependence.
2814  double validScreenSummedArea = 0.;
2815  double vmmhz_local_array[Anita::NFREQ];
2816  for (int jj=0; jj<panel1->GetNvalidPoints(); jj++){
2817  // fill the frequency array vmmhz_local_array
2818  sig1->GetVmMHz(panel1->GetVmmhz0(jj), vmmhz1m_max, pnu, anita1->freq, anita1->NOTCH_MIN, anita1->NOTCH_MAX, vmmhz_local_array, Anita::NFREQ);
2819  // apply the off-angle tapering
2820  for (int k=0;k<Anita::NFREQ;k++) {
2821  deltheta_em[k]=deltheta_em_max*anita1->FREQ_LOW/anita1->freq[k];
2822  deltheta_had[k]=deltheta_had_max*anita1->FREQ_LOW/anita1->freq[k];
2823  sig1->TaperVmMHz(panel1->GetViewangle(jj), deltheta_em[k], deltheta_had[k], emfrac, hadfrac, vmmhz_local_array[k], vmmhz_em[k]);// this applies the angular dependence.
2824  panel1->AddVmmhz_freq(vmmhz_local_array[k]);
2825  }
2826 
2827  validScreenSummedArea += panel1->GetWeight(jj);
2828  }//end jj over panel Nvalid points
2829  panel1->SetWeightNorm(validScreenSummedArea);
2830  vmmhz_max = 0.;
2831  for(int jj=0; jj<panel1->GetNvalidPoints(); jj++){
2832  vmmhz_max = Tools::dMax(vmmhz_max, panel1->GetVmmhz_freq(jj*Anita::NFREQ));
2833  }
2834  }//end else roughness
2835  // the screen is now finished
2837 
2838  if( settings1->ROUGHNESS && !panel1->GetNvalidPoints() ){
2839  DO_SKIP
2840  }
2841 
2842  // reject if the event is undetectable.
2843  // THIS ONLY CHECKS IF ROUGHNESS == 0, WE WILL SKIP THIS IF THERE IS ROUGHNESS
2844  // if (!settings1->ROUGHNESS){
2845  if(settings1->CHANCEINHELL_FACTOR*vmmhz1m_fresneledtwice*heff_max*0.5*(anita1->bwmin/1.E6)<anita1->maxthreshold*anita1->VNOISE[0]/10.&& !settings1->SKIPCUTS) {
2846  if (bn1->WHICHPATH==3)
2847  cout<<"Event is undetectable. Leaving loop."<<endl;
2848 
2849  DO_SKIP
2850  }
2851  count1->nchanceinhell_fresnel[whichray]++;
2852  // } //end if CHANCEINHELL factor and SKIPCUTS
2853 
2854 
2855  // for plotting
2856  diffexit=ray1->rfexit[0].Distance(ray1->rfexit[1]);
2857  diffnorm=acos(ray1->nsurf_rfexit[0]*ray1->nsurf_rfexit[1]);
2858  diffrefr=acos(ray1->nrf_iceside[4]*ray1->nrf_iceside[0]);
2859 
2860  // scale by 1/r once you've found the 3rd iteration exit point
2861  // ALREADY DEALT WITH IN CASE OF ROUGHNESS
2862  if (!settings1->ROUGHNESS) {
2863  //cout << "Oindree: vmmhz1m_fresneledtwice " << vmmhz1m_fresneledtwice << "\n";
2864  //oindree_file << vmmhz1m_fresneledtwice << "\n";
2865  if (whichray==0)
2866  vmmhz_max=ScaleVmMHz(vmmhz1m_fresneledtwice, interaction1->posnu, bn1->r_bn, ray1->rfexit[2]);
2867  if (whichray==1)
2868  vmmhz_max=ScaleVmMHz(vmmhz1m_fresneledtwice, interaction1->posnu_down, bn1->r_bn, ray1->rfexit[2]);//use the mirror point
2869  }
2870 
2871 
2872  //cout << "Oindree: ray1->rfexit[2] " << ray1->rfexit[2] << "\n";
2873  //cout << "Oindree: bn1->r_bn " << bn1->r_bn << "\n";
2874  //oindree_file << whichray << " " << vmmhz1m_fresneledtwice << " " << vmmhz_max << " " << interaction1->posnu[0] << " " << interaction1->posnu[1] << " " << interaction1->posnu[2] << " " << bn1->r_bn[0] << " " << bn1->r_bn[1] << " " << bn1->r_bn[2] << " " << ray1->rfexit[2][0] << " " << ray1->rfexit[2][1] << " " << ray1->rfexit[2][2] << "\n";
2875 
2876  // reject if the event is undetectable.
2877  if (!settings1->ROUGHNESS){
2878  if (settings1->CHANCEINHELL_FACTOR*vmmhz_max*heff_max*0.5*(anita1->bwmin/1.E6)<anita1->maxthreshold*anita1->VNOISE[0]/10. && !settings1->SKIPCUTS) {
2879  if (bn1->WHICHPATH==3)
2880  cout<<"Event is undetectable. Leaving loop."<<endl;
2881  //
2882  DO_SKIP
2883  } //if
2884  }
2885  count1->nchanceinhell_1overr[whichray]++;
2886 
2887  // distance ray travels through ice.
2888  if (!settings1->ROUGHNESS) {
2889  if (whichray==0) {
2890  rflength=interaction1->posnu.Distance(ray1->rfexit[2]);
2891  }
2892  if (whichray==1) {
2893  rflength=interaction1->posnu_down.Distance(ray1->rfexit[2]);//use the real distance that singals pass
2894  }
2895  }
2896 
2897  if (bn1->WHICHPATH==4)
2898  cout << "rflength is " << rflength << "\n";
2899 
2900  // applying ice attenuation factor
2901  if (!settings1->ROUGHNESS) {
2902  if (whichray==0)
2903  Attenuate(antarctica, settings1, vmmhz_max, rflength, interaction1->posnu);
2904  if (whichray==1)
2905  Attenuate_down(antarctica, settings1, vmmhz_max, ray1->rfexit[2], interaction1->posnu, interaction1->posnu_down);
2906  }
2907 
2908  //oindree_file << vmmhz1m_fresneledtwice << " " << vmmhz_max << "\n";
2909 
2910  // roughness attenuation already dealt with
2911  // fill for just 1/10 of the events.
2912  if (tree2->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1 && bn1->WHICHPATH != 3)
2913  tree2->Fill();
2914 
2915  // intermediate counting
2916  count_dbexitsice++;
2917 
2918  // reject if the event is undetectable.
2919  if (!settings1->ROUGHNESS){
2920  if (settings1->CHANCEINHELL_FACTOR*vmmhz_max*heff_max*0.5*(anita1->bwmin/1.E6)<anita1->maxthreshold*anita1->VNOISE[0]/10. && !settings1->SKIPCUTS) {
2921  if (bn1->WHICHPATH==3)
2922  cout<<"Event is undetectable. Leaving loop."<<endl;
2923  //
2924  DO_SKIP;
2925  } //if
2926  }
2927 
2928  count1->nchanceinhell[whichray]++;
2929 
2930  // for plotting
2931  if (tree3->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1 && bn1->WHICHPATH != 3)
2932  tree3->Fill();
2933 
2934  // index for each antenna so you can use it to fill arrays
2935  count_rx=0;
2936  // keeps track of maximum voltage seen on either polarization of any antenna
2937  volts_rx_max=0;
2938 
2939  // Make a vector of V/m/MHz scaled by 1/r and attenuated.
2940  // Calculates Jaime's V/m/MHz at 1 m for each frequency
2941  // then multiplies by scale factor vmmhz_max/vmmhz1m_max
2942  // this will need to be improved once frequency-dependent
2943  // attenuation length is included.
2944  if (!settings1->ROUGHNESS){
2945  if (settings1->FORSECKEL==1)
2946  sig1->SetNDepth(sig1->NICE); // for making array of signal vs. frequency, viewangle
2947 
2948  sig1->GetVmMHz(vmmhz_max, vmmhz1m_max, pnu, anita1->freq, anita1->NOTCH_MIN, anita1->NOTCH_MAX, vmmhz, Anita::NFREQ); // here we get the array vmmhz by taking vmmhz1m_max (signal at lowest frequency bin) and
2949  // vmmhz_max (signal at lowest frequency after applying 1/r factor and attenuation factor)
2950  // and making an array across frequency bins by putting in frequency dependence.
2951  }
2952 
2953  // For each frequency, get the width of Cerenkov cone
2954  // and size of signal once position of viewing angle is taken into account
2955 
2956  // these variables are for energy reconstruction studies
2957 
2958  undogaintoheight_e=0;
2959  undogaintoheight_h=0;
2960 
2961  for (int k=0;k<4;k++) {
2962  undogaintoheight_e_array[k]=0.;
2963  undogaintoheight_h_array[k]=0.;
2964  nbins_array[k]=0;
2965  true_efield_array[k]=0.;
2966  rec_efield_array[k]=0.;
2967  }
2968 
2969  rec_efield=0;
2970  true_efield=0;
2971 
2972 
2973  if (!settings1->ROUGHNESS){
2974  // don't loop over frequencies if the viewing angle is too far off
2975  double rtemp=Tools::dMin((viewangle-sig1->changle)/(deltheta_em_max), (viewangle-sig1->changle)/(deltheta_had_max));
2976  if (rtemp>Signal::VIEWANGLE_CUT && !settings1->SKIPCUTS) {
2977  //delete interaction1;
2978  DO_SKIP
2979  }
2980  count1->nviewanglecut[whichray]++;
2981 
2982  //oindree_file << Tools::dMax(vmmhz, Anita::NFREQ) << "\n";
2983 
2985  for (int k=0;k<Anita::NFREQ;k++) {
2986  deltheta_em[k]=deltheta_em_max*anita1->FREQ_LOW/anita1->freq[k];
2987  deltheta_had[k]=deltheta_had_max*anita1->FREQ_LOW/anita1->freq[k];
2988 
2989  if (settings1->FORSECKEL==1) {// this is for making plots of the signal
2990  for (int iviewangle=0;iviewangle<NVIEWANGLE;iviewangle++) {// loop over viewing angles
2991  // remove the 1/r and attenuation factors that are contained in the ratio vmmhz1m_max/vmmhz_max
2992  vmmhz_temp=vmmhz[k]*vmmhz1m_max/vmmhz_max;
2993 
2994  viewangle_temp=viewangles[iviewangle]; //grab the viewing angle from this array
2995  //apply the gaussian dependence away from the cerenkov angle. vmmhz_temp is both an input and an output.
2996  //vmmhz_temp as an output is the signal with the angular dependence applied.
2997  sig1->TaperVmMHz(viewangle_temp, deltheta_em[k], deltheta_had[k], emfrac, hadfrac, vmmhz_temp, djunk);
2998  forseckel[iviewangle][k]=vmmhz_temp;// put this in an array which we will plot later.
2999  } //for (loop over viewing angles)
3000  } //if (settings1->FORSECKEL==1)
3001 
3002  //if (k == (Anita::NFREQ - 1) ) {
3003  //oindree_file << weight1 << " " << pnu << " " << viewangle << " " << deltheta_em[k] << " " << deltheta_had[k] << " " << emfrac << " " << hadfrac << " " << vmmhz[k] << " " << vmmhz_em[k] << "\n";
3004  //}
3005 
3007  sig1->TaperVmMHz(viewangle, deltheta_em[k], deltheta_had[k], emfrac, hadfrac, vmmhz[k], vmmhz_em[k]);// this applies the angular dependence.
3008  // viewangle is which viewing angle we are at
3009  // deltheta_em is the width of the em component at this frequency
3010  // deltheta_had is the width of the had component at this frequency
3011  // emfrac is the em fraction of the shower
3012  // hadfrac is the hadronic fraction of the shower
3013  // vmmhz is the strength of the signal in V/m/MHz at this viewing angle
3014  // vmmhz_em is the strength of the em component
3015 
3016  vmmhz_lowfreq=vmmhz[0]; // for plotting, vmmhz at the lowest frequency
3017 
3018  // just want to see the maximum effect of viewing angle being off cerenkov cone
3019  // should be at highest frequency
3020  // just for plotting
3021  maxtaper=-1000;
3022  if (sig1->logscalefactor_taper>maxtaper)
3023  maxtaper=sig1->logscalefactor_taper;
3024 
3025  if (interaction1->nuflavor=="nue") pdgcode = 12;
3026  else if (interaction1->nuflavor=="numu") pdgcode = 14;
3027  else if (interaction1->nuflavor=="nutau") pdgcode = 16;
3028 
3029  if (settings1->HIST==1 && !settings1->ONLYFINAL && bn1->WHICHPATH != 3 && k==Anita::NFREQ/2 && tree18->GetEntries()<settings1->HIST_MAX_ENTRIES) {
3030 
3031  tree18->Fill();
3032  }
3033 
3034  if (bn1->WHICHPATH == 3)
3035  interaction1->banana_volts += vmmhz[k]*(settings1->BW/(double)Anita::NFREQ/1.E6);
3036 
3037  }//end for (int k=0;k<Anita::NFREQ;k++)
3039 
3040  //oindree_file << Tools::dMax(vmmhz, Anita::NFREQ) << "\n";
3041 
3042 
3043  if (bn1->WHICHPATH==3 && interaction1->banana_volts != 0 && settings1->HIST && banana_tree->GetEntries()<settings1->HIST_MAX_ENTRIES) {
3044  banana_tree->Fill();
3045  DO_SKIP
3046  } //This is all the data needed for the banana plot - we now have the final value of vmmhz[]
3047  else if (bn1->WHICHPATH==3 && interaction1->banana_volts == 0) {
3048  DO_SKIP //Exit the loop if there's no voltage here - no value at a point is the same as zero, and this will save HD space
3049  }
3050  // reject if it is undetectable now that we have accounted for viewing angle
3051 
3052  //cout << "nviewanglecut " << (double)count1->nviewanglecut[0] << " nchanceinhell2 " << count1->nchanceinhell2[0] << "\n";
3053  //oindree_file << (double)count1->nviewanglecut[0] << " " << count1->nchanceinhell2[0] << "\n";
3054 
3055  //oindree_file << weight1 << " " << pnu << " " << (settings1->CHANCEINHELL_FACTOR*Tools::dMax(vmmhz, Anita::NFREQ)*heff_max*0.5*(anita1->bwmin/1.E6)) << " " << anita1->maxthreshold*anita1->VNOISE[0]/10. << " " << settings1->SKIPCUTS << "\n";
3056 
3057  //oindree_file << weight1 << " " << pnu << " " << settings1->CHANCEINHELL_FACTOR << " " << Tools::dMax(vmmhz,Anita::NFREQ) << " " << 0.5*heff_max << " " << anita1->bwmin/1.E6 << "\n";
3058 
3059  if (settings1->CHANCEINHELL_FACTOR*Tools::dMax(vmmhz, Anita::NFREQ)*heff_max*0.5*(anita1->bwmin/1.E6) < anita1->maxthreshold*anita1->VNOISE[0]/10. && !settings1->SKIPCUTS) {
3060  //if (settings1->CHANCEINHELL_FACTOR*Tools::dMax(vmmhz, Anita::NFREQ)*heff_max*0.5*(anita1->bwmin/1.E6) < anita1->maxthreshold*anita1->VNOISE[0]/10.) {
3061  //cout << "chance fail" << "\n";
3062  DO_SKIP
3063  }
3064  }//end if roughness==0 before the Anita::NFREQ k loop, this isolates the TaperVmMHz()
3065 
3066 
3067  // just for plotting
3068  if(!settings1->ROUGHNESS){
3069  vmmhz_max=Tools::dMax(vmmhz, Anita::NFREQ);
3070  vmmhz_min=Tools::dMin(vmmhz, Anita::NFREQ);
3071  }
3072  // intermediate counting
3073  count1->nchanceinhell2[whichray]++;
3074  chanceinhell2=1;
3075 
3076  //cout << "count chance " << count1->nchanceinhell2[whichray] << "\n";
3077 
3078  isDead = false;
3079  // Dead time
3080  if (settings1->USEDEADTIME){
3081  if ( (getRNG(RNG_DEADTIME)->Uniform(1)<anita1->deadTime) ){
3082  isDead = true;
3083  if (settings1->MINBIAS!=1) {
3084  DO_SKIP
3085  }
3086  }
3087  }
3088 
3089  count1->ndeadtime[whichray]++;
3090 
3091  Tools::Zero(sumsignal_aftertaper, 5);
3092 
3093  // // Create a pointer to the SimulatedSignal
3094  // SimulatedSignal *simSignal = new SimulatedSignal();
3095  // // Define the SimSignal from vmmhz
3096  // simSignal->updateSimSignalFromVmmhz(Anita::NFREQ, anita1->freq, vmmhz);
3097  // simSignal->addCW(250E6, 0, 0.01);
3098  // simSignal->getVmmhz(anita1, vmmhz);
3099  // delete simSignal;
3100 
3101  //if no-roughness case, add its parameters to the saved screen parameters so specular and roughness simulations use the same code in the waveform construction
3102  if(!settings1->ROUGHNESS){
3103  panel1->SetNvalidPoints(1);
3104  for (int k=0;k<Anita::NFREQ;k++) {
3105  //cout << anita1->freq[k] << " " << vmmhz[k] << " " << vmmhz2[k] << " " << vmmhz[k]/vmmhz2[k] << endl;
3106  panel1->AddVmmhz_freq(vmmhz[k]);
3107  }
3108  panel1->AddVmmhz0(vmmhz[0]);
3109  panel1->AddVec2bln(ray1->n_exit2bn[2]);
3110  panel1->AddPol(n_pol);
3111  panel1->AddDelay( 0. );
3112  panel1->AddImpactPt(ray1->rfexit[2]);
3113  panel1->AddViewangle(viewangle);
3114  if(settings1->FIRN){
3115  panel1->AddIncidenceAngle(ray1->nsurf_rfexit.Angle(ray1->nrf_iceside[3]));
3116  }
3117  else{
3118  panel1->AddIncidenceAngle(ray1->nsurf_rfexit.Angle(ray1->nrf_iceside[4]));
3119  }
3120  panel1->AddTransmissionAngle(ray1->nsurf_rfexit.Angle(ray1->n_exit2bn[2]));
3121  panel1->AddWeight( 1. );
3122  panel1->SetWeightNorm( 1. );
3123  panel1->AddFacetLength( 1. );
3124  panel1->AddTparallel_polParallel(t_coeff_pokey);
3125  panel1->AddTperpendicular_polPerpendicular(t_coeff_slappy);
3126 
3127  panel1->AddTparallel_polPerpendicular(0.);
3128  panel1->AddTperpendicular_polParallel(0.);
3129 
3130  for (int k=0;k<Anita::NFREQ;k++) {
3131  if (bn1->WHICHPATH==4)
3132  IntegrateBands(anita1, k, panel1, anita1->freq, vmmhz1m_max/(vmmhz_max*1.E6), sumsignal_aftertaper);
3133  }
3134  }
3135 
3136  // make a global trigger object (but don't touch the electric fences)
3137  globaltrig1 = new GlobalTrigger(settings1, anita1);
3138 
3139  Tools::Zero(anita1->arrival_times[0], Anita::NLAYERS_MAX*Anita::NPHI_MAX);
3140  Tools::Zero(anita1->arrival_times[1], Anita::NLAYERS_MAX*Anita::NPHI_MAX);
3141  if (!settings1->TRIGGEREFFSCAN){
3142  if(settings1->BORESIGHTS)
3143  anita1->GetArrivalTimesBoresights(ray1->n_exit2bn_eachboresight[2]);
3144  else
3145  anita1->GetArrivalTimes(ray1->n_exit2bn[2],bn1,settings1);
3146  }
3147  anita1->rx_minarrivaltime=Tools::WhichIsMin(anita1->arrival_times[0], settings1->NANTENNAS);
3148 
3149  //Zeroing
3150  for (int i=0;i<settings1->NANTENNAS;i++) {
3151  voltagearray[i]=0;
3152  discones_passing=0;
3153  } //Zero the trigger array
3154 
3155  max_antenna0=-1;
3156  max_antenna1=-1;
3157  max_antenna2=-1;
3158  max_antenna_volts0 =0;
3159  max_antenna_volts1 =0;
3160  max_antenna_volts2 =0;
3161  e_comp_max1 = 0;
3162  h_comp_max1 = 0;
3163  e_comp_max2 = 0;
3164  h_comp_max2 = 0;
3165  e_comp_max3 = 0;
3166  h_comp_max3 = 0;
3167  //End zeroing
3168 
3169 
3170  // start looping over antennnas.
3171  // ilayer loops through vertical layers
3172 
3173  if (settings1->SLAC)
3174  fslac_hitangles << bn1->sslacpositions[bn1->islacposition] << "\n";
3175 
3176  if (RANDOMISEPOL) {
3177  double rotateangle=getRNG(RNG_RANDOMISE_POL)->Gaus(RANDOMISEPOL*RADDEG);
3178  n_pol=n_pol.Rotate(rotateangle, ray1->n_exit2bn[2]);
3179  }
3180 
3181  if (bn1->WHICHPATH==4) {
3182  Tools::Zero(sumsignal, 5);
3183  for (int k=0;k<Anita::NFREQ;k++)
3184  IntegrateBands(anita1, k, panel1, anita1->freq, bn1->r_bn.Distance(interaction1->posnu)/1.E6, sumsignal);
3185  }//end if whichpath==4
3186 
3187  if (settings1->CENTER){
3188  bn1->CenterPayload(hitangle_e);
3189  }
3190 
3191  if (settings1->MAKEVERTICAL) {
3192  n_pol=bn1->n_bn;
3193  // rotate n_exit2bn too
3194  // rotation axis n_bn crossed with n_exit2bn
3195  Vector rotationaxis=ray1->n_exit2bn[2].Cross(bn1->n_bn);
3196  double rotateangle=PI/2.-ray1->n_exit2bn[2].Dot(bn1->n_bn);
3197  ray1->n_exit2bn[2]=ray1->n_exit2bn[2].Rotate(rotateangle, rotationaxis);
3198 
3199  for (int ilayer=0; ilayer < settings1->NLAYERS; ilayer++) { // loop over layers on the payload
3200  // ifold loops over phi
3201  for (int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) {
3202  Vector rotationaxis2=ray1->n_exit2bn_eachboresight[2][ilayer][ifold].Cross(n_pol_eachboresight[ilayer][ifold]);
3203  double rotateangle2=PI/2.-ray1->n_exit2bn_eachboresight[2][ilayer][ifold].Dot(n_pol_eachboresight[ilayer][ifold]);
3204  ray1->n_exit2bn_eachboresight[2][ilayer][ifold].Rotate(rotateangle2, rotationaxis2);
3205  } // end loop over phi
3206  } // end loop over layers
3207  }//end if ray1->makevertical
3208 
3209  globaltrig1->volts_rx_rfcm_trigger.assign(16, vector <vector <double> >(3, vector <double>(0)));
3210  anita1->rms_rfcm_e_single_event = 0;
3211 
3212  if (!settings1->BORESIGHTS) {
3213  bn1->GetEcompHcompkvector(n_eplane, n_hplane, n_normal, ray1->n_exit2bn[2], e_component_kvector[0], h_component_kvector[0], n_component_kvector[0]);
3214  bn1->GetEcompHcompEvector(settings1, n_eplane, n_hplane, n_pol, e_component[0], h_component[0], n_component[0]);
3215  }
3216 
3217  for (int ilayer=0; ilayer < settings1->NLAYERS; ilayer++) { // loop over layers on the payload
3218  for (int ifold=0;ifold<anita1->NRX_PHI[ilayer];ifold++) { // ifold loops over phi
3219 
3220  ChanTrigger *chantrig1 = new ChanTrigger();
3221  chantrig1->InitializeEachBand(anita1);
3222 
3223  bn1->GetAntennaOrientation(settings1, anita1, ilayer, ifold, n_eplane, n_hplane, n_normal);
3224 
3225  if (settings1->BORESIGHTS){ // i.e. if BORESIGHTS is true
3226  bn1->GetEcompHcompkvector(n_eplane, n_hplane, n_normal, ray1->n_exit2bn_eachboresight[2][ilayer][ifold], e_component_kvector[count_rx], h_component_kvector[count_rx], n_component_kvector[count_rx]);
3227  bn1->GetEcompHcompEvector(settings1, n_eplane, n_hplane, n_pol_eachboresight[ilayer][ifold], e_component[count_rx], h_component[count_rx], n_component[count_rx]);
3228  if (settings1->SLAC) fslac_hitangles << ilayer << "\t" << ifold << "\t" << hitangle_e << "\t" << hitangle_h << "\t" << e_component_kvector << "\t" << h_component_kvector << "\t" << fresnel1_eachboresight[ilayer][ifold] << " " << mag1_eachboresight[ilayer][ifold] << "\n";
3229  }
3230  else if (count_rx > 0)
3231  {
3232  e_component_kvector[count_rx] = e_component_kvector[0];
3233  h_component_kvector[count_rx] = h_component_kvector[0];
3234  n_component_kvector[count_rx] = n_component_kvector[0];
3235  e_component[count_rx] = e_component[0];
3236  h_component[count_rx] = h_component[0];
3237  n_component[count_rx] = n_component[0];
3238  }
3239 
3240  bn1->GetHitAngles(e_component_kvector[count_rx], h_component_kvector[count_rx], n_component_kvector[count_rx], hitangle_e, hitangle_h);
3241  // store hitangles for plotting
3242  hitangle_h_all[count_rx]=hitangle_h;
3243  hitangle_e_all[count_rx]=hitangle_e;
3244  // for debugging
3245  if (h6->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
3246  h6->Fill(hitangle_h, ray1->n_exit2bn[2]*bn1->n_bn);
3247 
3248  antNum = anita1->GetRxTriggerNumbering(ilayer, ifold);
3249 
3250  chantrig1->ApplyAntennaGain(settings1, anita1, bn1, panel1, antNum, n_eplane, n_hplane, n_normal);
3251 
3252  chantrig1->TriggerPath(settings1, anita1, antNum, bn1);
3253 
3255  //if(settings1->ROUGHNESS){
3256 /* if(vmmhz_max>0.){
3257  std::string stemp=string(outputdir.Data())+"/rough_signalwaveforms_"+nunum+".dat";
3258  ofstream sigout(stemp.c_str(), ios::app);
3259  for (int iband=0;iband<5;iband++) {
3260  if (anita1->bwslice_allowed[iband]!=1) continue;
3261  for (int k=0;k<anita1->NFOUR/2;k++) {
3262  sigout << ilayer << " "
3263  << ifold << " "
3264  << iband << " "
3265  << k << " "
3266  << chantrig1->v_banding_rfcm_forfft[0][iband][k]<< " "
3267  << chantrig1->v_banding_rfcm_forfft[1][iband][k]<< " "
3268  << chantrig1->volts_rx_forfft[0][iband][k]<< " "
3269  << chantrig1->volts_rx_forfft[1][iband][k]<< " "
3270  << std::endl;
3271  }
3272  }
3273  sigout.close();
3274  }
3275  //}
3277 */
3278  chantrig1->DigitizerPath(settings1, anita1, antNum, bn1);
3279 
3280  chantrig1->TimeShiftAndSignalFluct(settings1, anita1, ilayer, ifold, volts_rx_rfcm_lab_e_all, volts_rx_rfcm_lab_h_all);
3281 
3282  chantrig1->saveTriggerWaveforms(anita1, justSignal_trig[0][antNum], justSignal_trig[1][antNum], justNoise_trig[0][antNum], justNoise_trig[1][antNum]);
3283  chantrig1->saveDigitizerWaveforms(anita1, justSignal_dig[0][antNum], justSignal_dig[1][antNum], justNoise_dig[0][antNum], justNoise_dig[1][antNum]);
3284 
3285  Tools::Zero(sumsignal, 5);
3286 
3287  if (bn1->WHICHPATH==4 && ilayer==anita1->GetLayer(anita1->rx_minarrivaltime) && ifold==anita1->GetIfold(anita1->rx_minarrivaltime)) {
3288  for (int ibw=0;ibw<5;ibw++) {
3289  cout << "Just after Taper, sumsignal is " << sumsignal_aftertaper[ibw] << "\n";
3290  cout << "Just after antennagain, sumsignal is " << sumsignal[ibw] << "\n";
3291  }
3292  }
3293 
3294  // for energy reconstruction studies
3295  if (count_rx==anita1->rx_minarrivaltime) {
3296  undogaintoheight_e/=(double)Anita::NFREQ;
3297  undogaintoheight_h/=(double)Anita::NFREQ;
3298  for (int k=0;k<4;k++) {
3299  undogaintoheight_e_array[k]/=(double)nbins_array[k];
3300  undogaintoheight_h_array[k]/=(double)nbins_array[k];
3301  }
3302  }
3303  if (settings1->SCALEDOWNLCPRX1)
3304  globaltrig1->volts[0][ilayer][0]=globaltrig1->volts[0][ilayer][0]/sqrt(2.);
3305 
3306  if (settings1->RCPRX2ZERO)
3307  globaltrig1->volts[1][ilayer][1]=0.;
3308 
3309  if (settings1->LCPRX2ZERO)
3310  globaltrig1->volts[0][ilayer][1]=0.;
3311 
3312  if (settings1->SIGNAL_FLUCT) {
3313  if (settings1->WHICH==0) {
3314  globaltrig1->volts[ilayer][ifold][0]+=getRNG(RNG_SIGNAL_FLUCT)->Gaus(0., anita1->VNOISE_ANITALITE[ifold]);
3315  globaltrig1->volts[ilayer][ifold][1]+=getRNG(RNG_SIGNAL_FLUCT)->Gaus(0., anita1->VNOISE_ANITALITE[ifold]);
3316  } //else
3317  } //if adding noise
3318  if (count_rx==anita1->rx_minarrivaltime) {
3319  rec_efield=sqrt(pow(globaltrig1->volts_original[0][ilayer][ifold]/(undogaintoheight_e*0.5), 2)+pow(globaltrig1->volts_original[1][ilayer][ifold]/(undogaintoheight_h*0.5), 2));
3320  for (int ibw=0;ibw<4;ibw++) {
3321  rec_efield_array[ibw]=sqrt(pow(chantrig1->bwslice_volts_pole[ibw]/(undogaintoheight_e_array[ibw]*0.5), 2)+pow(chantrig1->bwslice_volts_polh[ibw]/(undogaintoheight_h_array[ibw]*0.5), 2));
3322  bwslice_vnoise_thislayer[ibw]=anita1->bwslice_vnoise[ilayer][ibw];// this is just for filling into a tree
3323  } // end loop over bandwidth slices
3324 
3325  if (tree6b->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
3326  tree6b->Fill();
3327  } // end if this is the closest antenna
3328 
3329  //+++++//+++++//+++++//+++++//+++++//+++++//+++++
3330 
3331  chantrig1->WhichBandsPass(settings1, anita1, globaltrig1, bn1, ilayer, ifold, viewangle-sig1->changle, emfrac, hadfrac, thresholdsAnt[antNum]);
3332 
3333 
3334  if (Anita::GetAntennaNumber(ilayer, ifold)==anita1->rx_minarrivaltime) {
3335  for (int iband=0;iband<5;iband++) {
3336  for (int ipol=0;ipol<2;ipol++) {
3337  rx0_signal_eachband[ipol][iband]=chantrig1->signal_eachband[ipol][iband];
3338  rx0_threshold_eachband[ipol][iband]=chantrig1->threshold_eachband[ipol][iband];
3339  rx0_noise_eachband[ipol][iband]=chantrig1->noise_eachband[ipol][iband];
3340  rx0_passes_eachband[ipol][iband]=chantrig1->passes_eachband[ipol][iband];
3341  }
3342  }
3343  }
3344 
3345  //For verification plots: find antenna with max signal - added by Stephen
3346  if (ilayer == 0 && globaltrig1->volts[0][ilayer][ifold] > max_antenna_volts0) {
3347  max_antenna0 = count_rx;
3348  max_antenna_volts0 = globaltrig1->volts[0][ilayer][ifold];
3349  max_antenna_volts0_em=globaltrig1->volts_em[0][ilayer][ifold];
3350  ant_max_normal0 = ant_normal;
3351  e_comp_max1 = e_component[count_rx];
3352  h_comp_max1 = h_component[count_rx];
3353  }
3354  else if (ilayer == 0 && globaltrig1->volts[0][ilayer][ifold] == max_antenna_volts0 && globaltrig1->volts[0][ilayer][ifold] != 0){
3355  cout<<"Equal voltage on two antennas! Event : "<<inu<<endl;
3356  }
3357  else if (ilayer == 1 && globaltrig1->volts[0][ilayer][ifold] > max_antenna_volts1) {
3358  max_antenna1 = count_rx;
3359  max_antenna_volts1 = globaltrig1->volts[0][ilayer][ifold];
3360  ant_max_normal1 = ant_normal;
3361  e_comp_max2 = e_component[count_rx];
3362  h_comp_max2 = h_component[count_rx];
3363  }
3364  else if (ilayer == 1 && globaltrig1->volts[0][ilayer][ifold] == max_antenna_volts1 && globaltrig1->volts[0][ilayer][ifold] != 0){
3365  cout<<"Equal voltage on two antennas! Event : "<<inu<<endl;
3366  }
3367  else if (ilayer == 2 && globaltrig1->volts[0][ilayer][ifold] > max_antenna_volts2) {
3368  max_antenna2 = count_rx;
3369  max_antenna_volts2 = globaltrig1->volts[0][ilayer][ifold];
3370  ant_max_normal2 = ant_normal;
3371  e_comp_max3 = e_component[count_rx];
3372  h_comp_max3 = h_component[count_rx];
3373  }
3374  else if (ilayer == 2 && globaltrig1->volts[0][ilayer][ifold] == max_antenna_volts2 && globaltrig1->volts[0][ilayer][ifold] != 0){
3375  cout<<"Equal voltage on two antennas! Event : "<<inu<<endl;
3376  }
3377  voltagearray[count_rx] = globaltrig1->volts[0][ilayer][ifold];
3378  //End verification plot block
3379 
3380  count_rx++; // counting antennas that we loop through, for indexing
3381 
3382 
3383  if (settings1->TRIGTYPE==0 && ifold==1 && count_pass>=settings1->NFOLD) { //added djg --line below fills "direct" voltage output file
3384  al_voltages_direct<<"0 0 0"<<" "<<" "<<globaltrig1->volts_original[1][0][0]<<" "<<(globaltrig1->volts_original[0][0][0]/sqrt(2.))<<" "<<globaltrig1->volts_original[1][0][1]<<" "<<globaltrig1->volts_original[0][0][1]<<" "<<anita1->VNOISE[0]<<" "<<anita1->VNOISE[0]<<" "<<anita1->VNOISE[0]<<" "<<anita1->VNOISE[0]<<" "<<weight<<endl;
3385  }
3386  delete chantrig1;
3387  } //loop through the phi-fold antennas
3388  } //loop through the layers of antennas
3389 
3390 
3391  anita1->rms_rfcm_e_single_event = sqrt(anita1->rms_rfcm_e_single_event / (anita1->HALFNFOUR * settings1->NANTENNAS));
3392 
3393  if(!settings1->ROUGHNESS){
3394  if (settings1->DISCONES==1) {
3395  // loop through discones
3396  for (int idiscone=0;NDISCONES;idiscone++) {
3397  ChanTrigger *chantrig1=new ChanTrigger();
3398  volts_discone=0.;
3399  polarfactor_discone=n_pol.Dot(bn1->n_bn); // beam pattern
3400  for (int k=0;k<Anita::NFREQ;k++) {
3401  if (anita1->freq[k]>=FREQ_LOW_DISCONES && anita1->freq[k]<=FREQ_HIGH_DISCONES) {
3402  thislambda=CLIGHT/sig1->N_AIR/anita1->freq[k];
3403  heff_discone= thislambda*sqrt(2*Zr*gain_dipole/Z0/4/PI*sig1->N_AIR); // effective height of dipole, using formula from Ped's note
3404 
3405  volts_discone+=panel1->GetVmmhz_freq(k)*0.5*heff_discone*((settings1->BW/1E6)/(double)Anita::NFREQ)*polarfactor_discone;
3406  }
3407  }// end for k loop
3408 
3409  vnoise_discone=anita1->VNOISE[0]*sqrt(BW_DISCONES/settings1->BW_SEAVEYS);
3410 
3411  if (settings1->SIGNAL_FLUCT) {
3412  volts_discone+=getRNG(RNG_SIGNAL_FLUCT)->Gaus(0., vnoise_discone); // here I'm using the noise seen by an antenna pointed with a 10 degree cant. Should be different for a discone but we'll change it later.
3413  }
3414 
3415  if (fabs(volts_discone)/vnoise_discone>anita1->maxthreshold)
3416  discones_passing++;
3417 
3418  delete chantrig1;
3419  } // end looping through discones
3420  } //end if settings discones==1
3421  }
3422  for (int irx=0;irx<settings1->NANTENNAS;irx++) {
3423  nchannels_perrx_triggered[irx]=globaltrig1->nchannels_perrx_triggered[irx];
3424  }
3425 
3426  nchannels_triggered=Tools::iSum(globaltrig1->nchannels_perrx_triggered, settings1->NANTENNAS); // find total number of antennas that were triggered.
3427  volts_rx_ave=GetAverageVoltageFromAntennasHit(settings1, globaltrig1->nchannels_perrx_triggered, voltagearray, volts_rx_sum);
3428 
3429  // if it passes the trigger, then go ahead and
3430  // calculate the chord length, etc.
3431  // intermediate counter
3432  if(sec1->secondbang && sec1->interestedintaus)
3433  count_asktrigger_nfb++; // just for taus
3434  else
3435  count_asktrigger++;
3436  dist_int_bn_2d_chord = ray1->rfexit[0].Distance(bn1->r_bn_shadow)/1000; // for sensitivity vs. distance plot
3437  //distance across the surface - Stephen
3438  dist_int_bn_2d = ray1->rfexit[0].SurfaceDistance(bn1->r_bn_shadow, bn1->surface_under_balloon) / 1000;
3439  //---------------------
3440  //just added this temporarily - will make it run slower
3441  //this gets the weight due to stopping in earth
3442  //returns 0 if chord<1m
3443 
3444  if (!antarctica->Getchord(settings1, len_int_kgm2, interaction1->r_in, interaction1->pathlength_inice, settings1->UNBIASED_SELECTION ==0,
3445  interaction1->posnu, inu, interaction1->chord, interaction1->weight_nu_prob, interaction1->weight_nu, nearthlayers, myair, total_kgm2, crust_entered, mantle_entered, core_entered)){
3446  interaction1->weight_nu_prob = -1.;
3447  }
3448 
3449  if(tauweighttrigger==1) {
3450  weight1=interaction1->weight_nu_prob; //?????? this is probably not right...
3451  weight_prob=interaction1->weight_nu_prob+ taus1->weight_tau_prob;
3452  }
3453 
3454  else {
3455  weight1=interaction1->weight_nu;
3456  weight_prob=interaction1->weight_nu_prob;
3457  }
3458 
3459  //if we are using the correct sampling mode, should need to time weight.
3460 
3461  weight = weight1 / interaction1->dnutries * settings1->SIGMA_FACTOR * time_weight; // total weight is the earth absorption factor
3462  weight_prob = weight_prob / interaction1->dnutries * settings1->SIGMA_FACTOR * time_weight; // total weight is the earth absorption factor
3463  // divided by the factor accounting for the fact that we only chose our interaction point within the horizon of the balloon
3464  // then multiply by the cross section multiplier, to account for the fact that we get more interactions when the cross section is higher
3465  //if (weight < settings1->CUTONWEIGHTS && !settings1->SOURCE) {
3466  //oindree_file << weight << "\n";
3467 
3468 
3469 
3470 #ifdef ANITA3_EVENTREADER
3471  if (truthNuPtr) truthNuPtr->setWeights(weight, 1./interaction1->dnutries, time_weight);
3472 #endif
3473  havent_set_weights = false;
3474 
3475 
3476  if (weight < settings1->CUTONWEIGHTS || weight_prob < settings1->CUTONWEIGHTPROBS) {
3477  delete globaltrig1;
3478  DO_SKIP
3479  }
3480 
3481  eventsfound_beforetrigger+=weight;
3482 
3484  // EVALUATE GLOBAL TRIGGER //
3485  // FOR VPOL AND HPOL //
3487 
3488  int thispasses[Anita::NPOL]={0,0};
3489  int thispassesnoise[Anita::NPOL]={0,0};
3490 
3491  if (!isDead){
3492  // calculate global trigger on noise only waveforms
3493  globaltrig1->PassesTrigger(settings1, anita1, discones_passing, 2, l3trignoise, l2trig, l1trig, settings1->antennaclump, loctrig, loctrig_nadironly, inu,
3494  thispassesnoise, true);
3495  // calculate global trigger on noise + signal waveforms
3496  globaltrig1->PassesTrigger(settings1, anita1, discones_passing, 2, l3trig, l2trig, l1trig, settings1->antennaclump, loctrig, loctrig_nadironly, inu,
3497  thispasses);
3498  // if ( (l3trignoise[0]>0 && l3trignoise[0]==l3trig[0]) || (l3trignoise[1]>0 && l3trignoise[1]==l3trig[1] ) ){
3499  if ( (l3trignoise[0]>0 ) || (l3trignoise[1]>0 ) ){
3500  cout << "A thermal noise fluctuation generated this trigger!" << l3trignoise[0] << " " << l3trig[0] << " " << l3trignoise[1] << " " << l3trig[1] << endl;
3501  delete globaltrig1;
3502  DO_SKIP
3503  }
3504  }
3505 
3506  for (int i=0;i<2;i++) {
3507  for (int j=0;j<16;j++) {
3508  for (int k=0;k<anita1->HALFNFOUR;k++) {
3509  count1->nl1triggers[i][whichray]+=anita1->l1trig_anita3and4_inanita[i][j][k];
3510  }
3511  }
3512  }
3513 
3515  // Require that it passes //
3516  // global trigger //
3518  // for Anita-lite, Anita Hill, just L1 requirement on 2 antennas. This option is currently disabled
3519  // Save events that generate an RF trigger or that are part of the min bias sample
3520  // Minimum bias sample: save all events that we could see at the payload
3521  // Independentely from the fact that they generated an RF trigger
3522 
3523  if ( (thispasses[0]==1 && anita1->pol_allowed[0]==1)
3524  || (thispasses[1]==1 && anita1->pol_allowed[1]==1)
3525  || (settings1->TRIGTYPE==0 && count_pass>=settings1->NFOLD)
3526  || (settings1->MINBIAS==1)){
3527 
3528  if (bn1->WHICHPATH==4)
3529  cout << "This event passes.\n";
3530 
3531  anita1->passglobtrig[0]=thispasses[0];
3532  anita1->passglobtrig[1]=thispasses[1];
3533 
3534  //calculate the phi angle wrt +x axis of the ray from exit to balloon
3535  n_exit_phi = Tools::AbbyPhiCalc(ray1->n_exit2bn[2][0], ray1->n_exit2bn[2][1]);
3536  //cout << "n_exit_phi is " << n_exit_phi << "\n";
3537 
3538  // keep track of events passing trigger
3539  count1->npassestrigger[whichray]++;
3540  // tags this event as passing
3541  passestrigger=1;
3542 
3543  // for plotting
3544  if (tree11->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
3545  tree11->Fill();
3546 
3547  // for taus
3548  if(sec1->secondbang && sec1->interestedintaus)
3549  count_passestrigger_nfb++;
3550 
3551  crust_entered=0; //These are switches that let us tell how far a given neutrino penetrated. Clear them before entering Getchord.
3552  mantle_entered=0;
3553  core_entered=0;
3554 
3555  // this gets the weight due to stopping in earth
3556  // returns 0 if chord<1m
3557  if (tautrigger==1 || interaction1->weight_nu_prob >= 0) {
3558  //cout << "passes chord.\n";
3559  if (nupathtree->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
3560  nupathtree->Fill();
3561 
3562  // counts how many have a good chord length
3563  count_chordgoodlength++;
3564 
3565  pieceofkm2sr=weight*antarctica->volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr/(double)NNU/len_int;
3566  if (h10->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST)
3567  h10->Fill(hitangle_e_all[0], weight);
3568 //cerr << inu<<" passes. weight= "<<weight<<" El.Angle= "<<(antarctica->GetSurfaceNormal(bn1->r_bn).Cross(ray1->n_exit2bn[2])).Cross(antarctica->GetSurfaceNormal(bn1->r_bn)).Unit().Angle(ray1->n_exit2bn[2].Unit())*180./PI<<" Distance= "<< bn1->r_bn.Distance(ray1->rfexit[2])<<" screenNpts="<<panel1->GetNvalidPoints()<< ": vmmhz[0] = "<<panel1->GetVmmhz_freq(0)<<" : trans pol "<< panel1->GetPol(0)<<" : IncAngle "<<panel1->GetIncidenceAngle(0)*180./PI<< " : TransAngle "<<panel1->GetTransmissionAngle(0)*180./PI<<" : Tslappy "<<panel1->GetTperpendicular_polPerpendicular(0)<<" : Tpokey "<<panel1->GetTparallel_polParallel(0)<< endl;
3569 //cerr<<bn1->r_bn.Lat()<<" "<<-90.+bn1->r_bn.Lat()<<endl;
3570 //cerr<<interaction1->posnu.Lon()<<" "<<-90.+interaction1->posnu.Lat()<<endl;
3571 //cerr<<ray1->rfexit[2].Lon()<<" "<<-90.+ray1->rfexit[2].Lat()<<endl;
3572 //cerr<<ray1->rfexit[2].Distance(interaction1->posnu)<<endl;
3573 //cerr<<interaction1->nnu.Angle(antarctica->GetSurfaceNormal(interaction1->posnu))<<endl;
3574 //cerr<<interaction1->nnu.Angle(ray1->n_exit2bn[2])<<endl;
3575 //cerr<<ray1->rfexit[2].Distance(bn1->r_bn)<<endl;
3576 //cerr<<interaction1->posnu.Distance(bn1->r_bn)<<endl;
3577  // log of weight and chord for plotting
3578  logweight=log10(weight);
3579  interaction1->logchord=log10(interaction1->chord);
3580 // cerr<<"-> We got a live one! "<<nunum<<" Nscreenvalid: "<<panel1->GetNvalidPoints()<<" weight: "<<weight<<endl;
3581  // if neutrino travels more than one meter in ice
3582  if (interaction1->d2>1) {
3583  // intermediate counter
3584  count_d2goodlength++;
3585 
3586  // for taus
3587  // add to tally of neutrinos found, weighted.
3588  if(sec1->secondbang && sec1->interestedintaus) {
3589  eventsfound_nfb+=weight;
3590  index_weights=(int)(((logweight-MIN_LOGWEIGHT)/(MAX_LOGWEIGHT-MIN_LOGWEIGHT))*(double)NBINS);
3591  eventsfound_nfb_binned[index_weights]++;
3592  if (tree16->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
3593  tree16->Fill();
3594  }//end if secondbang & interestedintaus
3595  else {
3596  allcuts[whichray]++;
3597  allcuts_weighted[whichray]+=weight;
3598  if (thispasses[0] && thispasses[1]) {
3599  allcuts_weighted_polarization[2]+=weight;
3600  } else if (thispasses[0]){
3601  allcuts_weighted_polarization[0]+=weight;
3602  } else if (thispasses[1]){
3603  allcuts_weighted_polarization[1]+=weight;
3604  }
3605  anita1->weight_inanita=weight;
3606 
3607  if (h1mybeta->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1)
3608  h1mybeta -> Fill(mybeta, weight); //get the angle distribution of mybeta
3609 
3610  eventsfound+=weight; // counting events that pass, weighted.
3611  eventsfound_prob+=weight_prob; // counting events that pass, probabilities.
3612 
3613  eventsfound_per_source[which_source]+=weight*src_time_weight/time_weight; // counting events that pass, weighted.
3614  eventsfound_prob_per_source[which_source]+=weight_prob*src_time_weight/time_weight; // counting events that pass, probabilities.
3615 
3616 
3617  if (cosalpha>0)
3618  eventsfound_belowhorizon+=weight;
3619 
3620  count1->npass[whichray]++; // counting events that pass, unweighted.
3621  // for calculating errors on sensitivity
3622  // need to find how many events as a function of weight
3623  // here, we find how to index weight
3624  if (logweight<MIN_LOGWEIGHT) // underflows, set to 0th bin
3625  index_weights=0;
3626  else if (logweight>MAX_LOGWEIGHT) // overflows, set to last bin
3627  index_weights=NBINS-1;
3628  else // which index weight corresponds to.
3629  index_weights=(int)(((logweight-MIN_LOGWEIGHT)/(MAX_LOGWEIGHT-MIN_LOGWEIGHT))*(double)NBINS);
3630 
3631  // count number of events that pass, binned in weight
3632  if (index_weights<NBINS)
3633  eventsfound_binned[index_weights]++;
3634 
3635  // number of events in a ring at distance from balloon
3636  if (index_distance<NBINS_DISTANCE)
3637  eventsfound_binned_distance[index_distance]+= weight;
3638 
3639  // same, now binned in weight, for calculating errors
3640  if (index_distance<NBINS_DISTANCE && index_weights<NBINS)
3641  eventsfound_binned_distance_forerror[index_distance][index_weights]++;
3642  // for debugging
3643  if (logweight>-3)
3644  eventsfound_weightgt01+=weight;
3645 
3646  // how many events just pass through crust, for same purpose.
3647  if (nearthlayers==1)
3648  eventsfound_crust+=weight;
3649 
3650  if (h1mybeta->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && settings1->HIST==1) {
3651  h1mybeta -> Fill(mybeta, weight);
3652  h1mytheta -> Fill(mytheta, weight);//fill mytheta
3653  }
3654  }//end else secondbang & interestedintaus
3655 
3656  //for plotting events distribution map only
3657  if(weight>0.0001){
3658  double int_lon, int_lat;
3659  double E,N;
3660  //here are the longitude and altitude which Amy defined
3661  int_lon = interaction1->posnu.Lon(); // what latitude, longitude does interaction occur at
3662  int_lat = interaction1->posnu.Lat();
3663  antarctica->LonLattoEN(int_lon, int_lat, E, N);
3664  if(whichray==0)//direct
3665  dir_int_coord->Fill(E, N);
3666  if(whichray==1)
3667  ref_int_coord->Fill(E, N);
3668  }
3669 
3670  // just for plotting.
3671  offaxis=(double)fabs(viewangle-sig1->changle);
3672  nsigma_offaxis=offaxis/deltheta_had_max;
3673 
3674  hundogaintoheight_e->Fill(undogaintoheight_e, weight);
3675  hundogaintoheight_h->Fill(undogaintoheight_h, weight);
3676  rec_diff->Fill((rec_efield-true_efield)/true_efield, weight);
3677  rec_diff0->Fill((rec_efield_array[0]-true_efield_array[0])/true_efield_array[0], weight);
3678  rec_diff1->Fill((rec_efield_array[1]-true_efield_array[1])/true_efield_array[1], weight);
3679  rec_diff2->Fill((rec_efield_array[2]-true_efield_array[2])/true_efield_array[2], weight);
3680  rec_diff3->Fill((rec_efield_array[3]-true_efield_array[3])/true_efield_array[3], weight);
3681  recsum_diff->Fill((rec_efield_array[0]+rec_efield_array[1]+rec_efield_array[2]+rec_efield_array[3]-true_efield)/true_efield, weight);
3682 
3683  // calc source lon, lat, alt
3684  sourceLon = ray1->rfexit[2].Lon() - 180;
3685  sourceLat = ray1->rfexit[2].Lat() - 90;
3686  sourceAlt = antarctica->SurfaceAboveGeoid(sourceLon+180, sourceLat+90);
3687 
3688  //Now put data in Vectors and Positions into arrays for output to the ROOT file.
3689  if (settings1->HIST && finaltree->GetEntries()<settings1->HIST_MAX_ENTRIES) {
3690  for (int i=0;i<3;i++) {
3691  nnu_array[i] = interaction1->nnu[i];
3692  r_in_array[i] = interaction1->r_in[i];
3693  r_bn_array[i] = bn1->r_bn[i];
3694  n_bn_array[i] = bn1->n_bn[i];
3695  posnu_array[i] = interaction1->posnu[i];
3696  ant_max_normal0_array[i] = ant_max_normal0[i];
3697  ant_max_normal1_array[i] = ant_max_normal1[i];
3698  ant_max_normal2_array[i] = ant_max_normal2[i];
3699  n_pol_array[i] = n_pol[i];
3700  r_enterice_array[i] = interaction1->r_enterice[i];
3701  nsurf_rfexit_array[i] = ray1->nsurf_rfexit[i];
3702  nsurf_rfexit_db_array[i] = ray1->nsurf_rfexit_db[i];
3703  } //end for (fill arrays)
3704  for (int j=0;j<5;j++) {
3705  for (int i=0;i<3;i++) {
3706  nrf_iceside_array[j][i] = ray1->nrf_iceside[j][i];
3707  nrf_iceside_db_array[j][i] = nrf_iceside_db[j][i];
3708  n_exit2bn_array[j][i] = ray1->n_exit2bn[j][i];
3709  n_exit2bn_db_array[j][i] = n_exit2bn_db[j][i];
3710  rfexit_array[j][i] = ray1->rfexit[j][i];
3711  rfexit_db_array[j][i] = ray1->rfexit_db[j][i];
3712  } //end for
3713  } //end for
3714  if (settings1->HIST && vmmhz_tree->GetEntries()<20) {
3715  vmmhz_tree->Fill();
3716  }
3717 
3718  nuflavorint2 = interaction1->nuflavorint;
3719  costheta_nutraject2=interaction1->costheta_nutraject;
3720  phi_nutraject2=interaction1->phi_nutraject;
3721  altitude_int2=interaction1->altitude_int;
3722  currentint2=interaction1->currentint;
3723  d12=interaction1->d1;
3724  d22=interaction1->d2;
3725  dtryingdirection2=interaction1->dtryingdirection;
3726  logchord2=interaction1->logchord;
3727  r_fromballoon2=interaction1->r_fromballoon[0];
3728  chord_kgm2_bestcase2=interaction1->chord_kgm2_bestcase;
3729  chord_kgm2_ice2=interaction1->chord_kgm2_ice;
3730  weight_bestcase2=interaction1->weight_bestcase;
3731  r_exit2bn2=interaction1->r_exit2bn;
3732  r_exit2bn_measured2=interaction1->r_exit2bn_measured;
3733 
3734  sourceMag = ray1->rfexit[2].Mag();
3735  sample_x = antarctica->getSampleX();
3736  sample_y = antarctica->getSampleY();
3737 
3738  finaltree->Fill();
3739  count1->IncrementWeights_r_in(interaction1->r_in, weight);
3740  } //end if HIST & HISTMAXENTRIES
3741 
3742 #ifdef ANITA_UTIL_EXISTS
3743  realEvPtr = new UsefulAnitaEvent();
3744  rawHeaderPtr = new RawAnitaHeader();
3745  Adu5PatPtr = new Adu5Pat();
3746  Adu5PatPtr->latitude= bn1->latitude;
3747  Adu5PatPtr->longitude=bn1->longitude;
3748  Adu5PatPtr->altitude=bn1->altitude;
3749  Adu5PatPtr->realTime=bn1->realTime_flightdata;
3750  Adu5PatPtr->heading = bn1->heading;
3751  Adu5PatPtr->pitch = bn1->pitch;
3752  Adu5PatPtr->roll = bn1->roll;
3753  Adu5PatPtr->run = run_no;
3754 
3755  memset(realEvPtr->fNumPoints, 0, sizeof(realEvPtr->fNumPoints) );
3756  memset(realEvPtr->fVolts, 0, sizeof(realEvPtr->fVolts) );
3757  memset(realEvPtr->fTimes, 0, sizeof(realEvPtr->fTimes) );
3758 
3759  int fNumPoints = 260;
3760  for (int ichan=0; ichan<108; ichan++){
3761  realEvPtr->fNumPoints[ichan] = fNumPoints;
3762 
3763  for (int j = 0; j < fNumPoints; j++) {
3764  // convert seconds to nanoseconds
3765  realEvPtr->fTimes[ichan][j] = j * anita1->TIMESTEP * 1.0E9;
3766  }
3767  }
3768  realEvPtr->fRFSpike = 0;// glitch does not likely happen in mc data.
3769  for (int iant = 0; iant < settings1->NANTENNAS; iant++){
3770  //int IceMCAnt = GetIceMCAntfromUsefulEventAnt(anita1, AnitaGeom1, iant);
3771  int IceMCAnt = GetIceMCAntfromUsefulEventAnt(settings1, iant);
3772  int UsefulChanIndexH = AnitaGeom1->getChanIndexFromAntPol(iant, AnitaPol::kHorizontal);
3773  int UsefulChanIndexV = AnitaGeom1->getChanIndexFromAntPol(iant, AnitaPol::kVertical);
3774  // realEvPtr->fNumPoints[UsefulChanIndexV] = fNumPoints;
3775  // realEvPtr->fNumPoints[UsefulChanIndexH] = fNumPoints;
3776  realEvPtr->chanId[UsefulChanIndexV] = UsefulChanIndexV;
3777  realEvPtr->chanId[UsefulChanIndexH] = UsefulChanIndexH;
3778 
3779  for (int j = 0; j < fNumPoints; j++) {
3780  // convert seconds to nanoseconds
3781  // realEvPtr->fTimes[UsefulChanIndexV][j] = j * anita1->TIMESTEP * 1.0E9;
3782  // realEvPtr->fTimes[UsefulChanIndexH][j] = j * anita1->TIMESTEP * 1.0E9;
3783  // convert volts to millivolts
3784  realEvPtr->fVolts[UsefulChanIndexH][j] = volts_rx_rfcm_lab_h_all[IceMCAnt][j+128]*1000;
3785  realEvPtr->fCapacitorNum[UsefulChanIndexH][j] = 0;
3786  realEvPtr->fVolts[UsefulChanIndexV][j] = volts_rx_rfcm_lab_e_all[IceMCAnt][j+128]*1000;
3787  realEvPtr->fCapacitorNum[UsefulChanIndexV][j] = 0;
3788  }//end int j
3789  }// end int iant
3790 
3791  realEvPtr->eventNumber = eventNumber;
3792 
3793  rawHeaderPtr->eventNumber = eventNumber;
3794  rawHeaderPtr->surfSlipFlag = 0;
3795  rawHeaderPtr->errorFlag = 0;
3796 
3797  if (settings1->MINBIAS==1)
3798  rawHeaderPtr->trigType = 8; // soft-trigger
3799  else
3800  rawHeaderPtr->trigType = 1; // RF trigger
3801 
3802 
3803  rawHeaderPtr->run = run_no;
3804  // put the vpol only as a placeholder - these are only used in Anita-2 anyway
3805  rawHeaderPtr->upperL1TrigPattern = l1trig[0][0];
3806  rawHeaderPtr->lowerL1TrigPattern = l1trig[0][1];
3807  rawHeaderPtr->nadirL1TrigPattern = l1trig[0][2];
3808 
3809  rawHeaderPtr->upperL2TrigPattern = l2trig[0][0];
3810  rawHeaderPtr->lowerL2TrigPattern = l2trig[0][1];
3811  rawHeaderPtr->nadirL2TrigPattern = l2trig[0][2];
3812 
3813  if (settings1->WHICH<9){
3814  rawHeaderPtr->phiTrigMask = (short) anita1->phiTrigMask;
3815  rawHeaderPtr->l3TrigPattern = (short) l3trig[0];
3816  }
3817 
3818  rawHeaderPtr->calibStatus = 31;
3819  rawHeaderPtr->realTime = bn1->realTime_flightdata;
3820  rawHeaderPtr->triggerTime = bn1->realTime_flightdata;
3821  Adu5PatPtr->latitude= bn1->latitude;
3822  Adu5PatPtr->longitude=bn1->longitude;
3823  Adu5PatPtr->altitude=bn1->altitude;
3824  Adu5PatPtr->realTime=bn1->realTime_flightdata;
3825  Adu5PatPtr->heading = bn1->heading;
3826  Adu5PatPtr->pitch = bn1->pitch;
3827  Adu5PatPtr->roll = bn1->roll;
3828  Adu5PatPtr->run = run_no;
3829 
3830  cout << "" << endl;
3831  cout << "Neutrino (evNum = " << eventNumber << ", weight = " << weight << " weight_prob = " << weight_prob <<") passed" << endl;
3832 
3833 #ifdef ANITA3_EVENTREADER
3834  if (settings1->WHICH==9 || settings1->WHICH==10) {
3835  rawHeaderPtr->setTrigPattern((short) l3trig[0], AnitaPol::kVertical);
3836  rawHeaderPtr->setTrigPattern((short) l3trig[1], AnitaPol::kHorizontal);
3837  rawHeaderPtr->setMask( (short) anita1->l1TrigMask, (short) anita1->phiTrigMask, AnitaPol::kVertical);
3838  rawHeaderPtr->setMask( (short) anita1->l1TrigMaskH, (short) anita1->phiTrigMaskH, AnitaPol::kHorizontal);
3839  }
3840 
3841  truthEvPtr = new TruthAnitaEvent();
3842  truthEvPtr->eventNumber = eventNumber;
3843  truthEvPtr->realTime = bn1->realTime_flightdata;
3844  truthEvPtr->run = run_no;
3845  truthEvPtr->nuMom = pnu;
3846  truthEvPtr->showerE = pnu * sumfrac;
3847  truthEvPtr->nu_pdg = pdgcode;
3848  memcpy(truthEvPtr->e_component, e_component, sizeof(truthEvPtr->e_component));
3849  memcpy(truthEvPtr->h_component, h_component, sizeof(truthEvPtr->h_component));
3850  memcpy(truthEvPtr->n_component, n_component, sizeof(truthEvPtr->n_component));
3851  memcpy(truthEvPtr->e_component_k ,e_component_kvector, sizeof(truthEvPtr->e_component_k));
3852  memcpy(truthEvPtr->h_component_k ,h_component_kvector, sizeof(truthEvPtr->h_component_k));
3853  memcpy(truthEvPtr->n_component_k ,n_component_kvector, sizeof(truthEvPtr->n_component_k));
3854  truthEvPtr->sourceLon = sourceLon;
3855  truthEvPtr->sourceLat = sourceLat;
3856  truthEvPtr->sourceAlt = sourceAlt;
3857 
3858  if(src_model){cout << "It originated from " << objName << " (" << RA*15 << "°, " << dec << "°)" << endl;}
3859 
3860  truthEvPtr->weight = weight;
3861  truthEvPtr->weight1 = weight1;
3862  truthEvPtr->weight_prob = weight_prob;
3863  truthEvPtr->phaseWeight = 1./interaction1->dnutries;
3864  truthEvPtr->timeWeight = time_weight;
3865  truthEvPtr->sourceTimeWeight = src_time_weight;
3866  truthEvPtr->tuffIndex = (short)anita1->tuffIndex;
3867 
3868  // for passed neutrinos:
3869 
3870 #ifdef ANITA3_EVENTCORRELATOR
3871  if(settings1->ALL_SKY_MAP)
3872  {
3873  astroObject->SetX(RA);
3874  astroObject->SetY(dec);
3875  astroObject->SetMarkerStyle(20);
3876  astroObject->SetMarkerSize(1.5);
3877  astroObject->SetMarkerColor(9);
3878  skyMapOut->addMarker(astroObject);
3879  }
3880 #endif
3881 
3882 
3883  truthEvPtr->source_index = which_source;
3884  truthEvPtr->RA = RA;
3885  truthEvPtr->dec = dec;
3886 
3887  truthEvPtr->objName =objName;
3888  //
3889 
3890  for (int i=0;i<3;i++){
3891  truthEvPtr->balloonPos[i] = bn1->r_bn[i];
3892  truthEvPtr->balloonDir[i] = bn1->n_bn[i];
3893  truthEvPtr->nuPos[i] = interaction1->posnu[i];
3894  truthEvPtr->nuDir[i] = interaction1->nnu[i];
3895  }
3896  for (int i=0;i<5;i++){
3897  for (int j=0;j<3;j++){
3898  truthEvPtr->rfExitNor[i][j] = ray1->n_exit2bn[i][j];
3899  truthEvPtr->rfExitPos[i][j] = ray1->rfexit[i][j];
3900  }
3901  }
3902  for (int i=0;i<48;i++){
3903  truthEvPtr->hitangle_e[i] = hitangle_e_all[i];
3904  truthEvPtr->hitangle_h[i] = hitangle_h_all[i];
3905  }
3906  if(!settings1->ROUGHNESS){
3907  for (int i=0;i<Anita::NFREQ;i++)
3908  truthEvPtr->vmmhz[i] = panel1->GetVmmhz_freq(i);
3909  }
3910 
3911 
3912  memset(truthEvPtr->SNRAtTrigger, 0, sizeof(truthEvPtr->SNRAtTrigger) );
3913  memset(truthEvPtr->fSignalAtTrigger, 0, sizeof(truthEvPtr->fSignalAtTrigger) );
3914  memset(truthEvPtr->fNoiseAtTrigger, 0, sizeof(truthEvPtr->fNoiseAtTrigger) );
3915  memset(truthEvPtr->SNRAtDigitizer, 0, sizeof(truthEvPtr->SNRAtDigitizer) );
3916  memset(truthEvPtr->thresholds, 0, sizeof(truthEvPtr->thresholds) );
3917  memset(truthEvPtr->fDiodeOutput, 0, sizeof(truthEvPtr->fDiodeOutput) );
3918 
3919  truthEvPtr->maxSNRAtTriggerV=0;
3920  truthEvPtr->maxSNRAtTriggerH=0;
3921  truthEvPtr->maxSNRAtDigitizerV=0;
3922  truthEvPtr->maxSNRAtDigitizerH=0;
3923 
3924  for (int iant = 0; iant < settings1->NANTENNAS; iant++){
3925  int UsefulChanIndexH = AnitaGeom1->getChanIndexFromAntPol(iant, AnitaPol::kHorizontal);
3926  int UsefulChanIndexV = AnitaGeom1->getChanIndexFromAntPol(iant, AnitaPol::kVertical);
3927 
3928  truthEvPtr->SNRAtTrigger[UsefulChanIndexV] = Tools::calculateSNR(justSignal_trig[0][iant], justNoise_trig[0][iant]);
3929  truthEvPtr->SNRAtTrigger[UsefulChanIndexH] = Tools::calculateSNR(justSignal_trig[1][iant], justNoise_trig[1][iant]);
3930 
3931  if (truthEvPtr->SNRAtTrigger[UsefulChanIndexV]>truthEvPtr->maxSNRAtTriggerV) truthEvPtr->maxSNRAtTriggerV=truthEvPtr->SNRAtTrigger[UsefulChanIndexV];
3932  if (truthEvPtr->SNRAtTrigger[UsefulChanIndexH]>truthEvPtr->maxSNRAtTriggerH) truthEvPtr->maxSNRAtTriggerH=truthEvPtr->SNRAtTrigger[UsefulChanIndexH];
3933 
3934  truthEvPtr->SNRAtDigitizer[UsefulChanIndexV] = Tools::calculateSNR(justSignal_dig[0][iant], justNoise_dig[0][iant]);
3935  truthEvPtr->SNRAtDigitizer[UsefulChanIndexH] = Tools::calculateSNR(justSignal_dig[1][iant], justNoise_dig[1][iant]);
3936 
3937  if (truthEvPtr->SNRAtDigitizer[UsefulChanIndexV]>truthEvPtr->maxSNRAtDigitizerV) truthEvPtr->maxSNRAtDigitizerV=truthEvPtr->SNRAtDigitizer[UsefulChanIndexV];
3938  if (truthEvPtr->SNRAtDigitizer[UsefulChanIndexH]>truthEvPtr->maxSNRAtDigitizerH) truthEvPtr->maxSNRAtDigitizerH=truthEvPtr->SNRAtDigitizer[UsefulChanIndexH];
3939 
3940 
3941  truthEvPtr->thresholds[UsefulChanIndexV] = thresholdsAnt[iant][0][4];
3942  truthEvPtr->thresholds[UsefulChanIndexH] = thresholdsAnt[iant][1][4];
3943  int irx = iant;
3944  if (iant<16){
3945  if (iant%2) irx = iant/2;
3946  else irx = iant/2 + 1;
3947  }
3948 
3949  for (int j = 0; j < fNumPoints; j++) {
3950  truthEvPtr->fTimes[UsefulChanIndexV][j] = j * anita1->TIMESTEP * 1.0E9;
3951  truthEvPtr->fTimes[UsefulChanIndexH][j] = j * anita1->TIMESTEP * 1.0E9;
3952 
3953  truthEvPtr->fSignalAtTrigger[UsefulChanIndexV][j] = justSignal_trig[0][iant][j+128]*1000;
3954  truthEvPtr->fSignalAtTrigger[UsefulChanIndexH][j] = justSignal_trig[1][iant][j+128]*1000;
3955  truthEvPtr->fNoiseAtTrigger[UsefulChanIndexV][j] = justNoise_trig[0][iant][j+128]*1000;
3956  truthEvPtr->fNoiseAtTrigger[UsefulChanIndexH][j] = justNoise_trig[1][iant][j+128]*1000;
3957  truthEvPtr->fSignalAtDigitizer[UsefulChanIndexV][j] = justSignal_dig[0][iant][j+128]*1000;
3958  truthEvPtr->fSignalAtDigitizer[UsefulChanIndexH][j] = justSignal_dig[1][iant][j+128]*1000;
3959  truthEvPtr->fNoiseAtDigitizer[UsefulChanIndexV][j] = justNoise_dig[0][iant][j+128]*1000;
3960  truthEvPtr->fNoiseAtDigitizer[UsefulChanIndexH][j] = justNoise_dig[1][iant][j+128]*1000;
3961 
3962  truthEvPtr->fDiodeOutput[UsefulChanIndexV][j] = anita1->timedomain_output_allantennas[0][irx][j];
3963  truthEvPtr->fDiodeOutput[UsefulChanIndexH][j] = anita1->timedomain_output_allantennas[1][irx][j];
3964  }//end int j
3965 
3966  }// end int iant
3967 
3968  if (truthNuPtr) truthNuPtr->setSkipped(false);
3969 
3970 
3971 // printf("objname: 0x%p %s\n", &truthEvPtr->objName, truthEvPtr->objName.Data());
3972  if (truthAnitaNuTree) truthAnitaNuTree->Fill();
3973  truthAnitaTree->Fill();
3974  delete truthEvPtr;
3975 #endif
3976 
3977  headTree->Fill();
3978  eventTree->Fill();
3979  adu5PatTree->Fill();
3980 
3981  delete realEvPtr;
3982  delete rawHeaderPtr;
3983  delete Adu5PatPtr;
3984 #endif
3985 
3986  sum_weights+=weight;
3987  neutrinos_passing_all_cuts++;
3988  times_crust_entered_det+=crust_entered; //Increment counter for neutrino numbers in each earth layer - passing neutrinos
3989  times_mantle_entered_det+=mantle_entered;
3990  times_core_entered_det+=core_entered;
3991 
3992  if (settings1->WRITEPOSFILE==1)
3993  WriteNeutrinoInfo(interaction1->posnu, interaction1->nnu, bn1->r_bn, interaction1->altitude_int, interaction1->nuflavor, interaction1->current, elast_y, nu_out);
3994 
3995  // sample first 1000 events that pass to see the distribution of weights
3996  if (settings1->HIST && !settings1->ONLYFINAL && sampleweights->GetEntries()<settings1->HIST_MAX_ENTRIES) {
3997  if (weight>1.E-6)
3998  sampleweights->Fill(log10(weight));
3999  else
4000  sampleweights->Fill(-6.);
4001 
4002  // on the 1000th one, see how low you should make the cut so that you catch 99% of the events (weighted)
4003  if (sampleweights->GetEntries()==1000) {
4004  double sum_sampleintegral=0.;
4005  double sum_sample=0.;
4006  // first calculate total integral of all the weights
4007  for (int k=sampleweights->GetNbinsX();k>=1;k--) {
4008  sum_sampleintegral+=sampleweights->GetBinContent(k)*pow(10., sampleweights->GetBinLowEdge(k));
4009  }
4010  // treat the underflow bin specially
4011  sum_sampleintegral+=sampleweights->GetBinContent(0)*pow(10., sampleweights->GetBinLowEdge(1));
4012  // now sum until you reach 99% of the integral.
4013  for (int k=sampleweights->GetNbinsX();k>=1;k--) {
4014  sum_sample+=sampleweights->GetBinContent(k)*pow(10., sampleweights->GetBinLowEdge(k));
4015  if (sum_sample>0.99*sum_sampleintegral) {
4016  // reset the cut value.
4017  //settings1->CUTONWEIGHTS=pow(10., sampleweights->GetBinLowEdge(k));
4018  //cout << "settings1->CUTONWEIGHTS is " << settings1->CUTONWEIGHTS << "\n";
4019  k=0;
4020  }
4021  }
4022  }
4023  }//end if HIST & ONLYFINAL & sampleweights HISTMAXENTRIES
4024 
4025  //cout << "cut on weights = " << settings1->CUTONWEIGHTS << endl;
4026 
4027  // outputs to text file variables relevant to sky map.
4028  forbrian << interaction1->costheta_nutraject << " " << n_nutraject_ontheground.Phi() << " " << bn1->phi_bn << " " << logweight << "\n";
4029  // incrementing by flavor
4030  // also bin in weight for error calculation.
4031  if (interaction1->nuflavor=="nue") {
4032  sum[0]+=weight;
4033  sum_prob[0]+=weight_prob;
4034  eventsfound_binned_e[index_weights]++;
4035  } //if
4036  if (interaction1->nuflavor=="numu") {
4037  sum[1]+=weight;
4038  sum_prob[1]+=weight_prob;
4039  eventsfound_binned_mu[index_weights]++;
4040  } //if
4041  if(!sec1->secondbang || !sec1->interestedintaus) {
4042  if (interaction1->nuflavor=="nutau") {
4043  sum[2]+=weight;
4044  sum_prob[2]+=weight_prob;
4045  eventsfound_binned_tau[index_weights]++;
4046  } //if
4047  } //if
4048 
4049  } //end if interaction1->d2>1
4050 
4051  } //end if tautrigger || GetChord
4052  else {
4053  cout << "Chord is less than 1m.\n";
4054  } //end else GetChord
4055 
4056  if (settings1->HIST==1 && !settings1->ONLYFINAL && anita1->tglob->GetEntries()<settings1->HIST_MAX_ENTRIES) {// all events
4057  // cout << "Filling global trigger tree. inu is " << inu << "\n";
4058  anita1->tglob->Fill();
4059  anita1->tdata->Fill();
4060  anita1->tgaryanderic->Fill();
4061  }
4062 
4063  passes_thisevent=1; // flag this event as passing
4064  } // end if passing global trigger conditions
4065  else {
4066  passes_thisevent=0; // flag this event as not passing
4067  //hack so continue doesn't exit loop
4068  do
4069  {
4070  DO_SKIP
4071  }while(0);
4072 
4073  if (bn1->WHICHPATH==4)
4074  cout << "This event does not pass.\n";
4075  }// end else event does not pass trigger
4076 
4078  //
4079  // WE GET HERE REGARDLESS OF WHETHER THE TRIGGER PASSES
4080  //
4082 /*
4083  Vector tempa = ray1->n_exit2bn[2].Unit() - antarctica->GetSurfaceNormal(bn1->r_bn).Dot(ray1->n_exit2bn[2].Unit()) * antarctica->GetSurfaceNormal(bn1->r_bn);
4084  Position posa = ray1->rfexit[2] + 300.*tempa;
4085  Vector tempb = interaction1->nnu.Unit() - antarctica->GetSurfaceNormal(interaction1->posnu).Dot(interaction1->nnu.Unit()) * antarctica->GetSurfaceNormal(interaction1->posnu);
4086  Position posb = interaction1->posnu + 300.*tempb;
4087  if(vmmhz_max>0.){
4088  stemp=string(outputdir.Data())+"/rough_evtweight_"+nunum+".dat";
4089  ofstream evtwgtout(stemp.c_str());
4090  evtwgtout << weight << " "
4091  << thispasses[0] << " "
4092  << anita1->pol_allowed[0] << " "
4093  << thispasses[1] << " "
4094  << anita1->pol_allowed[1] << " "
4095  << ray1->rfexit[2].Lon()<< " "
4096  << -90+ray1->rfexit[2].Lat()<< " "
4097  << posa.Lon() <<" "
4098  << -90+posa.Lat()<<" "
4099  << interaction1->posnu.Lon() << " "
4100  << -90+interaction1->posnu.Lat() << " "
4101  << posb.Lon() <<" "
4102  <<-90+posb.Lat()<<" "
4103  <<std::endl;
4104  evtwgtout.close();
4105  }*/
4106  delete globaltrig1;
4107 
4108  // keeping track of intermediate counters, incrementing by weight1.
4109  // weight1 was not yet determined when integer counters were incremented.
4110  if (chanceinhell2)
4111  count_chanceinhell2_w += weight;
4112 
4113  if (passestrigger)
4114  count_passestrigger_w += weight;
4115 
4116  volume_thishorizon=antarctica->volume_inhorizon[bn1->Getibnposition()]/1.E9;
4117 
4118  if (settings1->HIST==1
4119  && !settings1->ONLYFINAL
4120  && tree1->GetEntries()<settings1->HIST_MAX_ENTRIES
4121  && bn1->WHICHPATH != 3){ // all events
4122  tree1->Fill();
4123  }//end if
4124 
4125  } // end for WHICHRAY
4126  //looping over two types of rays - upgoing and downgoing.
4127  if (ABORT_EARLY){
4128  std::cout << "\n***********************************************************";
4129  std::cout << "\n* SIGINT received, aborting loop over events early.";
4130  std::cout << "\n* Stopped after event " << inu << " instead of " << NNU;
4131  std::cout << "\n* Any output which relied on NNU should be corrected for.";
4132  std::cout << "\n***********************************************************\n";
4133  foutput << "\n***********************************************************";
4134  foutput << "\n* SIGINT received, aborting loop over events early.";
4135  foutput << "\n* Stopped after event " << inu << " instead of " << NNU;
4136  foutput << "\n* Any output which relied on NNU should be corrected for.";
4137  foutput << "\n***********************************************************\n";
4138  break;
4139  }
4140 
4141  //cout << "Oindree: nnu is " << interaction1->nnu << "\n";
4142  }//end NNU neutrino loop
4143 
4144 
4145  cout << "about to close tsignals tree.\n";
4146  anita1->fsignals=anita1->tsignals->GetCurrentFile();
4147  anita1->fdata=anita1->tdata->GetCurrentFile();
4148  anita1->fdata=anita1->tgaryanderic->GetCurrentFile();
4149  anita1->fsignals->Write();
4150  anita1->fsignals->Close();
4151 
4152  anita1->fdata=anita1->tglob->GetCurrentFile();
4153  anita1->fdata->Write();
4154  anita1->fdata->Close();
4155 
4156  if (settings1->EVENTSMAP){
4157  //draw the S80-degree-latitude circle
4158  TH2F *lat80deg=new TH2F("lat80deg", "", 600, -3000, 3000, 500, -2500, 2500);
4159  lat80deg->SetMarkerColor(kRed);
4160  double E,N;
4161  for(double lon=0;lon<360.;lon+=0.5){
4162  double lat=10.;
4163  antarctica->LonLattoEN(lon, lat, E, N);
4164  lat80deg->Fill(E, N);
4165  }//end for lon loop
4166  }// end if EVENTSMAP
4167 
4168  if (bn1->WHICHPATH==4) {// this is for comparing with Peter
4169  cout << "Earth radius at South Pole: " << antarctica->Geoid(0.) << "\n";
4170  Position posnu_temp=Position(180., 0., 1.); // points at the south pole
4171  cout << "Surface of ice at the South Pole: " << antarctica->Surface(posnu_temp) << "\n";
4172  cout << "Average balloon altitude is " << average_altitude << "\n";
4173  cout << "Average distance from earth center is " << average_rbn << "\n";
4174  cout << "Average height of balloon above ice surface is " << average_rbn-antarctica->Surface(bn1->r_bn) << "\n";
4175  cout << "theta_zenith are " << anita1->THETA_ZENITH[0]*DEGRAD << " " << anita1->THETA_ZENITH[1]*DEGRAD << " " << anita1->THETA_ZENITH[2]*DEGRAD << "\n";
4176  cout << "Index of refraction at this depth is " << sig1->N_DEPTH << "\n";
4177  cout << "Cerenkov angle is " << sig1->changle*DEGRAD << "\n";
4178  cout << "Nadir angle to surface exit point is " << DEGRAD*bn1->r_bn.Angle(ray1->n_exit2bn[2]) << "\n";
4179  cout << "Distance from rfexit to balloon is " << (bn1->r_bn+ -1*ray1->rfexit[2]).Mag() << "\n";
4180  cout << "Payload zenith angle at event source is " << DEGRAD*ray1->rfexit[2].Angle(ray1->n_exit2bn[2]) << "\n";
4181  cout << "Angle of incidence just below surface is " << DEGRAD*ray1->rfexit[2].Angle(ray1->nrf_iceside[4]) << "\n";
4182  cout << "Angle between neutrino and surface normal is " << DEGRAD*ray1->rfexit[0].Angle(interaction1->nnu)-90. << "\n";
4183  cout << "Angle of incidence below firn surface is " << DEGRAD*ray1->rfexit[2].Angle(ray1->nrf_iceside[3]) << "\n";
4184  }
4185  cout << "about to Summarize.\n";
4186 
4187  anita1->rms_rfcm[0] = sqrt(anita1->rms_rfcm[0] / (double)anita1->count_getnoisewaveforms)*1000.;
4188  anita1->rms_rfcm[1] = sqrt(anita1->rms_rfcm[1] / (double)anita1->count_getnoisewaveforms)*1000.;
4189  anita1->rms_lab[0] = sqrt(anita1->rms_lab[0] / (double)anita1->count_getnoisewaveforms)*1000.;
4190  anita1->rms_lab[1] = sqrt(anita1->rms_lab[1] / (double)anita1->count_getnoisewaveforms)*1000.;
4191 
4192  cout << "RMS noise in rfcm e-pol is " << anita1->rms_rfcm[0] << " mV.\n";
4193  cout << "RMS noise in rfcm h-pol is " << anita1->rms_rfcm[1] << " mV.\n";
4194  cout << "RMS noise in lab e-pol is " << anita1->rms_lab[0] << "mV.\n";
4195  cout << "RMS noise in lab h-pol is " << anita1->rms_lab[1] << "mV.\n";
4196  for (int i=0;i<Anita::NFREQ;i++) {
4197  anita1->avgfreq_rfcm[i]/=(double)anita1->count_getnoisewaveforms;
4198  anita1->avgfreq_rfcm_lab[i]/=(double)anita1->count_getnoisewaveforms;
4199  }
4200 
4201  rms_rfcm_e=anita1->rms_rfcm[0];
4202  rms_rfcm_h=anita1->rms_rfcm[1];
4203  rms_lab_e=anita1->rms_lab[0];
4204  rms_lab_h=anita1->rms_lab[1];
4205  for (int i=0;i<Anita::NFREQ;i++) {
4206  avgfreq_rfcm[i]=anita1->avgfreq_rfcm[i];
4207  avgfreq_rfcm_lab[i]=anita1->avgfreq_rfcm_lab[i];
4208  freq[i]=anita1->freq[i];
4209  }
4210  cout << "Filling summarytree. rms_rfcm_e is " << rms_rfcm_e << "\n";
4211  summarytree->Fill();
4212 
4213 
4214  // Recalculate the cross section because for the final volume approximation we just use the neutrino CC cross section
4215  primary1->GetSigma(pnu, sigma, len_int_kgm2, settings1, xsecParam_nutype, xsecParam_nuint);
4216  len_int=1.0/(sigma*sig1->RHOH20*(1./M_NUCL)*1000);
4217 
4218  // makes the output file
4219  Summarize(settings1, anita1, count1, spectra1, sig1, primary1, pnu, eventsfound, eventsfound_db, eventsfound_nfb, sigma, sum, antarctica->volume, antarctica->ice_area, km3sr, km3sr_e, km3sr_mu, km3sr_tau, foutput, distanceout, outputdir, bn1, src_model);
4220 
4221  std::string spec_string = src_model ? settings1->SOURCE : std::to_string( settings1->EXPONENT);
4222  veff_out << spec_string << "\t" << km3sr << "\t" << km3sr_e << "\t" << km3sr_mu << "\t" << km3sr_tau << "\t" << settings1->SIGMA_FACTOR << endl;//this is for my convenience
4223 
4224  // for each neutrino flavor, fraction each contributes to sensitivity.
4225  sum_frac[0]=sum[0]/eventsfound;
4226  sum_frac[1]=sum[1]/eventsfound;
4227  sum_frac[2]=sum[2]/eventsfound;
4228 
4229  // for taus.
4230  sum_frac_db[0]=sum[0]/(eventsfound+eventsfound_db+eventsfound_nfb);
4231  sum_frac_db[1]=sum[1]/(eventsfound+eventsfound_db+eventsfound_nfb);
4232  sum_frac_db[2]=(sum[2]+eventsfound_db+eventsfound_nfb)/(eventsfound+eventsfound_db+eventsfound_nfb);
4233  //if (tree17->GetEntries()<settings1->HIST_MAX_ENTRIES && !settings1->ONLYFINAL && HIST==1)
4234  //tree17->Fill();
4235 
4236 
4237 
4238 
4239 #ifdef ANITA_UTIL_EXISTS
4240 
4241  anitafileEvent->cd();
4242  eventTree->Write("eventTree");
4243  anitafileEvent->Close();
4244  delete anitafileEvent;
4245 
4246  anitafileHead->cd();
4247  headTree->Write("headTree");
4248  anitafileHead->Close();
4249  delete anitafileHead;
4250 
4251  anitafileGps->cd();
4252  adu5PatTree->Write("adu5PatTree");
4253  anitafileGps->Close();
4254  delete anitafileGps;
4255 
4256 #ifdef ANITA3_EVENTREADER
4257  anitafileTruth->cd();
4258  configAnitaTree->Write("configAnitaTree");
4259  truthAnitaTree->Write("truthAnitaTree");
4260  if (truthAnitaNuTree) truthAnitaNuTree->Write();
4261  triggerSettingsTree->Write("triggerSettingsTree");
4262  summaryAnitaTree->Fill();
4263  summaryAnitaTree->Write("summaryAnitaTree");
4264  anitafileTruth->Close();
4265  delete anitafileTruth;
4266 #endif
4267 
4268 #endif
4269 
4270 
4271  #ifdef ANITA3_EVENTCORRELATOR
4272  if(settings1->ALL_SKY_MAP)
4273  {
4274  TCanvas *skyMapC = new TCanvas("skyMapC", "skyMapC", 1000, 500);
4275  skyMapC->cd(1);
4276  skyMapOut->Draw();
4277  string outputSkyMap =string(outputdir.Data())+"/allSkyMap"+run_num+".png";
4278  skyMapC->SaveAs(outputSkyMap.c_str());
4279  }
4280  #endif
4281 
4282  cout << "closing file.\n";
4283  CloseTFile(hfile);
4284 
4285  time_t raw_end_time = time(NULL);
4286  struct tm * end_time = localtime(&raw_end_time);
4287  cout << "Date and time at end of run are: " << asctime (end_time) << "\n";
4288  cout<<"Total time elapsed is "<<(int)((raw_end_time - raw_start_time)/60)<<":"<< ((raw_end_time - raw_start_time)%60)<<endl;
4289 
4290  foutput << "\nTotal time elapsed in run is " <<(int)((raw_end_time - raw_start_time)/60)<<":"<< ((raw_end_time - raw_start_time)%60)<<endl;
4291 
4292  delete anita1;
4293  return 0;
4294 
4295 } //END MAIN PROGRAM
4296 
4297 
4298 
4299 
4300 
4301 
4302 
4303 
4304 
4305 //
4306 // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4307 // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4308 //
4309 //
4310 // Auxiliary functions
4311 //
4312 //
4313 //
4314 
4315 
4316 void IntegrateBands(Anita *anita1, int k, Screen *panel1, double *freq, double scalefactor, double *sumsignal) {
4317  for (int j=0;j<5;j++) {
4318  // if this frequency is in this bandwidth slice
4319  for (int jpt=0; jpt<panel1->GetNvalidPoints(); jpt++){
4320  if (anita1->bwslice_min[j]<=freq[k] && anita1->bwslice_max[j]>freq[k])
4321  sumsignal[j]+=panel1->GetVmmhz_freq(jpt*Anita::NFREQ + k)*(freq[k+1]-freq[k])*scalefactor;
4322  }
4323  }
4324 }
4325 //end IntegrateBands()
4326 
4327 
4328 void Integrate(Anita *anita1, int j, int k, double *vmmhz, double *freq, double scalefactor, double sumsignal) {
4329  // if this frequency is in this bandwidth slice
4330  if (anita1->bwslice_min[j]<=freq[k] && anita1->bwslice_max[j]>freq[k])
4331  sumsignal+=vmmhz[k]*(freq[k+1]-freq[k])*scalefactor;
4332 }
4333 //end Integrate()
4334 
4335 
4336 void WriteNeutrinoInfo(Position &posnu, Vector &nnu, Position &r_bn, double altitude_int, string nuflavor, string current, double elast_y, ofstream &nu_out) {
4337  nu_out << "\n" << inu << "\t" << posnu[0] << " " << posnu[1] << " " << posnu[2] << "\t" << altitude_int << "\t" << nnu[0] << " " << nnu[1] << " " << nnu[2] << "\t" << r_bn[0] << " " << r_bn[1] << " " << r_bn[2] << "\t" << nuflavor << "\t" << current << "\t" << elast_y << "\n\n";
4338 }
4339 //end WriteNeutrinoInfo()
4340 
4341 
4342 void Summarize(Settings *settings1, Anita* anita1, Counting *count1, Spectra *spectra1, Signal *sig1, Primaries *primary1, double pnu, double eventsfound, double eventsfound_db, double eventsfound_nfb, double sigma, double* sum, double volume, double ice_area, double& km3sr, double& km3sr_e, double& km3sr_mu, double& km3sr_tau, ofstream &foutput, ofstream &distanceout, TString outputdir, Balloon * bn1, SourceModel * src_model) {
4343  double rate_v_thresh[NTHRESHOLDS];
4344  double errorup_v_thresh[NTHRESHOLDS];
4345  double errordown_v_thresh[NTHRESHOLDS];
4346  double rate_h_thresh[NTHRESHOLDS];
4347  double errorup_h_thresh[NTHRESHOLDS];
4348  double errordown_h_thresh[NTHRESHOLDS];
4349  double zeroes[NTHRESHOLDS];
4350  Tools::Zero(zeroes, NTHRESHOLDS);
4351 
4352  // plot result of threshold scan
4353  for (int i=0;i<NTHRESHOLDS;i++) {
4354  rate_v_thresh[i]=npass_v_thresh[i]/denom_v_thresh[i];
4355  // cout << "i, npass_v_thresh are " << i << "\t" << npass_v_thresh[i] << " " << denom_v_thresh[i] << " " << rate_v_thresh[i] << "\n";
4356  if (npass_v_thresh[i]<=20) {
4357  errorup_v_thresh[i]=poissonerror_plus[(int)npass_v_thresh[i]]/denom_v_thresh[i];
4358  errordown_v_thresh[i]=poissonerror_minus[(int)npass_v_thresh[i]]/denom_v_thresh[i];
4359  // cout << errorup_v_thresh[i] << " " << errordown_v_thresh[i] << endl;
4360  }//end if
4361  if (settings1->WHICH==9 || settings1->WHICH==10){ // Anita-3
4362  rate_h_thresh[i]=npass_h_thresh[i]/denom_h_thresh[i];
4363  if (npass_h_thresh[i]<=20) {
4364  errorup_h_thresh[i]=poissonerror_plus[(int)npass_h_thresh[i]]/denom_h_thresh[i];
4365  errordown_h_thresh[i]=poissonerror_minus[(int)npass_h_thresh[i]]/denom_h_thresh[i];
4366  }//end if
4367  }//end if WHICH==9
4368 
4369  }//end for NTHRESHOLDS
4370 
4371  string stemp=string(outputdir.Data())+"/thresholds.root";
4372  TFile *fthresholds=new TFile(stemp.c_str(), "RECREATE");
4373  TCanvas *cthresh=new TCanvas("cthresh", "cthresh", 880, 800);
4374  cthresh->SetLogy();
4375 
4376  TGraph *gnpass=new TGraph(NTHRESHOLDS, thresholds, npass_v_thresh);
4377  gnpass->SetName("npass");
4378  TGraph *gdenom=new TGraph(NTHRESHOLDS, thresholds, denom_v_thresh);
4379  gdenom->SetName("denom");
4380 
4381  TGraphAsymmErrors *g=new TGraphAsymmErrors(NTHRESHOLDS, thresholds, rate_v_thresh, zeroes, zeroes, errorup_v_thresh, errordown_v_thresh);
4382  g->SetName("rate");
4383 
4384  g->SetLineWidth(2);
4385  g->SetMarkerStyle(21);
4386  g->Draw("ape");
4387 
4388  stemp = string(outputdir.Data())+"/thresholds.eps";
4389  cthresh->Print((TString)stemp);
4390  g->Write();
4391  gdenom->Write();
4392  gnpass->Write();
4393 
4394 
4395  if (settings1->WHICH==9 || settings1->WHICH==10){ // Anita-3 or Anita-4
4396  TGraph *gnpassH=new TGraph(NTHRESHOLDS, thresholds, npass_h_thresh);
4397  gnpassH->SetName("npassH");
4398  TGraph *gdenomH=new TGraph(NTHRESHOLDS, thresholds, denom_h_thresh);
4399  gdenomH->SetName("denomH");
4400  TGraphAsymmErrors *gH=new TGraphAsymmErrors(NTHRESHOLDS, thresholds, rate_h_thresh, zeroes, zeroes, errorup_h_thresh, errordown_h_thresh);
4401  gH->SetName("rate");
4402  gH->SetLineWidth(2);
4403  gH->SetMarkerStyle(21);
4404  gH->Draw("ape");
4405  stemp = string(outputdir.Data())+"/thresholds_HPOL.eps";
4406  cthresh->Print((TString)stemp);
4407 
4408  gH->Write();
4409  gdenomH->Write();
4410  gnpassH->Write();
4411  }//end if WHICH==9 or WHICH==10
4412 
4413  fthresholds->Write();
4414  fthresholds->Close();
4415 
4416  // double ses; // single-event sensitivity
4417  double km2sr; // aperture km**2-sr
4418 
4419  foutput << "\n";
4420 
4421  // write out summary
4422  foutput << "Generated " << NNU << " neutrinos with energy " << pnu << "\n";
4423  foutput << "Number of unweighted direct, reflected that pass is: " << count1->npass[0] << "\t" << count1->npass[1] << "\n";
4424  foutput << "Number of (weighted) neutrinos that pass is: " << eventsfound << "\n";
4425  foutput << "Number of (weighted) neutrinos that pass, multiplied by prob. of interacting in the ice, is: " << eventsfound_prob << "\n";
4426  foutput << "Number of weighted direct, reflected that pass is: " << allcuts_weighted[0] << "\t" << allcuts_weighted[1] << "\n";
4427  foutput << "Number of (weighted) neutrinos that pass (with weight>0.001) is: " << eventsfound_weightgt01 << "\n";
4428  foutput << "Number of (weighted) neutrinos that only traverse the crust is " << eventsfound_crust << " -> " << eventsfound_crust/eventsfound*100 << "%\n\n";
4429  foutput << "Number of (weighted) neutrinos that pass only VPOL trigger is: " << allcuts_weighted_polarization[0] << "\n";
4430  foutput << "Number of (weighted) neutrinos that pass only HPOL trigger is: " << allcuts_weighted_polarization[1] << "\n";
4431  foutput << "Number of (weighted) neutrinos that pass both pol triggers is: " << allcuts_weighted_polarization[2] << "\n\n";
4432 
4433  cout << "Number of (weighted) neutrinos that pass (with weight>0.001) is: " << eventsfound_weightgt01 << "\n";
4434  cout << "Number of (weighted) neutrinos that pass, multiplied by prob. of interacting in the ice, is: " << eventsfound_prob << "\n";
4435  cout << "Number of (weighted) neutrinos that only traverse the crust is " << eventsfound_crust << " -> " << eventsfound_crust/eventsfound*100 << "%\n\n";
4436  cout << "Number of (weighted) neutrinos that pass only VPOL trigger is: " << allcuts_weighted_polarization[0] << "\n";
4437  cout << "Number of (weighted) neutrinos that pass only HPOL trigger is: " << allcuts_weighted_polarization[1] << "\n";
4438  cout << "Number of (weighted) neutrinos that pass both pol triggers is: " << allcuts_weighted_polarization[2] << "\n\n";
4439 
4440  foutput << "Total number of thrown electron neutrinos is : " << (double)count1->nnu_e << "\n";
4441  foutput << "Total number of thrown muon neutrinos is : " << (double)count1->nnu_mu << "\n";
4442  foutput << "Total number of thrown tau neutrinos is : " << (double)count1->nnu_tau << "\n";
4443  foutput << "Number of (weighted) electron neutrinos that pass trigger is : " << sum[0] << "\n";
4444  foutput << "Number of (weighted) muon neutrinos that pass trigger is : " << sum[1] << "\n";
4445  foutput << "Number of (weighted) tau neutrinos that pass trigger is : " << sum[2] << "\n\n";
4446 
4447  cout << "Total number of thrown electron neutrinos is : " << (double)count1->nnu_e << "\n";
4448  cout << "Total number of thrown muon neutrinos is : " << (double)count1->nnu_mu << "\n";
4449  cout << "Total number of thrown tau neutrinos is : " << (double)count1->nnu_tau << "\n";
4450  cout << "Number of (weighted) electron neutrinos that pass trigger is : " << sum[0] << "\n";
4451  cout << "Number of (weighted) muon neutrinos that pass trigger is : " << sum[1] << "\n";
4452  cout << "Number of (weighted) tau neutrinos that pass trigger is : " << sum[2] << "\n\n";
4453 
4454  foutput << "Volume of ice is " << volume << "\n";
4455  foutput << "Value of 4*pi*pi*r_earth*r_earth in km^2 " << 4*PI*PI*(EarthModel::R_EARTH*EarthModel::R_EARTH/1.E6) << "\n";
4456 
4457 
4458  // single event sensitivity for 150 MHz array per year
4459  // everything is normalized to the active volume
4460  // assume dF/dE propto E**-2
4461  // assume 2pi sr or 4pi sr depending on whether below horizon is used
4462  // assume 3.16e7 seconds/year
4463  //------------------------------------------------
4464 
4465  // ses=1/(A_eff * sr * t)
4466  //ses=1.0/(sigma*volume*RHOSALT*(1./M_NUCL)*3.16E7); // 1 per year
4467 
4468 
4469  double nevents = 0;
4470  //double nweights=0;
4471  double nevents_db=0;
4472  double nevents_nfb=0;
4473 
4474 
4475  nevents+=eventsfound;
4476  nevents_db+=eventsfound_db;
4477  nevents_nfb+=eventsfound_nfb;
4478  error_plus=0;
4479  error_e_plus=0;
4480  error_mu_plus=0;
4481  error_tau_plus=0;
4482  error_minus=0;
4483  error_e_minus=0;
4484  error_mu_minus=0;
4485  error_tau_minus=0;
4486 
4487  error_nfb=0;
4488  error_km3sr_nfb=0;
4489  error_percent_increase_nfb=0;
4490 
4491 
4492  // loop over bins in weights
4493  for (int i=0;i<NBINS;i++) {
4494  if (eventsfound_binned[i]<=20) {
4495  error_plus+=pow(poissonerror_plus[(int)eventsfound_binned[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4496  error_e_plus+=pow(poissonerror_plus[(int)eventsfound_binned_e[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4497  error_mu_plus+=pow(poissonerror_plus[(int)eventsfound_binned_mu[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4498  error_tau_plus+=pow(poissonerror_plus[(int)eventsfound_binned_tau[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4499  error_minus+=pow(poissonerror_minus[(int)eventsfound_binned[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4500  error_e_minus+=pow(poissonerror_minus[(int)eventsfound_binned_e[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4501  error_mu_minus+=pow(poissonerror_minus[(int)eventsfound_binned_mu[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4502  error_tau_minus+=pow(poissonerror_minus[(int)eventsfound_binned_tau[i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4503  } //if
4504  else {
4505  error_plus+=eventsfound_binned[i]*pow(pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4506  error_e_plus+=eventsfound_binned_e[i]*pow(pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4507  error_mu_plus+=eventsfound_binned_mu[i]*pow(pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4508  error_tau_plus+=eventsfound_binned_tau[i]*pow(pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4509  error_minus=error_plus;
4510  error_e_minus=error_e_plus;
4511  error_mu_minus=error_mu_plus;
4512  error_tau_minus=error_tau_plus;
4513  } //else
4514 
4515  error_nfb+=eventsfound_nfb_binned[i]*pow(pow(10., ((double)i+0.5)/(double)NBINS*4.+-5.), 2);
4516  for (int j=0;j<NBINS_DISTANCE;j++) {
4517  if (eventsfound_binned_distance_forerror[j][i]<=20) {
4518  error_distance_plus[j]+=pow(poissonerror_plus[(int)eventsfound_binned_distance_forerror[j][i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4519  error_distance_minus[j]+=pow(poissonerror_minus[(int)eventsfound_binned_distance_forerror[j][i]]*pow(10., ((double)i+0.5)/(double)NBINS*(MAX_LOGWEIGHT-MIN_LOGWEIGHT)+MIN_LOGWEIGHT), 2);
4520  }//end if forerror
4521  }//end for NBINS_DISTANCE
4522  }//end for NBINS
4523 
4524 
4525  error_plus=sqrt(error_plus);
4526  error_e_plus=sqrt(error_e_plus);
4527  error_mu_plus=sqrt(error_mu_plus);
4528  error_tau_plus=sqrt(error_tau_plus);
4529 
4530  error_minus=sqrt(error_minus);
4531  error_e_minus=sqrt(error_e_minus);
4532  error_mu_minus=sqrt(error_mu_minus);
4533  error_tau_minus=sqrt(error_tau_minus);
4534 
4535 
4536  error_nfb=sqrt(error_nfb);
4537  for (int j=0;j<NBINS_DISTANCE;j++) {
4538  error_distance_plus[j]=sqrt(error_distance_plus[j]);
4539  error_distance_minus[j]=sqrt(error_distance_minus[j]);
4540  }
4541 
4542 
4543  // account for efficiency
4544  if (NNU != 0 && nevents!=0) {
4545  km3sr=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*nevents/(double)NNU/settings1->SIGMA_FACTOR;
4546 
4547  cout << nevents << " events passed out of " << NNU << "\n";
4548 
4549  error_plus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_plus/(double)NNU/settings1->SIGMA_FACTOR;
4550  error_minus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_minus/(double)NNU/settings1->SIGMA_FACTOR;
4551 
4552  percent_increase_db=km3sr_db/km3sr*100;
4553  percent_increase_nfb=km3sr_nfb/km3sr*100;
4554 
4555  error_percent_increase_nfb=sqrt(pow(error_km3sr_nfb/km3sr_nfb, 2)+pow(error_plus/km3sr, 2))*percent_increase_nfb;
4556 
4557  percent_increase_total=percent_increase_db+percent_increase_nfb;
4558 
4559  km3sr_e = (pow(1.e-3, 3))*volume*sr*(sum[0]/(double)count1->nnu_e)*sig1->RHOMEDIUM/sig1->RHOH20/settings1->SIGMA_FACTOR;
4560 
4561  cout << sum[0]/(double)nevents*100. << "% are electron neutrinos\n";
4562 
4563  error_e_plus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_e_plus/(double)count1->nnu_e/settings1->SIGMA_FACTOR;
4564  error_e_minus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_e_minus/(double)count1->nnu_e/settings1->SIGMA_FACTOR;
4565 
4566  km3sr_mu = (pow(1.e-3, 3))*volume*sr*(sum[1]/(double)count1->nnu_mu)*sig1->RHOMEDIUM/sig1->RHOH20/settings1->SIGMA_FACTOR;
4567 
4568  cout << sum[1]/(double)nevents*100. << "% are muon neutrinos\n";
4569 
4570  error_mu_plus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_mu_plus/(double)count1->nnu_mu/settings1->SIGMA_FACTOR;
4571  error_mu_minus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_mu_minus/(double)count1->nnu_mu/settings1->SIGMA_FACTOR;
4572 
4573  km3sr_tau = (pow(1.e-3, 3))*volume*sr*(sum[2]/(double)count1->nnu_tau)*sig1->RHOMEDIUM/sig1->RHOH20/settings1->SIGMA_FACTOR;
4574 
4575  cout << sum[2]/(double)nevents*100. << "% are tau neutrinos\n";
4576 
4577  error_tau_plus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_tau_plus/(double)count1->nnu_tau/settings1->SIGMA_FACTOR;
4578  error_tau_minus=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/sig1->RHOH20*sr*error_tau_minus/(double)count1->nnu_tau/settings1->SIGMA_FACTOR;
4579 
4580  double sum_km3sr=0;
4581  double sum_km3sr_error_plus=0;
4582  double sum_km3sr_error_minus=0;
4583  for (int i=0;i<NBINS_DISTANCE;i++) {
4584  sum_km3sr+= (pow(1.e-3, 3))*volume*sr*eventsfound_binned_distance[i]*sig1->RHOMEDIUM/sig1->RHOH20/(double)NNU/settings1->SIGMA_FACTOR;
4585  km3sr_distance[i]=sum_km3sr;
4586  sum_km3sr_error_plus+=pow(pow(1.E-3, 3)*volume*error_distance_plus[i]*sig1->RHOMEDIUM/sig1->RHOH20*sr/(double)NNU, 2)/settings1->SIGMA_FACTOR;
4587  error_distance_plus[i]=sqrt(sum_km3sr_error_plus);
4588  sum_km3sr_error_minus+=pow(pow(1.E-3, 3)*volume*error_distance_minus[i]*sig1->RHOMEDIUM/sig1->RHOH20*sr/(double)NNU, 2)/settings1->SIGMA_FACTOR;
4589  error_distance_minus[i]=sqrt(sum_km3sr_error_minus);
4590  distanceout << 700000./(double)NBINS_DISTANCE*(double)i << "\t" << km3sr_distance[i] << "\t" << error_distance_plus[i] << "\t" << error_distance_minus[i] << "\n";
4591  } //for
4592 
4593  foutput << "Total volume * solid angle is \t\t\t\t" << km3sr << " + " << error_plus << " - " << error_minus << " km^3 str\n";
4594  foutput << "Total volume * solid angle for electron neutrinos is \t" << km3sr_e << " + " << error_e_plus << " - " << error_e_minus << " km^3 str\n";
4595  foutput << "Total volume * solid angle for muon neutrinos is \t" << km3sr_mu << " + " << error_mu_plus << " - " << error_mu_minus << " km^3 str\n";
4596  foutput << "Total volume * solid angle for tau neutrinos is \t" << km3sr_tau << " + " << error_tau_plus << " - " << error_tau_minus << " km^3 str\n";
4597  cout << "Total volume * solid angle is \t\t\t\t" << km3sr << " + " << error_plus << " - " << error_minus << " km^3 str\n";
4598  cout << "Total volume * solid angle for electron neutrinos is \t" << km3sr_e << " + " << error_e_plus << " - " << error_e_minus << " km^3 str\n";
4599  cout << "Total volume * solid angle for muon neutrinos is \t" << km3sr_mu << " + " << error_mu_plus << " - " << error_mu_minus << " km^3 str\n";
4600  cout << "Total volume * solid angle for tau neutrinos is \t" << km3sr_tau << " + " << error_tau_plus << " - " << error_tau_minus << " km^3 str\n";
4601 
4602  if ( spectra1->IsMonoenergetic() ) {
4603  cout << "Cross section is " << sigma << "m^2\n";
4604  double len_int=1.0/(sigma*sig1->RHOH20*(1./M_NUCL)*1000);
4605  cout << "Interaction length is " << len_int << " km\n\n";
4606  foutput << "Interaction length is " << len_int << "\n";
4607  km2sr=km3sr/len_int;
4608  foutput << "Total area x steradians using km3sr/len_int is \t\t\t\t" << km2sr << " km^2 str\n\n";
4609  cout << "Total area x steradians is \t\t" << km2sr << " km^2 str\n\n";
4610  km2sr=ice_area/(1.E6)*PI*eventsfound_prob/(double)NNU;
4611  foutput << "Total area x steradians using 4*PI*R_EARTH^2*eff. is \t" << km2sr << " km^2 str\n\n";
4612  foutput << "These are not the same because we are not throwing all directions on all points of the surface. Believe the first one as an approximation, we are working on this for high cross sections.\n";
4613  // ses=(pnu/1.E9)/(km2sr*3.16E7);
4614  }//end if IsMonoenergetic
4615 
4616  }//end if NNU!=0 and nevents!=0
4617 
4618 
4619  foutput << "\t\t\t\t\t\t\tprobability of passing \t# events passing\n";
4620 
4621  foutput.precision(4);
4622  foutput << "No way this neutrino will see any ice \t\t\t" << (double)count1->noway[0]/(double)count_total << "\t" <<
4623  (double)count1->noway[1]/(double)count_total << "\t\t" <<
4624  count1->noway[0] << "\t" << count1->noway[1] << "\n";
4625 
4626  foutput.precision(4);
4627  foutput << "Wheredoesitleave in PickUnbiased gives an error \t" << (double)count1->wheredoesitleave_err[0]/(double)count1->noway[0] << "\t" <<
4628  (double)count1->wheredoesitleave_err[1]/(double)count1->noway[1] << "\t\t" <<
4629  count1->wheredoesitleave_err[0] << "\t" << count1->wheredoesitleave_err[1] << "\n";
4630 
4631  foutput.precision(4);
4632  foutput << "This neutrino direction never sees ice \t\t\t" << (double)count1->neverseesice[0]/(double)count1->wheredoesitleave_err[0] << "\t" <<
4633  (double)count1->neverseesice[1]/(double)count1->wheredoesitleave_err[1] << "\t\t" <<
4634  count1->neverseesice[0] << "\t" << count1->neverseesice[1] << "\n";
4635 
4636 
4637  foutput.precision(4);
4638  foutput << "WhereDoesItEnterIce in PickUnbiased gives an error \t\t\t" << (double)count1->wheredoesitenterice_err[0]/(double)count1->neverseesice[0] << "\t" <<
4639  (double)count1->wheredoesitenterice_err[1]/(double)count1->neverseesice[1] << "\t\t" <<
4640  count1->wheredoesitenterice_err[0] << "\t" << count1->wheredoesitenterice_err[1] << "\n";
4641 
4642  foutput.precision(4);
4643  foutput << "Interaction point too high \t\t\t\t" << (double)count1->toohigh[0]/(double)count1->wheredoesitenterice_err[0] << "\t" <<
4644  (double)count1->toohigh[1]/(double)count1->wheredoesitenterice_err[1] << "\t\t" <<
4645  count1->toohigh[0] << "\t" << count1->toohigh[1] << "\n";
4646 
4647  foutput.precision(4);
4648  foutput << "Interaction point too low \t\t\t\t" << (double)count1->toolow[0]/(double)count1->toohigh[0] << "\t" <<
4649  (double)count1->toolow[1]/(double)count1->toohigh[1] << "\t\t" <<
4650  count1->toolow[0] << "\t" << count1->toolow[1] << "\n";
4651 
4652 
4653 
4654 
4655  foutput.precision(4);
4656  foutput << "There is an interaction in ice \t\t\t\t" << (double)count1->iceinteraction[0]/(double)count1->toolow[0] << "\t" <<
4657  (double)count1->iceinteraction[1]/(double)count1->toolow[1] << "\t\t" <<
4658  count1->iceinteraction[0] << "\t" << count1->iceinteraction[1] << "\n";
4659 
4660  foutput.precision(4);
4661  foutput << "In horizon \t\t\t\t\t\t" << (double)count1->inhorizon[0]/(double)count1->iceinteraction[0] << "\t" <<
4662  (double)count1->inhorizon[1]/(double)count1->iceinteraction[1] << "\t\t" <<
4663  count1->inhorizon[0] << "\t" << count1->inhorizon[1] << "\n";
4664 
4665 
4666 
4667  foutput.precision(4);
4668  foutput << "From surface to balloon, ray not intersected by earth \t" << (double)count1->nraypointsup1[0]/(double)count1->inhorizon[0] << "\t" <<
4669  (double)count1->nraypointsup1[1]/(double)count1->inhorizon[1] << "\t\t" <<
4670  count1->nraypointsup1[0] << "\t" << count1->nraypointsup1[1] << "\n";
4671 
4672  foutput.precision(4);
4673  foutput << "After 1/r scaling and best case attenuation, \n\tMaximum signal is detectable\t\t\t" << (double)count1->nnottoosmall[0]/(double)count1->nraypointsup1[0] << "\t" <<
4674  (double)count1->nnottoosmall[1]/(double)count1->nraypointsup1[1] << "\t\t"
4675  << count1->nnottoosmall[0] << "\t" << count1->nnottoosmall[1] << "\n";
4676 
4677 
4678  foutput.precision(4);
4679  foutput << "Viewing angle lt 90 degrees\t\t\t" << (double)count1->nviewangle_lt_90[0]/(double)count1->nnottoosmall[0] << "\t" <<
4680  (double)count1->nviewangle_lt_90[1]/(double)count1->nnottoosmall[1] << "\t\t"
4681  << count1->nviewangle_lt_90[0] << "\t" << count1->nviewangle_lt_90[1] << "\n";
4682 
4683 
4684  foutput.precision(4);
4685  foutput << "Reality check: EM and hadronic fractions both nonzero\t" << (double)count1->ngoodfracs[0]/(double)count1->nviewangle_lt_90[0] << "\t" <<
4686  (double)count1->ngoodfracs[1]/(double)count1->nviewangle_lt_90[1] << "\t\t"
4687  << count1->ngoodfracs[0] << "\t" << count1->ngoodfracs[1] << "\n";
4688  foutput.precision(4);
4689  foutput << "\tBoth EM and hadronic fractions are zero\t\t" << (double)count1->nbadfracs[0]/(double)count1->nviewangle_lt_90[0] << "\t" <<
4690  (double)count1->nbadfracs[1]/(double)count1->nviewangle_lt_90[1] << "\t\t" <<
4691  count1->nbadfracs[0] << "\t" << count1->nbadfracs[1] << "\n";
4692 
4693  foutput.precision(4);
4694  foutput << "After finding neutrino direction, \n\tchance of making through Earth\t\t\t" << (double)count_chanceofsurviving/(double)count1->ngoodfracs[0] << "\t\t\t";
4695  foutput.precision(10);
4696  foutput << count_chanceofsurviving << "\n";
4697  foutput.precision(4);
4698  foutput << "Neutrino enters ice south of 60deg S latitude\t\t" << (double)count1->nentersice[0]/(double)count_chanceofsurviving << "\t" <<
4699  (double)count1->nentersice[1]/(double)count_chanceofsurviving <<
4700  "\t\t" <<
4701  count1->nentersice[0] << "\t" << count1->nentersice[1] << "\n";
4702 
4703  foutput.precision(4);
4704  foutput << "Neutrino reasonably likely to survive trip through Earth " << (double)count1->nabsorbed[0]/(double)count1->nentersice[0] << "\t" <<
4705  (double)count1->nabsorbed[1]/(double)count1->nentersice[1] << "\t\t"
4706  << count1->nabsorbed[0] << "\t" << count1->nabsorbed[1] << "\n";
4707  foutput.precision(4);
4708  foutput << "Ray leaves the ice south of 60deg S latitude\t\t" << (double)count1->nraywithincontinent1[0]/(double)count1->nabsorbed[0] << "\t" <<
4709  (double)count1->nraywithincontinent1[1]/(double)count1->nabsorbed[1] << "\t" <<
4710  count1->nraywithincontinent1[0] << "\t" <<
4711  count1->nraywithincontinent1[1] << "\n";
4712 
4713  foutput.precision(4);
4714  foutput << "After 1/r, best guess ice attenuation, \n\tmaximum signal is detectable\t\t\t" << (double)count_chanceinhell0/(double)count1->nraywithincontinent1[0] << "\t\t\t";
4715  foutput.precision(10);
4716  foutput <<count_chanceinhell0 << "\n";
4717 
4718  foutput.precision(4);
4719  foutput << "Ray is not totally internally reflected\t\t\t" << (double)count1->nnottir[0]/(double)count_chanceinhell0 << "\t" <<
4720  (double)count1->nnottir[1]/(double)count_chanceinhell0 << "\t\t" <<
4721  count1->nnottir[0] << "\t" << count1->nnottir[1] << "\n";
4722 
4723  foutput.precision(4);
4724  foutput << "From surface to balloon, ray not intersected by earth \t" << (double)count1->nraypointsup2[0]/(double)count1->nnottir[0] << "\t" <<
4725  (double)count1->nraypointsup2[1]/(double)count1->nnottir[1] <<
4726  "\t\t"
4727  << count1->nraypointsup2[0] << "\t" << count1->nraypointsup2[1] << "\n";
4728  foutput.precision(4);
4729 
4730  foutput << "Ray leaves the ice south of 60deg S latitude\t\t" << (double)count1->nraywithincontinent2[0]/(double)count1->nraypointsup2[0] <<"\t" <<
4731  (double)count1->nraywithincontinent2[0]/(double)count1->nraypointsup2[1] <<
4732  "\t\t" << count1->nraywithincontinent2[0] << "\t" <<
4733  count1->nraywithincontinent2[1] << "\n";
4734  foutput.precision(4);
4735 
4736  foutput << "Ray leaves where there is ice\t\t\t\t" << (double)count1->nacceptablerf[0]/(double)count1->nraywithincontinent2[0] << "\t" <<
4737  (double)count1->nacceptablerf[1]/(double)count1->nraywithincontinent2[1] << "\t\t"
4738  << count1->nacceptablerf[0] << "\t" << count1->nacceptablerf[1] << "\n";
4739  foutput.precision(4);
4740 
4741  foutput << "Ray tracing converges to within 10 m\t\t\t" << (double)count1->nconverges[0]/(double)count1->nacceptablerf[0] << "\t" <<
4742  (double)count1->nconverges[1]/(double)count1->nacceptablerf[1] <<
4743  "\t\t" << count1->nconverges[0] << "\t" << count1->nconverges[1] << "\n";
4744  foutput.precision(4);
4745 
4746  foutput << "After fresnel coefficient, \n\tmaximum signal is detectable\t\t\t" << (double)count1->nchanceinhell_fresnel[0]/(double)count1->nconverges[0] << "\t" << (double)count1->nchanceinhell_fresnel[1]/(double)count1->nconverges[1] <<
4747  "\t\t" <<count1->nchanceinhell_fresnel[0] << "\t" << count1->nchanceinhell_fresnel[1] << "\n";
4748  foutput.precision(4);
4749  foutput << "After 1/r, \n\tmaximum signal is detectable\t\t\t" << (double)count1->nchanceinhell_1overr[0]/(double)count1->nchanceinhell_fresnel[0] << "\t" << (double)count1->nchanceinhell_1overr[1]/(double)count1->nchanceinhell_fresnel[1] << "\t\t" <<count1->nchanceinhell_1overr[0] << "\t" << count1->nchanceinhell_1overr[1] << "\n";
4750  foutput.precision(4);
4751 
4752  foutput << "After ice attenuation, \n\tmaximum signal is detectable\t\t\t" << (double)count1->nchanceinhell[0]/(double)count1->nchanceinhell_1overr[0] << "\t" <<
4753  (double)count1->nchanceinhell[1]/(double)count1->nchanceinhell_1overr[1] << "\t" <<count1->nchanceinhell[0] << "\t" << count1->nchanceinhell[1] << "\n";
4754  foutput.precision(4);
4755 
4756  foutput << "After viewing angle cut, \t\t\t\t" << (double)count1->nviewanglecut[0]/(double)count1->nchanceinhell[0] << "\t" << (double)count1->nviewanglecut[1]/(double)count1->nchanceinhell[1] << "\t\t" << count1->nviewanglecut[0] << " " << count1->nviewanglecut[1] << "\n";
4757 
4758  foutput.precision(4);
4759  foutput << "After factoring in off-Cerenkov cone tapering, \n\tMaximum signal is detectable\t\t\t" << (double)count1->nchanceinhell2[0]/(double)count1->nviewanglecut[0] << "\t" << (double)count1->nchanceinhell2[1]/(double)count1->nviewanglecut[1] << "\t\t" << count1->nchanceinhell2[0] << " " << count1->nchanceinhell2[1] << "\n";
4760 
4761  foutput << "Survive dead time \t\t\t\t\t" << (double)count1->ndeadtime[0]/(double)count1->nchanceinhell2[0] << "\t" << (double)count1->ndeadtime[1]/(double)count1->nchanceinhell2[1] << "\t\t" << (double)count1->ndeadtime[0] << " " << count1->ndeadtime[1] << "\n";
4762 
4763  foutput << "Passes trigger\t\t\t\t\t\t" << (double)count1->npassestrigger[0]/(double)count1->ndeadtime[0] << "\t" << (double)count1->npassestrigger[1]/(double)count1->ndeadtime[1] << "\t\t" << count1->npassestrigger[0] << "\t" << count1->npassestrigger[1] << "\n";
4764  foutput << "Number of l1 triggers\t\t\t\t\t\t" << (double)count1->nl1triggers[0][0] << "\t" << (double)count1->nl1triggers[1][0] << "\n";
4765 
4766  foutput << "Chord is good length\t\t\t\t\t" << (double)count_chordgoodlength/(double)count1->npassestrigger[0] << "\t\t\t";
4767  foutput.precision(10);
4768  foutput <<count_chordgoodlength << "\n";
4769  foutput.precision(4);
4770  foutput << "Neutrino's path in ice more than 1m \t\t\t" << (double)count_d2goodlength/(double)count_chordgoodlength << "\t\t\t";
4771  foutput.precision(10);
4772  foutput << count_d2goodlength << "\n";
4773  foutput.precision(4);
4774  foutput << "Events that pass all cuts\t\t\t\t" << (double)count1->npass[0]/(double)count_d2goodlength << "\t" << (double)count1->npass[1]/(double)count_d2goodlength << "\t\t";
4775  foutput.precision(10);
4776  foutput <<count1->npass[0] << "\t" << count1->npass[1] << "\n";
4777 
4778  cout << "Events that pass all cuts\t\t\t\t" << (double)count1->npass[0]/(double)count_d2goodlength << "\t" << (double)count1->npass[1]/(double)count_d2goodlength << "\t\t";
4779  cout <<count1->npass[0] << "\t" << count1->npass[1] << "\n";
4780 
4781 
4782  if (src_model)
4783  {
4784 
4785  TString str; str.Form("%s/source_times.txt", outputdir.Data());
4786  FILE * f = fopen(str.Data(),"w");
4787  std::vector<double> times;
4788  src_model->computeFluxTimeChanges(&times);
4789  for (unsigned i = 0; i < times.size(); i++)
4790  {
4791  fprintf(f,"%f\n", times[i]);
4792  }
4793  fclose(f);
4794  }
4795 
4796  // if (EXPONENT<=10||EXPONENT>100) {
4797  if ( src_model || spectra1->IsSpectrum() ) {
4798  double sum_events=0.;
4799  double thisenergy=0.;
4800  double thislen_int_kgm2=0.;
4801  // double *energy=spectra1->GetEnergyArray();
4802  // double *EdNdEdAdt=spectra1->GetEdNdEdAdt();
4803 
4804  // for models which don't have even spaced energy bin,
4805  double even_E;
4806  int N_even_E = 12;
4807  double integral=0;
4808  double min_energy = src_model ? settings1->SOURCE_MIN_E : spectra1->Getenergy()[0];
4809  double max_energy = src_model ? settings1->SOURCE_MAX_E : spectra1->Getenergy()[spectra1->GetE_bin()-1];
4810  even_E = ( max_energy - min_energy ) / ( (double) N_even_E );
4811 
4812  TH1 * src_flux = 0;
4813  if (src_model)
4814  {
4815  src_flux = src_model->estimateFlux(bn1->min_time,bn1->max_time, TMath::Power(10,min_energy-9), TMath::Power(10,max_energy-9), 2*N_even_E, 10000);
4816 // TFile fsrcflux("fsrcflux.root","RECREATE");
4817 // src_flux->Write();
4818  }
4819 
4820 
4821  for (int i=0;i<N_even_E;i++) {
4822  thisenergy=pow(10., (min_energy+((double)i)*even_E));
4823  primary1->GetSigma(thisenergy, sigma, thislen_int_kgm2, settings1, xsecParam_nutype, xsecParam_nuint);
4824 
4825  // are the units of this in log (eV) ???!????!??
4826  double EdNdEdAdt = src_model ? 1e9*src_flux->Interpolate(thisenergy*1e-9) : spectra1->GetEdNdEdAdt(log10(thisenergy));
4827 
4828  // EdNdEdAdt is in #/cm^2/s
4829  // need to be multiplied by 1e4 to change 1/cm2 to 1/m^2
4830  // can also be written dN/d(lnE)dAdt
4831  // = dN*log(10)/d(log E)dAdt
4832  // the bin spacing is 0.5
4833  // so # events ~ dN*log(10)*0.5/d(log E)dAdt
4834  sum_events+=even_E*log(10.)*( EdNdEdAdt*1e4 )/(thislen_int_kgm2/sig1->RHOH20);
4835  integral+=even_E*log(10.)*(EdNdEdAdt);
4836  cout << "thisenergy, EdNdEdAdt is " << thisenergy << " " << EdNdEdAdt << "\n";
4837  //foutput << "interaction length is " << thislen_int_kgm2/RHOH20 << "\n";
4838  }//end for N_even_E
4839  // for (int i=0;i<12;i++) {
4840  // thisenergy=pow(10., (spectra1->Getenergy())[0]+((double)i)*0.5);
4841  // primary1->GetSigma(thisenergy, sigma, thislen_int_kgm2, settings1, xsecParam_nutype, xsecParam_nuint);
4842  // // EdNdEdAdt is in #/cm^2/s
4843  // // can also be written dN/d(lnE)dAdt
4844  // // = dN*log(10)/d(log E)dAdt
4845  // // the bin spacing is 0.5
4846  // // so # events ~ dN*log(10)*0.5/d(log E)dAdt
4847  // sum_events+=0.5*log(10.)*(spectra1->GetEdNdEdAdt())[i]/(thislen_int_kgm2/sig1->RHOH20);
4848  // cout << "thisenergy, EdNdEdAdt is " << thisenergy << " " << spectra1->EdNdEdAdt[i] << "\n";
4849  // //foutput << "interaction length is " << thislen_int_kgm2/RHOH20 << "\n";
4850  // } //end for i
4851  //km3sr=volume*pow(1.E-3, 3)*sig1->RHOMEDIUM/RHOH20*sr*nevents/(double)NNU;
4852  cout << "SUM EVENTS IS " << sum_events << endl;
4853  cout << "INTEGRAL : " << integral << endl;
4854  sum_events*=volume*anita1->LIVETIME*sig1->RHOMEDIUM/sig1->RHOH20*nevents/(double)NNU*sr;
4855  // sum_events*=anita1->LIVETIME*km3sr*1e9;
4856  foutput << "volume, LIVETIME, sig1->RHOMEDIUM, RHOH20, nevents, NNU, sr are " << volume << " " << anita1->LIVETIME << " " << sig1->RHOMEDIUM << " " << sig1->RHOH20 << " " << nevents << " " << NNU << " " << sr << "\n";
4857  foutput << "Total events observed is " << sum_events << "\n";
4858  } //end if IsSpectrum
4859 
4860 }
4861 //end Summarize()
4862 
4863 
4864 double GetAirDistance(double altitude_bn, double beta) { // given beta=angle wrt horizontal that the ray hits the balloon, calculate distance that the ray traveled in air, including curvature of earth
4865  return EarthModel::R_EARTH*acos((altitude_bn+EarthModel::R_EARTH)/EarthModel::R_EARTH*(1-sin(beta)*sin(beta))+1/EarthModel::R_EARTH*sin(beta)*sqrt((altitude_bn+EarthModel::R_EARTH)*(altitude_bn+EarthModel::R_EARTH)*sin(beta)*sin(beta)-2*EarthModel::R_EARTH*altitude_bn-altitude_bn*altitude_bn));
4866 }
4867 //end GetAirDistance()
4868 
4869 
4870 double GetAverageVoltageFromAntennasHit(Settings *settings1, int *nchannels_perrx_triggered, double *voltagearray, double& volts_rx_sum) {
4871  double sum=0;
4872  int count_hitantennas=0;
4873  for (int i=0;i<settings1->NANTENNAS;i++) {
4874  if (nchannels_perrx_triggered[i]>=3) {
4875  sum+=voltagearray[i];
4876  count_hitantennas++;
4877  } //if
4878  } //for
4879  volts_rx_sum = sum;
4880  sum = sum/(double)count_hitantennas;
4881  return sum;
4882 }
4883 //end GetAverageVoltageFromAntennasHit()
4884 
4885 
4886 Vector GetPolarization(const Vector &nnu, const Vector &nrf2_iceside) {
4887  // Want to find a unit vector in the same plane as nnu and n_refr,
4888  // but perpendicular to n_refr, pointing away from nnu.
4889 
4890  // cross nnu with n_refr to get the direction of the B field.
4891  Vector n_bfield = nnu.Cross(nrf2_iceside);
4892  // cross b-field with nrf2_iceside to get the polarization vector.
4893  Vector n_pol = n_bfield.Cross(nrf2_iceside);
4894  n_pol = n_pol.Unit();
4895  // check and make sure E-field is pointing in the right direction.
4896  if (nnu*nrf2_iceside>0 && n_pol*nnu>0){
4897  cout << "error in GetPolarization. Event is " << inu << "\n";
4898  }
4899  return n_pol;
4900 }
4901 //end GetPolarization()
4902 
4903 
4904 void CloseTFile(TFile *hfile) {
4905  hfile->cd();
4906  hfile->Write();
4907  hfile->Close();
4908 }
4909 //end CloseTFile()
4910 
4911 
4912 double IsItDoubleBang(double exitlength, double plepton) {
4913  double gamma=plepton/MTAU;
4914  return 1-exp(-1*exitlength/(TAUDECAY_TIME*CLIGHT*gamma));
4915 }
4916 //end IsItDoubleBang()
4917 
4918 
4919 int WhereIsSecondBang(const Position &posnu, const Vector &nnu, double nuexitlength, double pnu, IceModel *antarctica1, const Position &r_bn, Position &posnu2, Position &rfexit_db, Vector &n_exit2bn_db) {
4920  double rnd1=0;
4921  double rnd2=2;
4922  double gamma=pnu/MTAU;
4923 
4924  if (exp(-1*nuexitlength/(TAUDECAY_TIME*CLIGHT*gamma))>0.999){
4925  rnd1=getRNG(RNG_SECOND_BANG)->Rndm()*nuexitlength;
4926  }
4927  else {
4928  while (rnd2>1-exp(-1*rnd1/(TAUDECAY_TIME*CLIGHT*gamma))) {
4929  rnd1=getRNG(RNG_SECOND_BANG)->Rndm()*nuexitlength;
4930  rnd2=getRNG(RNG_SECOND_BANG)->Rndm();
4931  } //while
4932  } //else
4933  posnu2 = posnu + rnd1*nnu;
4934  rfexit_db = antarctica1->Surface(posnu2)*posnu2.Unit();
4935 
4936  // unit vector pointing to antenna from exit point.
4937  n_exit2bn_db = (r_bn - rfexit_db) / r_bn.Distance(rfexit_db);
4938 
4939  double cosangle=(n_exit2bn_db * posnu2) / posnu2.Mag();
4940  if (cosangle<0){
4941  return 0;
4942  }
4943  return 1;
4944 }
4945 //end WhereIsSecondBang()
4946 
4947 
4948 //the following is a new function only for reflected case.
4949 void Attenuate_down(IceModel *antarctica1, Settings *settings1, double& vmmhz_max, const Position &rfexit2, const Position &posnu, const Position &posnu_down) {
4950  double ATTENLENGTH=700;
4951  if(!settings1->VARIABLE_ATTEN){
4952  ATTENLENGTH=antarctica1->EffectiveAttenuationLength(settings1, posnu, 1);
4953  }
4954 
4955  int position_in_iceshelves=antarctica1->IceOnWater(posnu);
4956  int position_in_rossexcept=antarctica1->RossExcept(posnu);
4957  // int position_in_ross = antarctica->RossIceShelf(posnu);
4958  // int position_in_ronne = antarctica->RonneIceShelf(posnu);
4959  double dtemp=posnu_down.Distance(rfexit2)/ATTENLENGTH;
4960 
4961  if (dtemp<20) {
4962  // if(position_in_ross || position_in_ronne) {
4963  if(position_in_iceshelves && (!position_in_rossexcept)){
4964  // scalefactor_attenuation=0.310227766*exp(-dtemp);
4965  // vmmhz_max=vmmhz_max*exp(-dtemp)*0.310227766;//10% of power reflected
4966  scalefactor_attenuation=0.71*exp(-dtemp);
4967  vmmhz_max=vmmhz_max*0.71*exp(-dtemp);//50% of power reflected. -3dB
4968  } //end if
4969  else if(position_in_rossexcept){
4970  scalefactor_attenuation=0.1*exp(-dtemp);
4971  vmmhz_max=0.1*vmmhz_max*exp(-dtemp);//1% of power reflected. -20dB
4972  }//end else if
4973  else {
4974  scalefactor_attenuation=sqrt(0.001)*exp(-dtemp);
4975  vmmhz_max=sqrt(0.001)*vmmhz_max*exp(-dtemp);//0.1% of power reflected.-30dB
4976  } //else
4977  } //if
4978  else {
4979  scalefactor_attenuation=0;
4980  vmmhz_max=0;
4981  } //else
4982 }
4983 //end Attenuate_down()
4984 
4985 
4986 void Attenuate(IceModel *antarctica1, Settings *settings1, double& vmmhz_max, double rflength, const Position &posnu) {
4987  double ATTENLENGTH=700; // constant attenuation length for now.
4988  if (!settings1->VARIABLE_ATTEN){
4989  ATTENLENGTH = antarctica1->EffectiveAttenuationLength(settings1, posnu, 0);
4990  }
4991 
4992  double dtemp=(rflength/ATTENLENGTH);
4993  if(!settings1->ROUGHNESS){
4994  if (dtemp<20) {
4995  scalefactor_attenuation=exp(-dtemp);
4996  vmmhz_max=vmmhz_max*exp(-dtemp);
4997  } //if
4998  else {
4999  scalefactor_attenuation=0;
5000  vmmhz_max=0;
5001  } //else
5002  }
5003  else{ // use a larger allowable value in case of roughness
5004  if (dtemp<10000) {
5005  scalefactor_attenuation=exp(-dtemp);
5006  vmmhz_max=vmmhz_max*exp(-dtemp);
5007  } //if
5008  else {
5009  scalefactor_attenuation=0;
5010  vmmhz_max=0;
5011  } //else
5012  }
5013 }
5014 //end Attenuate()
5015 
5016 
5017 void IsAbsorbed(double chord_kgm2, double len_int_kgm2, double &weight1) {
5018  // see if neutrino is absorbed
5019  // weighting works, but not to much purpose since nu's always
5020  // interact at these energies.
5021  double rtemp;
5022 
5023  rtemp=chord_kgm2/len_int_kgm2;
5024  if (rtemp<=20)
5025  weight1=exp(-rtemp);
5026  else
5027  weight1=0;
5028 }
5029 //end IsAbsorbed()
5030 
5031 
5032 void GetSmearedIncidentAngle(Vector &specular, Vector &nrf_iceside, Vector &n_exit2bn, double SMEARINCIDENTANGLE){
5033  // void GetSmearedIncidentAngle(Vector &specular, Vector &nsurf_rfexit, Vector &nrf_iceside, Vector &n_exit2bn, double SMEARINCIDENTANGLE, double theta_inc_smeared) {
5034  // Smear the incident angle for roughness studies
5035  specular+=nrf_iceside; // specular is the ray that we got from Snell's law
5036  Vector parallel_to_surface; // find vector parallel to surface to rotate the vector around
5037  parallel_to_surface+=n_exit2bn; // want to cross specular with n_exit2bn
5038  parallel_to_surface.Cross(specular);
5039  nrf_iceside.Rotate(SMEARINCIDENTANGLE*(2*getRNG(RNG_SMEARED_INCIDENT_ANGLE)->Rndm()-1.), parallel_to_surface); // smear the incident ray
5040  // theta_inc_smeared=acos(nrf_iceside.Dot(nsurf_rfexit));
5041 }
5042 //end GetSmearedIncidentAngle()
5043 
5044 
5045 int GetRayIceSide(const Vector &n_exit2rx, const Vector &nsurf_rfexit, double nexit, double nenter, Vector &nrf2_iceside) {
5046  // this function performs snell's law in three dimensions
5047  double costh=0;
5048  double NRATIO=nexit/nenter;
5049  costh=(n_exit2rx*nsurf_rfexit)/(n_exit2rx.Mag() * nsurf_rfexit.Mag()); // cos(theta) of the transmission angle
5050 
5051  if (costh<0) {
5052  //cout << "returning 0. inu is " << inu << "\n";
5053  return 0;
5054  }
5055  double sinth=sqrt(1 - costh*costh);
5056  double factor=NRATIO*costh-sqrt(1-(NRATIO*sinth*NRATIO*sinth));
5057  nrf2_iceside = -factor*nsurf_rfexit + NRATIO*n_exit2rx;
5058  nrf2_iceside = nrf2_iceside.Unit(); // normalize
5059  return 1;
5060 }
5061 //end GetRayIceSide()
5062 
5063 
5064 int GetDirection(Settings *settings1, Interaction *interaction1, const Vector &refr, double deltheta_em, double deltheta_had, double emfrac, double hadfrac, double vmmhz1m_max, double r_fromballoon, Ray *ray1, Signal *sig1, Position posnu, Anita *anita1, Balloon *bn1, Vector &nnu, double& costhetanu, double& theta_threshold) {
5065 
5066  // in the specular (settings1->ROUGHNESS = 0) this function sets the neutrino direction according to a selection routine based on veiweing within the Cerenkov cone
5067 
5068  // in the roughness case we just want to pick a random allowable direction, so let's keep the original sampled neutrino direction from back in IceModel::PickUnbiased() inside Ray::PickRoughnessInteractionPoint()
5069 
5070  //if (!settings1->ROUGHNESS){ // no roughness, use the original routine
5071  int dont_count=0;
5072  double theta_test=0;
5073  double vmmhz1m_test=0;
5074  double costhetanu1 = 0;
5075  double costhetanu2 = 0;
5076 
5077  if (bn1->WHICHPATH==3) { //To make a banana plot, force neutrino direction
5078  nnu = interaction1->nnu_banana;
5079  theta_threshold = 0; //not used for anything in banana plots
5080  return 1;
5081  } //if (make banana plot)
5082 
5083 
5084  if (settings1->SKIPCUTS || !settings1->USEDIRECTIONWEIGHTS) { // this is a setting that allows all neutrino angles, no restriction. Makes the code slower.
5085  costhetanu2=1.;
5086  costhetanu1=-1.;
5087  theta_threshold=1;
5088  } //end if (settings1->SKIPCUTS || !USEWEIGHTS)
5089  else {
5090  if (emfrac<=1.E-10 && deltheta_had >1.E-10) {
5091  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(hadfrac*vmmhz1m_max/r_fromballoon*heff_max*anita1->bwmin/1.E6)*sin(sig1->changle)>1)
5092  //if (Tools::dMax(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(hadfrac*vmmhz1m_max*heff_max*bw/1.E6)*sin(sig1->changle)>1)
5093  theta_threshold=-1;
5094  else {
5095  //theta_threshold=sqrt(-1*deltheta_had*deltheta_had*log(Tools::dMax(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(hadfrac*vmmhz1m_max*heff_max*bw/1.E6)*sin(sig1->changle))/ALOG2);
5096  theta_threshold=sqrt(-1*deltheta_had*deltheta_had*log(anita1->VNOISE[0]/10.*anita1->maxthreshold/(hadfrac*vmmhz1m_max/r_fromballoon*heff_max*anita1->bwmin/1.E6)*sin(sig1->changle))/ALOG2);
5097  averaging_thetas1+=theta_threshold;
5098  } //else
5099  count_inthisloop1++;
5100  } //if
5101 
5102  if (emfrac>1.E-10 && deltheta_had <=1.E-10) {
5103  dont_count++;
5104  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(emfrac*vmmhz1m_max/r_fromballoon*heff_max*anita1->bwmin/1.E6)*sin(sig1->changle)>1)
5105  //if (Tools::dMax(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(emfrac*vmmhz1m_max*heff_max*bw/1.E6)*sin(sig1->changle)>1)
5106  theta_threshold=-1;
5107  else {
5108  //theta_threshold=sqrt(-1*deltheta_em*deltheta_em*log(Tools::dMax(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(emfrac*vmmhz1m_max*heff_max*bw/1.E6)*sin(sig1->changle))/0.5);
5109  theta_threshold=sqrt(-1*deltheta_em*deltheta_em*log(anita1->VNOISE[0]/10.*anita1->maxthreshold/(emfrac*vmmhz1m_max/r_fromballoon*heff_max*anita1->bwmin/1.E6)*sin(sig1->changle))/0.5);
5110  averaging_thetas2+=theta_threshold;
5111  } //else
5112  count_inthisloop2++;
5113  } //if
5114 
5115 
5116  //start big code block of ifs/elses
5117  if (emfrac>1.E-10 && deltheta_had>1.E-10) {
5118  // if the electromagnetic and hadronic components of the shower are both non-negligible
5119  // then theta_threshold cannot be determined analytically so we step away from the cerenkov angle in steps equal to 1/2 * deltheta_em
5120  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/((hadfrac+emfrac)*vmmhz1m_max/r_fromballoon*heff_max*anita1->bwmin/1.E6)>1.) {
5121  //if (Tools::dMin(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/((hadfrac+emfrac)*vmmhz1m_max*heff_max*bw/1.E6)>1.) {
5122  theta_threshold=-1.; // if it's not detectable at all
5123  }
5124  else { // otherwise, start stepping.
5125  theta_test=deltheta_em; // this is the angle we start stepping at
5126  vmmhz1m_test=vmmhz1m_max; // this will be the magnitude of the signal at theta_test away from the cerenkov cone.
5127  // find the magnitude of the signal at theta_test away from the cerenkov cone.
5128  sig1->TaperVmMHz(sig1->changle+theta_test, deltheta_em, deltheta_had, emfrac, hadfrac, vmmhz1m_test, djunk);
5129  // if (Tools::dMin(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(vmmhz1m_test*heff_max*bw/1.E6)>1.) { // is this electric field already too low to have a chance of passing the trigger threshold?
5130  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(vmmhz1m_test/r_fromballoon*heff_max*anita1->bwmin/1.E6)>1.) { // is this electric field already too low to have a chance of passing the trigger threshold?
5131  theta_threshold=theta_test; // then that is the maximum angular deviation
5132  }
5133  else { // otherwise increment by the step size and check again.
5134  theta_test=1.5*deltheta_em;
5135  vmmhz1m_test=vmmhz1m_max;
5136  sig1->TaperVmMHz(sig1->changle+theta_test, deltheta_em, deltheta_had, emfrac, hadfrac, vmmhz1m_test, djunk);
5137 
5138  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(vmmhz1m_test/r_fromballoon*heff_max*anita1->bwmin/1.E6)>1.) {
5139  //if (Tools::dMin(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(vmmhz1m_test*heff_max*bw/1.E6)>1.) {
5140  theta_threshold=theta_test;
5141  }
5142  else { // otherwise increment by the step size and check again.
5143  theta_test=2*deltheta_em;
5144  vmmhz1m_test=vmmhz1m_max;
5145  sig1->TaperVmMHz(sig1->changle+theta_test, deltheta_em, deltheta_had, emfrac, hadfrac, vmmhz1m_test, djunk);
5146  //if (Tools::dMin(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(vmmhz1m_test*heff_max*bw/1.E6)>1.)
5147  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(vmmhz1m_test/r_fromballoon*heff_max*anita1->bwmin/1.E6)>1.)
5148  theta_threshold=theta_test;
5149  else { // otherwise increment by the step size and check again.
5150  theta_test=3*deltheta_em;
5151  vmmhz1m_test=vmmhz1m_max;
5152  sig1->TaperVmMHz(sig1->changle+theta_test, deltheta_em, deltheta_had, emfrac, hadfrac, vmmhz1m_test, djunk);
5153  //if (Tools::dMin(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(vmmhz1m_test*heff_max*bw/1.E6)>1.)
5154 
5155  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(vmmhz1m_test/r_fromballoon*heff_max*anita1->bwmin/1.E6)>1.)
5156  theta_threshold=theta_test;
5157  else { // otherwise, set is the the width of the hadronic component (much wider than the electromagnetic component)
5158  theta_test=deltheta_had;
5159  vmmhz1m_test=vmmhz1m_max;
5160  sig1->TaperVmMHz(sig1->changle+theta_test, deltheta_em, deltheta_had, emfrac, hadfrac, vmmhz1m_test, djunk);
5161  // if at the hadronic width, you're below the threshold
5162  if (anita1->VNOISE[0]/10.*anita1->maxthreshold/(vmmhz1m_test/r_fromballoon*heff_max*anita1->bwmin/1.E6)>1.)
5163  //if (Tools::dMin(VNOISE, settings1->NLAYERS)*anita1->maxthreshold/(vmmhz1m_test*heff_max*bw/1.E6)>1.) // if at the hadronic width, you're below the threshold
5164  theta_threshold=theta_test; // set theta_threshold
5165  else { // otherwise, find theta_threshold considering the hadronic component alone. This is conservative-- an electromagnetic component would only make it narrower.
5166  theta_threshold=sqrt(-1*deltheta_had*deltheta_had*log(anita1->VNOISE[0]/10.*anita1->maxthreshold/(hadfrac*vmmhz1m_max/r_fromballoon*heff_max*anita1->bwmin/1.E6)*sin(sig1->changle))/0.5);
5167  } // else: not below threshold at deltheta_had
5168  } // else: not below threshold at 3*deltheta_em
5169 
5170  } // else: not below threshold at 2.5*deltheta_em
5171  } // else: not below threshold at 2.0*deltheta_em
5172 
5173  } // else: not below threshold at 1.5*deltheta_em
5174 
5175  } // not below threshold at 1.0*deltheta_em
5176  count_inthisloop3++;
5177  averaging_thetas3+=theta_threshold;
5178 
5179  } // end if both the em and hadronic components are non-negligible.
5180  //end big code block of ifs/elses
5181 
5182  theta_threshold*=settings1->THETA_TH_FACTOR; // multiply theta_threshold by scale factor if requested, for testing purposes.
5183  if (theta_threshold>0) { // we only pick the angle between 0 and pi so set the upper and lower limits accordingly.
5184  if (sig1->changle-theta_threshold<0 && sig1->changle+theta_threshold> PI) {
5185  costhetanu2=1.;
5186  costhetanu1=-1.;
5187  } //if
5188  else if (sig1->changle-theta_threshold>0 && sig1->changle+theta_threshold> PI) {
5189  costhetanu2=cos(sig1->changle-theta_threshold);
5190  costhetanu1=-1.;
5191  } //else if
5192  else if (sig1->changle-theta_threshold<0 && sig1->changle+theta_threshold< PI) {
5193  costhetanu2=1.;
5194  costhetanu1=cos(sig1->changle+theta_threshold);
5195  } //else if
5196  else if (sig1->changle-theta_threshold>0 && sig1->changle+theta_threshold< PI) {
5197  costhetanu2=cos(sig1->changle-theta_threshold);
5198  costhetanu1=cos(sig1->changle+theta_threshold);
5199  } //else if
5200  } // end if theta_threshold>0
5201 
5202 
5203  } // if SKIP_CUTS !=0
5204 
5205  if (theta_threshold>0) {
5206  // pick the neutrino direction, in a coordinate system where the z axis lies along the cerenkov cone.
5207  costhetanu=costhetanu1+getRNG(RNG_DIRECTION)->Rndm()*(costhetanu2-costhetanu1);
5208 
5209  double phinu=TWOPI*getRNG(RNG_DIRECTION)->Rndm(); // pick the phi of the neutrino direction, in the same coordinate system.
5210  double sinthetanu=sqrt(1-costhetanu*costhetanu);
5211  // 3-vector of neutrino direction, at that same coordinate system.
5212  nnu = Vector(sinthetanu*cos(phinu), sinthetanu*sin(phinu), costhetanu);
5213  nnu = nnu.ChangeCoord(refr); // rotate so it's in our normal coordinate system.
5214  // now the ray is aligned along the cerenkov cone and
5215  // the neutrino is rotated by that same angle
5216 
5217  //dtryingdirection+=4*PI/(2.*theta_threshold*sin(sig1->changle)*2*PI);
5218  interaction1->dtryingdirection=1/((costhetanu2-costhetanu1)/2.);
5219  if (bn1->WHICHPATH==4) {
5220  //double angle=(PI/2.-sig1->changle)-ray1->rfexit[0].Angle(ray1->nrf_iceside[4])+1.*RADDEG;
5221  double angle=(PI/2.-sig1->changle)-ray1->rfexit[0].Angle(ray1->nrf_iceside[4]); // this will put the viewing angle at the cerenkov angle
5222  double thetaposnu=posnu.Theta();
5223  //double phiposnu=posnu.Phi();
5224  costhetanu=cos(PI/2+(thetaposnu-angle));
5225  sinthetanu=sqrt(1-costhetanu*costhetanu);
5226  //phinu=0.95993;
5227  phinu=-1.339; // this is the phi where it's coming *from.*
5228  // we want the neutrino to be headed north
5229  nnu = Vector(-1.*sinthetanu*cos(phinu), -1.*sinthetanu*sin(phinu), -1.*costhetanu);// 3-vector of neutrino direction, at that same coordinate system.
5230  }
5231  return 1;
5232  } //end if theta_threshold
5233  else if (theta_threshold==-1.) {
5234  cout << "theta_threshold is " << theta_threshold << "\n";
5235  return 0;
5236  }
5237  else if (emfrac<=1.E-10 && deltheta_had <= 1.E-10) {
5238  cout << "Error: emfrac, hadfrac are (1st place)" << emfrac << " " << hadfrac << " " << "\n";
5239  return 0;
5240  } //else if
5241 
5242  return 0;
5243  //} // end NO ROUGHNESS
5244 
5245  // treat the roughness case
5246  /*else if(settings1->ROUGHNESS){
5247  //copy SKIPCUTS and USEDIRECTIONWEIGHTS from earlier in this function
5248  double costhetanu2=1.;
5249  double costhetanu1=-1.;
5250  double costhetanu=costhetanu1+gRandom->Rndm()*(costhetanu2-costhetanu1);
5251 
5252  double phinu=TWOPI*gRandom->Rndm(); // pick the phi of the neutrino direction, in the same coordinate system.
5253  double sinthetanu=sqrt(1-costhetanu*costhetanu);
5254  // 3-vector of neutrino direction, at that same coordinate system.
5255  nnu = Vector(sinthetanu*cos(phinu), sinthetanu*sin(phinu), costhetanu);
5256  nnu = nnu.ChangeCoord(refr); // rotate so it's in our normal coordinate system.
5257  // now the ray is aligned along the cerenkov cone and
5258  // the neutrino is rotated by that same angle
5259 
5260  //dtryingdirection+=4*PI/(2.*theta_threshold*sin(sig1->changle)*2*PI);
5261  interaction1->dtryingdirection=1/((costhetanu2-costhetanu1)/2.);
5262  }
5263 
5264  else{ //something bad happened
5265  cout<<"Something bad happened in GetDirection."<<endl;
5266  return 1;
5267  }*/
5268 }
5269 //end GetDirection()
5270 
5271 
5272 double ScaleVmMHz(double vmmhz1m_max, const Position &posnu1, const Position &r_bn, const Position &rfexit) {
5273 
5274  //ofstream oindree_file;
5275  //oindree_file.open("oindree_file.txt",std::ios_base::app);
5276 
5277  double dtemp1 = r_bn.Distance(rfexit);
5278 
5279  double dtemp2 = rfexit.Distance(posnu1);
5280 
5281  //double dtemp = r_bn.Distance(rfexit) + rfexit.Distance(posnu1);
5282 
5283  double dtemp = dtemp1 + dtemp2;
5284 
5285  vmmhz1m_max= vmmhz1m_max/dtemp;
5286 
5287  scalefactor_distance=1/dtemp;
5288 
5289  //cout << "Oindree: dtemp1 is " << dtemp1 << " dtemp2 is " << dtemp2 << " dtemp is " << dtemp << "\n";
5290  //oindree_file << dtemp1 << " " << dtemp2 << " " << vmmhz1m_max << "\n";
5291 
5292  return vmmhz1m_max;
5293 
5294 }
5295 //end ScaleVmMHz()
5296 
5297 
5298 void SetupViewangles(Signal *sig1) {
5299  double viewangle_max=90.*RADDEG;
5300  double viewangle_min=30.*RADDEG;
5301  for (int i=0;i<NVIEWANGLE-2;i++) {
5302  viewangles[i]=viewangle_max-(viewangle_max-viewangle_min)/(double)(NVIEWANGLE-2)*(double)i;
5303  }
5304  viewangles[NVIEWANGLE-2]=acos(1/sig1->N_DEPTH);
5305  viewangles[NVIEWANGLE-1]=90.*RADDEG;
5306 }
5307 //end SetupViewAngles()
5308 
5309 
5310 double GetThisAirColumn(Settings* settings1, Position r_in, Vector nnu, Position posnu, double *col1, double& cosalpha, double& mytheta, double& cosbeta0, double& mybeta) {
5311  double myair=0; // this is the output
5312  // it is the column of air in kg/m^2
5313  cosalpha=(r_in * nnu) / r_in.Mag(); // cosangle that the neutrino enters the earth wrt surface normal at its entrry point
5314  mytheta=(double)(acos(cosalpha)*DEGRAD)-90.; // turn this into an angle
5315 
5316  //------------------added on Dec 8------------------------
5317  if (settings1->ATMOSPHERE) {
5318  int index11=int(mytheta*10.); // which index this theta corresponds to
5319  int index12=index11+1;
5320  // find column of air at this theta
5321  myair=(col1[index11]+(col1[index12]-col1[index11])*(mytheta*10.-double(index11)))*10.;//unit is kg/m^2
5322  }
5323  else
5324  myair=0.;//don't include effect of atmosphere
5325 
5326  //cout<<"mytheta="<<mytheta<<"; myair="<<myair<<endl;
5327  //------------------added on Dec 8------------------------
5328  cosbeta0= (posnu * nnu) / posnu.Mag(); // cos angle of neutrino wrt person standing over the interaction point
5329  mybeta=(double)(acos(cosbeta0)*DEGRAD)-90.; // turn that into a theta
5330  return myair;
5331 }
5332 //end GetThisAirColumn()
5333 
5334 
5335 void GetAir(double *col1) {
5336  double nothing;
5337  ifstream air1(ICEMC_SRC_DIR+"/data/atmosphere.dat"); // length of chord in air vs. theta (deg)
5338  //where theta is respect to "up"
5339  // binned in 0.1 degrees
5340  for(int iii=0;iii<900;iii++) {
5341  air1>>nothing>>col1[iii];
5342  } // read in chord lengths
5343 }
5344 //end GetAir()
5345 
5346 
5347 int TIR(const Vector &n_surf, const Vector &nrf2_iceside, double N_IN, double N_OUT) {
5348  double test=sin(nrf2_iceside.Angle(n_surf))*N_IN/N_OUT;
5349  if(test>=1)
5350  return 1;
5351  else
5352  return 0;
5353 
5354  return 0;
5355 }
5356 //end TIR()
5357 
5358 
5359 double GetViewAngle(const Vector &nrf2_iceside, const Vector &nnu) {
5360  // get viewing angle of shower
5361  //cout << "nnu inside GetViewAngle : " << nnu << " nrf2_iceside " << nrf2_iceside << "\n";
5362  double dtemp = nrf2_iceside*nnu;
5363  if (dtemp>=1 && dtemp<1.02)
5364  dtemp=0.999999;
5365  if (dtemp<=-1 && dtemp>-1.02)
5366  dtemp=-0.9999999;
5367 
5368  //cout << "return " << acos(dtemp) << "\n";
5369 
5370  return acos(dtemp);
5371 }
5372 //end ())etViewAngle
5373 
5374 
5375 TStyle* RootStyle() {
5376  TStyle *RootStyle = new TStyle("Root-Style", "The Perfect Style for Plots ;-)");
5377 
5378 #ifdef __CINT__
5379  TStyle *GloStyle;
5380  GloStyle = gStyle; // save the global style reference
5381  gStyle = RootStyle;
5382 #endif
5383  // otherwise you need to call TROOT::SetStyle("Root-Style")
5384 
5385  // Paper size
5386  RootStyle->SetPaperSize(TStyle::kUSLetter);
5387 
5388  // Canvas
5389  RootStyle->SetCanvasColor (0);
5390  RootStyle->SetCanvasBorderSize(10);
5391  RootStyle->SetCanvasBorderMode(0);
5392  RootStyle->SetCanvasDefH (600);
5393  RootStyle->SetCanvasDefW (600);
5394  RootStyle->SetCanvasDefX (10);
5395  RootStyle->SetCanvasDefY (10);
5396 
5397  // Pads
5398  RootStyle->SetPadColor (0);
5399  RootStyle->SetPadBorderSize (10);
5400  RootStyle->SetPadBorderMode (0);
5401  // RootStyle->SetPadBottomMargin(0.13);
5402  RootStyle->SetPadBottomMargin(0.16);
5403  RootStyle->SetPadTopMargin (0.08);
5404  RootStyle->SetPadLeftMargin (0.18);
5405  RootStyle->SetPadRightMargin (0.05);
5406  RootStyle->SetPadGridX (0);
5407  RootStyle->SetPadGridY (0);
5408  RootStyle->SetPadTickX (1);
5409  RootStyle->SetPadTickY (1);
5410 
5411  // Frames
5412  RootStyle->SetFrameFillStyle ( 0);
5413  RootStyle->SetFrameFillColor ( 0);
5414  RootStyle->SetFrameLineColor ( 1);
5415  RootStyle->SetFrameLineStyle ( 0);
5416  RootStyle->SetFrameLineWidth ( 2);
5417  RootStyle->SetFrameBorderSize(10);
5418  RootStyle->SetFrameBorderMode( 0);
5419 
5420 
5421  // Histograms
5422  RootStyle->SetHistFillColor(0);
5423  RootStyle->SetHistFillStyle(1);
5424  RootStyle->SetHistLineColor(1);
5425  RootStyle->SetHistLineStyle(0);
5426  RootStyle->SetHistLineWidth(2);
5427 
5428  // Functions
5429  RootStyle->SetFuncColor(1);
5430  RootStyle->SetFuncStyle(0);
5431  RootStyle->SetFuncWidth(1);
5432 
5433  //Legends
5434  RootStyle->SetStatBorderSize(2);
5435  RootStyle->SetStatFont (42);
5436  // RootStyle->SetOptStat (111111);
5437  RootStyle->SetOptStat (0);
5438  RootStyle->SetStatColor (0);
5439  RootStyle->SetStatX (0.93);
5440  RootStyle->SetStatY (0.90);
5441  RootStyle->SetStatFontSize (0.07);
5442  // RootStyle->SetStatW (0.2);
5443  // RootStyle->SetStatH (0.15);
5444 
5445  // Labels, Ticks, and Titles
5446  RootStyle->SetTickLength ( 0.015, "X");
5447  RootStyle->SetTitleSize ( 0.10, "X");
5448  RootStyle->SetTitleOffset( 1.20, "X");
5449  RootStyle->SetTitleBorderSize(0);
5450  // RootStyle->SetTitleFontSize((double)3.);
5451  RootStyle->SetLabelOffset( 0.015, "X");
5452  RootStyle->SetLabelSize ( 0.050, "X");
5453  RootStyle->SetLabelFont ( 42 , "X");
5454  RootStyle->SetTickLength ( 0.015, "Y");
5455  RootStyle->SetTitleSize ( 0.10, "Y");
5456  RootStyle->SetTitleOffset( 0.600, "Y");
5457  RootStyle->SetLabelOffset( 0.015, "Y");
5458  RootStyle->SetLabelSize ( 0.050, "Y");
5459  RootStyle->SetLabelFont ( 42 , "Y");
5460  RootStyle->SetTitleFont (42, "XY");
5461  RootStyle->SetTitleColor (1);
5462 
5463  // Options
5464  RootStyle->SetOptFit (0);
5465  RootStyle->SetMarkerStyle(20);
5466  RootStyle->SetMarkerSize(0.4);
5467 
5468  // cout << ">> Style initialized with the Root Style!" << endl;
5469  // cout << ">> " << modified << endl << endl;
5470  return RootStyle;
5471 }
5472 //end RootStyle()
5473 
5474 
5475 void GetFresnel(Roughness *rough1, int ROUGHNESS_SETTING, const Vector &surface_normal,
5476  const Vector &air_rf,
5477  Vector &pol,
5478  const Vector &firn_rf,
5479  double efield,
5480  double emfrac, double hadfrac, double deltheta_em_max, double deltheta_had_max,
5481  double &t_coeff_pokey, double &t_coeff_slappy,
5482  double &fresnel,
5483  double &mag) {
5484 
5485  // find angle of incidence and angle of transmission
5486  double incident_angle = surface_normal.Angle(firn_rf);
5487  double transmitted_angle = surface_normal.Angle(air_rf);
5488 
5489  // double t_coeff_pokey, t_coeff_slappy;
5490 
5491  // this is perp the surface normal and transmitted ray, parallel to surface
5492  Vector perp = air_rf.Cross(surface_normal).Unit();
5493  // this is in the bending plane
5494  Vector air_parallel = perp.Cross(air_rf).Unit();
5495  // this is in the bending plane
5496  Vector firn_parallel = perp.Cross(firn_rf).Unit();
5497 
5498  // component of polarization (in the air) perp to surface normal
5499  double pol_perp_firn = pol*perp; // this is the slappy component in the firn
5500  double pol_parallel_firn = pol*firn_parallel; // this is the pokey component in the firn
5501  double pol_perp_air=0, pol_parallel_air=0;
5502 
5503  double r_coeff_pokey = tan(incident_angle - transmitted_angle) / tan(incident_angle + transmitted_angle);
5504  t_coeff_pokey = sqrt((1. - r_coeff_pokey*r_coeff_pokey));
5505  pol_parallel_air = t_coeff_pokey * pol_parallel_firn; // find pokey component in the air
5506 
5507  double r_coeff_slappy = sin(incident_angle - transmitted_angle) / sin(incident_angle + transmitted_angle);
5508  t_coeff_slappy = sqrt((1. - r_coeff_slappy*r_coeff_slappy));
5509  pol_perp_air = t_coeff_slappy * pol_perp_firn; // find slappy component in the firn
5510 
5511  mag=sqrt( tan(incident_angle) / tan(transmitted_angle) );
5512 
5513  fresnel = sqrt( pow(efield * pol_perp_air, 2) + pow(efield * pol_parallel_air, 2)) / efield;
5514 
5515  pol = (pol_perp_air * perp + pol_parallel_air * air_parallel).Unit();
5516 //cerr<<"(spec): inc "<<incident_angle*180./PI<<" : trans "<<transmitted_angle*180./PI<<" : tpokey "<<t_coeff_pokey<<" : tslappy "<<t_coeff_slappy<< endl;
5517 }
5518 //end GetFresnel()
5519 
5520 
5521 void GetBalloonLocation(Interaction *interaction1,Ray *ray1,Balloon *bn1,IceModel *antarctica) {
5522  // brian enter function to calculate balloon position on your map.
5523  // use interaction1->posnu // location of neutrino interaction
5524  // coordinate system: +z="up" at the south pole
5525  // bn1->r_bn
5526  // nnu
5527  // ray1->nsurf_rfexit
5528 
5529 
5530  // brian enter function to calculate balloon position on your map.
5531  // use interaction1->posnu // location of neutrino interaction
5532  // coordinate system: +z="up" at the south pole
5533  // bn1->r_bn
5534  // nnu
5535 
5536 
5537  // balloonvector = balloonvector - nuvector;//change origin to the nuetrino interaction point
5538 
5539  const Vector nuvector = interaction1->nnu;
5540  // double interactiondepth = nuvector[2];//NOT CORRECT! need depth BELOW the ice. this is height above center of earth.
5541 
5542  Vector zcoordvector = ray1->nsurf_rfexit;
5543  zcoordvector=zcoordvector.Unit();
5544 
5545  // double thetainc =acos(zcoordvector.Dot(nuvector))*180/PI;
5546  //nsurf_rfexit is z direction for new coordinate system. Need to make sure the n-vector is in x-z plane.
5547 
5548  Vector xcoordvector = nuvector-(zcoordvector.Dot(nuvector))*zcoordvector;//xcoordvector is such that nnu lies in the x-z plane
5549  xcoordvector = xcoordvector.Unit();
5550 
5551  const Vector ycoordvector = zcoordvector.Cross(xcoordvector);//Need this for ChangeCoord.
5552 
5553 
5554  Vector origin_brian_tmp;
5555  if (interaction1->nnu.Dot(zcoordvector)>0) // up going
5556  origin_brian_tmp=interaction1->nuexit; // the origin is the neutrino exit point
5557  else {
5558  Vector nnu_flipped=interaction1->nnu;
5559  nnu_flipped=nnu_flipped-2.*nnu_flipped.Dot(zcoordvector)*zcoordvector; // take it's upgoing reflection from surface
5560 
5561  Position nuexit_flipped;
5562  if (Ray::WhereDoesItLeave(interaction1->posnu,nnu_flipped,antarctica,nuexit_flipped))
5563  origin_brian_tmp=nuexit_flipped;
5564  }// end else
5565 
5566  Vector r_bn_tmp=bn1->r_bn-origin_brian_tmp;
5567  r_bn_tmp=r_bn_tmp.ChangeCoord(xcoordvector,ycoordvector);//change coordinates
5568 
5569  // double balloondist =r_bn_tmp.Mag();//this is above center of earth, if i understand correctly. Need above the surface of the earth.
5570  double balloonphi = r_bn_tmp.Phi(); //phi position of the balloon
5571  if (balloonphi>PI)
5572  balloonphi=balloonphi-2*PI;
5573 
5574  double balloontheta = r_bn_tmp.Theta();// costheta position of the baloon
5575  // get this by dotting ray1->nsurf_rfexit with nnu?
5576  // double thetainc = acos(interaction1->nnu[2])*180/PI; //nnu is unit vector; cos(thetainc) = z/r
5577  balloontheta = PI-balloontheta;//walter.cc uses a pos z as down. this corrects for that.
5578 
5579  // define a coordinate system with ray1->nsurf_rfexit defining +z
5580  // nnu direction defines the x-z plane
5581  // find balloon position in that coordinate system
5582  //to get the values from walter.cc we need : E_shower, correlation length, rms height and the em_frac and had_frac. the last
5583  // two are so we can multiply the number from sky maps by the correct frac and then add the em and hadronic portion together
5584  // to get the total.
5585 }
5586 
5587 
5588 void interrupt_signal_handler(int sig){
5589  signal(sig, SIG_IGN);
5590  ABORT_EARLY = true;
5591  return;
5592 }
5593 //end interrupt_signal_handler()
5594 
5595 
5596 #ifdef ANITA_UTIL_EXISTS
5597 //int GetIceMCAntfromUsefulEventAnt(Anita *anita1, AnitaGeomTool *AnitaGeom1, int UsefulEventAnt){
5598 int GetIceMCAntfromUsefulEventAnt(Settings *settings1, int UsefulEventAnt){
5599  //int layer_temp = IceMCLayerPosition[UsefulEventIndex][0];
5600  //int position_temp = IceMCLayerPosition[UsefulEventIndex][1];
5601  //int IceMCIndex = anita1->GetRx(layer_temp, position_temp);
5602  int IceMCAnt = UsefulEventAnt;
5603  if ((settings1->WHICH==9 || settings1->WHICH==10) && UsefulEventAnt<16) {
5604  IceMCAnt = (UsefulEventAnt%2==0)*UsefulEventAnt/2 + (UsefulEventAnt%2==1)*(UsefulEventAnt/2+8);
5605  }
5606 
5607  return IceMCAnt;
5608 }
5609 //end GetIceMCAntfromUsefulEventAnt()
5610 
5611 
5612 #endif
void AddTparallel_polPerpendicular(double A)
Appends a parallel transmission coefficient value to the fTcoeff_parl array.
Definition: screen.cc:249
UInt_t eventNumber
Event number from software.
Definition: RawAnitaEvent.h:33
double weight_bestcase
what weight1 would be if whole earth had density of crust - for quick and dirty calculation of best c...
Definition: Primaries.h:200
int getDirectionAndEnergy(Vector *nudir, double t, double &nuE, double minE=1e9, double maxE=1e12)
Definition: source.cc:518
UShort_t lowerL2TrigPattern
Bit mask for lower ring l2 cluster triggers. eg. if the bit 1 (the lowest bit) is active it means the...
UChar_t surfSlipFlag
Sync Slip between SURF 2-9 and SURF 1.
Double_t h_component_k[48]
Component of the e-field along the rx h-plane.
void SetUnitX(Vector a)
Sets an orientation vector of the screen.
Definition: screen.cc:55
Double_t rfExitPos[5][3]
Position where the RF exits the ice- 5 iterations, 3 dimensions each.
Vector GetUnitY()
Gets another orientation vector.
Definition: screen.cc:83
UChar_t errorFlag
Error Flag.
int WHICHPATH
0=fixed balloon position,1=randomized,2=ANITA-lite GPS data,3=banana plot
Definition: balloon.hh:57
void PassesTrigger(Settings *settings1, Anita *anita1, int discones_passing, int mode, int *l3trig, int l2trig[Anita::NPOL][Anita::NTRIGGERLAYERS_MAX], int l1trig[Anita::NPOL][Anita::NTRIGGERLAYERS_MAX], int antennaclump, int loctrig[Anita::NPOL][Anita::NLAYERS_MAX][Anita::NPHI_MAX], int loctrig_nadironly[Anita::NPOL][Anita::NPHI_MAX], int inu, int *thispasses, bool noiseOnly=false)
Evaluate the full trigger simulation for a given payload configuration.
void AddTperpendicular_polParallel(double A)
Appends a perpendicular transmission coefficient value to the fTcoeff_perp array. ...
Definition: screen.cc:241
void AddTparallel_polParallel(double A)
Appends a parallel transmission coefficient value to the fTcoeff_parl array.
Definition: screen.cc:233
void SetNvalidPoints(int i)
Sets the total number of points on the screen.
Definition: screen.cc:153
Double_t weight
Weight assigned by icemc.
Int_t nu_pdg
Neutrino PDG code.
Position r_bn
position of balloon
Definition: balloon.hh:66
Double_t sourceLat
RF position when leaving the ice: Latitude (using icemc model)
void SetNormal(Vector a)
Sets the screen normal.
Definition: screen.cc:51
int currentint
Ditto - Stephen.
Definition: Primaries.h:224
void AddViewangle(double A)
Appends a viewangle value to the fViewangle array.
Definition: screen.cc:134
Float_t pitch
in degrees
Definition: Adu5Pat.h:46
void AddPol(Vector v)
Appends a vector to the fPols array.
Definition: screen.cc:173
Double_t showerE
Shower energy.
double GetViewangle(int i)
Get the viewangle value stored at the specified index.
Definition: screen.cc:138
double r_fromballoon[2]
distance from interaction to balloon for each ray
Definition: Primaries.h:246
Double_t timeWeight
Relative Time weight assigned by icemc.
double chord_kgm2_ice
from ice entrance to interaction point
Definition: Primaries.h:202
void SetCosineProjectionFactor(double a)
Sets the projection factor of the screen relative to the specular RF exit point.
Definition: screen.cc:42
double GetVmmhz0(int i)
Gets the Vmmhz0 value stored at the specified index.
Definition: screen.cc:130
Global Trigger.
Definition: GlobalTrigger.h:12
void InitializeEachBand(Anita *anita1)
Initialize trigger bands.
Definition: ChanTrigger.cc:711
UShort_t upperL1TrigPattern
Bit mask for upper ring l1 antenna triggers. eg. if the bit 1 (the lowest bit) is active it means the...
void AddVec2bln(Vector v)
Appends a vector to the fVec2blns array.
Definition: screen.cc:163
UShort_t l3TrigPattern
Bit mask for l3 global triggers. eg. if the bit 1 (the lowest bit) is active it means that phi sector...
Adu5Pat – The ADU5 Position and Attitude Data.
Definition: Adu5Pat.h:26
void TriggerPath(Settings *settings1, Anita *anita1, int ant, Balloon *bn1)
Apply trigger path.
Definition: ChanTrigger.cc:871
double rms_rfcm_e_single_event
This is in Volts, not mV!
Definition: anita.hh:261
static const int NPOL
number of polarizations
Definition: anita.hh:51
Double_t n_component_k[48]
Component of the e-field along the normal.
int GetSigma(double pnu, double &sigma, double &len_int_kgm2, Settings *settings1, int nu_nubar, int currentint)
Neutrino-nucleon cross-sections using model chosen.
Definition: Primaries.cc:159
void SetCentralPoint(Position a)
Sets the position of the central point of the screen.
Definition: screen.cc:38
Vector nnu_banana
Forced neutrino direction.
Definition: Primaries.h:232
Position nu_banana_surface
The location of the surface above the forced neutrino interaction point.
Definition: Primaries.h:235
UShort_t calibStatus
Calib/Relay Status.
double LAYER_VPOSITION[Anita::NLAYERS_MAX]
position of layers in z relative to vertical center of the payload
Definition: anita.hh:81
Definition: screen.hh:22
Float_t latitude
In degrees.
Definition: Adu5Pat.h:42
void ApplyAntennaGain(Settings *settings1, Anita *anita1, Balloon *bn1, Screen *panel1, int ant, Vector &n_eplane, Vector &n_hplane, Vector &n_normal)
Apply the antenna gain.
Definition: ChanTrigger.cc:743
int GetRxTriggerNumbering(int ilayer, int ifold)
get antenna number based on which layer and position it is
Definition: anita.cc:208
double THETA_ZENITH[NLAYERS_MAX]
how the antenna is tilted in theta (in radians with 0=up)
Definition: anita.hh:75
double chord
chord in m from earth entrance to rock-ice boundary
Definition: Primaries.h:198
Int_t source_index
Name of the source.
double fVolts[12 *9][260]
Array of unwrapped (unless kNoCalib) voltages for each channel.
void SetUnitY(Vector a)
Sets another orientation vector of the screen.
Definition: screen.cc:59
STL namespace.
double weight_tau_prob
Weight for tau neutrino to interact, create a tau, tau survives and decays in the ice...
Definition: Taumodel.hh:72
static Int_t getChanIndexFromAntPol(Int_t ant, AnitaPol::AnitaPol_t pol)
Convert ant-pol to logical index.
double r_exit2bn
exit to balloon
Definition: Primaries.h:249
Radiation from interaction.
Definition: signal.hh:13
double dnutries
product of dtryingdirection and dtryingposition
Definition: Primaries.h:239
Double_t sourceLon
RF position when leaving the ice: Longitude (using icemc model)
Double_t sourceAlt
RF position when leaving the ice: Altitude (using icemc model)
Double_t fSignalAtDigitizer[12 *9][260]
Array of signal at digitizer.
void TimeShiftAndSignalFluct(Settings *settings1, Anita *anita1, int ilayer, int ifold, double volts_rx_rfcm_lab_e_all[48][512], double volts_rx_rfcm_lab_h_all[48][512])
Time shift and fluctuate signal.
Float_t longitude
In degrees.
Definition: Adu5Pat.h:43
void SetWeightNorm(double a)
Sets the normalization factor for the weights (so they sum to 1)
Definition: screen.cc:201
Double_t sourceTimeWeight
Relative Time weight for the given source assigned by icemc.
TTree * tdata
writing data out for the analysers
Definition: anita.hh:273
double GetVmmhz_freq(int i)
Get the Vmmhz value stored at the specified index.
Definition: screen.cc:121
int fNumPoints[12 *9]
Number of poins per channel.
UInt_t realTime
Time from the GPS unit.
Definition: Adu5Pat.h:37
const char * ICEMC_SRC_DIR()
void computeFluxTimeChanges(std::vector< double > *changes) const
Definition: source.cc:502
Double_t n_component[48]
Normal comp along polarization.
Double_t balloonPos[3]
Balloon position.
UChar_t nadirL2TrigPattern
8-bit trigger mask for L2 nadir triggers. Nadir L2 triggers are for the even phi sectors and are just...
double dtryingdirection
weighting factor: how many equivalent tries each neutrino counts for after having reduced angular pha...
Definition: Primaries.h:238
void saveTriggerWaveforms(Anita *anita1, double sig0[48], double sig1[48], double noise0[48], double noise1[48])
Save signal and noise waveforms at trigger.
double GetNvalidPoints()
Gets the total number of points.
Definition: screen.cc:158
void Initialize(Settings *settings1, ofstream &foutput, int inu, TString outputdir)
initialize a bunch of stuff
Definition: anita.cc:249
double costheta_nutraject
theta of nnu with earth center to balloon as z axis
Definition: Primaries.h:188
void AddImpactPt(Position p)
Appends a vector to the fImpactPt array.
Definition: screen.cc:183
double weight_nu
Weight for neutrino that survives to posnu.
Definition: Primaries.h:191
static constexpr double banana_sigma
NSIGMA in the case of a banana plot.
Definition: Primaries.h:213
double noise_eachband[2][Anita::NBANDS_MAX]
Noise in each band.
Definition: ChanTrigger.h:441
Double_t vmmhz[128]
V/m/MHz at balloon (128 frequency bins)
double SurfaceDistance(const Position &second, double local_surface) const
Returns "surface distance" between two positions.
Definition: position.cc:43
RawAnitaHeader – The Raw ANITA Event Header.
void SetNsamples(int i)
Sets number of grid divisions for the base screen.
Definition: screen.cc:23
Class that handles the channel trigger.
Definition: ChanTrigger.h:18
void AddFacetLength(double A)
Appends a facet edge length value to the fFacetLength array.
Definition: screen.cc:225
Reads in and stores input settings for the run.
Definition: Settings.h:35
Double_t fNoiseAtDigitizer[12 *9][260]
Array of noise at digitizer.
double Lat() const
Returns latitude, where the +z direction is at 0 latitude.
Definition: position.cc:47
double PHI_EACHLAYER[NLAYERS_MAX][NPHI_MAX]
phi of the center of each antenna on each layer
Definition: anita.hh:70
double PHI_OFFSET[NLAYERS_MAX]
antenna offset in phi for each layer (radians)
Definition: anita.hh:74
Int_t run
Run number, assigned on ground.
Functions you need to generate a primary interaction including cross sections and picking charged cur...
Definition: Primaries.h:83
TString objName
Declination of source.
Double_t fNoiseAtTrigger[12 *9][260]
Array of noise at trigger.
Double_t maxSNRAtTriggerV
Max SNR at trigger V-POL.
int CENTER
whether or not to center one phi sector of the payload on the incoming signal (for making signal effi...
Definition: Settings.h:105
This class is a 3-vector that represents a position on the Earth&#39;s surface.
Definition: position.hh:26
Secondary interactions.
Definition: secondaries.hh:28
void saveDigitizerWaveforms(Anita *anita1, double sig0[48], double sig1[48], double noise0[48], double noise1[48])
Save signal and noise waveforms at digitizer.
Short_t tuffIndex
TUFF configuration index.
Double_t dec
Right ascension of source.
double logchord
log_10 of chord length earth entrance to where it enters ice
Definition: Primaries.h:199
void AddVmmhz0(double A)
Appends a Vmmhz value (for the lowest Anita frequency) to the fVmmhz0 array.
Definition: screen.cc:126
Double_t h_component[48]
H comp along polarization.
UChar_t chanId[12 *9]
Definition: RawAnitaEvent.h:39
TTree * tgaryanderic
writing data out for the analysers
Definition: anita.hh:274
double rms_lab[2]
rms noise at lab chip
Definition: anita.hh:266
UInt_t realTime
unixTime of readout
Stores everything about a particular neutrino interaction. Interaction.
Definition: Primaries.h:136
int fCapacitorNum[12 *9][260]
Array of capacitor numbers.
int GetNsamples()
Gets number of grid divisions for the base screen.
Definition: screen.cc:28
Double_t rfExitNor[5][3]
Normal vector in direction of exit point to balloon - 5 iterations.
UsefulAnitaEvent – The Calibrated Useful Anita Event object.
double pickY(Settings *settings1, double pnu, int nu_nubar, int currentint)
pick inelasticity y according to chosen model
Definition: Primaries.cc:141
double RRX[Anita::NLAYERS_MAX]
radius that the antenna sits from the axis of the payload (feedpoint)
Definition: anita.hh:87
double GetTauWeight(Primaries *primary1, Settings *settings1, IceModel *antarctica1, Interaction *interaction1, double pnu, int nu_nubar, double &ptauf, int &crust_entered)
GetTauWeight is the function that will calculate the probability that a tau neutrino will interact al...
Definition: Taumodel.cc:82
Float_t altitude
In metres.
Definition: Adu5Pat.h:44
UShort_t phiTrigMask
16-bit phi mask (from TURF)
Double_t hitangle_h[48]
Hit angles rel. to h plane stored for each antenna.
Position GetCentralPoint()
Gets the position of the screen&#39;s central point.
Definition: screen.cc:68
static SourceModel * getSourceModel(const char *key, Restriction r=Restriction())
Definition: source.cc:99
double altitude_int_mirror
depth of the mirror point of interaction.
Definition: Primaries.h:244
Neutrino spectra.
Definition: Spectra.h:12
double r_exit2bn_measured
exit to balloon deduced from measured theta
Definition: Primaries.h:250
void DigitizerPath(Settings *settings1, Anita *anita1, int ant, Balloon *bn1)
Apply digitizer path.
Contains everything about positions within payload and signals it sees for each event, in both the trigger and signal paths.
Definition: anita.hh:32
int nuflavorint
Added by Stephen for output purposes.
Definition: Primaries.h:223
void AddWeight(double a)
Appends a weight value to the fWeight array.
Definition: screen.cc:193
double GetEdgeLength()
Gets the screen length.
Definition: screen.cc:63
double rms_rfcm[2]
rms noise just after rfcm&#39;s
Definition: anita.hh:265
Position r_in
position where neutrino enters the earth
Definition: Primaries.h:194
double phi_nutraject
phi of nnu with earth center to balloon as z axis
Definition: Primaries.h:189
TruthAnitaEvent – The Truth ANITA Event.
Double_t e_component[48]
E comp along polarization.
double threshold_eachband[2][Anita::NBANDS_MAX]
Threshold in each band.
Definition: ChanTrigger.h:440
Shape of the earth, ice thicknesses, profiles of earth layers, densities, neutrino absorption...
Definition: earthmodel.hh:40
Double_t weight1
Absorption weight assigned by icemc.
Double_t weight_prob
weight including probability of interacting!
static const int NLAYERS_MAX
max number of layers (in smex design, it&#39;s 4)
Definition: anita.hh:59
UShort_t lowerL1TrigPattern
Bit mask for lower ring l1 antenna triggers. eg. if the bit 1 (the lowest bit) is active it means the...
double altitude_int
depth of interaction
Definition: Primaries.h:243
void addSource(Source *source)
Definition: source.hh:65
double FREQ_HIGH
highest frequency
Definition: anita.hh:313
void AddVmmhz_freq(double A)
Appends a Vmmhz value to the fVmmhz_freq array.
Definition: screen.cc:115
double weight_nu_prob
Weight for neutrino that survives to posnu and interacts in the ice.
Definition: Primaries.h:192
int passes_eachband[2][Anita::NBANDS_MAX]
Whether the signal passes or not each band.
Definition: ChanTrigger.h:442
double banana_volts
Total voltage measured at a spot on the sky.
Definition: Primaries.h:211
double FREQ_LOW
lowest frequency
Definition: anita.hh:312
Double_t nuDir[3]
Neutrino direction.
double chord_kgm2_bestcase
the chord the neutrino would traverse if it all was crust density
Definition: Primaries.h:201
static constexpr double banana_y
Elasticity. 0.2 is an average number.
Definition: Primaries.h:208
int iceinteraction
whether or not there is an interaction in the ice
Definition: Primaries.h:251
double bwslice_volts_polh[5]
Sum voltage for each slice in bandwidth for the h polarization.
Definition: ChanTrigger.h:426
double timedomain_output_allantennas[2][48][HALFNFOUR]
this is across all antennas, just the full band
Definition: anita.hh:216
int inu
Neutrino number.
Definition: anita.hh:78
void WhichBandsPass(Settings *settings1, Anita *anita1, GlobalTrigger *globaltrig1, Balloon *bn1, int ilayer, int ifold, double dangle, double emfrac, double hadfrac, double thresholds[2][5])
Which bands passes the trigger.
Definition: ChanTrigger.cc:54
Vertical Polarisation.
Settings()
Definition: Settings.cc:43
Double_t e_component_k[48]
Component of e-field along the rx e-plane.
Double_t maxSNRAtDigitizerV
Max SNR at digitizer V-POL.
Double_t nuMom
Neutrino momentum.
string nuflavor
neutrino flavor
Definition: Primaries.h:221
Position GetPosition(int i, int j)
Calculates the physical position of the screen corresponding to the specified counter value...
Definition: screen.cc:98
Double_t deadTime
fractional deadTime
Definition: anita.hh:143
Int_t fRFSpike
Flag raised if the ADC value is too large or small in RF.
Handles everything related to balloon positions, payload orientation over the course of a flight...
Definition: balloon.hh:30
Position nuexitice
place where neutrino would have left the ice
Definition: Primaries.h:197
void SetEdgeLength(double a)
Sets the physical length of a side of the screen.
Definition: screen.cc:33
void AddTperpendicular_polPerpendicular(double A)
Appends a perpendicular transmission coefficient value to the fTcoeff_perp array. ...
Definition: screen.cc:257
Position nuexit
place where neutrino would have left the earth
Definition: Primaries.h:196
This class represents a three-vector. Operators are overloaded to provide for the familiar operations...
Definition: vector.hh:27
Position nu_banana
The forced interaction point of the neutrino for the banana plots.
Definition: Primaries.h:234
void ResetParameters()
Resets the following screen parameters (fNvalidpoints,fVmmhz_freq,fVmmhz0,fViewangle,fDelays,fVec2blns,fPols,fImpactPt,fWeight,fWeightNorm)
Definition: screen.cc:265
UShort_t upperL2TrigPattern
Bit mask for upper ring l2 cluster triggers. eg. if the bit 1 (the lowest bit) is active it means the...
Double_t SNRAtTrigger[12 *9]
Array of SNR at trigger.
void AddIncidenceAngle(double A)
Appends an incidence angle value to the fIncAngles array.
Definition: screen.cc:209
Definition: SkyMap.h:21
Double_t SNRAtDigitizer[12 *9]
Array of SNR at digitizer.
static const int NPHI_MAX
max number of antennas around in phi (in smex, 16)
Definition: anita.hh:61
double bwslice_volts_pole[5]
Sum voltage for each slice in bandwidth for the e polarization.
Definition: ChanTrigger.h:424
Horizontal Polarisation.
double ptauf
Final energy of the tau.
Definition: Taumodel.hh:71
Float_t heading
0 is facing north, 180 is facing south
Definition: Adu5Pat.h:45
Double_t maxSNRAtTriggerH
Max SNR at trigger H-POL.
Handles event counting as cuts are made.
Definition: counting.hh:10
UInt_t realTime
unixTime of readout
Definition: rx.hpp:21
Double_t thresholds[12 *9]
Channel thresholds used in icemc.
UChar_t nadirL1TrigPattern
8-bit trigger mask for L1 nadir triggers. Here bit 1 is antenna 33 (phi 1), bit 2 is antenna 34 (phi ...
string current
CC or NC?
Definition: Primaries.h:222
double d2
ice-rock boundary to interaction point in m
Definition: Primaries.h:204
void AddDelay(double A)
Appends a delay value to the fDelays array.
Definition: screen.cc:143
static AnitaGeomTool * Instance(int anita_version=0)
Instance generator. If version_number == 0, uses AnitaVersion::get();.
AnitaGeomTool – The ANITA Geometry Tool.
Definition: AnitaGeomTool.h:48
double Distance(const Position &second) const
Returns chord distance (direct distance between two vectors)
Definition: position.cc:37
Double_t fSignalAtTrigger[12 *9][260]
Array of signal at trigger.
UInt_t eventNumber
Software event number.
double signal_eachband[2][Anita::NBANDS_MAX]
Signal in each band.
Definition: ChanTrigger.h:439
double r_fromballoon_db
same, for double bangs
Definition: Primaries.h:248
Double_t nuPos[3]
Neutrino position.
Ray tracing.
Definition: ray.hh:20
double GetWeight(int i)
Gets the weight value at the specified index.
Definition: screen.cc:197
double NOTCH_MIN
low edge of notch filter. This is set in the input file
Definition: anita.hh:315
Double_t hitangle_e[48]
Hit angles rel. to e plane stored for each antenna.
Int_t run
Run number.
Position r_enterice
position where neutrino enters the ice
Definition: Primaries.h:195
double fTimes[12 *9][260]
Array of unwrapped (unless kNoCalib) times for each channel.
double d1
same as chord in m (earth entrance to rock-ice boundary)
Definition: Primaries.h:203
Double_t fTimes[12 *9][260]
Array of unwrapped (unless kNoCalib) times for each channel.
int NRX_PHI[NLAYERS_MAX]
number of antennas around in each layer. (radians)
Definition: anita.hh:69
Double_t maxSNRAtDigitizerH
Max SNR at digitizer H-POL.
static constexpr double banana_signal_fluct
Turn off noise for banana plots (settings1->SIGNAL_FLUCT) (shouldn&#39;t matter)
Definition: Primaries.h:212
UChar_t trigType
Bit 0 is RF, 1 is ADU5, 2 is G12, 3 is software/external.
void setUpWeights(double t0, double t1, double minE=1e9, double maxE=1e12, int N=1e6)
Definition: source.cc:634
UInt_t triggerTime
Trigger time from TURF converted to unixTime.
Double_t phaseWeight
Phase weight assigned by icemc.
Double_t fDiodeOutput[12 *9][260]
Array of tunnel diode output.
Double_t balloonDir[3]
Balloon direction.
Ice thicknesses and water depth.
Definition: icemodel.hh:88
double Lon() const
Returns longitude.
Definition: position.cc:51
void AddTransmissionAngle(double A)
Appends a transmission angle value to the fTransAngles array.
Definition: screen.cc:217
Vector nnu
direction of neutrino (+z in south pole direction)
Definition: Primaries.h:187