Friday, May 21, 2010

Simple user-defined models using a function

Typically, users have a particular model in mind for use in Sherpa. Here is a simple user-model example of creating a gaussian plus a constant.

I define a function 'mymodel' that accepts a Python list of parameter values and a Numpy ndarray of x values. It calculates and returns the sum of a gaussian and constant as a NumPy ndarray.

I define a 1D dataspace from [0.1, 10] with a bin size of 0.01 and load the user-model function identified as 'mdl'. Using the identifier, I populate the parameter names and initial values.

Setup the model, fake the data, and plot!

#!/usr/bin/env python
from
sherpa.astro.ui import *

import numpy as np



def
mymodel(pars, x, *args, **kwargs):

"""

Evaluate a 1D Gaussian plus constant

pars = { fwhm, pos, ampl, const }

"""

gfactor = 4.0*np.log(2.0)
ratio = (x - pars[1])/pars[0]
return pars[2] * np.exp(-gfactor * ratio * ratio) + pars[3]


# create simple grid [0.1, 10] with a bin size of 0.01

dataspace1d(0.1,10,0.01,dstype=Data1D)


# load the user-model mymodel() with parameter names into

# variable 'mdl'

load_user_model(mymodel,'mdl')

add_user_pars('mdl',['fwhm', 'pos', 'ampl', 'const'])


# initialize parameter values

mdl.pos = 5.0

mdl.fwhm = 2.5

mdl.ampl = 75

mdl.const = 0.1


# set the identifier as the associated model

set_model(mdl)


# evaluate, add poisson noise,
and populate the
# dataspace

fake()


# plot faked data

plot_data()

No comments:

Post a Comment