IAP GITLAB

Cascade.h 15 KB
Newer Older
André Schmidt's avatar
André Schmidt committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/*
 * (c) Copyright 2018 CORSIKA Project, corsika-project@lists.kit.edu
 *
 * See file AUTHORS for a list of contributors.
 *
 * This software is distributed under the terms of the GNU General Public
 * Licence version 3 (GPL Version 3). See file LICENSE for a full version of
 * the license.
 */

#ifndef _include_corsika_cascade_Cascade_h_
#define _include_corsika_cascade_Cascade_h_

#include <corsika/environment/Environment.h>
#include <corsika/process/ProcessReturn.h>
#include <corsika/random/ExponentialDistribution.h>
#include <corsika/random/RNGManager.h>
#include <corsika/random/UniformRealDistribution.h>
#include <corsika/stack/SecondaryView.h>
#include <corsika/units/PhysicalUnits.h>

#include <corsika/setup/SetupTrajectory.h>

/*  see Issue 161, we need to include SetupStack only because we need
    to globally define StackView. This is clearly not nice and should
    be changed, when possible. It might be that StackView needs to be
    templated in Cascade, but this would be even worse... so we don't
    do that until it is really needed.
 */
#include <corsika/setup/SetupStack.h>

#include <cassert>
#include <cmath>
#include <iostream>
#include <limits>
#include <type_traits>

38 39 40
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;

André Schmidt's avatar
André Schmidt committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
/**
 * The cascade namespace assembles all objects needed to simulate full particles cascades.
 */

namespace corsika::cascade {

  /**
   * \class Cascade
   *
   * The Cascade class is constructed from template arguments making
   * it very versatile. Via the template arguments physics models are
   * plugged into the cascade simulation.
   *
   * <b>TTracking</b> must be a class according to the
   * TrackingInterface providing the functions:
   * <code>auto GetTrack(Particle const& p)</auto>,
   * with the return type <code>geometry::Trajectory<corsika::geometry::Line>
   * </code>
   *
   * <b>TProcessList</b> must be a ProcessSequence.   *
   * <b>Stack</b> is the storage object for particle data, i.e. with
   * Particle class type <code>Stack::ParticleType</code>
   *
   *
   */

  template <typename TTracking, typename TProcessList, typename TStack,
            /*
              TStackView is needed as template parameter because of issue 161 and the
              inability of clang to understand "MakeView" so far.
             */
            typename TStackView = corsika::setup::StackView>
  class Cascade {
    using Particle = typename TStack::ParticleType;
    using VolumeTreeNode =
        std::remove_pointer_t<decltype(((Particle*)nullptr)->GetNode())>;
    using MediumInterface = typename VolumeTreeNode::IModelProperties;

    // we only want fully configured objects
    Cascade() = delete;

  public:
    /**
     * Cascade class cannot be default constructed, but needs a valid
     * list of physics processes for configuration at construct time.
     */
    Cascade(corsika::environment::Environment<MediumInterface> const& env, TTracking& tr,
            TProcessList& pl, TStack& stack)
        : fEnvironment(env)
        , fTracking(tr)
        , fProcessSequence(pl)
        , fStack(stack) {}

    /**
     * The Init function is called before the actual cascade simulations.
     * All components of the Cascade simulation must be configured here.
     */
    void Init() {
      fProcessSequence.Init();
      fStack.Init();
    }

    /**
     * set the nodes for all particles on the stack according to their numerical
     * position
     */
    void SetNodes() {
      std::for_each(fStack.begin(), fStack.end(), [&](auto& p) {
        auto const* numericalNode =
            fEnvironment.GetUniverse()->GetContainingNode(p.GetPosition());
        p.SetNode(numericalNode);
      });
    }

    /**
     * The Run function is the main simulation loop, which processes
     * particles from the Stack until the Stack is empty.
     */
    void Run() {
      SetNodes();

      while (!fStack.IsEmpty()) {
        while (!fStack.IsEmpty()) {
          auto pNext = fStack.GetNextParticle();
          std::cout << "========= next: " << pNext.GetPID() << std::endl;
          Step(pNext);
          std::cout << "========= stack ============" << std::endl;
          fProcessSequence.DoStack(fStack);
        }
        // do cascade equations, which can put new particles on Stack,
        // thus, the double loop
        // DoCascadeEquations();
      }
    }

    /**
     * Force an interaction of the top particle of the stack at its current position.
     * Note that SetNodes() or an equivalent procedure needs to be called first if you
     * want to call forceInteraction() for the primary interaction.
     */
    void forceInteraction() {
      std::cout << "forced interaction!" << std::endl;
      auto vParticle = fStack.GetNextParticle();
      TStackView secondaries(vParticle);
      auto projectile = secondaries.GetProjectile();
      interaction(vParticle, projectile);
      fProcessSequence.DoSecondaries(secondaries);
      vParticle.Delete(); // todo: this should be reviewed, see below
    }

