<commit_before># building of radial_oned_model

import numpy as np
import plasma, packet_source
import logging

import pandas as pd
from pandas.io.pytables import HDFStore
from astropy import constants, units as u
import montecarlo_multizone
import os
import yaml

import scipy.special

import itertools
from tardis import config_reader
from tardis.plasma import intensity_black_body

logger = logging.getLogger(__name__)

c = constants.c.cgs.value
h = constants.h.cgs.value
kb = constants.k_B.cgs.value

w_estimator_constant = (c ** 2 / (2 * h)) * (15 / np.pi ** 4) * (h / kb) ** 4 / (4 * np.pi)

t_rad_estimator_constant = np.pi**4 / (15 * 24 * scipy.special.zeta(5, 1))

synpp_default_yaml_fname = os.path.join(os.path.dirname(__file__), 'data', 'synpp_default.yaml')


class Radial1DModel(object):
    """
        Class to hold the states of the individual shells (the state of the plasma (as a `~plasma.BasePlasma`-object or one of its subclasses),
        , the plasma parameters (e.g. temperature, dilution factor), the dimensions of the shell).


        Parameters
        ----------

        tardis_configuration : `tardis.config_reader.TardisConfiguration`

        velocities : `np.ndarray`
            an array with n+1 (for n shells) velocities (in cm/s) for each of the boundaries (velocities[0] describing
            the inner boundary and velocities[-1] the outer boundary

        densities : `np.ndarray`
            an array with n densities - being the density mid-shell (assumed for the whole shell)

        abundances : `list` or `dict`
            a dictionary for uniform abundances throughout all shells, e.g. dict(Fe=0.5, Si=0.5)
            For a different abundance for each shell list of abundance dictionaries.


        time_explosion : `float`
            time since explosion in seconds

        atom_data : `~tardis.atom_data.AtomData` class or subclass
            Containing the atom data needed for the plasma calculations

        ws : `None` or `list`-like
            ws can only be specified for plasma_type 'nebular'. If `None` is specified at first initialization the class
            calculates an initial geometric dilution factor. When giving a list positive values will be accepted, whereas
            negative values trigger the usage of the geometric calculation

        plasma_type : `str`
            plasma type currently supports 'lte' (using `tardis.plasma.LTEPlasma`)
            or 'nebular' (using `tardis.plasma.NebularPlasma`)

        initial_t_rad : `float`-like or `list`-like
            initial radiative temperature for each shell, if a scalar is specified it initializes with a uniform
            temperature for all shells




    """


    def __init__(self, tardis_config):
        #final preparation for configuration object
        self.tardis_config = tardis_config
        self.gui = None
        self.converged = False

        self.atom_data = tardis_config.atom_data
        if tardis_config.plasma.type == 'nebular':
            if not self.atom_data.has_zeta_data:
                raise ValueError("Requiring Recombination coefficients Zeta for 'nebular' plasma_type")

        self.packet_src = packet_source.SimplePacketSource.from_wavelength(tardis_config.spectrum.start,
                                                                           tardis_config.spectrum.end)
        self.current_no_of_packets = tardis_config.montecarlo.no_of_packets

        self.t_inner = tardis_config.plasma.t_inner
        self.t_rads = tardis_config.plasma.t_rads

        self.iterations_max_requested = tardis_config.montecarlo.iterations
        self.iterations_remaining = self.iterations_max_requested - 1
        self.iterations_executed = 0

        #self.sigma_thomson = tardis_config.sigma_thomson

#        self.spec_nu_bins = np.linspace(tardis_config.spectrum_start_nu.value, tardis_config.spectrum_end_nu.value,
#                                        tardis_config.spectrum_bins + 1)
#        self.spec_nu = self.spec_nu_bins[:-1]

#        self.spec_virtual_flux_nu = np.zeros_like(self.spec_nu)

#        self.spec_angstrom = u.Unit('Hz').to('angstrom', self.spec_nu, u.spectral())

