<commit_before>import logging
import numpy as np
import os

import matplotlib.pyplot as plt
from matplotlib import gridspec

from pystella.util.phys_var import phys

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

__author__ = 'bakl'

eve_elements = map(str.strip, "Ni56 H He C N O Ne Na  Mg  Al  Si  S  Ar  Ca  Fe  Ni".split())
eve_colors = dict(Ni56="red", H="blue", He="cyan", C="darkorange", N="coral",
                  O="violet", Ne="green", Na="sandybrown",
                  Mg="skyblue", Si="olive", Al="lime",
                  S="indigo", Ar="brown", Ca="purple",
                  Fe='maroon', Ni='magenta')
eve_lntypes = dict((k, '--') for k, v in eve_colors.items())  # no y-shift
eve_lntypes['H'] = '-'
eve_lntypes['He'] = '-'
eve_lntypes['O'] = '-'
eve_lntypes['C'] = '-'
eve_lntypes['Ni56'] = '-'


class PreSN(object):
    """
    A class that holds data of presupernova
    """
    sRho = 'Rho'
    sM = 'M'
    sT = 'T'
    sR = 'R'
    sV = 'V'
    presn_hydro = (sM, sR, sT, sRho, sV)
    presn_elements = map(str.strip, "H He C N O Ne Na  Mg  Al  Si  S  Ar  Ca  Fe  Ni Ni56".split())

    def __init__(self, name, nzon):
        """Creates a PreSN model instance.  Required parameters:  name, nzon"""
        self.name = name
        self._nzon = nzon
        self._data_hyd = np.empty(nzon, dtype=PreSN.dtype_hyd())
        self._data_chem = np.empty(nzon, dtype=PreSN.dtype_chem())
        self._params = {}
        self._loads = []

    @staticmethod
    def dtype_hyd():
        dt = np.dtype({'names': PreSN.presn_hydro, 'formats': np.repeat('f8', len(PreSN.presn_hydro))})
        return dt

    @staticmethod
    def dtype_chem():
        dt = np.dtype({'names': PreSN.presn_elements, 'formats': np.repeat('f8', len(PreSN.presn_elements))})
        return dt

    def show_info(self):
        print "-"*20
        print " Name: %s    nzon: %d" % (self.name, self.nzon)
        print " m_tot: {:5.3f} r_cen: {:12.6e}".format(self.m_tot, self.r_cen)

    @property
    def nzon(self):
        """ time start"""
        return self._nzon

    @property
    def time_start(self):
        """ time start"""
        return self.par('time_start', 0.)

    @property
    def r_cen(self):
        """Center radius"""
        p = 'r_cen'
        if self.is_set(PreSN.sR):
            d = self.hyd(PreSN.sR)[0]
        else:
            d = 0.
        return self.par(p, d)

    @property
    def m_tot(self):
        """Total mass"""
        p = 'm_tot'
        if self.is_set(PreSN.sM):
            d = self.hyd(PreSN.sM)[0]
        else:
            d = 0.
        return self.par(p, d)

    @property
    def rho_cen(self):
        """ Center density"""
        p = 'rho_cen'
        if self.is_set(PreSN.sRho):
            d = self.hyd(PreSN.sRho)[0]
        else:
            d = 0.
        return self.par(p, d)

    @property
    def lg_rho(self):
        """logarithmic density"""
        return np.log10(self.rho)

    @property
    def rho(self):
        """density"""
        return self.hyd(PreSN.sRho)

    @property
    def lg_r(self):
        """logarithmic radius"""
        return np.log10(self.r)

    @property
    def r(self):
        """logarithmic radius"""
        return self.hyd(PreSN.sR)

    @property
    def m(self):
        """Mass"""
        return self.hyd(PreSN.sM)

    @property
    def lgT(self):
        """Log T"""
        return np.log10(self.T)

    @property
    def T(self):
        """Temperature"""
        return self.hyd(PreSN.sT)

    @property
    def V(self):
        """Velocity"""
        return self.hyd(PreSN.sV)

    @property
    def lgV(self):
        """Log Velocity"""
        return np.log10(self.V)

    def hyd(self, v):
        """Hydro data"""
        if v not in self._loads:
            raise ValueError("There is no information about the parameter [%s]. You should set it." % v)
        return self._data_hyd[v]

    @property
    def chem(self):
        """Full hydro data"""
        return self._data_chem

    def par(self, name, d=None):
        return self._params.get(name, d)

    def set_par(self, name,  v):
        self._params[name] = v

    def lg_el(self, el):
        return np.log10(self.el(el))

    def el(self, el):
        if el not in PreSN.presn_elements:
            raise ValueError("There is no  element [%s] in elements" % el)
        if el not in self._loads:
            raise ValueError("There is no information about the element [%s]. You should set it." % el)
        return self._data_chem[el]

    def write_hyd(self, fname):
        """
        Code readheger.trf:
          BM1=cutmass; -- core Mass
          r(0)=Rcen;
          dum=0.;
          write(12,'(1p,e12.3,i6,2e13.5)') timeStart, NzoneHyd, BM1, Rcen;
          do km=1,NzoneHyd;
            write(12,'(1x,i4,1p,e12.4,e18.10,3e15.7,2e12.4)')
               km, dum, rHyd(km), rhoHyd(km), TpHyd(km), uHyd(km), aMr(km), dum;
          enddo;
        :return:
        """
        dum = np.zeros(self.nzon)
        logger.info(' Write hyd-data to %s' % fname)
        zones = range(1, self._nzon)
        with open(fname, 'w') as f:
            f.write('{:12.3e} {:6d} {:13.5e} {:13.5e} {:13.5e}\n'
                    .format(self.time_start, self.nzon, self.m_tot/phys.M_sun, self.r_cen, self.rho_cen))
            # a = '#No. Mr  dM  R  dR  Rho PRE T   V'.split()
            # f.write('           '.join(a)+'\n')
            # for _ in zip(zones, self.m/phys.M_sun, dum, self.r, dum, self.rho, dum, self.T, self.V):
            #     f.write(' %4d %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e \n' % _)
            # 'evehyd.trf: idum,dum,Radius(j),RHOeve(j),TMPR(j),VELOC(j), dum,dum; '
            a = '#No. M  R  Rho T   V   dum  dum '.split()
            f.write('  '+'            '.join(a)+'\n')
            for _ in zip(zones, self.m/phys.M_sun, self.r, self.rho, self.T, self.V, dum, dum):
                f.write(' %4d %15.7e %15.7e %15.7e %15.7e %15.7e  %8.1e  %8.1e\n' % _)
        return os.path.isfile(fname)<commit_msg>- FIX:  missed last line<commit_after>import logging
