<commit_before>import numpy
import collections
from Parameter import Parameter
import fancyDisplay
from IPython.display import display, Latex, HTML
import math
import scipy.integrate
import operator
import numexpr
import abc
import matplotlib.pyplot as plt



class ModelValidate(object):

    def __init__(self,model):

        self.keVtoErg                 = 1.60217657E-9
        self.checks = ["'self.functionName' not set in *setup* ",\
                    "'self.formula' not set in *setup*",\
                    "'self.parameters' not set in *setup*",\
                    "'self.integral(e1,e2)' not defined in *setup*"\
                    ]
        checks2 = "'self.parameters' is NOT of type collections.OrderedDict"

        self.tt = [hasattr(model,'functionName'),\
                   hasattr(model,'formula'),\
                   hasattr(model,'parameters'),\
                   hasattr(model,'integral')]


        if self.tt[2]: #Check that parameters exist
            
            self.checks.append(checks2)
            self.tt.append(isinstance(model.parameters,collections.OrderedDict))

        else:

            self._printSetupErr()
            return

        if self.tt[4]: #Check that the parameters are right type

            for p in model.parameters.keys():

                self.checks.append("self.parameters[%s] is not an instance Parameter"%p)
                self.tt.append(isinstance(model.parameters[p],Parameter))
                
        self._printSetupErr()



    
    def _printSetupErr(self):

        self.tt = ~numpy.array(self.tt)
        
        self.checks =numpy.array(self.checks)

        
        problems = self.checks[self.tt]

        if len(problems) == 0:
            return

        print "Error: The SpectralModel class is not proper!"
        print "The following problems were found:"
        print
        for prob in problems:
                print "\t"+prob

        raise RuntimeError("Correct the SpectralModel definition!")        
          
        



class SpectralModel(object):
    __metaclass__           = abc.ABCMeta # Make the user code certain
    

    def __init__(self):

        import collections        
        self.setup()


        self._validate() # Raise runtime error if the users

        for k,v in self.parameters.iteritems():

            object.__setattr__(self,k,v)



        
    @abc.abstractmethod
    def setup(*args,**kwargs):
        # virtual member implemented by the user
        pass
    
    def _validate(self):
        '''
        Member called to check that the model has all the proper
        attributes after the setup is called in the __init__ member
        '''
    
        val = ModelValidate(self)
    
    def __getattr__(self, item):
     
        
        
        if self.__dict__.has_key("parameters"):
            if self.parameters.has_key(item):
                return self.parameters[item]
            else:
                object.__getattribute__(self,item)
        else:
            object.__getattribute__(self,item)
        
    def __setattr__(self,item,value):

                
        
        if self.__dict__.has_key("parameters"):
            
            if self.parameters.has_key(item):
                (self.parameters[item]).setValue(value)
            else:
                object.__setattr__(self,item,value)
                
        else:
            
            object.__setattr__(self,item,value)

    # Removed by <NAME> to switch to a different scheme
    #def __getitem__(self,argument):
    #    return self.parameters[argument]


    def display(self,emin=10.,emax=5000.,logscale=True,fluxType="vfv"):
        '''
        Display the model 

        '''

        eIndxDic = {"ph":0.,"ene":1.,"vfv":2.}
        eIndx = eIndxDic[fluxType]
        
        self.eneUnit = 'keV'
        
        fig = plt.figure(567)
        ax = fig.add_subplot(111)
            
        if logscale:
            eGrid = numpy.logspace(numpy.log10(emin),numpy.log10(emax),100)

            ax.loglog(eGrid,eGrid**eIndx*self(eGrid),'-',color='red')

        else:
            eGrid = numpy.linspace(emin,emax,100)

            ax.plot(eGrid,eGrid**eIndx*self(eGrid),'-',color='red')








            
         
        ax.set_xlabel("Energy [%s]"%self.eneUnit)


        
    
    def __repr__(self):
        print("Spectral model: %s" %(self.functionName))
        print("Formula:\n")
        display(Latex(self.formula))
        print("")
        print("Current parameters:\n")
        table                    = fancyDisplay.HtmlTable(8)
        table.addHeadings("Name","Value","Minimum","Maximum","Delta","Status","Unit","Prior")
        for k,v in self.parameters.iteritems():
            if(v.isFree()):
                ff                   = "free"
            else:
                ff                   = "fixed"
        
        table.addRow(v.name,v.value,v.minValue,v.maxValue,v.delta,ff,v.unit,v.prior.getName())
        
        display(HTML(table.__repr__()))
    
        return ''
 
  
    @abc.abstractmethod<commit_msg>added astropy table<commit_after>import numpy
import collections
from Parameter import Parameter
#import fancyDisplay
from IPython.display import display, Latex, HTML
import math
import scipy.integrate
import operator
import numexpr
import abc
import matplotlib.pyplot as plt

