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