  private:
    /**
     * The Step function is executed for each particle from the
     * stack. It will calcualte geometric transport of the particles,
     * and apply continuous and stochastic processes to it, which may
     * lead to energy losses, scattering, absorption, decays and the
     * production of secondary particles.
     *
     * New particles produced in one step are subject to further
     * processing, e.g. thinning, etc.
     */
    void Step(Particle& vParticle) {
      using namespace corsika;
      using namespace corsika::units::si;

      // determine combined total interaction length (inverse)
      InverseGrammageType const total_inv_lambda =
          fProcessSequence.GetTotalInverseInteractionLength(vParticle);

      // sample random exponential step length in grammage
      corsika::random::ExponentialDistribution expDist(1 / total_inv_lambda);
      GrammageType const next_interact = expDist(fRNG);

      std::cout << "total_inv_lambda=" << total_inv_lambda
                << ", next_interact=" << next_interact << std::endl;

      auto const* currentLogicalNode = vParticle.GetNode();

      // assert that particle stays outside void Universe if it has no
      // model properties set
      assert(currentLogicalNode != &*fEnvironment.GetUniverse() ||
             fEnvironment.GetUniverse()->HasModelProperties());

      // determine combined total inverse decay time
      InverseTimeType const total_inv_lifetime =
          fProcessSequence.GetTotalInverseLifetime(vParticle);

      // sample random exponential decay time
      corsika::random::ExponentialDistribution expDistDecay(1 / total_inv_lifetime);
      TimeType const next_decay = expDistDecay(fRNG);
      std::cout << "total_inv_lifetime=" << total_inv_lifetime
                << ", next_decay=" << next_decay << std::endl;

      // convert next_decay from time to length [m]
      LengthType const distance_decay = next_decay * vParticle.GetMomentum().norm() /
                                        vParticle.GetEnergy() * units::constants::c;
197
                                    
André Schmidt's avatar
André Schmidt committed
198
      // determine geometric tracking
Andre Schmidt's avatar
Andre Schmidt committed
199
      auto [step, geomMaxLength, nextVol] = fTracking.GetTrack(vParticle);
André Schmidt's avatar
André Schmidt committed
200
      [[maybe_unused]] auto const& dummy_nextVol = nextVol;
201
      
André Schmidt's avatar
André Schmidt committed
202 203 204 205
      // convert next_step from grammage to length
      LengthType const distance_interact =
          currentLogicalNode->GetModelProperties().ArclengthFromGrammage(step,
                                                                         next_interact);
206
      
André Schmidt's avatar
André Schmidt committed
207 208 209 210
      // determine the maximum geometric step length
      LengthType const distance_max = fProcessSequence.MaxStepLength(vParticle, step);
      std::cout << "distance_max=" << distance_max << std::endl;

Andre Schmidt's avatar
Andre Schmidt committed
211
      // take minimum of geometry, interaction, decay for next step
André Schmidt's avatar
André Schmidt committed
212
      auto const min_distance = std::min(
Andre Schmidt's avatar
Andre Schmidt committed
213
          {distance_interact, distance_decay, distance_max, geomMaxLength});
André Schmidt's avatar
André Schmidt committed
214 215 216

      std::cout << " move particle by : " << min_distance << std::endl;

Andre Schmidt's avatar
Andre Schmidt committed
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
      //determine displacement by the magnetic field
	    auto const* currentLogicalVolumeNode = vParticle.GetNode();
      int chargeNumber;
      if(corsika::particles::IsNucleus(vParticle.GetPID())) {
        chargeNumber = vParticle.GetNuclearZ();
      } else {
     	  chargeNumber = corsika::particles::GetChargeNumber(vParticle.GetPID());
      }
      if(chargeNumber != 0) {
    		auto magneticfield = currentLogicalVolumeNode->GetModelProperties().GetMagneticField(vParticle.GetPosition());
    		geometry::Vector<SpeedType::dimension_type> velocity = vParticle.GetMomentum() / vParticle.GetEnergy() *
    			                                                     corsika::units::constants::c;
    		geometry::Vector<dimensionless_d> const directionBefore = velocity.normalized();
    		auto k = chargeNumber * corsika::units::constants::cSquared * 1_eV / 
                (velocity.GetNorm() * vParticle.GetEnergy() * 1_V);
    		LengthType const steplength = min_distance / 
                                      (directionBefore + directionBefore.cross(magneticfield) * k / 2).GetNorm();
    		// First Movement
    		//assuming magnetic field does not change during movement
    		auto position = vParticle.GetPosition() + directionBefore * Steplength / 2;
    		// Change of direction by magnetic field
    		geometry::Vector<dimensionless_d> const directionAfter = directionBefore + directionBefore.cross(magneticfield) *
                                                                Steplength * k; 
    		// Second Movement
    		position = position + directionAfter * Steplength / 2;
    		geometry::Vector<dimensionless_d> const direction = (position - vParticle.GetPosition()) / 
    									                                      (position - vParticle.GetPosition()).GetNorm();
        vParticle.SetMomentum(direction * vParticle.GetMomentum().GetNorm());
      }

André Schmidt's avatar
André Schmidt committed
247 248 249
      // here the particle is actually moved along the trajectory to new position:
      // std::visit(setup::ParticleUpdate<Particle>{vParticle}, step);
      vParticle.SetPosition(step.PositionFromArclength(min_distance));
250
      // .... also update time, momentum, direction, ...  
André Schmidt's avatar
André Schmidt committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      vParticle.SetTime(vParticle.GetTime() + min_distance / units::constants::c);

      step.LimitEndTo(min_distance);

      // apply all continuous processes on particle + track
      process::EProcessReturn status = fProcessSequence.DoContinuous(vParticle, step);

      if (status == process::EProcessReturn::eParticleAbsorbed) {
        std::cout << "Cascade: delete absorbed particle " << vParticle.GetPID() << " "
                  << vParticle.GetEnergy() / 1_GeV << "GeV" << std::endl;
        vParticle.Delete();
        return;
      }

      std::cout << "sth. happening before geometric limit ? "
                << ((min_distance < geomMaxLength) ? "yes" : "no") << std::endl;

      if (min_distance < geomMaxLength) { // interaction to happen within geometric limit

        // check whether decay or interaction limits this step the
        // outcome of decay or interaction MAY be a) new particles in
        // secondaries, b) the projectile particle deleted (or
        // changed)

        TStackView secondaries(vParticle);

Andre Schmidt's avatar
Andre Schmidt committed
277
        if (min_distance != distance_max) {
André Schmidt's avatar
André Schmidt committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
          /*
            Create SecondaryView object on Stack. The data container
            remains untouched and identical, and 'projectil' is identical
            to 'vParticle' above this line. However,
            projectil.AddSecondaries populate the SecondaryView, which can
            then be used afterwards for further processing. Thus: it is
            important to use projectle (and not vParticle) for Interaction,
            and Decay!
          */

          [[maybe_unused]] auto projectile = secondaries.GetProjectile();

          if (min_distance == distance_interact) {
            interaction(vParticle, projectile);
          } else {
            assert(min_distance == distance_decay);
            decay(vParticle, projectile);
            // make sure particle actually did decay if it should have done so
            if (secondaries.GetSize() == 1 &&
                projectile.GetPID() == secondaries.GetNextParticle().GetPID())
              throw std::runtime_error("Cascade::Step: Particle decays into itself!");
          }

          fProcessSequence.DoSecondaries(secondaries);
          vParticle.Delete(); // todo: this should be reviewed. Where
                              // exactly are particles best deleted, and
                              // where they should NOT be
                              // deleted... maybe Delete function should
                              // be "protected" and not accessible to physics

        } else { // step-length limitation within volume

          std::cout << "step-length limitation" << std::endl;
          fProcessSequence.DoSecondaries(secondaries);
        }

        [[maybe_unused]] auto const assertion = [&] {
          auto const* numericalNodeAfterStep =
              fEnvironment.GetUniverse()->GetContainingNode(vParticle.GetPosition());
          return numericalNodeAfterStep == currentLogicalNode;
        };

        assert(assertion()); // numerical and logical nodes don't match
      } else {               // boundary crossing, step is limited by volume boundary
        std::cout << "boundary crossing! next node = " << nextVol << std::endl;
        vParticle.SetNode(nextVol);
        // DoBoundary may delete the particle (or not)
        fProcessSequence.DoBoundaryCrossing(vParticle, *currentLogicalNode, *nextVol);
      }
    }

