Exemplo n.º 1
0
void DumpEnergy(const Spectrum* pSpectrum, const dCVector* pEnergy) {
    printf("Initial energy: %15.6E\n", GetEnergy(pSpectrum, pEnergy));
    printf("Nucleon fraction: %15.6E\n",
           GetNucleonEnergy(pSpectrum, pEnergy)/GetEnergy(pSpectrum, pEnergy));
    printf("electromagnetic fraction: %15.6E\n",
           GetEMEnergy(pSpectrum, pEnergy)/GetEnergy(pSpectrum, pEnergy));
}
Exemplo n.º 2
0
bool CNSVariable::SetPrimVar_Compressible(double eddy_visc, double turb_ke, CFluidModel *FluidModel) {
	unsigned short iVar;
  bool check_dens = false, check_press = false, check_sos = false, check_temp = false, RightVol = true;
  
  
  SetVelocity();   // Computes velocity and velocity^2
  double density = GetDensity();
  double staticEnergy = GetEnergy()-0.5*Velocity2 - turb_ke;

  /* check will be moved inside fluid model plus error description strings*/
  FluidModel->SetTDState_rhoe(density, staticEnergy);

  check_dens = SetDensity();
  check_press = SetPressure(FluidModel->GetPressure());
  check_sos = SetSoundSpeed(FluidModel->GetSoundSpeed2());
  check_temp = SetTemperature(FluidModel->GetTemperature());
  
  /*--- Check that the solution has a physical meaning ---*/
  
  if (check_dens || check_press || check_sos || check_temp) {
    
    /*--- Copy the old solution ---*/
    
    for (iVar = 0; iVar < nVar; iVar++)
      Solution[iVar] = Solution_Old[iVar];
    
    /*--- Recompute the primitive variables ---*/
    
    SetVelocity();   // Computes velocity and velocity^2
	double density = GetDensity();
	double staticEnergy = GetEnergy()-0.5*Velocity2 - turb_ke;
	/* check will be moved inside fluid model plus error description strings*/
	FluidModel->SetTDState_rhoe(density, staticEnergy);

	check_dens = SetDensity();
	check_press = SetPressure(FluidModel->GetPressure());
	check_sos = SetSoundSpeed(FluidModel->GetSoundSpeed2());
	check_temp = SetTemperature(FluidModel->GetTemperature());
    
    RightVol = false;
    
  }
  
  /*--- Set enthalpy ---*/
  
	SetEnthalpy();                                  // Requires pressure computation.
  
  /*--- Set laminar viscosity ---*/
  
	SetLaminarViscosity(FluidModel->GetLaminarViscosity(FluidModel->GetTemperature(), GetDensity()));
  
  /*--- Set eddy viscosity ---*/
  
  SetEddyViscosity(eddy_visc);
  
  return RightVol;
  
}
Exemplo n.º 3
0
void Margolus::PareEnergy(Cell& cellIn, Cell& cellOut, double& energy) {
    if (cellOut.HaveSolid()) {
        if (cellIn.HaveModifier()) {
            for (pSub & subIn : cellIn.GetSubs()) {
                if (subIn->GetType() != ACTIVE) {
                    energy += GetEnergy(subIn->GetName(), cellOut.GetSub(0)->GetName());
                }
            }
        } else {
            for (pSub & subIn : cellIn.GetSubs()) {
                energy += GetEnergy(subIn->GetName(), cellOut.GetSub(0)->GetName());
            }
        }
    }
}
Exemplo n.º 4
0
void Animal::SearchingForFood()
{
	this->SetEnergy(GetEnergy() - 1 - (2 * RandomGenerator::AdditionalPoints()));
	this->SetWeight(GetWeight() - 1 - RandomGenerator::AdditionalPoints());
	this->SetSize(GetSize() - 1 - RandomGenerator::AdditionalPoints());
	this->SetCurrentState(State::SearchingForFood);
}
Exemplo n.º 5
0
bool CAICallback::SendResources(float mAmount, float eAmount, int receivingTeamId)
{
	typedef unsigned char ubyte;
	bool ret = false;

	if (team != receivingTeamId) {
		if (receivingTeamId >= 0 && receivingTeamId < (MAX_TEAMS - 1)) {
			if (gs->Team(receivingTeamId) && gs->Team(team)) {
				if (!gs->Team(receivingTeamId)->isDead && !gs->Team(team)->isDead) {
					// note: we can't use the existing SendShare()
					// since its handler in CGame uses myPlayerNum
					// (NETMSG_SHARE param) to determine which team
					// the resources came from, which is not always
					// our AI team
					ret = true;

					// cap the amounts to how much M and E we have
					mAmount = std::max(0.0f, std::min(mAmount, GetMetal()));
					eAmount = std::max(0.0f, std::min(eAmount, GetEnergy()));
					std::vector<short> empty;

					net->Send(CBaseNetProtocol::Get().SendAIShare(ubyte(gu->myPlayerNum), ubyte(team), ubyte(receivingTeamId), mAmount, eAmount, empty));
				}
			}
		}
	}

	return ret;
}
Exemplo n.º 6
0
bool CEES_Node::EE_draw(const gsl_rng *r, CStorageHead &storage)
{
	if (next_level == NULL)
		return false; 
	int bin_id_next_level = next_level->BinID(ring_index_current); 
	if (!storage.DrawSample(bin_id_next_level, r, x_new))
		return false; 
	
	// if x_new is adopted
	// x_new.weight can be retained
	// x_new.log_prob needs to be updated to reflect current level's H and T

	double logRatio = LogProbRatio_Energy(x_new.GetWeight(), x_current.GetWeight()); 
	logRatio += next_level->LogProbRatio_Energy(x_current.GetWeight(), x_new.GetWeight()); 
	
	double uniform_draw = gsl_rng_uniform(r); 
	if (log(uniform_draw) <= logRatio)
	{
		x_current = x_new;  
		x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature();	
		return true; 
	}
	else 
		return false; 
}
Exemplo n.º 7
0
//------------------------------
Double_t KVCsI_e475s::GetCorrectedEnergy(KVNucleus*, Double_t , Bool_t)
//------------------------------
{
   //Do nothing more
   return GetEnergy();

}
Exemplo n.º 8
0
//------------------------------------------------------------------------------------------------
// function for belief propagation
//------------------------------------------------------------------------------------------------
double BPFlow::MessagePassing(int nIterations,int nHierarchy,double* pEnergyList)
{
	AllocateMessage();
	if(nHierarchy>0)
	{
		BPFlow bp;
		generateCoarserLevel(bp);
		bp.MessagePassing(20,nHierarchy-1);
		bp.propagateFinerLevel(*this);
	}
	if(pX!=NULL)
		_Release1DBuffer(pX);
	pX=new int[Area*2];
	double energy;
	for(int count=0;count<nIterations;count++)
	{
		//Bipartite(count);
		BP_S(count);
		//TRW_S(count);
		
		//FindOptimalSolutionSequential();
		ComputeBelief();
		FindOptimalSolution();

		energy=GetEnergy();
		if(IsDisplay)
			printf("No. %d energy: %f...\n",count,energy);
		if(pEnergyList!=NULL)
			pEnergyList[count]=energy;
	}
	return energy;
}
Exemplo n.º 9
0
Double_t KVBIC::GetCorrectedEnergy(KVNucleus* nuc, Double_t e, Bool_t transmit)
{
   //For a particle which passes through the BIC (i.e. is stopped in SIB behind it)
   //this will give the total energy loss of the particle in the BIC, i.e. including all
   //the dead zones.
   //If the particle stops in the BIC, this will not be correct, but in this case no
   //identification of the particle is possible, Z and A will not be known, so
   //this function should not be called.
   //If argument 'egas' not given, KVBIC::GetEnergy() is used

   if (!transmit) return 0.;

   e = ((e < 0.) ? GetEnergy() : e);

   if (e <= 0.)
      return 0.0;               //check measured (calibrated) energy in gas is reasonable (>0)

   Bool_t maxDE = kFALSE;

   //egas > max possible ?
   if (e > GetMaxDeltaE(nuc->GetZ(), nuc->GetA())) {
      e = GetMaxDeltaE(nuc->GetZ(), nuc->GetA());
      maxDE = kTRUE;
   }
   //calculate incident energy
   Double_t e_inc = GetIncidentEnergy(nuc->GetZ(), nuc->GetA(), e);

   //calculate residual energy
   Double_t e_res = GetERes(nuc->GetZ(), nuc->GetA(), e_inc);

   Double_t eloss = e_inc - e_res;
   if (maxDE)
      return (-eloss);
   return eloss;
}
Exemplo n.º 10
0
void Margolus::PareEnergyFull(Cell& cellIn, Cell& cellOut, double& energy) {
    // modifier & active in one cell
    for (pSub & subA : cellIn.GetSubs()) {
        if (subA->GetType() == ACTIVE) {
            for (pSub & subM : cellIn.GetSubs()) {
                if (subM->GetType() == MODIFIER) {
                    energy += GetEnergyCell(subA->GetName(), subM->GetName());
                }
            }
        }
    }
    // other
    if (cellOut.HaveSolid()) {
        if (cellIn.HaveModifier()) {
            for (pSub & subIn : cellIn.GetSubs()) {
                if (subIn->GetType() != ACTIVE) {
                    energy += GetEnergy(subIn->GetName(), cellOut.GetSub(0)->GetName());
                }
            }
        } else {
            for (pSub & subIn : cellIn.GetSubs()) {
                energy += GetEnergy(subIn->GetName(), cellOut.GetSub(0)->GetName());
            }
        }
    } else {
        if (cellIn.HaveSolid()) {
            if (cellOut.HaveModifier()) {
                for (pSub & subOut : cellOut.GetSubs()) {
                    if (subOut->GetType() != ACTIVE) {
                        energy += GetEnergy(subOut->GetName(), cellIn.GetSub(0)->GetName());
                    }
                }
            } else {
                for (pSub & subOut : cellOut.GetSubs()) {
                    energy += GetEnergy(subOut->GetName(), cellIn.GetSub(0)->GetName());
                }
            }
        } else {
            for (pSub & subIn : cellIn.GetSubs()) {
                for (pSub & subOut : cellOut.GetSubs()) {
                    energy += GetEnergy(subIn->GetName(), subOut->GetName());
                }
            }
        }
    }
}
Exemplo n.º 11
0
Double_t KVHarpeeSi::GetCanalFromEnergy( Double_t e ){
	// Inverts calibration, i.e. calculates the channel value associated
	// to a given energy (in MeV). If the energy is not given, the value
	// returned by GetEnergy() is used.

	if( e<0 ) e = GetEnergy();
	if( fCanalE && fCanalE->GetStatus() ) return fCanalE->Invert( e );
	return -1.;
}
Exemplo n.º 12
0
void SiliconData::PrintEvent()//Print out the 'proper' information about an event
{
  //Want to print out the number of valid silicon hits
  printf("Silicon hits: %d\n",SizeOfEvent());
  
  for(unsigned int i=0;i<SizeOfEvent();i++)
  {
    printf("Hit number: %d\n",i);
    printf("Energy: %g\n",GetEnergy(i));
  }
}
Exemplo n.º 13
0
void KVChIo::DeduceACQParameters(Int_t,Int_t)
{

    Double_t volts = GetVoltsFromEnergy(GetEnergy());
    Int_t cipg = (Int_t)GetCanalPGFromVolts(volts);
    Int_t cigg = (Int_t)GetCanalGGFromVolts(volts);
    //cout << "chio: pg = " << cipg << " gg = " << cigg << endl;
    GetACQParam("PG")->SetData((UShort_t)TMath::Min(4095,cipg));
    GetACQParam("GG")->SetData((UShort_t)TMath::Min(4095,cigg));
    GetACQParam("T")->SetData(110);

}
Exemplo n.º 14
0
int ChoiceTrackingFace3(CvFaceTracker* pTF, const int nElements, const CvFaceElement* big_face, CvTrackingRect* face, int& new_energy)
{
    CvTrackingRect* curr_face[NUM_FACE_ELEMENTS] = {NULL};
    CvTrackingRect* new_face[NUM_FACE_ELEMENTS] = {NULL};
    new_energy = 0x7fffffff;
    int curr_energy = 0x7fffffff;
    int found = 0;
    int N = 0;
    CvSeqReader reader_m, reader_l, reader_r;
    cvStartReadSeq( big_face[MOUTH].m_seqRects, &reader_m );
    for (int i_mouth = 0; i_mouth < big_face[MOUTH].m_seqRects->total && i_mouth < nElements; i_mouth++)
    {
        curr_face[MOUTH] = (CvTrackingRect*)(reader_m.ptr);
        cvStartReadSeq( big_face[LEYE].m_seqRects, &reader_l );
        for (int i_left = 0; i_left < big_face[LEYE].m_seqRects->total && i_left < nElements; i_left++)
        {
            curr_face[LEYE] = (CvTrackingRect*)(reader_l.ptr);
            if (curr_face[LEYE]->r.y + curr_face[LEYE]->r.height < curr_face[MOUTH]->r.y)
            {
                cvStartReadSeq( big_face[REYE].m_seqRects, &reader_r );
                for (int i_right = 0; i_right < big_face[REYE].m_seqRects->total && i_right < nElements; i_right++)
                {
                    curr_face[REYE] = (CvTrackingRect*)(reader_r.ptr);
                    if (curr_face[REYE]->r.y + curr_face[REYE]->r.height < curr_face[MOUTH]->r.y &&
                        curr_face[REYE]->r.x > curr_face[LEYE]->r.x + curr_face[LEYE]->r.width)
                    {
                        curr_energy = GetEnergy(curr_face, pTF->face, pTF->ptTempl, pTF->rTempl);
                        if (curr_energy < new_energy)
                        {
                            for (int elem = 0; elem < NUM_FACE_ELEMENTS; elem++)
                                new_face[elem] = curr_face[elem];
                            new_energy = curr_energy;
                            found = 1;
                        }
                        N++;
                    }
                }
            }
        }
    }
    if (found)
    {
        for (int elem = 0; elem < NUM_FACE_ELEMENTS; elem++)
            face[elem] = *(new_face[elem]);
    }
    return found;
} // int ChoiceTrackingFace3(const CvTrackingRect* tr_face, CvTrackingRect* new_face, int& new_energy)
Exemplo n.º 15
0
void CollisionSystem::EatEntity(std::shared_ptr<Entity> eaterEntity,
    std::shared_ptr<Entity> eatableEntity)
{
    LOG_D("[CollisionSystem] Entity " << eaterEntity->GetId() << " is eating entity " << eatableEntity->GetId());

    if (Engine::GetInstance().HasComponent(eaterEntity, "InfectionComponent"))
    {
        auto infectionComponent = std::static_pointer_cast<InfectionComponent>(Engine::GetInstance().GetSingleComponentOfClass(eaterEntity, "InfectionComponent"));

        if (infectionComponent->GetInfectionType() == CannotEat)
            return;
    }

    auto growthComponent = std::static_pointer_cast<GrowthComponent>(Engine::GetInstance().GetSingleComponentOfClass(eaterEntity, "GrowthComponent"));
    auto energy = growthComponent->GetEnergy();
    ++energy;
    growthComponent->SetEnergy(energy);
    DestroyEntity(eatableEntity);

    Engine::GetInstance().PlaySoundEffect(CFG_GETP("EAT_SOUND_EFFECT"));
}
Exemplo n.º 16
0
Double_t KVChIo::GetELossMylar(UInt_t z, UInt_t a, Double_t egas, Bool_t stopped)
{
    //Based on energy loss in gas, calculates sum of energy losses in mylar windows
    //from energy loss tables.
    //If argument 'egas' not given, KVChIo::GetEnergy() is used.
    //if stopped=kTRUE, we give the correction for a particle which stops in the detector
    //(by default we assume the particle continues after the detector)
    //
    // WARNING: if stopped=kFALSE, and if the residual energy after the detector
    //   is known (i.e. measured in a detector placed after this one), you should
    //   first call
    //       SetEResAfterDetector(Eres);
    //   before calling this method. Otherwise, especially for heavy ions, the
    //   correction may be false for particles which are just above the punch-through energy.

    egas = ((egas < 0.) ? GetEnergy() : egas);
    if (egas <= 0.)
        return 0.0;               //check measured (calibrated) energy in gas is reasonable (>0)

    KVNucleus tmp(z,a);
    Double_t emylar = GetCorrectedEnergy(&tmp,egas,!stopped) - egas;
    return emylar;
}
Exemplo n.º 17
0
Arquivo: reco.C Projeto: FCALSW/LuCaS
void reco( Double_t dcut , Long64_t nwanted, TString fname )
{
  // attache dictionaries before file
	gSystem->Load("./lib/libLucasDict.so");
        TFile fin ( fname );
        TTree *Lcal = (TTree*)fin.Get("Lcal");
        if (Lcal == 0) return;
	pTracks = 0; 
        pHits   = 0;

       Lcal->SetBranchAddress("vX", &vX ); 
       Lcal->SetBranchAddress("vY", &vY ); 
       Lcal->SetBranchAddress("vZ", &vZ ); 
       Lcal->SetBranchAddress("numPrim", &numPrim );
       Lcal->SetBranchAddress("numHits", &numHits );
       Lcal->SetBranchAddress("Etot", Etot );
       Lcal->SetBranchAddress("Emax", &Emax );
       Lcal->SetBranchAddress("Tracks", &pTracks ); 
       Lcal->SetBranchAddress("Hits", &pHits );
   
   Int_t Nbins = 300;
   Double_t Xlo=   2.5;
   Double_t Xup= 1502.5;
   //
   TFile *out = new TFile("reco-plots-rot0-uncor.root","RECREATE");
   //
   TF1 *res1 = new TF1("res1","sqrt([0]*[0]/x+[1]*[1])",1.,1601.);
   res1->SetParNames("a","b");
   TF1 *cfun1 = new TF1("cfun1","1.+[0]*exp(-[1]*x*x)+[2]/(x*x+[3])",-45.,45.);
   cfun1->SetParNames("A1","W1","A2","W2");
   TF1 *cfun2 = new TF1("cfun2","1.+ [0]/(x*x+[1])",-45.,45.);
   cfun2->SetParNames("A2","W2");
   //
   TProfile *hpr1 = new TProfile("hpr1"," ;E_{beam} [GeV]; E_{vis} [GeV]",Nbins,Xlo,Xup,0.,1000.,"S");
   TH1D *sigeove =  new TH1D("sigeove"," ;E_{beam} [GeV]; #sigma_{E}/E",Nbins,Xlo,Xup);
   TH1D *rmseove =  new TH1D("rmseove"," ;E_{beam} [GeV]; RMS_{E}/E",Nbins,Xlo,Xup);
   TH1D *dErec[NSAMP_MAX];
   TH1D *euse = new TH1D ( "euse"," ; E_{used}  [GeV] ; Number of events",600, 0., 6. );
   TH1D *edep[NSAMP_MAX];
   TH1D *dphi[NSAMP_MAX], *Qmax[NSAMP_MAX];
   //   TProfile *dgap[NSAMP_MAX];
   TH2D *dgap[NSAMP_MAX];
   TH1D *dtheta[NSAMP_MAX];
   double qmax[NSAMP_MAX];
   TProfile *phioff = new TProfile("phioff","#phi offset;1/P  [GeV^{-1}];<#Delta#Phi>   [rad]",500,0.,0.25,-TWO_PI,TWO_PI,"E");
   for( int ih=0; ih<NSAMP_MAX; ih++){
     TString nam1("dphi");
     TString nam2("edep");
     TString nam3("dErec");
     TString nam4("dgap");
     TString nam5("dtheta");
     TString nam6("Qmax");
     nam1 += ih;
     nam2 += ih;
     nam3 += ih;
     nam4 += ih;
     nam5 += ih;
     nam6 += ih;
     dphi[ih] = new TH1D(nam1,"; #Delta#Phi   [rad]; Number of events", 300, -0.3, 0.3 );
     dtheta[ih] = new TH1D(nam5,"; #Delta#theta   [rad]; Number of events", 200, -0.002, 0.002 );
     edep[ih] = new TH1D(nam2," ; E_{VIS}  [GeV] ; Number of events",500,Elo[ih],Eup[ih]);   
     dErec[ih] = new TH1D( nam3 ," ; #DeltaE   [GeV]; Number of events",60, -25., 25. );
     //     dgap[ih] = new TProfile(nam4,"; distance from the gap [mm]; <E_{VIS}>/E_{VIS}",900,-45.,45.,0.,1000.,"E");
     dgap[ih] = new TH2D(nam4,"; distance from the gap [mm]; <E_{VIS}>/E_{VIS}",900,-45.,45.,100,0.5,1.5);
     Qmax[ih] = new TH1D(nam6,"; Q_{max}    pC; number of events ",40,0.,20.);
     //     dErec[ih]->SetBit(TH1::kCanRebin);
     //     edep[ih]->SetBit(TH1::kCanRebin);
     //     dphi[ih]->SetBit(TH1::kCanRebin);
   }
   //
   //
   std::vector < myHit > hits_P;  // list of hits z > 0
   std::vector < myHit > hits_N;  //              z < 0
   //
   cout << " Energy saturation at "<< E_MAX << " [MeV] " << endl;
   cout << " Energy treshold at   "<< E_MIN << " [MeV] " << endl;
   Long64_t nentries = Lcal->GetEntries();
#ifdef si500
     Double_t p0 =  6.13e-4;   // si 500
     Double_t p1 =  1.71e-2;;
#else
#ifdef rot3_hh
   Double_t p0 = 1.771e-3;  // si=320
   Double_t p1 = 1.122e-2;
#else
   Double_t p0 = 2.145e-3;  // si=320
   Double_t p1 = 1.131e-2;
#endif
#endif
   Double_t C_fac = 0.01138;
  
     /*     Double_t g0 = 1.006e-2;
     Double_t g1 = 2.367e-7;
     Double_t g2 = -7.476e-10;
     */
     // Long64_t nskip = 0;
   nentries = ( nwanted > 0 && nwanted < nentries ) ? nwanted : nentries ;
   cout << " Nentries "<< nentries << endl;
   for (Long64_t jentry=0; jentry< nentries ;jentry++) {
     Double_t theta_rec1 = 0., phi_rec1=0. ;
     Double_t theta_rec2 = 0., phi_rec2=0. ;
     Double_t     e_use1 = 0.,   e_use2=0. ;
     Double_t     e_vis1 = 0.,   e_vis2=0. ;
      hits_N.clear();
      hits_P.clear();
      e_vis2 = 0.;

      Lcal->GetEntry(jentry);
      if ( Etot[1] <= 0.) continue;
      //
      double E_gen=0., theta_gen=0., phi_gen=0.;
      int numtr = pTracks->size();
      for ( int it=0; it< numtr; it++){
      Track_t track = (*pTracks)[it];
      E_gen = sqrt( track.pX*track.pX + track.pY*track.pY + track.pZ*track.pZ )/1000.;
      theta_gen = atan ( sqrt( track.pX*track.pX + track.pY*track.pY)/fabs(track.pZ));
      phi_gen = atan2 ( track.pY , track.pX);
      phi_gen = ( phi_gen > 0. ) ? phi_gen : phi_gen + TWO_PI;
      }
      //
      if ( theta_gen < 0.041 || theta_gen > 0.068 ){ continue;}
      //
      int sample=0;
      switch( (int)E_gen ){
      case 5:
	sample = 0;
        break;
      case 15:
	sample = 1;
        break;
      case 25:
	sample = 2;
        break;
      case 50:
	sample = 3;
        break;
      case 100:
	sample = 4;
        break;
      case 150:
	sample = 5;
        break;
      case 200:
	sample = 6;
        break;
      case 250:
	sample = 7;
        break;
      case 500:
	sample = 8;
        break;
      case 1500:
	sample = 9;
        break;
      default:
	cout<< "uknown case " << (int)E_gen << endl;
      }
      //
      // Fill the list of hits
      //
      int nHits = pHits->size();
      qmax[sample] = 0.;
      for ( Int_t ih=0; ih<nHits ; ih++) {
	// Int_t layer   = (cellID[ih] >> 16) & 0xff ;
	//
        Hit_t hit = (*pHits)[ih];
	double ehit = ( hit.eHit > E_MAX ) ? E_MAX : hit.eHit ;
	if ( ehit < E_MIN ) continue ;
        if ( qmax[sample] < ehit ) qmax[sample]=ehit; 
	// 
	//        Double_t rCell = sqrt( hit.xCell*hit.xCell+hit.yCell*hit.yCell);
        Double_t rCell = sqrt( hit.xHit*hit.xHit + hit.yHit*hit.yHit);
        Double_t phiCell = atan2( hit.yCell, hit.xCell );
        if ( hit.zCell < 0. ) {
          hits_N.push_back ( myHit( ehit, rCell, phiCell, hit.zCell) );
	}
        else {
          hits_P.push_back ( myHit( ehit, rCell, phiCell, hit.zCell) );
	} 

      } // end hit loop
      //
      // sort hits in descending order
      //
      //      cout<< " accepted " << nskip << " " << hits_P.size()<< " " << hits_N.size() << endl;
     
     if ( hits_N.begin() != hits_N.end() ) {
	std::sort ( hits_N.begin(), hits_N.end(), SortByEnergy );
	theta_rec1 = GetTheta ( hits_N );
	phi_rec1 = GetPhi ( hits_N );
	    e_vis1 = GetEnergy( theta_rec1, hits_N );
      }

      if ( hits_P.begin() != hits_P.end() ) {
	std::sort ( hits_P.begin(), hits_P.end(), SortByEnergy );
	theta_rec2 = GetTheta( hits_P );
	phi_rec2 = GetPhi ( hits_P );
#ifdef rot3_hh
	double dist = GetDistance( theta_rec2, phi_rec2, 3.75);
#else
	double dist = GetDistance( theta_rec2, phi_rec2, 0.);
#endif
      
	//       	if ( CheckSector( phi_rec2 ) )continue;
      	if ( fabs(dist) < dcut ) continue;
	double avrEvis = p0 + p1*E_gen;
	    e_vis2 = GetEnergy(  hits_P )/1000.;
	    //       	    e_vis2 *= GetCorrection( sample, dist);
	    dgap[sample]->Fill( dist, avrEvis/e_vis2, 1.  );
      }

      //
      // fill histograms
      //
      C_fac = (e_vis2 - p0)/p1;
      Double_t delta_phi = phi_gen - (phi_rec2 + PHI_OFFSET[sample]);
      Double_t pT = 1./(E_gen*sin(theta_rec2));
      Double_t E_rec = C_fac ;
      //      double delta = p1*p1 - 4.*p2*(p0-e_vis2);
      //      if( delta >= 0. ) E_rec = (-p1+sqrt(delta))/(2.*p2);
      Qmax[sample]->Fill( qmax[sample]*E2Q );
      dtheta[sample] -> Fill ( theta_rec2 - theta_gen );
      dphi[sample]-> Fill ( delta_phi);
      phioff->Fill( pT , delta_phi );
      if ( e_vis2 > 0. ) {
             edep [sample]-> Fill ( e_vis2 );
	     hpr1->Fill(E_gen,e_vis2,1.);
	     dErec[sample]  -> Fill ( ( E_rec - E_gen));
	     euse -> Fill ( e_use2 );
      }
      if  ( e_use1 > 0.) euse -> Fill ( e_use1 );
      //
      //
      // end of event
      // 
   }
   // final operations with histograms 
   //
   int binum[NSAMP_MAX] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
   int ii = 1;
   for ( int ib=1; ib < hpr1->GetNbinsX()+1; ib++ ){
     double binc = hpr1->GetBinContent(ib);
     if( binc > 0.){
      binum[ii] = ib;
      cout << "bin: " << ii << "\t value: " << binc << endl;
      ii++;
      }
   }
  //
   //
   for ( int ih=0;ih<NSAMP_MAX;ih++){
     if( edep[ih]->Integral() > 0. ) {
       cout<< " fitting ih: " << ih << "\t"<<ebeam[ih] << endl;
       edep[ih]->Fit("gaus","QS0");
       TF1 *f = edep[ih]->GetFunction("gaus");
       double mean = f->GetParameter(1);
       double rmse = f->GetParameter(2);
       double ratio = rmse/mean;
       double e1 = f->GetParError(1);
       double e2 = f->GetParError(2);
       double err = sqrt(e1*e1/(mean*mean)+e2*e2/(rmse*rmse))*ratio;
       cout << "<E> " << mean << " sigma "<< rmse << endl;
       sigeove->SetBinContent( binum[ih], ratio );
       sigeove->SetBinError( binum[ih], err );
    //
       mean = edep[ih]->GetMean();
       rmse = edep[ih]->GetRMS();
       e1 = edep[ih]->GetMeanError();
       e2 = edep[ih]->GetRMSError();
       ratio = rmse/mean;
       err = sqrt(e1*e1/(mean*mean)+e2*e2/(rmse*rmse))*ratio;
       rmseove->SetBinContent( binum[ih], ratio);
       rmseove->SetBinError( binum[ih],2.*err);
       dErec[ih]->Fit("gaus","QW");
     }
    }
   sigeove->Fit("res1");
   rmseove->Fit("res1");
   //
   //
   Double_t P0[NSAMP_MAX],P1[NSAMP_MAX],P2[NSAMP_MAX],P3[NSAMP_MAX];
   for ( int ih=0; ih<NSAMP_MAX; ih++){
     P0[ih] = 0.;
     P1[ih] = 0.;
     P2[ih] = 0.;
     P3[ih] = 0.;
   }

     for( int ih=0; ih<NSAMP_MAX; ih++){
       if( dphi[ih]->Integral() > 0. ) {
	 cout<< " Fitting gap: "<< ih <<"\t E= "<<ebeam[ih]<<endl;
         dphi[ih]->Fit("gaus","QS0");
         dtheta[ih]->Fit("gaus","QS0");
	 dgap[ih]->Fit("cfun2","QW");
	 TF1 *f=dgap[ih]->GetFunction("cfun2");
     // P0[ih]=f->GetParameter(0);
     // P1[ih]=f->GetParameter(1);
       P2[ih]=f->GetParameter(0);
       P3[ih]=f->GetParameter(1);
    
       dgap[ih]->GetYaxis()->SetRangeUser(0.9, 2.5);
       }
     }
     //
     
     cout << "const double a1[NSAMP_MAX] = {" ;
     for (int ih=0;ih<9;ih++) printf("%5.3e%1s",P0[ih],", ");
     cout<<endl;
     cout << "const double w1[NSAMP_MAX] = {" ;
     for (int ih=0;ih<9;ih++) printf("%5.3e%1s",P1[ih],", ");
     cout<<endl;
     cout << "const double a2[NSAMP_MAX] = {" ;
     for (int ih=0;ih<9;ih++) printf("%5.3e%1s",P2[ih],", ");
     cout<<endl;
     cout << "const double w2[NSAMP_MAX] = {" ;
      for (int ih=0;ih<9;ih++) printf("%5.3e%1s",P3[ih],", ");
     cout<<endl;
     
     /*

     hpr1->Write();
     phioff->Write();
     sigeove->Write();
     rmseove->Write();
     */
     out->Write();
     //    out->Close();
}
Exemplo n.º 18
0
func GetDamage() { return GetStrength() - GetEnergy() + 1; }
Exemplo n.º 19
0
void prop_second(const double dist_observer,
                 //const double InjEnergy,
                 //const PARTICLE part,
                 //const double HInjEnergy, const double deltaE_hadron,
                 const dCVector* pB_field,
                 const dCVector* pEnergy,
                 const dCVector* pEnergyWidth,
                 Spectrum* apInjectionSpectrum,
                 Spectrum* pSpectrum,
                 string aDirTables,
                 const int aIRFlag, const double aZmax_IR, const int aRadioFlag,
                 const double aH0 = H_0, const double aOmegaM = OMEGA_M,
                 const double aOmegaLambda = OMEGA_LAMBDA,
                 const double aCutcascade_Magfield = 0) {

    //-------- Declaration of main variables --------
    //---- Interaction table coefficients ----
    RawTotalRate ICSTotalRate;
    RawTotalRate PPTotalRate;
    RawTotalRate TPPTotalRate;
    RawTotalRate DPPRate;

    RawTotalRate PPPProtonLossRate;
    RawTotalRate PPPNeutronLossRate;
    RawTotalRate NPPTotalRate;
    // total (interaction) rates before being folded into the background

    RawDiffRate ICSPhotonRate;
    RawDiffRate ICSScatRate;
    RawDiffRate PPDiffRate;
    RawDiffRate TPPDiffRate;

    RawDiffRate PPPProtonScatRate;
    RawDiffRate PPPProtonNeutronRate;
    RawDiffRate PPPNeutronProtonRate;
    RawDiffRate PPPProtonPhotonRate;
    RawDiffRate PPPProtonElectronRate;
    RawDiffRate PPPProtonPositronRate;
    RawDiffRate PPPNeutronElectronRate;
    RawDiffRate NPPDiffRate;
    RawDiffRate PPPProtonElectronNeutrinoRate;
    RawDiffRate PPPProtonAntiElectronNeutrinoRate;
    RawDiffRate PPPProtonMuonNeutrinoRate;
    RawDiffRate PPPProtonAntiMuonNeutrinoRate;
    RawDiffRate PPPNeutronAntiElectronNeutrinoRate;
    RawDiffRate PPPNeutronMuonNeutrinoRate;
    RawDiffRate PPPNeutronAntiMuonNeutrinoRate;
    // differential rates before being folded into the background

    TotalRate neutronDecayRate;
    DiffRate neutronDecayElectronRate;
    DiffRate neutronDecayProtonRate;

    TotalRate NNElNeutTotalRate;
    TotalRate NNMuonNeutTotalRate;
    TotalRate NNTauNeutTotalRate;
    // These total rates are net rates; i.e. scattered flux into same bin is subtracted
    DiffRate NNElNeutScatRate;
    DiffRate NNElNeutMuonNeutRate;
    DiffRate NNElNeutTauNeutRate;
    DiffRate NNElNeutElectronRate;
    DiffRate NNElNeutPhotonRate;
    DiffRate NNElNeutProtonRate;
    DiffRate NNMuonNeutScatRate;
    DiffRate NNMuonNeutElNeutRate;
    DiffRate NNMuonNeutTauNeutRate;
    DiffRate NNMuonNeutElectronRate;
    DiffRate NNMuonNeutPhotonRate;
    DiffRate NNMuonNeutProtonRate;
    DiffRate NNTauNeutScatRate;
    DiffRate NNTauNeutElNeutRate;
    DiffRate NNTauNeutMuonNeutRate;
    DiffRate NNTauNeutElectronRate;
    DiffRate NNTauNeutPhotonRate;
    DiffRate NNTauNeutProtonRate;
    // rates from neutrino-neutrino interaction


    //---- Main parameter variables ----
    int B_bin, B_bins;     // bin numbers for B-field array

    dCVector deltaG; // dg used in continuous energy loss calculation

    dCVector bgEnergy;
    dCVector bgEnergyWidth;
    dCVector bgPhotonDensity;

    double distance;    // main distance variable (cm)

    int numSmallSteps;  // number of small steps in one redshift step
    double convergeParameter;   // redshift increment

    int synchrotronSwitch;
    double B_loc;     // local strength of extragalactic magnetic field (gauss)
    DiffRate syncRate;

    int sourceTypeSwitch;   // source type: single (0) or diffuse (1)
    double brightPhaseExp;  // bright phase exponent
    double startingRedshift;    // zsource in FORTRAN
    double minDistance;     // minimal distance to sources
    double bkgFactor;       // local background enhancement factor
    double totalEnergyInput;    // einj0 in FORTRAN

    Spectrum Q_0;    // standard injection function
    Spectrum spectrumNew;
    Spectrum derivative;

    double initialPhotonEnergy; // totpe in FORTRAN
    double initialLeptonEnergy; // totee
    double initialNucleonEnergy;
    double initialNeutrinoEnergy;
    double initialTotalEnergy;  // tote
    double initialPhotonNumber; // totpn
    double initialLeptonNumber; // toten
    double initialNucleonNumber;
    double initialNeutrinoNumber;
    double initialTotalNumber;  // totn

    int iterationCounter;   // niter in FORTRAN
    int firstIndex; // ifirst
    double leftRedshift;    // zi
    double deltaRedshift;   //zdelt
    int lastIndex;  // ilast
    double propagatingDistance;
    // totalx: total propagating distance (pc)
    double rightRedshift;   // zf
    double centralRedshift; // zt
    double redshiftRatio;   // erat
    //  double tempCoefficient;     // coeff
    double distanceStep;    // tzdist*tdz (cm)
    double rightDistance;   // d1 (Mpc)
    double leftDistance;    // d2 (Mpc)
    double evolutionFactor,evolutionFactor1; // zfact
    double smallDistanceStep;   // dx (pc)
    double x;   // x (pc)

    // Energy below which the 1D approximation is not a priori correct :
    bool lEcFlag ;
    int lIndex ;
    double lEnergy, t_sync, t_larmor, t_ics = 0 ;
    double a_ics = (3.-log10(4.))/4. ;
    double b_ics = pow(10.,8.-7.*a_ics) ;
    // (used if the flag aCutcascade_Magfield is set)

    //    FILE* input;
    int tauNeutrinoMassSwitch;

    // interaction switches
    int ICSSwitch;
    int PPSwitch;
    int TPPSwitch;
    int DPPSwitch;

    int PPPSwitch;
    int NPPSwitch;
    int neutronDecaySwitch;
    int nucleonToSecondarySwitch;

    int neutrinoNeutrinoSwitch;

    //---- interaction rates folded with photon background ----
    TotalRate leptonTotalRate;
    TotalRate photonTotalRate;
    TotalRate protonTotalRate;
    TotalRate neutronTotalRate;

    DiffRate leptonScatRate;
    DiffRate leptonExchRate;
    DiffRate leptonPhotonRate;
    DiffRate photonLeptonRate;

    DiffRate protonScatRate;
    DiffRate protonNeutronRate;
    DiffRate neutronProtonRate;
    DiffRate protonPhotonRate;
    DiffRate protonElectronRate;
    DiffRate protonPositronRate;
    DiffRate neutronElectronRate;
    DiffRate neutronPositronRate;
    DiffRate protonElectronNeutrinoRate;
    DiffRate protonAntiElectronNeutrinoRate;
    DiffRate protonMuonNeutrinoRate;
    DiffRate protonAntiMuonNeutrinoRate;
    DiffRate neutronAntiElectronNeutrinoRate;
    DiffRate neutronMuonNeutrinoRate;
    DiffRate neutronAntiMuonNeutrinoRate;

    TotalRate elNeutTotalRate;
    TotalRate muonNeutTotalRate;
    TotalRate tauNeutTotalRate;

    DiffRate elNeutScatRate;
    DiffRate elNeutMuonNeutRate;
    DiffRate elNeutTauNeutRate;
    DiffRate elNeutElectronRate;
    DiffRate elNeutPhotonRate;
    DiffRate elNeutProtonRate;
    DiffRate muonNeutScatRate;
    DiffRate muonNeutElNeutRate;
    DiffRate muonNeutTauNeutRate;
    DiffRate muonNeutElectronRate;
    DiffRate muonNeutPhotonRate;
    DiffRate muonNeutProtonRate;
    DiffRate tauNeutScatRate;
    DiffRate tauNeutElNeutRate;
    DiffRate tauNeutMuonNeutRate;
    DiffRate tauNeutElectronRate;
    DiffRate tauNeutPhotonRate;
    DiffRate tauNeutProtonRate;
    // rates from neutrino-neutrino interaction

    dCVector synchrotronLoss;    // sgdot
    dCVector otherLoss;    // tgdot
    dCVector continuousLoss;   // gdot
    dCVector protonContinuousLoss;    // pgdot

    int loopCounter;
    //-------- End of variable declaration --------

    //    numSmallSteps = 100;
    convergeParameter = 1.e-8;

    // -------- Redshift Estimation ---------------
    //  startingRedshift = pow(1. - 3.*H_0*1.e5*dist_observer/2./C, -2./3.) - 1.;
    // This was the old analytic redshift computation.
    dCVector RedshiftArray ;
    dCVector DistanceArray ;
    BuildRedshiftTable(aH0, aOmegaM, aOmegaLambda, &RedshiftArray, &DistanceArray) ;
    startingRedshift = getRedshift(RedshiftArray, DistanceArray, dist_observer) ;
    //    printf("distance/Mpc: %15.6E\n", dist_observer);
    //    printf("particle type: %d\n", part);
    //    printf("injection energy/eV: %15.6E\n", InjEnergy);

    B_bins = pB_field->dimension;

    synchrotronSwitch = 1;
    tauNeutrinoMassSwitch = 1;
    ICSSwitch = 1;
    PPSwitch = 1;
    TPPSwitch = 1;
    DPPSwitch = 1;
    //    PPPSwitch = 1;
    PPPSwitch = 0;
    NPPSwitch = 0;
    //     synchrotronSwitch = 0;
    //      tauNeutrinoMassSwitch = 0;
    //      ICSSwitch = 0;
    //      PPSwitch = 0;
    //      TPPSwitch = 0;
    //     DPPSwitch = 0;
    //    PPPSwitch = 1;
    PPPSwitch = 0;
    NPPSwitch = 0;
    //      printf("DINT modified!!\n");
#ifdef EXTRACT_PAIR_PROD_RATE
    NPPSwitch = 1; // (allows to compute new pair prod rate)
#endif

    //    neutronDecaySwitch = 1;
    neutronDecaySwitch = 0;
    nucleonToSecondarySwitch = 0;
    neutrinoNeutrinoSwitch = 1;
    sourceTypeSwitch = 0;
    minDistance = 0.;
    brightPhaseExp = 0.;

    //-------- Set up energy bins --------
    New_dCVector(&deltaG, NUM_MAIN_BINS);
    New_dCVector(&bgEnergy, NUM_BG_BINS);
    New_dCVector(&bgEnergyWidth, NUM_BG_BINS);
    New_dCVector(&bgPhotonDensity, NUM_BG_BINS);

    // set energy bins
    SetDeltaG(pEnergy, &deltaG);

    SetEnergyBins(BG_MIN_ENERGY_EXP, &bgEnergy, &bgEnergyWidth);

    NewSpectrum(&Q_0, NUM_MAIN_BINS);
    NewSpectrum(&spectrumNew, NUM_MAIN_BINS);
    NewSpectrum(&derivative, NUM_MAIN_BINS);

    New_dCVector(&synchrotronLoss, NUM_MAIN_BINS);
    New_dCVector(&otherLoss, NUM_MAIN_BINS);
    New_dCVector(&continuousLoss, NUM_MAIN_BINS);
    New_dCVector(&protonContinuousLoss, NUM_MAIN_BINS);


    //---- Select injection model ----
    //  SetInjectionSpectrum(part, InjEnergy, HInjEnergy, deltaE_hadron,
    //		       pEnergy, pEnergyWidth, &Q_0);
    //    SetInjectionSpectrum(part, pEnergy, pEnergyWidth, &Q_0, InjEnergy);

    SetSpectrum(&Q_0, apInjectionSpectrum) ;
    // No call anymore to SetInjectionSpectrum, which is not useful anymore.
    totalEnergyInput = GetEnergy(&Q_0, pEnergy);
#ifdef DEBUG
    DumpEnergy(&Q_0, pEnergy);
#endif

    //-------- Create arrays --------
    // NOTE: I first make them table size; they will be "clipped" after reading in tables
    if (ICSSwitch == 1) {
        NewRawTotalRate(&ICSTotalRate, EM_NUM_MAIN_BINS, NUM_BG_BINS);
        NewRawDiffRate(&ICSPhotonRate, EM_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_IP_ELEMENTS);
        NewRawDiffRate(&ICSScatRate, EM_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_IS_ELEMENTS);
    }

    if (PPSwitch == 1) {
        NewRawTotalRate(&PPTotalRate, EM_NUM_MAIN_BINS, NUM_BG_BINS);
        NewRawDiffRate(&PPDiffRate, EM_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_PP_ELEMENTS);
    }

    if (TPPSwitch == 1) {
        NewRawTotalRate(&TPPTotalRate, EM_NUM_MAIN_BINS, NUM_BG_BINS);
        NewRawDiffRate(&TPPDiffRate, EM_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_TPP_ELEMENTS);
    }

    if (DPPSwitch == 1)
        NewRawTotalRate(&DPPRate, EM_NUM_MAIN_BINS, NUM_BG_BINS);

    if (PPPSwitch == 1) {
        NewRawTotalRate(&PPPProtonLossRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS);
        NewRawTotalRate(&PPPNeutronLossRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS);

        NewRawDiffRate(&PPPProtonScatRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_PPP_PROTON_SCAT_ELEMENTS);
        NewRawDiffRate(&PPPProtonNeutronRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_PPP_PROTON_NEUTRON_ELEMENTS);
        NewRawDiffRate(&PPPNeutronProtonRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS,
                       NUM_PPP_PROTON_NEUTRON_ELEMENTS);

        if (nucleonToSecondarySwitch == 1) {
            NewRawDiffRate(&PPPProtonPhotonRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_PHOTON_ELEMENTS);
            NewRawDiffRate(&PPPProtonElectronRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_ELECTRON_ELEMENTS);
            NewRawDiffRate(&PPPProtonPositronRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_POSITRON_ELEMENTS);
            NewRawDiffRate(&PPPNeutronElectronRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_POSITRON_ELEMENTS);
            NewRawDiffRate(&PPPProtonElectronNeutrinoRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_ANTI_MUON_NEUTRINO_ELEMENTS);
            NewRawDiffRate(&PPPProtonAntiElectronNeutrinoRate,
                           NUC_NUM_MAIN_BINS, NUM_BG_BINS,
                           NUM_PPP_PROTON_ANTI_ELECTRON_NEUTRINO_ELEMENTS);
            NewRawDiffRate(&PPPProtonMuonNeutrinoRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_MUON_NEUTRINO_ELEMENTS);
            NewRawDiffRate(&PPPProtonAntiMuonNeutrinoRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_ANTI_MUON_NEUTRINO_ELEMENTS);
            NewRawDiffRate(&PPPNeutronAntiElectronNeutrinoRate,
                           NUC_NUM_MAIN_BINS, NUM_BG_BINS,
                           NUM_PPP_PROTON_ANTI_MUON_NEUTRINO_ELEMENTS);
            NewRawDiffRate(&PPPNeutronMuonNeutrinoRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_ANTI_MUON_NEUTRINO_ELEMENTS);
            NewRawDiffRate(&PPPNeutronAntiMuonNeutrinoRate, NUC_NUM_MAIN_BINS,
                           NUM_BG_BINS, NUM_PPP_PROTON_MUON_NEUTRINO_ELEMENTS);
        }
    }

    if (NPPSwitch == 1) {
        NewRawTotalRate(&NPPTotalRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS);

        if (nucleonToSecondarySwitch == 1)
            NewRawDiffRate(&NPPDiffRate, NUC_NUM_MAIN_BINS, NUM_BG_BINS,
                           NUM_NPP_ELEMENTS);
    }

    // neutron decay does not fit the general category because it is not
    //    really an interaction (with background)
    if (neutronDecaySwitch == 1) {
        NewTotalRate(&neutronDecayRate, NUC_NUM_MAIN_BINS);
        NewDiffRate(&neutronDecayProtonRate, NUC_NUM_MAIN_BINS);

        if (nucleonToSecondarySwitch == 1)
            NewDiffRate(&neutronDecayElectronRate, NUC_NUM_MAIN_BINS);
    }

    // neutrino-neutrino rates are already folded w/ neutrino background
    if (neutrinoNeutrinoSwitch == 1) {
        NewTotalRate(&NNElNeutTotalRate, NEUT_NUM_MAIN_BINS);
        NewTotalRate(&NNMuonNeutTotalRate, NEUT_NUM_MAIN_BINS);
        NewTotalRate(&NNTauNeutTotalRate, NEUT_NUM_MAIN_BINS);

        NewDiffRate(&NNElNeutScatRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNElNeutMuonNeutRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNElNeutTauNeutRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNElNeutElectronRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNElNeutPhotonRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNElNeutProtonRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNMuonNeutScatRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNMuonNeutElNeutRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNMuonNeutTauNeutRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNMuonNeutElectronRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNMuonNeutPhotonRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNMuonNeutProtonRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNTauNeutScatRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNTauNeutElNeutRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNTauNeutMuonNeutRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNTauNeutElectronRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNTauNeutPhotonRate, NEUT_NUM_MAIN_BINS);
        NewDiffRate(&NNTauNeutProtonRate, NEUT_NUM_MAIN_BINS);
    }

    //---- read in coefficient tables; clipping is done here if necessary ----
    if (ICSSwitch == 1)
        LoadICSTables(&ICSTotalRate, &ICSPhotonRate, &ICSScatRate,
                      NUM_MAIN_BINS, aDirTables);
    if (PPSwitch == 1)
        LoadPPTables(&PPTotalRate, &PPDiffRate, NUM_MAIN_BINS, aDirTables);
    if (TPPSwitch == 1)
        LoadTPPTables(&TPPTotalRate, &TPPDiffRate, NUM_MAIN_BINS, aDirTables);
    if (DPPSwitch == 1)
        LoadDPPTables(&DPPRate, NUM_MAIN_BINS, aDirTables);
    if (PPPSwitch == 1) {
        LoadPPPNucleonTables(&PPPProtonLossRate, &PPPNeutronLossRate,
                             &PPPProtonScatRate, &PPPProtonNeutronRate, &PPPNeutronProtonRate,
                             NUM_MAIN_BINS, aDirTables);

        if (nucleonToSecondarySwitch == 1) {
            LoadPPPEMTables(&PPPProtonPhotonRate, &PPPProtonElectronRate,
                            &PPPProtonPositronRate, &PPPNeutronElectronRate,
                            NUM_MAIN_BINS, aDirTables);
            LoadPPPNeutrinoTables(&PPPProtonElectronNeutrinoRate,
                                  &PPPProtonAntiElectronNeutrinoRate, &PPPProtonMuonNeutrinoRate,
                                  &PPPProtonAntiMuonNeutrinoRate,
                                  &PPPNeutronAntiElectronNeutrinoRate,
                                  &PPPNeutronMuonNeutrinoRate, &PPPNeutronAntiMuonNeutrinoRate,
                                  NUM_MAIN_BINS, aDirTables);
        }
    }
    if (NPPSwitch == 1) {
        LoadNPPNucleonTables(&NPPTotalRate, NUM_MAIN_BINS, aDirTables);

        if (nucleonToSecondarySwitch == 1)
            LoadNPPSecondaryTables(&NPPDiffRate, NUM_MAIN_BINS, aDirTables);
    }

    if (neutronDecaySwitch == 1) {
        LoadNeutronDecayNucleonTables(&neutronDecayRate,
                                      &neutronDecayProtonRate, NUM_MAIN_BINS, aDirTables);

        if (nucleonToSecondarySwitch == 1)
            LoadNeutronDecaySecondaryTables(&neutronDecayElectronRate,
                                            NUM_MAIN_BINS, aDirTables);
    }

    if (neutrinoNeutrinoSwitch == 1)
        LoadNeutrinoTables(tauNeutrinoMassSwitch, &NNElNeutTotalRate,
                           &NNMuonNeutTotalRate, &NNTauNeutTotalRate, &NNElNeutScatRate,
                           &NNElNeutMuonNeutRate, &NNElNeutTauNeutRate,
                           &NNElNeutElectronRate, &NNElNeutPhotonRate, &NNElNeutProtonRate,
                           &NNMuonNeutScatRate, &NNMuonNeutElNeutRate,
                           &NNMuonNeutTauNeutRate, &NNMuonNeutElectronRate,
                           &NNMuonNeutPhotonRate, &NNMuonNeutProtonRate, &NNTauNeutScatRate,
                           &NNTauNeutElNeutRate, &NNTauNeutMuonNeutRate,
                           &NNTauNeutElectronRate, &NNTauNeutPhotonRate,
                           &NNTauNeutProtonRate, NUM_MAIN_BINS, aDirTables);

#ifdef DEBUG
    printf("Starting computations...\n\n");
#endif

    //---- Initialize distance ----
    distance = 0.;  // distance variable: dist in FORTRAN

    PrepareSpectra(sourceTypeSwitch, &Q_0, pSpectrum, &spectrumNew,
                   &derivative);
    // NOTE: suspect derivative is never used???

    //  if (sourceTypeSwitch == 0)  // single source
    //        DumpSpectrum(pEnergy, pEnergyWidth, &Q_0, "InitialSpectrumDump.dat");

    ComputeTotalInitialContent(pEnergy, &Q_0, &initialPhotonEnergy,
                               &initialLeptonEnergy, &initialNucleonEnergy,
                               &initialNeutrinoEnergy, &initialTotalEnergy,
                               &initialPhotonNumber, &initialLeptonNumber,
                               &initialNucleonNumber, &initialNeutrinoNumber,
                               &initialTotalNumber);

    //--------- START of actual computation --------
    //---- initialize indices and parameters ----
    iterationCounter = 1;
    firstIndex = 0;
    leftRedshift = startingRedshift;
    deltaRedshift = 1. - (pEnergy->vector)[2]/(pEnergy->vector)[3];
    lastIndex = 0;
    propagatingDistance = 0.;


    NewTotalRate(&leptonTotalRate, NUM_MAIN_BINS);
    NewTotalRate(&photonTotalRate, NUM_MAIN_BINS);

    NewTotalRate(&protonTotalRate, NUM_MAIN_BINS);
    NewTotalRate(&neutronTotalRate, NUM_MAIN_BINS);


    NewDiffRate(&leptonScatRate, NUM_MAIN_BINS);
    NewDiffRate(&leptonExchRate, NUM_MAIN_BINS);
    NewDiffRate(&leptonPhotonRate, NUM_MAIN_BINS);
    NewDiffRate(&photonLeptonRate, NUM_MAIN_BINS);

    NewDiffRate(&protonScatRate, NUM_MAIN_BINS);
    NewDiffRate(&protonNeutronRate, NUM_MAIN_BINS);
    NewDiffRate(&neutronProtonRate, NUM_MAIN_BINS);
    NewDiffRate(&protonPhotonRate, NUM_MAIN_BINS);
    NewDiffRate(&protonElectronRate, NUM_MAIN_BINS);
    NewDiffRate(&protonPositronRate, NUM_MAIN_BINS);
    NewDiffRate(&neutronElectronRate, NUM_MAIN_BINS);
    NewDiffRate(&neutronPositronRate, NUM_MAIN_BINS);
    NewDiffRate(&protonElectronNeutrinoRate, NUM_MAIN_BINS);
    NewDiffRate(&protonAntiElectronNeutrinoRate, NUM_MAIN_BINS);
    NewDiffRate(&protonMuonNeutrinoRate, NUM_MAIN_BINS);
    NewDiffRate(&protonAntiMuonNeutrinoRate, NUM_MAIN_BINS);
    NewDiffRate(&neutronAntiElectronNeutrinoRate, NUM_MAIN_BINS);
    NewDiffRate(&neutronMuonNeutrinoRate, NUM_MAIN_BINS);
    NewDiffRate(&neutronAntiMuonNeutrinoRate, NUM_MAIN_BINS);


    NewTotalRate(&elNeutTotalRate, NUM_MAIN_BINS);
    NewTotalRate(&muonNeutTotalRate, NUM_MAIN_BINS);
    NewTotalRate(&tauNeutTotalRate, NUM_MAIN_BINS);

    NewDiffRate(&elNeutScatRate, NUM_MAIN_BINS);
    NewDiffRate(&elNeutMuonNeutRate, NUM_MAIN_BINS);
    NewDiffRate(&elNeutTauNeutRate, NUM_MAIN_BINS);
    NewDiffRate(&elNeutElectronRate, NUM_MAIN_BINS);
    NewDiffRate(&elNeutPhotonRate, NUM_MAIN_BINS);
    NewDiffRate(&elNeutProtonRate, NUM_MAIN_BINS);
    NewDiffRate(&muonNeutElNeutRate, NUM_MAIN_BINS);
    NewDiffRate(&muonNeutScatRate, NUM_MAIN_BINS);
    NewDiffRate(&muonNeutTauNeutRate, NUM_MAIN_BINS);
    NewDiffRate(&muonNeutElectronRate, NUM_MAIN_BINS);
    NewDiffRate(&muonNeutPhotonRate, NUM_MAIN_BINS);
    NewDiffRate(&muonNeutProtonRate, NUM_MAIN_BINS);
    NewDiffRate(&tauNeutElNeutRate, NUM_MAIN_BINS);
    NewDiffRate(&tauNeutMuonNeutRate, NUM_MAIN_BINS);
    NewDiffRate(&tauNeutScatRate, NUM_MAIN_BINS);
    NewDiffRate(&tauNeutElectronRate, NUM_MAIN_BINS);
    NewDiffRate(&tauNeutPhotonRate, NUM_MAIN_BINS);
    NewDiffRate(&tauNeutProtonRate, NUM_MAIN_BINS);
    /* I created all folded rates because I didn't want to pass all the
       switches to the subsequent functions, and these allocations are
       not so expensive anyway */

    //-------- This is where propagation takes place --------
    do {

        // this firstIndex & lastIndex pair is used to bin redshift finer
        //  near the end of propagation (z close to 0)
        ComputeRedshifts(sourceTypeSwitch, leftRedshift, &deltaRedshift,
                         &rightRedshift, &centralRedshift, &lastIndex);

        //---- compute various distance parameters ----
        redshiftRatio = (1. + rightRedshift)/(1. + leftRedshift);
        //    tempCoefficient = pow(OMEGA_M*pow(1. + centralRedshift,3.)+
        //			  OMEGA_LAMBDA, -1./2.)/(1.+centralRedshift);
        //        tempCoefficient = pow(1. + centralRedshift, -5./2.);
        //    distanceStep = (leftRedshift - rightRedshift)*tempCoefficient*C/
        //      (H_0*1.e5/1.e6/DISTANCE_UNIT);

        // (cosmological parameters added July 2005)
        leftDistance = getDistance(RedshiftArray,DistanceArray,leftRedshift) ;
        rightDistance =  getDistance(RedshiftArray,DistanceArray,rightRedshift) ;
        distanceStep = leftDistance - rightDistance ;
        distance += distanceStep;
        //    rightDistance = distance - distanceStep/2.;
        //    leftDistance = distance + distanceStep/2.;
        //        rightDistance = 2./3.*C/1.e5/H_0*(1. - pow(1. + rightRedshift, -1.5));
        //        leftDistance = 2./3.*C/1.e5/H_0*(1. - pow(1. + leftRedshift, -1.5));

        evolutionFactor1 = pow((1. + centralRedshift)/(1. + startingRedshift),
                               brightPhaseExp+3.);   // redshift evolution
        numSmallSteps = (int)(ceil(distanceStep/DISTANCE_UNIT/DMAX));
        smallDistanceStep = distanceStep/DISTANCE_UNIT/numSmallSteps;
        x = 0.;
        //	printf("small stepsize: %15.6E\n", smallDistanceStep);

        //---- compute the photon background at given redshift ----
        LoadPhotonBackground(centralRedshift, &bgEnergy, &bgEnergyWidth,
                             &bgPhotonDensity, aIRFlag, aZmax_IR, aRadioFlag,
                             aH0, aOmegaM, aOmegaLambda);

        //	if (rightRedshift < 1.e-5)
        // DumpBgSpectrum(&bgEnergy, &bgEnergyWidth, &bgPhotonDensity,"~/");

        //---- initialize rates ----
        InitializeLeptonCoefficients(&leptonTotalRate, &leptonScatRate,
                                     &leptonExchRate, &leptonPhotonRate);
        InitializePhotonCoefficients(&photonTotalRate, &photonLeptonRate);
        InitializeNucleonCoefficients(&protonTotalRate, &neutronTotalRate,
                                      &protonScatRate, &protonNeutronRate,
                                      &neutronProtonRate, &protonPhotonRate,
                                      &protonElectronRate, &protonPositronRate,
                                      &neutronElectronRate, &neutronPositronRate,
                                      &protonElectronNeutrinoRate,
                                      &protonAntiElectronNeutrinoRate,
                                      &protonMuonNeutrinoRate, &protonAntiMuonNeutrinoRate,
                                      &neutronAntiElectronNeutrinoRate, &neutronMuonNeutrinoRate,
                                      &neutronAntiMuonNeutrinoRate);
        InitializeNeutrinoCoefficients(&elNeutTotalRate, &muonNeutTotalRate,
                                       &tauNeutTotalRate, &elNeutScatRate, &elNeutMuonNeutRate,
                                       &elNeutTauNeutRate, &elNeutElectronRate,
                                       &elNeutPhotonRate, &elNeutProtonRate,
                                       &muonNeutElNeutRate, &muonNeutScatRate,
                                       &muonNeutTauNeutRate, &muonNeutElectronRate,
                                       &muonNeutPhotonRate, &muonNeutProtonRate,
                                       &tauNeutElNeutRate, &tauNeutMuonNeutRate,
                                       &tauNeutScatRate, &tauNeutElectronRate,
                                       &tauNeutPhotonRate, &tauNeutProtonRate);

        Initialize_dCVector(&continuousLoss);

        Initialize_dCVector(&otherLoss);
        Initialize_dCVector(&protonContinuousLoss);

        //---- fold interaction rates w/ photon background ----
        if (ICSSwitch == 1)
            FoldICS(&bgPhotonDensity, &ICSTotalRate, &ICSPhotonRate,
                    &ICSScatRate, &leptonTotalRate, &leptonPhotonRate,
                    &leptonScatRate);
        if (TPPSwitch == 1)
            FoldTPP(&bgPhotonDensity, pEnergy, &TPPTotalRate, &TPPDiffRate,
                    &leptonTotalRate, &leptonScatRate, &leptonExchRate,
                    &otherLoss);
        if (PPSwitch == 1)
            FoldPP(&bgPhotonDensity, &PPTotalRate, &PPDiffRate,
                   &photonTotalRate, &photonLeptonRate);
        if (DPPSwitch == 1)
            FoldDPP(&bgPhotonDensity, &DPPRate, &photonTotalRate,
                    &photonLeptonRate);
        if (PPPSwitch == 1) {
            FoldPPPNucleon(&bgPhotonDensity, &PPPProtonLossRate,
                           &PPPNeutronLossRate, &PPPProtonScatRate, &PPPProtonNeutronRate,
                           &PPPNeutronProtonRate, &protonTotalRate, &neutronTotalRate,
                           &protonScatRate, &protonNeutronRate, &neutronProtonRate);

            if (nucleonToSecondarySwitch == 1)
                FoldPPPSecondary(&bgPhotonDensity, &PPPProtonPhotonRate,
                                 &PPPProtonElectronRate, &PPPProtonPositronRate,
                                 &PPPNeutronElectronRate, &PPPProtonElectronNeutrinoRate,
                                 &PPPProtonAntiElectronNeutrinoRate,
                                 &PPPProtonMuonNeutrinoRate, &PPPProtonAntiMuonNeutrinoRate,
                                 &PPPNeutronAntiElectronNeutrinoRate,
                                 &PPPNeutronMuonNeutrinoRate,
                                 &PPPNeutronAntiMuonNeutrinoRate, &protonPhotonRate,
                                 &protonElectronRate, &protonPositronRate,
                                 &neutronElectronRate, &neutronPositronRate,
                                 &protonElectronNeutrinoRate,
                                 &protonAntiElectronNeutrinoRate,
                                 &protonMuonNeutrinoRate, &protonAntiMuonNeutrinoRate,
                                 &neutronAntiElectronNeutrinoRate, &neutronMuonNeutrinoRate,
                                 &neutronAntiMuonNeutrinoRate);
        }


#ifdef EXTRACT_PHOTON_TOTAL_RATE
        // Add - E.A. Dec. 2005
        // Extract photon total energy loss rate
        for (int i=0; i<pEnergy->dimension; i++) cout << (pEnergy->vector)[i] << " "
                    << (photonTotalRate.totalRate)[i]
                    << endl;
        exit(0) ;
#endif
#ifdef EXTRACT_LEPTON_RATE
        for (int i=0; i<pEnergy->dimension; i++) cout << (pEnergy->vector)[i] << " "
                    << (leptonTotalRate.totalRate)[i]
                    << endl;
        exit(0) ;
#endif

        if (NPPSwitch == 1) {

            FoldNPPNucleon(&bgPhotonDensity, pEnergy, &NPPTotalRate,
                           &protonContinuousLoss);

#ifdef EXTRACT_PAIR_PROD_RATE
            // Slight add - E.A. July 2005 .
            // To extract the pair production tables of protons on photon backgrounds.
            // (need to switch NPPSwitch!)
            for (int i=0; i<pEnergy->dimension; i++) cout << (pEnergy->vector)[i] << " "
                        << (protonContinuousLoss.vector)[i]
                        << endl;
            exit(0) ;
#endif

            if (nucleonToSecondarySwitch == 1)
                FoldNPPSecondary(&bgPhotonDensity, &NPPDiffRate,
                                 &protonPositronRate, &protonElectronRate);
        }

        if (neutrinoNeutrinoSwitch == 1)
            MapNeutRates(centralRedshift, lastIndex, tauNeutrinoMassSwitch,
                         &NNElNeutTotalRate, &NNMuonNeutTotalRate, &NNTauNeutTotalRate,
                         &NNElNeutScatRate, &NNElNeutMuonNeutRate,
                         &NNElNeutTauNeutRate, &NNElNeutElectronRate,
                         &NNElNeutPhotonRate, &NNElNeutProtonRate,
                         &NNMuonNeutElNeutRate, &NNMuonNeutScatRate,
                         &NNMuonNeutTauNeutRate, &NNMuonNeutElectronRate,
                         &NNMuonNeutPhotonRate, &NNMuonNeutProtonRate,
                         &NNTauNeutElNeutRate, &NNTauNeutMuonNeutRate,
                         &NNTauNeutScatRate, &NNTauNeutElectronRate,
                         &NNTauNeutPhotonRate, &NNTauNeutProtonRate, &elNeutTotalRate,
                         &muonNeutTotalRate, &tauNeutTotalRate, &elNeutScatRate,
                         &elNeutMuonNeutRate, &elNeutTauNeutRate, &elNeutElectronRate,
                         &elNeutPhotonRate, &elNeutProtonRate, &muonNeutElNeutRate,
                         &muonNeutScatRate, &muonNeutTauNeutRate, &muonNeutElectronRate,
                         &muonNeutPhotonRate, &muonNeutProtonRate, &tauNeutElNeutRate,
                         &tauNeutMuonNeutRate, &tauNeutScatRate, &tauNeutElectronRate,
                         &tauNeutPhotonRate, &tauNeutProtonRate);

        //---- main iteration (convergence) block ----

        for (loopCounter = 0; loopCounter < numSmallSteps; loopCounter++) {

            if (synchrotronSwitch == 1) {     // synchrotron == true (on)

                NewDiffRate(&syncRate, NUM_MAIN_BINS);

                B_bin = (int)((double)(B_bins)*(propagatingDistance+x)/1.e6/
                              dist_observer);
                B_loc=(pB_field->vector)[B_bin];
                InitializeSynchrotron(B_loc, pEnergy, pEnergyWidth,
                                      &synchrotronLoss, &syncRate,
                                      aDirTables);
            }
            //---- compute continuous energy loss for electrons ----
            ComputeContinuousEnergyLoss(synchrotronSwitch, &synchrotronLoss,
                                        &otherLoss, &continuousLoss);

            evolutionFactor = evolutionFactor1;
            if ((leftDistance - x/1.e6) < minDistance)
                evolutionFactor = 0.;
            if ((leftDistance - x/1.e6) < SOURCE_CLUSTER_DISTANCE)
                evolutionFactor = SOURCE_CLUSTER_FACTOR*evolutionFactor1;
            if ((leftDistance - x/1.e6) < CLUSTER_DISTANCE)
                bkgFactor = CLUSTER_FACTOR;
            else
                bkgFactor = 1.;

            AdvanceNucNeutStep(sourceTypeSwitch, PPPSwitch, NPPSwitch,
                               neutronDecaySwitch, nucleonToSecondarySwitch,
                               neutrinoNeutrinoSwitch, smallDistanceStep,
                               evolutionFactor, convergeParameter, bkgFactor, &Q_0,
                               &elNeutProtonRate,
                               &muonNeutProtonRate, &tauNeutProtonRate, &protonTotalRate,
                               &neutronTotalRate, &neutronDecayRate, &protonScatRate,
                               &protonNeutronRate, &neutronProtonRate,
                               &neutronDecayProtonRate, &protonMuonNeutrinoRate,
                               &neutronAntiMuonNeutrinoRate, &protonAntiMuonNeutrinoRate,
                               &neutronMuonNeutrinoRate, &protonElectronNeutrinoRate,
                               &neutronAntiElectronNeutrinoRate,
                               &protonAntiElectronNeutrinoRate, &neutronDecayElectronRate,
                               &elNeutTotalRate, &muonNeutTotalRate, &tauNeutTotalRate,
                               &elNeutScatRate, &elNeutMuonNeutRate, &elNeutTauNeutRate,
                               &muonNeutElNeutRate, &muonNeutScatRate, &muonNeutTauNeutRate,
                               &tauNeutElNeutRate, &tauNeutMuonNeutRate, &tauNeutScatRate,
                               &protonContinuousLoss, &deltaG, pSpectrum, &spectrumNew);

            SetNucleonSpectrum(pSpectrum, &spectrumNew);
            SetNeutrinoSpectrum(pSpectrum, &spectrumNew);

            AdvanceEMStep(sourceTypeSwitch, PPSwitch, ICSSwitch,
                          TPPSwitch, DPPSwitch, synchrotronSwitch, PPPSwitch,
                          NPPSwitch, neutronDecaySwitch, nucleonToSecondarySwitch,
                          neutrinoNeutrinoSwitch, smallDistanceStep, evolutionFactor,
                          convergeParameter, bkgFactor, &Q_0, &photonLeptonRate,
                          &protonElectronRate, &neutronPositronRate,
                          &protonPositronRate, &neutronElectronRate,
                          &neutronDecayElectronRate, &elNeutElectronRate,
                          &muonNeutElectronRate, &tauNeutElectronRate,
                          &protonPhotonRate, &elNeutPhotonRate, &muonNeutPhotonRate,
                          &tauNeutPhotonRate, &leptonTotalRate, &leptonScatRate,
                          &leptonExchRate, &continuousLoss, &deltaG, &photonTotalRate,
                          &leptonPhotonRate, &syncRate, pSpectrum, &spectrumNew);

            SetEMSpectrum(pSpectrum, &spectrumNew);
            // update spectrum

            if (aCutcascade_Magfield != 0 && B_loc != 0 ) {
                // Estimate the effect of B field on the 1D approximation (added E.A. June 2006)
                lEcFlag = 0 ;
                lIndex =  0;
                while (!lEcFlag) {
                    lEnergy = (pEnergy->vector)[lIndex] ;
                    // Time scales are computed in parsec
                    t_sync = 3.84e6/(lEnergy*B_loc*B_loc*ELECTRON_MASS) ;
                    t_larmor = (1.1e-21)*ELECTRON_MASS*lEnergy/(B_loc*aCutcascade_Magfield) ;
                    if (lEnergy <= 1.e15/ELECTRON_MASS) {
                        t_ics = 4.e2*1.e15/(ELECTRON_MASS*lEnergy) ;
                    } else if (lEnergy <= 1.e18/ELECTRON_MASS) {
                        t_ics = 4.e2*lEnergy*ELECTRON_MASS/1.e15 ;
                    } else if (lEnergy <= 1.e22/ELECTRON_MASS) {
                        t_ics = b_ics*pow(lEnergy*ELECTRON_MASS/1.e15,a_ics) ;
                    } else t_ics = 1.e8*lEnergy*ELECTRON_MASS/1.e22 ;
                    if (t_larmor >= t_sync || t_larmor >= t_ics) lEcFlag = 1 ;
                    // defines the "critical" energy : the e+/- spectrum is set to 0 for E<E_c
                    (pSpectrum->spectrum)[ELECTRON][lIndex]=0 ;
                    (pSpectrum->spectrum)[POSITRON][lIndex]=0 ;
                    lIndex++ ;
                }
            }

            if (synchrotronSwitch == 1)     // synchrotron == true (on)
                DeleteDiffRate(&syncRate);

            x += smallDistanceStep;
            iterationCounter++;
        }


        propagatingDistance += x;   // increment distance

        //---- redshift bins down ----
        RedshiftDown(lastIndex, redshiftRatio, pEnergy, pSpectrum,
                     &spectrumNew);

        //	printf("\nz = %g -> %g", leftRedshift, rightRedshift);
        //	printf("; d/Mpc = %g -> %g:\n", leftDistance, rightDistance);
        //	printf("%g, %g:\n", propagatingDistance, distance);
        CheckEnergy(sourceTypeSwitch, brightPhaseExp, startingRedshift,
                    rightRedshift, pSpectrum, pEnergy, initialTotalEnergy);

        //---- prepare for new step ----
        leftRedshift = rightRedshift;
    } while (lastIndex != 1);

    //---- I am done with the rates ----
    DeleteDiffRate(&leptonScatRate);
    DeleteDiffRate(&leptonExchRate);
    DeleteDiffRate(&leptonPhotonRate);
    DeleteDiffRate(&photonLeptonRate);
    DeleteDiffRate(&protonScatRate);
    DeleteDiffRate(&protonNeutronRate);
    DeleteDiffRate(&neutronProtonRate);
    DeleteDiffRate(&protonPhotonRate);
    DeleteDiffRate(&protonElectronRate);
    DeleteDiffRate(&protonPositronRate);
    DeleteDiffRate(&neutronElectronRate);
    DeleteDiffRate(&neutronPositronRate);
    DeleteDiffRate(&protonElectronNeutrinoRate);
    DeleteDiffRate(&protonAntiElectronNeutrinoRate);
    DeleteDiffRate(&protonMuonNeutrinoRate);
    DeleteDiffRate(&protonAntiMuonNeutrinoRate);
    DeleteDiffRate(&neutronAntiElectronNeutrinoRate);
    DeleteDiffRate(&neutronMuonNeutrinoRate);
    DeleteDiffRate(&neutronAntiMuonNeutrinoRate);

    DeleteDiffRate(&elNeutScatRate);
    DeleteDiffRate(&elNeutMuonNeutRate);
    DeleteDiffRate(&elNeutTauNeutRate);
    DeleteDiffRate(&elNeutElectronRate);
    DeleteDiffRate(&elNeutPhotonRate);
    DeleteDiffRate(&elNeutProtonRate);
    DeleteDiffRate(&muonNeutElNeutRate);
    DeleteDiffRate(&muonNeutScatRate);
    DeleteDiffRate(&muonNeutTauNeutRate);
    DeleteDiffRate(&muonNeutElectronRate);
    DeleteDiffRate(&muonNeutPhotonRate);
    DeleteDiffRate(&muonNeutProtonRate);
    DeleteDiffRate(&tauNeutElNeutRate);
    DeleteDiffRate(&tauNeutMuonNeutRate);
    DeleteDiffRate(&tauNeutScatRate);
    DeleteDiffRate(&tauNeutElectronRate);
    DeleteDiffRate(&tauNeutPhotonRate);
    DeleteDiffRate(&tauNeutProtonRate);

    DeleteTotalRate(&leptonTotalRate);
    DeleteTotalRate(&photonTotalRate);
    DeleteTotalRate(&protonTotalRate);
    DeleteTotalRate(&neutronTotalRate);
    DeleteTotalRate(&elNeutTotalRate);
    DeleteTotalRate(&muonNeutTotalRate);
    DeleteTotalRate(&tauNeutTotalRate);


    if (ICSSwitch == 1) {
        DeleteRawDiffRate(&ICSPhotonRate);
        DeleteRawDiffRate(&ICSScatRate);
        DeleteRawTotalRate(&ICSTotalRate);
    }
    if (PPSwitch == 1) {
        DeleteRawDiffRate(&PPDiffRate);
        DeleteRawTotalRate(&PPTotalRate);
    }
    if (TPPSwitch == 1) {
        DeleteRawDiffRate(&TPPDiffRate);
        DeleteRawTotalRate(&TPPTotalRate);
    }
    if (PPPSwitch == 1) {
        DeleteRawDiffRate(&PPPProtonScatRate);
        DeleteRawDiffRate(&PPPProtonNeutronRate);
        DeleteRawDiffRate(&PPPNeutronProtonRate);

        DeleteRawTotalRate(&PPPProtonLossRate);
        DeleteRawTotalRate(&PPPNeutronLossRate);

        if (nucleonToSecondarySwitch == 1) {
            DeleteRawDiffRate(&PPPProtonPhotonRate);
            DeleteRawDiffRate(&PPPProtonElectronRate);
            DeleteRawDiffRate(&PPPProtonPositronRate);
            DeleteRawDiffRate(&PPPNeutronElectronRate);
            DeleteRawDiffRate(&PPPProtonElectronNeutrinoRate);
            DeleteRawDiffRate(&PPPProtonAntiElectronNeutrinoRate);
            DeleteRawDiffRate(&PPPProtonMuonNeutrinoRate);
            DeleteRawDiffRate(&PPPProtonAntiMuonNeutrinoRate);
            DeleteRawDiffRate(&PPPNeutronAntiElectronNeutrinoRate);
            DeleteRawDiffRate(&PPPNeutronMuonNeutrinoRate);
            DeleteRawDiffRate(&PPPNeutronAntiMuonNeutrinoRate);
        }
    }
    if (NPPSwitch == 1) {
        if (nucleonToSecondarySwitch == 1)
            DeleteRawDiffRate(&NPPDiffRate);
        DeleteRawTotalRate(&NPPTotalRate);
    }
    if (DPPSwitch == 1)
        DeleteRawTotalRate(&DPPRate);

    if (neutronDecaySwitch == 1) {
        if (nucleonToSecondarySwitch == 1)
            DeleteDiffRate(&neutronDecayElectronRate);
        DeleteDiffRate(&neutronDecayProtonRate);
        DeleteTotalRate(&neutronDecayRate);
    }


    if (neutrinoNeutrinoSwitch == 1) {
        DeleteDiffRate(&NNElNeutScatRate);
        DeleteDiffRate(&NNElNeutMuonNeutRate);
        DeleteDiffRate(&NNElNeutTauNeutRate);
        DeleteDiffRate(&NNElNeutElectronRate);
        DeleteDiffRate(&NNElNeutPhotonRate);
        DeleteDiffRate(&NNElNeutProtonRate);
        DeleteDiffRate(&NNMuonNeutElNeutRate);
        DeleteDiffRate(&NNMuonNeutScatRate);
        DeleteDiffRate(&NNMuonNeutTauNeutRate);
        DeleteDiffRate(&NNMuonNeutElectronRate);
        DeleteDiffRate(&NNMuonNeutPhotonRate);
        DeleteDiffRate(&NNMuonNeutProtonRate);
        DeleteDiffRate(&NNTauNeutElNeutRate);
        DeleteDiffRate(&NNTauNeutMuonNeutRate);
        DeleteDiffRate(&NNTauNeutScatRate);
        DeleteDiffRate(&NNTauNeutElectronRate);
        DeleteDiffRate(&NNTauNeutPhotonRate);
        DeleteDiffRate(&NNTauNeutProtonRate);

        DeleteTotalRate(&NNElNeutTotalRate);
        DeleteTotalRate(&NNMuonNeutTotalRate);
        DeleteTotalRate(&NNTauNeutTotalRate);
    }

    //    FinalPrintOutToTheScreen(distance, startingRedshift, propagatingDistance);

    DeleteSpectrum(&Q_0);
    DeleteSpectrum(&spectrumNew);
    DeleteSpectrum(&derivative);

    Delete_dCVector(&synchrotronLoss);
    Delete_dCVector(&continuousLoss);
    Delete_dCVector(&otherLoss);
    Delete_dCVector(&protonContinuousLoss);

    Delete_dCVector(&deltaG);
    Delete_dCVector(&bgEnergy);
    Delete_dCVector(&bgEnergyWidth);
    Delete_dCVector(&bgPhotonDensity);

    Delete_dCVector(&RedshiftArray) ;
    Delete_dCVector(&DistanceArray) ;

}
Exemplo n.º 20
0
bool CEES_Node::Initialize(CStorageHead &storage, const gsl_rng *r)
{
	// random permutation of 0, 1, ..., K-1
	gsl_permutation *p = gsl_permutation_alloc(K); 
	gsl_permutation_init(p); 
	gsl_ran_shuffle(r, p->data, K, sizeof(int)); 
	
	int binOffset; 
	if (next_level == NULL)
		binOffset = this->BinID(0); 
	else 
		binOffset = next_level->BinID(0); 
	int index=0, bin_id;  
	while (index <K )
	{
		bin_id = binOffset+gsl_permutation_get(p, index); 
		if (storage.DrawSample(bin_id, r, x_current))
		{
			x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature();
			ring_index_current = GetRingIndex(x_current.GetWeight());
                        UpdateMinMaxEnergy(x_current.GetWeight());
			gsl_permutation_free(p); 
			return true; 
		}
		index ++; 
	}

	gsl_permutation_free(p); 	
	return false; 
	// Initialize using samples from the next level; 
	/*if (next_level == NULL)
	{
		for (int try_id = id; try_id >=0; try_id --)
		{
			int bin_id = this->BinID(try_id); 
			if (storage.DrawSample(bin_id, r, x_current))
			{
				x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature();
                        	ring_index_current = GetRingIndex(x_current.GetWeight());
                        	UpdateMinMaxEnergy(x_current.GetWeight());
                        	return true;
			}
		}
		for (int try_id = id+1; try_id <K; try_id ++)
		{
			int bin_id = this->BinID(try_id);
                        if (storage.DrawSample(bin_id, r, x_current))
                        {
                                x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature();
                                ring_index_current = GetRingIndex(x_current.GetWeight());
                                UpdateMinMaxEnergy(x_current.GetWeight());
                                return true;
                        }

		}
	}
	else 
	{       
		// Try next levels' bins with the same or lower energies
		for (int try_id = id; try_id >= 0; try_id --)
		{
			int bin_id_next_level = next_level->BinID(try_id); 
        		if (storage.DrawSample(bin_id_next_level, r, x_current))
			{
			// x_current.weight will remain the same 
			// x_current.log_prob needs to be updated according to 
			// current level's H and T
				x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature(); 
				ring_index_current = GetRingIndex(x_current.GetWeight());  
				UpdateMinMaxEnergy(x_current.GetWeight()); 
				return true;
			}
		}
		// If not successful, then try next level's bins with higher energies
		for (int try_id = id+1; try_id <K; try_id ++)
		{
			int bin_id_next_level = next_level->BinID(try_id);
                	if (storage.DrawSample(bin_id_next_level, r, x_current))
                	{
			// x_current.weight will remain the same 
			// x_current.log_prob needs to be updated according to
			// current level's H and  T
				x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature(); 
                        	ring_index_current = GetRingIndex(x_current.GetWeight());
				UpdateMinMaxEnergy(x_current.GetWeight()); 
                        	return true;
                	}
		}
	}
	return false; */
} 
Exemplo n.º 21
0
void CEES_Node::MH_StepSize_Tune(int initialPeriodL, int periodNumber, const gsl_rng *r, int mMH)
// Adapt from Dan's Adaptive Scaling
{
	// Save current state, because (1) tuning is based on a mode, and (2) after tuning is done, simulator will resume from the current state
	CSampleIDWeight x_current_saved = x_current; 

	ultimate_target->GetMode(x_current); 
	// At this moment x_current.weight and x_current.log_pron are wrt ultimate_target
	// x_current.weight will remain the same
	// x_current.log_prob needs to be updated to reflect this level's H and T
	x_current.log_prob = -(x_current.GetWeight() > GetEnergy() ? x_current.GetWeight() : GetEnergy())/GetTemperature(); 
	int dim_lum_sum=0; 
	for (int iBlock=0; iBlock<nBlock; iBlock++)
	{
		proposal[iBlock]->Tune(targetAcc[this->id], initialPeriodL, periodNumber, r, target, x_current, dim_lum_sum, blockSize[iBlock]); 
		dim_lum_sum += blockSize[iBlock];  
	}
	
	/*int nGenerated = initialPeriodL; // length of observation
	int nAccepted;  
	
	MHAdaptive *adaptive; 
	CTransitionModel_SimpleGaussian *individual_proposal = new CTransitionModel_SimpleGaussian(1); 
	  
	// Tune for a number of perioldNumber times
	int dim_lum_sum =0;
	bool new_sample_flag = false; 
	ultimate_target->GetMode(x_current, dataDim); 
	double log_prob_mode = target->log_prob(x_current, dataDim);  
	double log_prob_x; 
	for (int iBlock=0; iBlock<nBlock; iBlock++)
	{
		for (int iDim=0; iDim<blockSize[iBlock]; iDim++)
		{
			adaptive = new MHAdaptive(targetAcc[this->id], proposal[iBlock]->get_step_size(iDim)); 
			individual_proposal->set_step_size(proposal[iBlock]->get_step_size(iDim));
			for (int nPeriod=0; nPeriod<periodNumber; nPeriod++)
			{	
				// tuning starts from a mode of the target distribution
				ultimate_target->GetMode(x_current, dataDim); 
				nAccepted = 0;
				log_prob_x = log_prob_mode;  
				// draw samples 
				for (int iteration=0; iteration<nGenerated; iteration ++)
				{
					log_prob_x = target->draw_block(dim_lum_sum+iDim, 1, individual_proposal, x_new, dataDim, new_sample_flag, r, x_current,log_prob_x, mMH); 
					if (new_sample_flag)
					{
						memcpy(x_current, x_new, dataDim*sizeof(double));
						nAccepted ++; 
					}
				}
				// Update scale 
				if(adaptive->UpdateScale(nGenerated, nAccepted)) 
					individual_proposal->set_step_size(adaptive->GetScale()); 
			}
			proposal[iBlock]->set_step_size(adaptive->GetBestScale(), iDim); 
		}
		delete adaptive;
		dim_lum_sum += blockSize[iBlock]; 
	}
	
	delete individual_proposal; */
	// restore x_current
	x_current = x_current_saved; 
}
Exemplo n.º 22
0
double CEES_Node::LogProbRatio_Energy(double energy_x, double energy_y)
{
	double log_prob_x_bounded = -(energy_x > GetEnergy() ? energy_x : GetEnergy())/GetTemperature(); 
	double log_prob_y_bounded = -(energy_y > GetEnergy() ? energy_y : GetEnergy())/GetTemperature(); 
	return log_prob_x_bounded - log_prob_y_bounded; 
}
Exemplo n.º 23
0
void AngularCorrelationSelector::FillHistograms() {
	//without addback
	for(auto g1 = 0; g1 < fGrif->GetMultiplicity(); ++g1) {
		auto grif1 = fGrif->GetGriffinHit(g1);
		//check for coincident betas
		bool coincBeta = false;
		for(auto s = 0; s < fScep->GetMultiplicity(); ++s) {
			auto scep = fScep->GetSceptarHit(s);
			if(!coincBeta && gbLow <= grif1->GetTime()-scep->GetTime() && grif1->GetTime()-scep->GetTime() <= gbHigh) coincBeta = true;
			fH1["betaGammaTiming"]->Fill(scep->GetTime()-grif1->GetTime());
			fH2["betaGammaHP"]->Fill(scep->GetDetector(), grif1->GetArrayNumber());
		}
		fH1["gammaEnergy"]->Fill(grif1->GetEnergy());
		if(coincBeta) fH1["gammaEnergyBeta"]->Fill(grif1->GetEnergy());
		for(auto g2 = 0; g2 < fGrif->GetMultiplicity(); ++g2) {
			if(g1 == g2) continue;
			auto grif2 = fGrif->GetGriffinHit(g2);
			double angle = grif1->GetPosition().Angle(grif2->GetPosition())*180./TMath::Pi();
			if(angle < 0.0001) continue;
			auto angleIndex = fAngleMap.lower_bound(angle-0.0005);
			double ggTime = TMath::Abs(grif1->GetTime()-grif2->GetTime());
			fH1["gammaGammaTiming"]->Fill(ggTime);
			fH2["gammaGammaHP"]->Fill(grif1->GetArrayNumber(), grif2->GetArrayNumber());

			if(ggTime < ggHigh) {
				fH2["gammaGamma"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				fH2[Form("gammaGamma%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				if(coincBeta) {
					fH2["gammaGammaBeta"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
					fH2[Form("gammaGammaBeta%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				}
			} else if(bgLow < ggTime && ggTime < bgHigh) {
				fH2["gammaGammaBG"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				fH2[Form("gammaGammaBG%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				if(coincBeta) {
					fH2["gammaGammaBetaBG"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
					fH2[Form("gammaGammaBetaBG%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				}
			}
		}
		//event mixing, we use the last event as second griffin
		for(auto g2 = 0; g2 < fLastGrif.GetMultiplicity(); ++g2) {
			if(g1 == g2) continue;
			auto grif2 = fLastGrif.GetGriffinHit(g2);
			double angle = grif1->GetPosition().Angle(grif2->GetPosition())*180./TMath::Pi();
			if(angle < 0.0001) continue;
			auto angleIndex = fAngleMap.lower_bound(angle-0.0005);
			double ggTime = TMath::Abs(grif1->GetTime()-grif2->GetTime());
			fH2["gammaGammaHPMixed"]->Fill(grif1->GetArrayNumber(), grif2->GetArrayNumber());

			fH2["gammaGammaMixed"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
			fH2[Form("gammaGammaMixed%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
			if(coincBeta) {
				fH2["gammaGammaBetaMixed"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				fH2[Form("gammaGammaBetaMixed%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
			}
		}
	}
	//with addback
	for(auto g1 = 0; g1 < fGrif->GetAddbackMultiplicity(); ++g1) {
		auto grif1 = fGrif->GetAddbackHit(g1);
		//check for coincident betas
		bool coincBeta = false;
		for(auto s = 0; s < fScep->GetMultiplicity(); ++s) {
			auto scep = fScep->GetSceptarHit(s);
			if(!coincBeta && gbLow <= grif1->GetTime()-scep->GetTime() && grif1->GetTime()-scep->GetTime() <= gbHigh) coincBeta = true;
			fH1["betaAddbackTiming"]->Fill(scep->GetTime()-grif1->GetTime());
			fH2["betaAddbackHP"]->Fill(scep->GetDetector(), grif1->GetArrayNumber());
		}
		fH1["addbackEnergy"]->Fill(grif1->GetEnergy());
		if(coincBeta) fH1["addbackEnergyBeta"]->Fill(grif1->GetEnergy());
		for(auto g2 = 0; g2 < fGrif->GetAddbackMultiplicity(); ++g2) {
			if(g1 == g2) continue;
			auto grif2 = fGrif->GetAddbackHit(g2);
			double angle = grif1->GetPosition().Angle(grif2->GetPosition())*180./TMath::Pi();
			if(angle < 0.0001) continue;
			auto angleIndex = fAngleMapAddback.lower_bound(angle-0.0005);
			double ggTime = TMath::Abs(grif1->GetTime()-grif2->GetTime());
			fH1["addbackAddbackTiming"]->Fill(ggTime);
			fH2["addbackAddbackHP"]->Fill(grif1->GetArrayNumber(), grif2->GetArrayNumber());

			if(ggTime < ggHigh) {
				fH2["addbackAddback"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				fH2[Form("addbackAddback%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				if(coincBeta) {
					fH2["addbackAddbackBeta"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
					fH2[Form("addbackAddbackBeta%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				}
			} else if(bgLow < ggTime && ggTime < bgHigh) {
				fH2["addbackAddbackBG"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				fH2[Form("addbackAddbackBG%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				if(coincBeta) {
					fH2["addbackAddbackBetaBG"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
					fH2[Form("addbackAddbackBetaBG%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				}
			}
		}
		//event mixing, we use the last event as second griffin
		for(auto g2 = 0; g2 < fLastGrif.GetAddbackMultiplicity(); ++g2) {
			if(g1 == g2) continue;
			auto grif2 = fLastGrif.GetAddbackHit(g2);
			double angle = grif1->GetPosition().Angle(grif2->GetPosition())*180./TMath::Pi();
			if(angle < 0.0001) continue;
			auto angleIndex = fAngleMapAddback.lower_bound(angle-0.0005);
			double ggTime = TMath::Abs(grif1->GetTime()-grif2->GetTime());
			fH2["addbackAddbackHPMixed"]->Fill(grif1->GetArrayNumber(), grif2->GetArrayNumber());

			fH2["addbackAddbackMixed"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
			fH2[Form("addbackAddbackMixed%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
			if(coincBeta) {
				fH2["addbackAddbackBetaMixed"]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
				fH2[Form("addbackAddbackBetaMixed%d", angleIndex->second)]->Fill(grif1->GetEnergy(), grif2->GetEnergy());
			}
		}
	}

	//update "last" event
	fLastGrif = *fGrif;
	fLastScep = *fScep;
}
Exemplo n.º 24
0
void Animal::Sleep()
{
	this->SetEnergy(GetEnergy() + 1 + (3 * RandomGenerator::AdditionalPoints()));
	this->SetStrength(GetStrength() + 1 + RandomGenerator::AdditionalPoints());
	this->SetCurrentState(Sleeping);
}