Example #1
0
    def setXMLConfig(self, child):
        # print "setXMLConfig"
        #
        # read configuration from xml
        #
        loggingContext = "adapter '[{a:s}]'".format(a=self.name)
        if not environment.has_key('gui'):
            logger.error("No gui enabled . Do not configure gui")
            return

        # look for extension tag (new from 2017)
        for tle in child:
            if 'extension' == tle.tag:
                child = tle
                break

        for tle in child:
            if 'webserver' == tle.tag:
                for tle2 in tle:
                    if 'route' == tle2.tag:
                        name = tle2.attrib['name']
                        route = tle2.attrib['route']
                        environment.get('gui').websocketPlugin(
                            name, route, PendelWebSocket)
                    if 'html' == tle2.tag:
                        name = tle2.attrib['name']
                        path = tle2.attrib['path']
                        comment = tle2.attrib['comment']
                        environment.get('gui').htmlPlugin(name, path, comment)
Example #2
0
    def __init__(self, **kwargs):
        """ ## Parameters
            Master object carrying the cosmological state of the system and initial conditions """

        # Temperature bounds define the simulations boundaries of the system
        self.T = None

        # Arbitrary normalization of the conformal scale factor
        self.m = 1. * UNITS.MeV
        # Initial time
        self.t = 0. * UNITS.s
        # Hubble rate
        self.H = 0.
        # Total energy density
        self.rho = None
        self.N_eff = 0.

        self.dy = 0.05
        self.dx = 0.005 * UNITS.MeV

        for key in kwargs:
            setattr(self, key, kwargs[key])

        # As the initial scale factor is arbitrary, it can be use to ensure the initial $aT$ value\
        # equal to 1
        self.a = 1 * self.m / self.T
        self.a_ini = self.a

        self.infer()

        if environment.get('LOGARITHMIC_TIMESTEP') and not kwargs.get('dy'):
            raise Exception("Using logarithmic timestep, but no Params.dy was specified")
        if not environment.get('LOGARITHMIC_TIMESTEP') and not kwargs.get('dx'):
            raise Exception("Using linear timestep, but no Params.dx was specified")
Example #3
0
    def __init__(self, **kwargs):
        """ ## Parameters
            Master object carrying the cosmological state of the system and initial conditions """

        # Temperature bounds define the simulations boundaries of the system
        self.T = None

        # Arbitrary normalization of the conformal scale factor
        self.m = 1. * UNITS.MeV
        # Initial time
        self.t = 0. * UNITS.s
        # Hubble rate
        self.H = 0.
        # Total energy density
        self.rho = None
        self.N_eff = 0.

        self.dy = 0.05
        self.dx = 0.005 * UNITS.MeV

        for key in kwargs:
            setattr(self, key, kwargs[key])

        # As the initial scale factor is arbitrary, it can be use to ensure the initial $aT$ value\
        # equal to 1
        self.a = self.m / self.T

        self.infer()

        if environment.get('LOGARITHMIC_TIMESTEP') and not kwargs.get('dy'):
            raise Exception("Using logarithmic timestep, but no Params.dy was specified")
        if not environment.get('LOGARITHMIC_TIMESTEP') and not kwargs.get('dx'):
            raise Exception("Using linear timestep, but no Params.dx was specified")
Example #4
0
    def integrate(self, ps, stepsize=None, bounds=None):
        params = self.particle.params

        if self.reaction[0].specie.mass == 0:
            return numpy.zeros(len(ps))

        bounds = tuple(b1 / params.aT for b1 in self.grids.BOUNDS)

        if stepsize is None:
            stepsize = params.h

        if not environment.get('LOGARITHMIC_TIMESTEP'):
            stepsize /= params.aT

        self.creaction = [
            reaction_t3(
                specie=particle_t3(
                    m=particle.specie.conformal_mass / params.aT,
                    grid=grid_t3(
                        grid=particle.specie.grid.TEMPLATE / params.aT,
                        distribution=particle.specie._distribution
                    ),
                    eta=int(particle.specie.eta),
                    in_equilibrium=int(particle.specie.in_equilibrium),
                    T=particle.specie.aT / params.aT
                ),
                side=particle.side
            )
            for particle in self.reaction
        ]

        ps = ps / params.aT
        self.cMs = sum(M.K for M in self.Ms)

        constant_0 = self.cMs * params.aT / params.a / 8. / numpy.pi / params.H / self.particle.mass**2
        constant_else = self.cMs * params.a / params.aT / 32. / numpy.pi / params.H

        constant = numpy.append(constant_0, numpy.repeat(constant_else, len(ps) - 1))

        if not environment.get('LOGARITHMIC_TIMESTEP'):
            constant /= params.x

        stepsize *= constant_else

        if environment.get('SPLIT_COLLISION_INTEGRAL'):
            A = integration_3(ps, *bounds, self.creaction, stepsize, CollisionIntegralKind.F_1)
            B = integration_3(ps, *bounds, self.creaction, stepsize, CollisionIntegralKind.F_f)
            return numpy.array(A) * constant, numpy.array(B) * constant

        fullstack = integration_3(ps, *bounds, self.creaction, stepsize, self.kind)

        if self.kind == CollisionIntegralKind.F_f or self.kind == CollisionIntegralKind.F_f_vacuum_decay:
            constant *= self.particle._distribution

        return numpy.array(fullstack) * constant