#        self.spec_flux_angstrom = np.ones_like(self.spec_angstrom)
#        self.spec_virtual_flux_angstrom = np.ones_like(self.spec_angstrom)


        #reading the convergence criteria


        if tardis_config.montecarlo.convergence.type == 'specific':
            self.global_convergence_parameters = tardis_config.global_convergence_parameters.copy()

        self.t_rads = tardis_config.plasma.t_rads
        self.ws = np.zeros_like(tardis_config.structure.r_inner)
        self.tau_sobolevs = np.zeros((tardis_config.structure.no_of_shells, len(self.atom_data.lines)))
        self.j_blues = np.zeros_like(self.tau_sobolevs)
        self.j_blues_norm_factor = (constants.c.cgs *  /
                       (4 * np.pi * self.time_of_simulation * self.volumes)).reshape((self.volumes.shape[0], 1))

        self.calculate_j_blues()
        self.plasmas = []


        for i in xrange(len(tardis_config.r_inner)):
            if tardis_config.plasma.type == 'lte':
                self.ws[i] = 1.0

                current_plasma_class = plasma.LTEPlasma

            elif tardis_config.plasma_type == 'nebular':
                self.ws[i] = (0.5 * (1 - np.sqrt(1 -
                    (tardis_config.structure.r_inner[0] ** 2 / tardis_config.structure.r_middle[i] ** 2).to(1).value)))
                current_plasma_class = plasma.NebularPlasma

            self.plasmas.append(current_plasma_class(self.t_rads[i], self.number_densities.ix[i],
                                                     self.atom_data,
                                                     tardis_config.supernova.time_explosion.to('s').value,
                                                     self.j_blues[i]))

        current_plasma = plasma.LTEPlasma(self.t_rads[i], self.number_densities.ix[i], self.atom_data,
                                                  tardis_config.supernova.time_explosion.value)




        #initializing temperatures



    @property
    def electron_densities(self):
        return np.array([plasma.electron_density for plasma in self.plasmas])

    @property
    def line_interaction_type(self):
        return self._line_interaction_type

    @line_interaction_type.setter
    def line_interaction_type(self, value):
        if value in ['scatter', 'downbranch', 'macroatom']:
            self._line_interaction_type = value
            self.tardis_config.plasma.line_interaction_type = value
            #final preparation for atom_data object - currently building data
            self.atom_data.prepare_atom_data(self.tardis_config.number_densities.columns,
                                             line_interaction_type=self.line_interaction_type, max_ion_number=None,
                                             nlte_species=self.tardis_config.nlte_species)
        else:
            raise ValueError('line_interaction_type can only be "scatter", "downbranch", or "macroatom"')



    @property
    def t_inner(self):
        return self._t_inner

    @t_inner.setter
    def t_inner(self, value):
        self._t_inner = value
        self.luminosity_inner = 4 * np.pi * constants.sigma_sb.cgs * self.tardis_config.structure.r_inner[0] ** 2 * \
                                self._t_inner ** 4
        self.time_of_simulation = 1 / self.luminosity_inner


    def create_packets(self):
        #Energy emitted from the inner boundary

        no_of_packets = self.current_no_of_packets
        self.packet_src.create_packets(no_of_packets, self.t_inner)
<commit_msg>made j_blues_norm_factor into a quantity - there could be a danger.<commit_after># building of radial_oned_model

import numpy as np
import plasma, packet_source
import logging

import pandas as pd
from pandas.io.pytables import HDFStore
from astropy import constants, units as u
import montecarlo_multizone
import os
import yaml

import scipy.special

import itertools
from tardis import config_reader
from tardis.plasma import intensity_black_body

logger = logging.getLogger(__name__)

c = constants.c.cgs.value
h = constants.h.cgs.value
kb = constants.k_B.cgs.value

w_estimator_constant = (c ** 2 / (2 * h)) * (15 / np.pi ** 4) * (h / kb) ** 4 / (4 * np.pi)

t_rad_estimator_constant = np.pi**4 / (15 * 24 * scipy.special.zeta(5, 1))

synpp_default_yaml_fname = os.path.join(os.path.dirname(__file__), 'data', 'synpp_default.yaml')


class Radial1DModel(object):
    """
        Class to hold the states of the individual shells (the state of the plasma (as a `~plasma.BasePlasma`-object or one of its subclasses),
        , the plasma parameters (e.g. temperature, dilution factor), the dimensions of the shell).


        Parameters
        ----------

        tardis_configuration : `tardis.config_reader.TardisConfiguration`

        velocities : `np.ndarray`
            an array with n+1 (for n shells) velocities (in cm/s) for each of the boundaries (velocities[0] describing
            the inner boundary and velocities[-1] the outer boundary

        densities : `np.ndarray`
            an array with n densities - being the density mid-shell (assumed for the whole shell)

        abundances : `list` or `dict`
            a dictionary for uniform abundances throughout all shells, e.g. dict(Fe=0.5, Si=0.5)
            For a different abundance for each shell list of abundance dictionaries.


        time_explosion : `float`
            time since explosion in seconds

        atom_data : `~tardis.atom_data.AtomData` class or subclass
            Containing the atom data needed for the plasma calculations

        ws : `None` or `list`-like
            ws can only be specified for plasma_type 'nebular'. If `None` is specified at first initialization the class
            calculates an initial geometric dilution factor. When giving a list positive values will be accepted, whereas
            negative values trigger the usage of the geometric calculation

        plasma_type : `str`
            plasma type currently supports 'lte' (using `tardis.plasma.LTEPlasma`)
            or 'nebular' (using `tardis.plasma.NebularPlasma`)

        initial_t_rad : `float`-like or `list`-like
            initial radiative temperature for each shell, if a scalar is specified it initializes with a uniform
            temperature for all shells




    """


    def __init__(self, tardis_config):
        #final preparation for configuration object
        self.tardis_config = tardis_config
        self.gui = None
        self.converged = False

        self.atom_data = tardis_config.atom_data
        if tardis_config.plasma.type == 'nebular':
            if not self.atom_data.has_zeta_data:
                raise ValueError("Requiring Recombination coefficients Zeta for 'nebular' plasma_type")

        self.packet_src = packet_source.SimplePacketSource.from_wavelength(tardis_config.spectrum.start,
                                                                           tardis_config.spectrum.end)
        self.current_no_of_packets = tardis_config.montecarlo.no_of_packets

        no_of_shells = tardis_config.structure.no_of_shells

        self.t_inner = tardis_config.plasma.t_inner
        self.t_rads = tardis_config.plasma.t_rads

        self.iterations_max_requested = tardis_config.montecarlo.iterations
        self.iterations_remaining = self.iterations_max_requested - 1
        self.iterations_executed = 0

        #self.sigma_thomson = tardis_config.sigma_thomson