import astropy.table


class ModelValidate(object):

    def __init__(self,model):

        self.keVtoErg                 = 1.60217657E-9
        self.checks = ["'self.functionName' not set in *setup* ",\
                    "'self.formula' not set in *setup*",\
                    "'self.parameters' not set in *setup*",\
                    "'self.integral(e1,e2)' not defined in *setup*"\
                    ]
        checks2 = "'self.parameters' is NOT of type collections.OrderedDict"

        self.tt = [hasattr(model,'functionName'),\
                   hasattr(model,'formula'),\
                   hasattr(model,'parameters'),\
                   hasattr(model,'integral')]


        if self.tt[2]: #Check that parameters exist
            
            self.checks.append(checks2)
            self.tt.append(isinstance(model.parameters,collections.OrderedDict))

        else:

            self._printSetupErr()
            return

        if self.tt[4]: #Check that the parameters are right type

            for p in model.parameters.keys():

                self.checks.append("self.parameters[%s] is not an instance Parameter"%p)
                self.tt.append(isinstance(model.parameters[p],Parameter))
                
        self._printSetupErr()



    
    def _printSetupErr(self):

        self.tt = ~numpy.array(self.tt)
        
        self.checks =numpy.array(self.checks)

        
        problems = self.checks[self.tt]

        if len(problems) == 0:
            return

        print "Error: The SpectralModel class is not proper!"
        print "The following problems were found:"
        print
        for prob in problems:
                print "\t"+prob

        raise RuntimeError("Correct the SpectralModel definition!")        
          
        



class SpectralModel(object):
    __metaclass__           = abc.ABCMeta # Make the user code certain
    

    def __init__(self):

        import collections        
        self.setup()


        self._validate() # Raise runtime error if the users

        for k,v in self.parameters.iteritems():

            object.__setattr__(self,k,v)



        
    @abc.abstractmethod
    def setup(*args,**kwargs):
        # virtual member implemented by the user
        pass
    
    def _validate(self):
        '''
        Member called to check that the model has all the proper
        attributes after the setup is called in the __init__ member
        '''
    
        val = ModelValidate(self)
    
    def __getattr__(self, item):
     
        
        
        if self.__dict__.has_key("parameters"):
            if self.parameters.has_key(item):
                return self.parameters[item]
            else:
                object.__getattribute__(self,item)
        else:
            object.__getattribute__(self,item)
        
    def __setattr__(self,item,value):

                
        
        if self.__dict__.has_key("parameters"):
            
            if self.parameters.has_key(item):
                (self.parameters[item]).setValue(value)
            else:
                object.__setattr__(self,item,value)
                
        else:
            
            object.__setattr__(self,item,value)

    # Removed by <NAME> to switch to a different scheme
    #def __getitem__(self,argument):
    #    return self.parameters[argument]


    def display(self,emin=10.,emax=5000.,logscale=True,fluxType="vfv"):
        '''
        Display the model 

        '''

        eIndxDic = {"ph":0.,"ene":1.,"vfv":2.}
        eIndx = eIndxDic[fluxType]
        
        self.eneUnit = 'keV'
        
        fig = plt.figure(567)
        ax = fig.add_subplot(111)
            
        if logscale:
            eGrid = numpy.logspace(numpy.log10(emin),numpy.log10(emax),100)

            ax.loglog(eGrid,eGrid**eIndx*self(eGrid),'-',color='red')

        else:
            eGrid = numpy.linspace(emin,emax,100)

            ax.plot(eGrid,eGrid**eIndx*self(eGrid),'-',color='red')








            
         
        ax.set_xlabel("Energy [%s]"%self.eneUnit)


        
    
    def __repr__(self):
        print("Spectral model: %s" %(self.functionName))
        print("Formula:\n")
        display(Latex(self.formula))
        print("")
        print("Current parameters:\n")

        maxLen = max(map(lambda p: len(p.name) ,self.parameters.values()))

        
        table = astropy.table.Table(names=["Name","Value","Minimum","Maximum","Delta","Status","Unit","Prior"],dtype=["S%d"%maxLen,float,float,float,float,"S5","S6","S20"])
        for k,v in self.parameters.iteritems():
            if(v.isFree()):
                ff                   = "free"
            else:
                ff                   = "fixed"
        
            table.add_row ([v.name,v.value,v.minValue,v.maxValue,v.delta,ff,v.unit,v.prior.getName()])
        
        display()
    
        return ''
 
  
    @abc.abstractmethod
{'fraction_non_alphanumeric': 0.11135965765415289, 'fraction_numerical': 0.008655903520715814, 'mean_word_length': 1.7218104817363684, 'pattern_counts': {'":': 6, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3690661', 'n_tokens_mistral': 3073, 'n_tokens_neox': 2848, 'n_words': 590}