import numpy as np
import os

import matplotlib.pyplot as plt
from matplotlib import gridspec

from pystella.util.phys_var import phys

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

__author__ = 'bakl'

eve_elements = map(str.strip, "Ni56 H He C N O Ne Na  Mg  Al  Si  S  Ar  Ca  Fe  Ni".split())
eve_colors = dict(Ni56="red", H="blue", He="cyan", C="darkorange", N="coral",
                  O="violet", Ne="green", Na="sandybrown",
                  Mg="skyblue", Si="olive", Al="lime",
                  S="indigo", Ar="brown", Ca="purple",
                  Fe='maroon', Ni='magenta')
eve_lntypes = dict((k, '--') for k, v in eve_colors.items())  # no y-shift
eve_lntypes['H'] = '-'
eve_lntypes['He'] = '-'
eve_lntypes['O'] = '-'
eve_lntypes['C'] = '-'
eve_lntypes['Ni56'] = '-'


class PreSN(object):
    """
    A class that holds data of presupernova
    """
    sRho = 'Rho'
    sM = 'M'
    sT = 'T'
    sR = 'R'
    sV = 'V'
    presn_hydro = (sM, sR, sT, sRho, sV)
    presn_elements = map(str.strip, "H He C N O Ne Na  Mg  Al  Si  S  Ar  Ca  Fe  Ni Ni56".split())

    def __init__(self, name, nzon):
        """Creates a PreSN model instance.  Required parameters:  name, nzon"""
        self.name = name
        self._nzon = nzon
        self._data_hyd = np.empty(nzon, dtype=PreSN.dtype_hyd())
        self._data_chem = np.empty(nzon, dtype=PreSN.dtype_chem())
        self._params = {}
        self._loads = []

    @staticmethod
    def dtype_hyd():
        dt = np.dtype({'names': PreSN.presn_hydro, 'formats': np.repeat('f8', len(PreSN.presn_hydro))})
        return dt

    @staticmethod
    def dtype_chem():
        dt = np.dtype({'names': PreSN.presn_elements, 'formats': np.repeat('f8', len(PreSN.presn_elements))})
        return dt

    def show_info(self):
        print "-"*20
        print " Name: %s    nzon: %d" % (self.name, self.nzon)
        print " m_tot: {:5.3f} r_cen: {:12.6e}".format(self.m_tot, self.r_cen)

    @property
    def nzon(self):
        """ time start"""
        return self._nzon

    @property
    def time_start(self):
        """ time start"""
        return self.par('time_start', 0.)

    @property
    def r_cen(self):
        """Center radius"""
        p = 'r_cen'
        if self.is_set(PreSN.sR):
            d = self.hyd(PreSN.sR)[0]/2.  # todo check Rcen
        else:
            d = 0.
        return self.par(p, d)

    @property
    def m_tot(self):
        """Total mass"""
        p = 'm_tot'
        if self.is_set(PreSN.sM):
            d = self.hyd(PreSN.sM)[0]
        else:
            d = 0.
        return self.par(p, d)

    @property
    def rho_cen(self):
        """ Center density"""
        p = 'rho_cen'
        if self.is_set(PreSN.sRho):
            d = self.hyd(PreSN.sRho)[0]
        else:
            d = 0.
        return self.par(p, d)

    @property
    def lg_rho(self):
        """logarithmic density"""
        return np.log10(self.rho)

    @property
    def rho(self):
        """density"""
        return self.hyd(PreSN.sRho)

    @property
    def lg_r(self):
        """logarithmic radius"""
        return np.log10(self.r)

    @property
    def r(self):
        """logarithmic radius"""
        return self.hyd(PreSN.sR)

    @property
    def m(self):
        """Mass"""
        return self.hyd(PreSN.sM)

    @property
    def lgT(self):
        """Log T"""
        return np.log10(self.T)

    @property
    def T(self):
        """Temperature"""
        return self.hyd(PreSN.sT)

    @property
    def V(self):
        """Velocity"""
        return self.hyd(PreSN.sV)

    @property
    def lgV(self):
        """Log Velocity"""
        return np.log10(self.V)

    def hyd(self, v):
        """Hydro data"""
        if v not in self._loads:
            raise ValueError("There is no information about the parameter [%s]. You should set it." % v)
        return self._data_hyd[v]

    @property
    def chem(self):
        """Full hydro data"""
        return self._data_chem

    def par(self, name, d=None):
        return self._params.get(name, d)

    def set_par(self, name,  v):
        self._params[name] = v

    def lg_el(self, el):
        return np.log10(self.el(el))

    def el(self, el):
        if el not in PreSN.presn_elements:
            raise ValueError("There is no  element [%s] in elements" % el)
        if el not in self._loads:
            raise ValueError("There is no information about the element [%s]. You should set it." % el)
        return self._data_chem[el]

    def write_hyd(self, fname):
        """
        Code readheger.trf:
          BM1=cutmass; -- core Mass
          r(0)=Rcen;
          dum=0.;
          write(12,'(1p,e12.3,i6,2e13.5)') timeStart, NzoneHyd, BM1, Rcen;
          do km=1,NzoneHyd;
            write(12,'(1x,i4,1p,e12.4,e18.10,3e15.7,2e12.4)')
               km, dum, rHyd(km), rhoHyd(km), TpHyd(km), uHyd(km), aMr(km), dum;
          enddo;
        :return:
        """
        dum = np.zeros(self.nzon)
        logger.info(' Write hyd-data to %s' % fname)
        zones = range(1, self._nzon+1)
        with open(fname, 'w') as f:
            f.write('{:12.3e} {:6d} {:13.5e} {:13.5e} {:13.5e}\n'
                    .format(self.time_start, self.nzon, self.m_tot/phys.M_sun, self.r_cen, self.rho_cen))
            # a = '#No. Mr  dM  R  dR  Rho PRE T   V'.split()
            # f.write('           '.join(a)+'\n')
            # for _ in zip(zones, self.m/phys.M_sun, dum, self.r, dum, self.rho, dum, self.T, self.V):
            #     f.write(' %4d %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e \n' % _)
            # 'evehyd.trf: idum,dum,Radius(j),RHOeve(j),TMPR(j),VELOC(j), dum,dum; '
            a = '#No. M  R  Rho T   V   dum  dum '.split()
            f.write('  '+'            '.join(a)+'\n')
            for _ in zip(zones, self.m/phys.M_sun, self.r, self.rho, self.T, self.V, dum, dum):
                f.write(' %4d %15.7e %15.7e %15.7e %15.7e %15.7e  %8.1e  %8.1e\n' % _)
        return os.path.isfile(fname)
{'fraction_non_alphanumeric': 0.16016494845360824, 'fraction_numerical': 0.021443298969072166, 'mean_word_length': 1.9417758369723435, '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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '85248', 'n_tokens_mistral': 4745, 'n_tokens_neox': 4523, 'n_words': 1046}