#        self.spec_nu_bins = np.linspace(tardis_config.spectrum_start_nu.value, tardis_config.spectrum_end_nu.value,
#                                        tardis_config.spectrum_bins + 1)
#        self.spec_nu = self.spec_nu_bins[:-1]

#        self.spec_virtual_flux_nu = np.zeros_like(self.spec_nu)

#        self.spec_angstrom = u.Unit('Hz').to('angstrom', self.spec_nu, u.spectral())

#        self.spec_flux_angstrom = np.ones_like(self.spec_angstrom)
#        self.spec_virtual_flux_angstrom = np.ones_like(self.spec_angstrom)


        #reading the convergence criteria


        if tardis_config.montecarlo.convergence.type == 'specific':
            self.global_convergence_parameters = tardis_config.global_convergence_parameters.copy()

        self.t_rads = tardis_config.plasma.t_rads
        self.ws = np.zeros_like(tardis_config.structure.r_inner)
        self.tau_sobolevs = np.zeros((no_of_shells, len(self.atom_data.lines)))
        self.j_blues = np.zeros_like(self.tau_sobolevs)
        j_blues_norm_factor = constants.c.cgs *  tardis_config.supernova.time_explosion / \
                       (4 * np.pi * self.time_of_simulation * tardis_config.structure.volumes.value)
        self.j_blues_norm_factor = j_blues_norm_factor.value.reshape((no_of_shells, 1)) * j_blues_norm_factor.unit


        self.calculate_j_blues()
        self.plasmas = []


        for i in xrange(no_of_shells):
            if tardis_config.plasma.type == 'lte':
                self.ws[i] = 1.0

                current_plasma_class = plasma.LTEPlasma

            elif tardis_config.plasma.type == 'nebular':
                self.ws[i] = (0.5 * (1 - np.sqrt(1 -
                    (tardis_config.structure.r_inner[0] ** 2 / tardis_config.structure.r_middle[i] ** 2).to(1).value)))
                current_plasma_class = plasma.NebularPlasma

            self.plasmas.append(current_plasma_class(self.t_rads[i], self.number_densities.ix[i],
                                                     self.atom_data,
                                                     tardis_config.supernova.time_explosion.to('s').value,
                                                     self.j_blues[i]))

        current_plasma = plasma.LTEPlasma(self.t_rads[i], self.number_densities.ix[i], self.atom_data,
                                                  tardis_config.supernova.time_explosion.value)




        #initializing temperatures



    @property
    def electron_densities(self):
        return np.array([plasma.electron_density for plasma in self.plasmas])

    @property
    def line_interaction_type(self):
        return self._line_interaction_type

    @line_interaction_type.setter
    def line_interaction_type(self, value):
        if value in ['scatter', 'downbranch', 'macroatom']:
            self._line_interaction_type = value
            self.tardis_config.plasma.line_interaction_type = value
            #final preparation for atom_data object - currently building data
            self.atom_data.prepare_atom_data(self.tardis_config.number_densities.columns,
                                             line_interaction_type=self.line_interaction_type, max_ion_number=None,
                                             nlte_species=self.tardis_config.nlte_species)
        else:
            raise ValueError('line_interaction_type can only be "scatter", "downbranch", or "macroatom"')



    @property
    def t_inner(self):
        return self._t_inner

    @t_inner.setter
    def t_inner(self, value):
        self._t_inner = value
        self.luminosity_inner = 4 * np.pi * constants.sigma_sb.cgs * self.tardis_config.structure.r_inner[0] ** 2 * \
                                self._t_inner ** 4
        self.time_of_simulation = (1.0 * u.erg / self.luminosity_inner)


    def create_packets(self):
        #Energy emitted from the inner boundary

        no_of_packets = self.current_no_of_packets
        self.packet_src.create_packets(no_of_packets, self.t_inner)

{'fraction_non_alphanumeric': 0.0842422687026819, 'fraction_numerical': 0.00564609264724753, 'mean_word_length': 2.40625, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6511165', 'n_tokens_mistral': 4854, 'n_tokens_neox': 4603, 'n_words': 1018}