    auto decay(Particle& particle,
               decltype(std::declval<TStackView>().GetProjectile()) projectile) {
      std::cout << "decay" << std::endl;
      units::si::InverseTimeType const actual_decay_time =
          fProcessSequence.GetTotalInverseLifetime(particle);

      random::UniformRealDistribution<units::si::InverseTimeType> uniDist(
          actual_decay_time);
      const auto sample_process = uniDist(fRNG);
      units::si::InverseTimeType inv_decay_count = units::si::InverseTimeType::zero();
      return fProcessSequence.SelectDecay(particle, projectile, sample_process,
                                          inv_decay_count);
    }

    auto interaction(Particle& particle,
                     decltype(std::declval<TStackView>().GetProjectile()) projectile) {
      std::cout << "collide" << std::endl;

      units::si::InverseGrammageType const current_inv_length =
          fProcessSequence.GetTotalInverseInteractionLength(particle);

      random::UniformRealDistribution<units::si::InverseGrammageType> uniDist(
          current_inv_length);
      const auto sample_process = uniDist(fRNG);
      auto inv_lambda_count = units::si::InverseGrammageType::zero();
      return fProcessSequence.SelectInteraction(particle, projectile, sample_process,
                                                inv_lambda_count);
    }

  private:
    corsika::environment::Environment<MediumInterface> const& fEnvironment;
    TTracking& fTracking;
    TProcessList& fProcessSequence;
    TStack& fStack;
    corsika::random::RNG& fRNG =
        corsika::random::RNGManager::GetInstance().GetRandomStream("cascade");
  }; // namespace corsika::cascade

} // namespace corsika::cascade

#endif