Example #5
0
def interpolation_4p(interaction, ps, slice_1):
    interpolate = False
    grid = interaction.particle.grid
    if grid.MAX_MOMENTUM / (grid.MOMENTUM_SAMPLES - 1) < environment.get(
            'FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV:
        steps = np.ceil(
            slice_1[-1] /
            (environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV))
        interp_pos = np.searchsorted(ps, np.linspace(ps[0], ps[-1], steps))
        ps = ps[interp_pos]
        interpolate = True
    return ps, interpolate
Example #6
0
    def __init__(self, MOMENTUM_SAMPLES=None, MAX_MOMENTUM=None):
        if not MAX_MOMENTUM:
            MAX_MOMENTUM = environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV
        if not MOMENTUM_SAMPLES:
            MOMENTUM_SAMPLES = environment.get('MOMENTUM_SAMPLES')

        self.MIN_MOMENTUM = 0
        self.MAX_MOMENTUM = self.MIN_MOMENTUM + MAX_MOMENTUM
        self.BOUNDS = (self.MIN_MOMENTUM, self.MAX_MOMENTUM)
        self.MOMENTUM_SAMPLES = MOMENTUM_SAMPLES

        self.TEMPLATE = self.generate_template()
Example #7
0
    def __init__(self, MOMENTUM_SAMPLES=None, MAX_MOMENTUM=None):
        if not MAX_MOMENTUM:
            MAX_MOMENTUM = environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV
        if not MOMENTUM_SAMPLES:
            MOMENTUM_SAMPLES = environment.get('MOMENTUM_SAMPLES')

        self.MIN_MOMENTUM = 0
        self.MAX_MOMENTUM = self.MIN_MOMENTUM + MAX_MOMENTUM
        self.BOUNDS = (self.MIN_MOMENTUM, self.MAX_MOMENTUM)
        self.MOMENTUM_SAMPLES = MOMENTUM_SAMPLES

        self.TEMPLATE = self.generate_template()
Example #8
0
def temperature_regime_switching_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.regime == REGIMES.INTERMEDIATE

    params.aT = params.a * electron.mass * environment.get('REGIME_SWITCHING_FACTOR') * 2
    electron.update()
    assert electron.regime == REGIMES.RADIATION

    params.aT = params.a * electron.mass / environment.get('REGIME_SWITCHING_FACTOR') / 2
    electron.update()
    assert electron.regime == REGIMES.DUST
Example #9
0
def temperature_regime_switching_test(params):

    electron = Particle(params=params, **SMP.leptons.electron)
    assert electron.regime == REGIMES.INTERMEDIATE

    params.aT = params.a * electron.mass * environment.get(
        'REGIME_SWITCHING_FACTOR') * 2
    electron.update()
    assert electron.regime == REGIMES.RADIATION

    params.aT = params.a * electron.mass / environment.get(
        'REGIME_SWITCHING_FACTOR') / 2
    electron.update()
    assert electron.regime == REGIMES.DUST
Example #10
0
def grid_params_meson(mass, mixing_angle):
    pion_mass = 134.98 * UNITS.MeV

    if mass < pion_mass:
        MAX_MOMENTUM = environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV
    elif mass - pion_mass < 0.35 * UNITS.MeV:
        MAX_MOMENTUM = 10 * environment.get('MAX_SCALE_FACTOR') * UNITS.MeV
    else:
        MAX_MOMENTUM = np.sqrt(mass**2 - pion_mass**2) * environment.get(
            'MAX_SCALE_FACTOR')

    MOMENTUM_SAMPLES = MAX_MOMENTUM / grid_resolution_meson(mass, mixing_angle)

    return int(MOMENTUM_SAMPLES), MAX_MOMENTUM
Example #11
0
def grid_params_lepton(mass, mixing_angle, std=False):
    muon_mass = 105.658 * UNITS.MeV

    if mass < muon_mass or std:
        MAX_MOMENTUM = mass * environment.get('MAX_SCALE_FACTOR')
    elif mass - muon_mass < 0.35 * UNITS.MeV:
        MAX_MOMENTUM = 10 * environment.get('MAX_SCALE_FACTOR') * UNITS.MeV
    else:
        MAX_MOMENTUM = np.sqrt(mass**2 - muon_mass**2) * environment.get(
            'MAX_SCALE_FACTOR')

    MOMENTUM_SAMPLES = MAX_MOMENTUM / grid_resolution_lepton(
        mass, mixing_angle, std=std)

    return int(MOMENTUM_SAMPLES), MAX_MOMENTUM
Example #12
0
    def integrand(self, t, y):
        """ ## Temperature equation integrand

            Master equation for the temperature looks like

            \begin{equation}
                \frac{d (aT)}{dx} = \frac{\sum_i{N_i}}{\sum_i{D_i}}
            \end{equation}

            Where $N_i$ and $D_i$ represent contributions from different particle species.

            See definitions for different regimes:
              * [[Radiation|particles/RadiationParticle.py#master-equation-terms]]
              * [[Intermediate|particles/IntermediateParticle.py#master-equation-terms]]
              * [[Dust|particles/DustParticle.py#master-equation-terms]]
              * [[Non-equilibrium|particles/NonEqParticle.py#master-equation-terms]]
        """

        # 1\. Update particles states
        self.update_particles()
        # 2\. Initialize non-equilibrium interactions
        self.init_interactions()
        # 3\. Calculate collision integrals
        self.calculate_collisions()
        # 4\. Update particles distributions
        self.update_distributions()
        # 5\. Calculate temperature equation terms
        numerator, denominator = self.calculate_temperature_terms()

        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.fraction = self.params.x * numerator / denominator
        else:
            self.fraction = numerator / denominator

        return self.fraction
Example #13
0
    def integrand(self, t, y):
        """ ## Temperature equation integrand

            Master equation for the temperature looks like

            \begin{equation}
                \frac{d (aT)}{dx} = \frac{\sum_i{N_i}}{\sum_i{D_i}}
            \end{equation}

            Where $N_i$ and $D_i$ represent contributions from different particle species.

            See definitions for different regimes:
              * [[Radiation|particles/RadiationParticle.py#master-equation-terms]]
              * [[Intermediate|particles/IntermediateParticle.py#master-equation-terms]]
              * [[Dust|particles/DustParticle.py#master-equation-terms]]
              * [[Non-equilibrium|particles/NonEqParticle.py#master-equation-terms]]
        """

        # 1\. Update particles states
        self.update_particles()
        # 2\. Initialize non-equilibrium interactions
        self.init_interactions()
        # 3\. Calculate collision integrals
        self.calculate_collisions()
        # 4\. Update particles distributions
        self.update_distributions()
        # 5\. Calculate temperature equation terms
        numerator, denominator = self.calculate_temperature_terms()

        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.fraction = self.params.x * numerator / denominator
        else:
            self.fraction = numerator / denominator

        return self.fraction
Example #14
0
def get_base_docker_run_args(workspace,
                             sanitizer=constants.DEFAULT_SANITIZER,
                             language=constants.DEFAULT_LANGUAGE,
                             architecture=constants.DEFAULT_ARCHITECTURE,
                             docker_in_docker=False):
  """Returns arguments that should be passed to every invocation of 'docker
  run'."""
  docker_args = _DEFAULT_DOCKER_RUN_ARGS.copy()
  env_mapping = {
      'SANITIZER': sanitizer,
      'ARCHITECTURE': architecture,
      'FUZZING_LANGUAGE': language,
      'OUT': workspace.out
  }
  docker_args += get_docker_env_vars(env_mapping)
  docker_container = environment.get('CFL_CONTAINER_ID',
                                     utils.get_container_name())
  logging.info('Docker container: %s.', docker_container)
  if docker_container and not docker_in_docker:
    # Don't map specific volumes if in a docker container, it breaks when
    # running a sibling container.
    docker_args += ['--volumes-from', docker_container]
  else:
    docker_args += _get_args_mapping_host_path_to_container(workspace.workspace)
  return docker_args, docker_container
Example #15
0
    def infer(self):
        """ Set initial cosmological parameters based on the value of `T` """

        # Compute present-state parameters that can be inferred from the base ones
        self.x = self.a * self.m
        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.y = numpy.log(self.a)
        self.aT = self.a * self.T

        # Conformal scale factor step size during computations
        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.dx = self.x * self.dy
            self.h = self.dy
        else:
            self.dy = None
            self.h = self.dx
Example #16
0
    def infer(self):
        """ Set initial cosmological parameters based on the value of `T` """

        # Compute present-state parameters that can be inferred from the base ones
        self.x = self.a * self.m
        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.y = numpy.log(self.a)
        self.aT = self.a * self.T

        # Conformal scale factor step size during computations
        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.dx = self.x * self.dy
            self.h = self.dy
        else:
            self.dy = None
            self.h = self.dx
Example #17
0
    def regime(self):
        """
        ### Regime-switching ratio
        For ultra-relativistic particles the mass is effectively `0`. This implies that all\
        computed numerically values can be as well obtained analytically: energy density, pressure,\
        etc.

        Let particle mass be equal $M$ and regime factor equal $\gamma$. As soon as the \
        temperature of the system $T$ drops to the value about $ M \gamma $, particle should be \
        switched to the computation regime where its mass is also considered: \
        `REGIMES.INTERMEDIATE`. When $T$ drops down even further to the value $ M / \gamma $,\
        particle species can be treated as `REGIMES.DUST` with a Boltzmann distribution function.
        """
        regime_factor = environment.get('REGIME_SWITCHING_FACTOR')

        if not self.in_equilibrium:
            return REGIMES.NONEQ

        if self.T > self.mass * regime_factor:
            regime = REGIMES.RADIATION
        elif self.T * regime_factor < self.mass:
            regime = REGIMES.DUST
        else:
            regime = REGIMES.INTERMEDIATE

        return regime
Example #18
0
def Neglect4pInteraction(interaction, ps):
    # If particle has decayed, don't calculate creation integrals for decay products
    if utils.reaction_type(
            interaction).CREATION and interaction.reaction[-1].specie.decayed:
        return True

    # If particles have diluted to such extent that they can be neglected
    scat_thr = 1e-10 * (interaction.particle.params.a_ini / 10)**3
    if utils.reaction_type(interaction).SCATTERING and (interaction.reaction[0].specie.density / interaction.reaction[0].specie.data['params']['density'][0] < scat_thr\
    or interaction.reaction[1].specie.density / interaction.reaction[1].specie.data['params']['density'][0] < scat_thr)\
    and (interaction.reaction[2].specie.density / interaction.reaction[2].specie.data['params']['density'][0] < scat_thr or\
    interaction.reaction[3].specie.density / interaction.reaction[3].specie.data['params']['density'][0] < scat_thr):
        return True
    #TODO: Improve this (zero initial density etc)

    # If there are no muons/mesons created yet, skip creation and decay reactions
    if utils.reaction_type(interaction).CREATION and hasattr(interaction.reaction[-1].specie, 'fast_decay') and interaction.reaction[-1].specie.num_creation == 0\
    or utils.reaction_type(interaction).DECAY and hasattr(interaction.reaction[0].specie, 'fast_decay') and interaction.reaction[0].specie.num_creation == 0:
        return True

    # Decoupling of scattering reactions involving HNL
    if utils.reaction_type(interaction).SCATTERING and any(item.specie.name == 'Sterile neutrino (Dirac)' for item in interaction.reaction)\
    and (environment.get('Relativistic_decoupling') and interaction.particle.params.T < interaction.particle.params.m / interaction.particle.params.a_ini / 15. or interaction.particle.params.T < 1. * UNITS.MeV):
        return True

    # If temperature is higher than HNL mass, skip decay reaction to prevent incorrect computation of collision integral
    if utils.reaction_type(
            interaction
    ).DECAY and interaction.particle.name == 'Sterile neutrino (Dirac)' and interaction.particle.params.T > interaction.particle.mass:
        return True

    return False
Example #19
0
def integrate_1D(integrand, bounds):
    if not environment.get('FIXED_ORDER_1D_QUADRATURE'):
        integral, error = integrate.quad(integrand, bounds[0], bounds[1])
    else:
        integral = gaussian(integrand, bounds[0], bounds[1])
        error = numpy.nan

    return integral, error
Example #20
0
def load(path):
    global g_frame
    streams = None
    stream = None
    object = None
    entry = None
    value = None
    key = None

    # load the YAML entries.
    streams = yaml.load(file(path, 'r'))

    # create an new frame object.
    g_frame = c_frame()

    # try to fill the g_frame object with the YAML entries.
    for stream in streams:
        try:
            g_frame.title = stream["title"]
            g_frame.description = stream["description"]

            continue
        except:
            pass

        entry = c_entry()

        try:
            entry.frame = stream["frame"]
            entry.path = stream["path"]
            entry.type = TYPE_FRAME

            g_frame.list.append(entry.frame)
            g_frame.entries.append(entry)
        except:
            try:
                entry.type = TYPE_VARIABLE
                entry.variable = environment.get(stream["variable"])

                if not entry.variable:
                    continue

                # build the list and current value for each variable type.
                if entry.variable.type == environment.TYPE_SET:
                    for key, value in entry.variable.values.items():
                        if entry.variable.assignment == value:
                            entry.current = key

                        entry.list.append(key)
                elif entry.variable.type == environment.TYPE_ANY:
                    entry.current = entry.variable.assignment

                g_frame.list.append(entry.variable.string)
                g_frame.entries.append(entry)

            except:
                continue
Example #21
0
def load(path):
    global g_frame
    streams = None
    stream = None
    object = None
    entry = None
    value = None
    key = None

    # load the YAML entries.
    streams = yaml.load(file(path, "r"))

    # create an new frame object.
    g_frame = c_frame()

    # try to fill the g_frame object with the YAML entries.
    for stream in streams:
        try:
            g_frame.title = stream["title"]
            g_frame.description = stream["description"]

            continue
        except:
            pass

        entry = c_entry()

        try:
            entry.frame = stream["frame"]
            entry.path = stream["path"]
            entry.type = TYPE_FRAME

            g_frame.list.append(entry.frame)
            g_frame.entries.append(entry)
        except:
            try:
                entry.type = TYPE_VARIABLE
                entry.variable = environment.get(stream["variable"])

                if not entry.variable:
                    continue

                # build the list and current value for each variable type.
                if entry.variable.type == environment.TYPE_SET:
                    for key, value in entry.variable.values.items():
                        if entry.variable.assignment == value:
                            entry.current = key

                        entry.list.append(key)
                elif entry.variable.type == environment.TYPE_ANY:
                    entry.current = entry.variable.assignment

                g_frame.list.append(entry.variable.string)
                g_frame.entries.append(entry)

            except:
                continue
Example #22
0
def grid_resolution_lepton(mass, mixing_angle, std=False):
    muon_mass = 105.658 * UNITS.MeV
    pion_mass = 139.57 * UNITS.MeV

    if mass < pion_mass or std:
        if mass > muon_mass and mass - muon_mass < 10 * UNITS.MeV:
            return environment.get(
                'FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV / 2.
        return environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV

    momentum_cm = cm_momentum(pion_mass, 0, muon_mass)
    energy_cm = np.sqrt(momentum_cm**2 + muon_mass**2)

    meson_resolution = 0.67 * np.sqrt(pion_mass * UNITS.MeV * 0.5)
    delta_y_lepton = np.sqrt((energy_cm + meson_resolution * momentum_cm / pion_mass)**2 - muon_mass**2) \
                    - np.sqrt((energy_cm - meson_resolution * momentum_cm / pion_mass)**2 - muon_mass**2)

    return min(delta_y_lepton,
               environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV)
Example #23
0
def grid_resolution_neutrino(mass, mixing_angle):
    muon_mass = 105.658 * UNITS.MeV
    pion_mass = 134.98 * UNITS.MeV

    if mass < pion_mass:
        if mass > muon_mass and mass - muon_mass < 10 * UNITS.MeV:
            return environment.get(
                'FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV / 2.
        return environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV

    meson_masses = np.array(
        [134.98, 139.57, 547.86, 775.11, 782.65, 957.78, 1019.46]) * UNITS.MeV
    meson_mass = meson_masses[np.searchsorted(meson_masses, mass) - 1]
    delta_y_nu = 2 * cm_momentum(mass, 0, meson_mass) * grid_resolution_HNL(
        mass, mixing_angle) / mass

    return min(
        delta_y_nu * .75,
        environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV / 3.)
Example #24
0
def four_particle_grid_cutoff_scattering(particle):
    grid = particle.grid.TEMPLATE

    if particle.name == 'Sterile neutrino (Dirac)':
        max_mom = particle.grid.MAX_MOMENTUM  #3 * particle.params.T
    elif particle.name != 'Sterile neutrino (Dirac)' and environment.get(
            'HNL_ENERGY'):
        HNL_energy = float(environment.get('HNL_ENERGY'))
        max_mom = max(np.sqrt(HNL_energy**2 - particle.conformal_mass**2),
                      environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV)
    else:
        max_mom = environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV

    upper_element_grid = min(len(grid) - 1, np.searchsorted(grid, max_mom))

    slice_1 = grid[:upper_element_grid + 1]
    slice_2 = [0] * (len(grid[upper_element_grid:]) - 1)

    return np.array(slice_1), slice_2
Example #25
0
def grid_resolution_meson(mass, mixing_angle):
    if mass < 134.98 * UNITS.MeV:
        return environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV

    meson_masses = np.array([
        134.98, 139.57, 493.677, 497.611, 547.86, 775.11, 782.65, 957.78,
        1019.46
    ]) * UNITS.MeV
    meson_mass = meson_masses[np.searchsorted(meson_masses, mass) - 1]
    momentum_cm = cm_momentum(mass, 0, meson_mass)
    energy_cm = np.sqrt(momentum_cm**2 + meson_mass**2)

    delta_y_meson = np.sqrt((energy_cm + grid_resolution_HNL(mass, mixing_angle) * momentum_cm / mass)**2 - meson_mass**2) \
                    - np.sqrt((energy_cm - grid_resolution_HNL(mass, mixing_angle) * momentum_cm / mass)**2 - meson_mass**2)

    if not delta_y_meson > 0:
        delta_y_meson = environment.get(
            'FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV / 3.

    return min(delta_y_meson / 3.,
               environment.get('FOUR_PARTICLE_GRID_RESOLUTION') * UNITS.MeV)
Example #26
0
 def __init__(self):
     self.workspace = os.getenv('GITHUB_WORKSPACE')
     self.project_name = _get_project_name()
     # Check if failures should not be reported.
     self.dry_run = _is_dry_run()
     self.sanitizer = _get_sanitizer()
     self.build_integration_path = os.getenv('BUILD_INTEGRATION_PATH')
     self.language = _get_language()
     event_path = os.getenv('GITHUB_EVENT_PATH')
     self.is_github = bool(event_path)
     logging.debug('Is github: %s.', self.is_github)
     # TODO(metzman): Parse env like we do in ClusterFuzz.
     self.low_disk_space = environment.get('LOW_DISK_SPACE', False)
Example #27
0
    def setXMLConfig(self, child):
        # print "setXMLConfig"
        #
        # read configuration from xml
        #
        loggingContext = "adapter '[{a:s}]'".format(a=self.name)
        if not environment.has_key("gui"):
            logger.error("No gui enabled . Do not configure gui")
            return

        for tle in child:
            if "webserver" == tle.tag:
                for tle2 in tle:
                    if "route" == tle2.tag:
                        name = tle2.attrib["name"]
                        route = tle2.attrib["route"]
                        environment.get("gui").websocketPlugin(name, route, PendelWebSocket)
                    if "html" == tle2.tag:
                        name = tle2.attrib["name"]
                        path = tle2.attrib["path"]
                        comment = tle2.attrib["comment"]
                        environment.get("gui").htmlPlugin(name, path, comment)
Example #28
0
def four_particle_bounds_creation(reaction=None):
    " Returns kinematically allowed lower and upper momentum bounds for particle A in reaction A + B + C <-- D "
    specie_1 = reaction[0].specie
    specie_2 = reaction[1].specie
    specie_3 = reaction[2].specie
    specie_4 = reaction[3].specie

    max_momentum = np.sqrt(
        (np.sqrt(specie_4.grid.MAX_MOMENTUM**2 + specie_4.conformal_mass**2) -
         specie_2.conformal_mass - specie_3.conformal_mass)**2 -
        specie_1.conformal_mass**2)

    return max(max_momentum, environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV)
Example #29
0
    def __init__(self, MOMENTUM_SAMPLES=None, MAX_MOMENTUM=None):
        if not MAX_MOMENTUM:
            MAX_MOMENTUM = environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV
        if not MOMENTUM_SAMPLES:
            MOMENTUM_SAMPLES = environment.get('MOMENTUM_SAMPLES')

        self.MIN_MOMENTUM = 0
        self.MAX_MOMENTUM = MAX_MOMENTUM
        self.BOUNDS = (self.MIN_MOMENTUM, self.MAX_MOMENTUM)
        self.MOMENTUM_SAMPLES = MOMENTUM_SAMPLES

        """
        Grid template can be copied when defining a new distribution function and is convenient to\
        calculate any _vectorized_ function over the grid. For example,

        ```python
            particle.conformal_energy(GRID.TEMPLATE)
        ```

        yields an array of particle conformal energy mapped over the `GRID`
        """
        self.TEMPLATE = numpy.linspace(self.MIN_MOMENTUM, self.MAX_MOMENTUM,
                                       num=self.MOMENTUM_SAMPLES, endpoint=True)
Example #30
0
    def __init__(self, MOMENTUM_SAMPLES=None, MAX_MOMENTUM=None):
        if not MAX_MOMENTUM:
            MAX_MOMENTUM = environment.get('MAX_MOMENTUM_MEV') * UNITS.MeV
        if not MOMENTUM_SAMPLES:
            MOMENTUM_SAMPLES = environment.get('MOMENTUM_SAMPLES')

        self.MIN_MOMENTUM = 0
        self.MAX_MOMENTUM = MAX_MOMENTUM
        self.BOUNDS = (self.MIN_MOMENTUM, self.MAX_MOMENTUM)
        self.MOMENTUM_SAMPLES = MOMENTUM_SAMPLES

        """
        Grid template can be copied when defining a new distribution function and is convenient to\
        calculate any _vectorized_ function over the grid. For example,

        ```python
            particle.conformal_energy(GRID.TEMPLATE)
        ```

        yields an array of particle conformal energy mapped over the `GRID`
        """
        self.TEMPLATE = numpy.linspace(self.MIN_MOMENTUM, self.MAX_MOMENTUM,
                                       num=self.MOMENTUM_SAMPLES, endpoint=True)
Example #31
0
def integrate_1D(integrand, bounds):
    if not environment.get('FIXED_ORDER_1D_QUADRATURE'):
        integral, error = integrate.quad(
            integrand,
            bounds[0], bounds[1]
        )
    else:
        integral = gaussian(
            integrand,
            bounds[0], bounds[1]
        )
        error = numpy.nan

    return integral, error
Example #32
0
def gaussian_test():
    func = lambda z: special.jn(3, z)
    adaptive_result, error = integrate.quad(func, 0, 10)
    fixed_result, _ = integrate.fixed_quad(func, 0, 10, n=environment.get('GAUSS_LEGENDRE_ORDER'))
    own_result = integrators.gaussian(func, 0, 10)

    print(adaptive_result, error)
    print(fixed_result)
    print(own_result)

    assert numpy.isclose(integrators.gaussian(func, 0, 10), -integrators.gaussian(func, 10, 0))

    assert adaptive_result - fixed_result < error, "Gauss-Legendre quadrature order is insufficient"
    assert adaptive_result - own_result < error, "Own integrator is inaccurate"
Example #33
0
def gaussian_test():
    func = lambda z: special.jn(3, z)
    adaptive_result, error = integrate.quad(func, 0, 10)
    fixed_result, _ = integrate.fixed_quad(
        func, 0, 10, n=environment.get('GAUSS_LEGENDRE_ORDER'))
    own_result = integrators.gaussian(func, 0, 10)

    print(adaptive_result, error)
    print(fixed_result)
    print(own_result)

    assert numpy.isclose(integrators.gaussian(func, 0, 10),
                         -integrators.gaussian(func, 10, 0))

    assert adaptive_result - fixed_result < error, "Gauss-Legendre quadrature order is insufficient"
    assert adaptive_result - own_result < error, "Own integrator is inaccurate"
Example #34
0
def numerator(particle):
    if environment.get('SIMPSONS_INTEGRATION'):
        y = particle.grid.TEMPLATE
        return simps((
            -1. * particle.dof / 2. / numpy.pi**2
            * y**2 * particle.conformal_energy(y)
            * particle.collision_integral / particle.params.x
        ), y)
    else:
        integral = linear_interpolation(particle.collision_integral / particle.params.x,
                                        particle.grid.TEMPLATE)
        return lambda_integrate()(lambda particle: numpy.vectorize(lambda y: (
            -1. * particle.dof / 2. / numpy.pi**2
            * y**2 * particle.conformal_energy(y)
            * integral(y)
        ), otypes=[numpy.float_]))(particle)
Example #35
0
def neutron_lifetime_test():
    from kawano import q as Q, m_e
    q = Q / m_e

    def func(e):
        return e * (e - q)**2 * numpy.sqrt(e**2 - 1)

    adaptive_result, error = integrate.quad(func, 1, q)
    fixed_result, _ = integrate.fixed_quad(func, 1, q, n=environment.get('GAUSS_LEGENDRE_ORDER'))
    own_result = integrators.gaussian(func, 1, q)

    print(adaptive_result, error)
    print(fixed_result)
    print(own_result)

    assert adaptive_result - fixed_result < error, "Gauss-Legendre quadrature order is insufficient"
    assert adaptive_result - own_result < error, "Own integrator is inaccurate"
Example #36
0
    def oscillation_parameters(self):

        if self.oscillation_matter:
            MSW_12 = CONST.MSW_constant * self.oscillation_particles[
                0].grid.TEMPLATE**2 * self.params.T**4 / CONST.delta_m12_sq / self.params.a**2
            MSW_13 = CONST.MSW_constant * self.oscillation_particles[
                0].grid.TEMPLATE**2 * self.params.T**4 / CONST.delta_m13_sq / self.params.a**2
            if not environment.get("NORMAL_HIERARCHY_NEUTRINOS"):
                MSW_13 *= -1

        else:
            MSW_12 = 0.
            MSW_13 = 0.

        pattern = self.pattern_function(MSW_12, MSW_13,
                                        self.oscillation_matter)
        self.oscillations = (pattern, self.oscillation_particles)
Example #37
0
    def make_step(self):
        self.integrand(self.params.x, self.params.aT)

        if self.step_monitor:
            self.step_monitor(self)

        if environment.get('ADAMS_BASHFORTH_TEMPERATURE_CORRECTION'):
            fs = (list(self.data['fraction'][-MAX_ADAMS_BASHFORTH_ORDER:]) + [self.fraction])

            self.params.aT += adams_bashforth_correction(fs=fs, h=self.params.h)
        else:
            self.params.aT += self.fraction * self.params.h

        self.params.x += self.params.dx
        self.params.update(self.total_energy_density(), self.total_entropy())

        self.log_throttler.update()
Example #38
0
def neutron_lifetime_test():
    from kawano import q as Q, m_e
    q = Q / m_e

    def func(e):
        return e * (e - q)**2 * numpy.sqrt(e**2 - 1)

    adaptive_result, error = integrate.quad(func, 1, q)
    fixed_result, _ = integrate.fixed_quad(
        func, 1, q, n=environment.get('GAUSS_LEGENDRE_ORDER'))
    own_result = integrators.gaussian(func, 1, q)

    print(adaptive_result, error)
    print(fixed_result)
    print(own_result)

    assert adaptive_result - fixed_result < error, "Gauss-Legendre quadrature order is insufficient"
    assert adaptive_result - own_result < error, "Own integrator is inaccurate"
Example #39
0
def unit_non_equilibrium_test(params, universe):
    params.update(universe.total_energy_density(), universe.total_entropy())
    photon, neutrino_e, neutrino_mu = universe.particles

    universe.update_particles()
    universe.init_interactions()

    integral = neutrino_e.collision_integrals[0]

    if environment.get('SPLIT_COLLISION_INTEGRAL'):
        A, B = integral.integrate(neutrino_e.grid.TEMPLATE)
        collision_integral = (A + neutrino_e._distribution * B)
    else:
        collision_integral = integral.integrate(neutrino_e.grid.TEMPLATE)

    universe.calculate_collisions()

    assert numpy.allclose(collision_integral - neutrino_e.collision_integral, 0)
Example #40
0
    def make_step(self):
        self.integrand(self.params.x, self.params.aT)

        if self.step_monitor:
            self.step_monitor(self)

        if environment.get('ADAMS_BASHFORTH_TEMPERATURE_CORRECTION'):
            fs = (list(self.data['fraction'][-MAX_ADAMS_BASHFORTH_ORDER:]) +
                  [self.fraction])

            self.params.aT += adams_bashforth_correction(fs=fs,
                                                         h=self.params.h)
        else:
            self.params.aT += self.fraction * self.params.h

        self.params.x += self.params.dx
        self.params.update(self.total_energy_density(), self.total_entropy())

        self.log_throttler.update()
Example #41
0
def Int(particle, y_power=2):
    if environment.get('LAGUERRE_GAUSS_FOR_MASSIVE_EQUILIBRIUM_PARTICLES'):
        aT = particle.params.aT
        mat = particle.conformal_mass / aT

        laguerre = (
            particle.dof / 2. / numpy.pi**2 * aT**(y_power + 1) *
            numpy.exp(-mat) * gauss_laguerre.integrate_1D(lambda eps: (
                (eps + mat) * (eps * (eps + 2. * mat))**((y_power - 1.) / 2.) /
                (numpy.exp(-eps - mat) + particle.eta)**2))[0])
        return laguerre
    else:
        legendre = particle.dof / 2. / numpy.pi**2 * integrators.integrate_1D(
            lambda y:
            (y**y_power * numpy.exp(
                particle.conformal_energy(y) / particle.params.aT) /
             (numpy.exp(particle.conformal_energy(y) / particle.params.aT) +
              particle.eta)**2),
            (particle.grid.MIN_MOMENTUM, particle.grid.MAX_MOMENTUM))[0]

        return legendre
Example #42
0
    def update(self, rho, S):
        """ Hubble expansion parameter defined by a Friedmann equation:

            \begin{equation}
                H = \sqrt{\frac{8 \pi}{3} G \rho}
            \end{equation}
        """
        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.dx = self.x * self.dy
        self.rho = rho
        self.S = S
        self.H = numpy.sqrt(8./3. * numpy.pi * rho) / CONST.M_p

        self.N_eff = (
            (rho - (numpy.pi**2 / 15. * self.T**4))
            / (7./8. * numpy.pi**2 / 15. * (self.T / 1.401)**4)
        )

        old_a = self.a
        """ Physical scale factor and temperature for convenience """
        self.a = self.x / self.m
        self.T = self.aT / self.a

        """ Time step size is inferred from the approximation of the scale factor `a`
            derivative and a definition of the Hubble parameter `H`:

            \begin{equation}
                H = \frac{\dot{a}}{a} = \frac{1}{a_{i-1}} \frac{a_i - a_{i-1}}{\Delta t}
                  = \frac{1}{\Delta t}(\frac{a_i}{a_{i-1}} -1)
            \end{equation}

            \begin{equation}
                \Delta t = \frac{1}{H} (\frac{a_i}{a_{i-1}} - 1)
            \end{equation}
        """
        # dt = (self.a / old_a - 1) / self.H
        dt = (1 - old_a / self.a) / self.H
        # dt = self.dx / self.x / self.H
        self.t += dt
Example #43
0
    def update(self, rho, S):
        """ Hubble expansion parameter defined by a Friedmann equation:

            \begin{equation}
                H = \sqrt{\frac{8 \pi}{3} G \rho}
            \end{equation}
        """
        if environment.get('LOGARITHMIC_TIMESTEP'):
            self.dx = self.x * self.dy
        self.rho = rho
        self.S = S
        self.H = numpy.sqrt(8./3. * numpy.pi * rho) / CONST.M_p

        self.N_eff = (
            (rho - (numpy.pi**2 / 15. * self.T**4))
            / (7./8. * numpy.pi**2 / 15. * (self.T / 1.401)**4)
        )

        old_a = self.a
        """ Physical scale factor and temperature for convenience """
        self.a = self.x / self.m
        self.T = self.aT / self.a

        """ Time step size is inferred from the approximation of the scale factor `a`
            derivative and a definition of the Hubble parameter `H`:

            \begin{equation}
                H = \frac{\dot{a}}{a} = \frac{1}{a_{i-1}} \frac{a_i - a_{i-1}}{\Delta t}
                  = \frac{1}{\Delta t}(\frac{a_i}{a_{i-1}} -1)
            \end{equation}

            \begin{equation}
                \Delta t = \frac{1}{H} (\frac{a_i}{a_{i-1}} - 1)
            \end{equation}
        """
        # dt = (self.a / old_a - 1) / self.H
        dt = (1 - old_a / self.a) / self.H
        # dt = self.dx / self.x / self.H
        self.t += dt
Example #44
0
def Int(particle, y_power=2):
    if environment.get('LAGUERRE_GAUSS_FOR_MASSIVE_EQUILIBRIUM_PARTICLES'):
        aT = particle.params.aT
        mat = particle.conformal_mass / aT

        laguerre = (
            particle.dof / 2. / numpy.pi**2 * aT**(y_power + 1) * numpy.exp(-mat)
            * gauss_laguerre.integrate_1D(lambda eps: (
                (eps + mat) * (eps * (eps + 2. * mat))**((y_power - 1.) / 2.)
                / (numpy.exp(-eps - mat) + particle.eta)**2
            ))[0]
        )
        return laguerre
    else:
        legendre = particle.dof / 2. / numpy.pi**2 * integrators.integrate_1D(
            lambda y: (
                y**y_power * numpy.exp(particle.conformal_energy(y) / particle.params.aT)
                / (numpy.exp(particle.conformal_energy(y) / particle.params.aT) + particle.eta)**2
            ),
            (particle.grid.MIN_MOMENTUM, particle.grid.MAX_MOMENTUM)
        )[0]

        return legendre
Example #45
0
    def save(self):
        """ Save current Universe parameters into the data arrays or output files """
        self.save_params()

        if self.kawano and self.params.T <= self.kawano.T_kawano:

            #     t[s]         x    Tg[10^9K]   dTg/dt[10^9K/s] rho_tot[g cm^-3]     H[s^-1]
            # n nue->p e  p e->n nue  n->p e nue  p e nue->n  n e->p nue  p nue->n e

            rates = self.kawano.baryonic_rates(self.params.a)

            if environment.get('LOGARITHMIC_TIMESTEP'):
                dTdt = (self.fraction -
                        self.params.aT) * self.params.H / self.params.a
            else:
                dTdt = (self.fraction - self.params.T /
                        self.params.m) * self.params.H * self.params.m

            row = {
                self.kawano_data.columns[0]: self.params.t,
                self.kawano_data.columns[1]: self.params.x,
                self.kawano_data.columns[2]: self.params.T,
                self.kawano_data.columns[3]: dTdt,
                self.kawano_data.columns[4]: self.params.rho,
                self.kawano_data.columns[5]: self.params.H
            }

            row.update({
                self.kawano_data.columns[i]: rate
                for i, rate in enumerate(rates, 6)
            })

            self.kawano_data.append(row)

            if self.log_throttler.output:
                print("KAWANO", self.kawano_data.row_repr(-1, names=True))
            self.kawano_log.write(self.kawano_data.row_repr(-1) + "\n")
Example #46
0
def init_quadrature():
    global points, weights, grid
    points, weights = numpy.polynomial.legendre.leggauss(environment.get('GAUSS_LEGENDRE_ORDER'))
    grid = numpy.meshgrid(points, points)
Example #47
0
def _get_pr_ref(event):
    if event == 'pull_request':
        return environment.get('GITHUB_REF')
    return None
Example #48
0
def run(suite, spawn_browser=True, verbosity=1, quiet=False,
        failfast=False, catch_break=False, buffer=True, **kwargs):
    """A simple test runner.

    This test runner is essentially equivalent to ``unittest.main``
    from the standard library, but adds support for loading test
    classes with extra keyword arguments.

    The easiest way to run a test is via the command line::

        python -m semiauto test_sms

    See the standard library unittest module for ways in which tests
    can be specified.

    For example it is possible to automatically discover tests::

        python -m semiauto discover .

    """

    if catch_break:
        import unittest.signals
        unittest.signals.installHandler()

    test_runner = runner.PreInstantiatedTestRunner(verbosity=verbosity,
                                                   failfast=failfast,
                                                   buffer=buffer,
                                                   **kwargs)

    delegator = runner.TestEventDelegator(
        test_runner.stream, test_runner.descriptions, test_runner.verbosity)
    test_runner.resultclass = delegator

    # Start new test environment, because first environment.get does
    # that for us the first time.
    #
    # This is a hack and shouldn't be here.  The reason it is is
    # because unittest doesn't allow us to modify the runner in a
    # TestCase's setUp.
    #
    # Generally a lot of this code should live in TestCase.setUp.
    env = environment.get(environment.InProcessTestEnvironment)

    # TODO(ato): Only spawn a browser when asked to.
    if spawn_browser:
        import webbrowser
        webbrowser.open("http://localhost:6666/")
    else:
        print("Please connect your browser to http://%s:%d/" %
              (env.server.addr[0], env.server.addr[1]))

    # Get a reference to the WebSocket handler that we can use to
    # communicate with the client browser.  This blocks until a client
    # connects.
    from semiauto import server
    # A timeout is needed because of http://bugs.python.org/issue1360
    handler = server.clients.get(block=True, timeout=sys.maxint)

    # Send list of tests to client.
    test_list = runner.serialize_suite(suite)
    handler.emit("testList", test_list)

    handler.suite = suite
    environment.env.handler = handler

    # Due to extent of how much unittest sucks, this is unfortunately
    # necessary:
    _install_test_event_hooks(test_runner, handler)

    try:
        results = test_runner.run(suite)
    except (SystemExit, KeyboardInterrupt) as e:
        sys.exit(1)

    return results