Документ взят из кэша поисковой машины. Адрес оригинального документа : http://www.stsci.edu/institute/itsd/information/streaming/archive/InstrumentDivisionTrainingSeries/PerryGreenfield061405_supporting/PerryGreenfield061405html
Дата изменения: Tue Sep 25 16:26:37 2012
Дата индексирования: Tue Apr 12 12:05:23 2016
Кодировка:
Python T5: 061405 script

Examples corresponding to source files are followed by examples of usage

[Example 1, clown.py] *************************************************

class Clown:
'''Educational Class''' # docstring
def __init__(self, noise='Honk Honk'):
self.noise = noise
def makenoise(self):
print self.noise

>>> import clown
>>> bozo = clown.Clown() # create first clown object
>>> weepy = clown.Clown('Boo Hoo') # create second clown object
>>> bozo.makenoise()
Honk Honk
>>> weepy.makenoise()
>>> Boo Hoo

>>> bozo.realname = 'Clark Kent'

[Example 2, point.py] *************************************************

class Point:
'''structure to hold coordinates of a point'''
def __init__(self, x, y):
self.x = x
self.y = y

>>> import point
>>> p1 = point.Point(0., 0.)
>>> p2 = point.Point(10.3, -22)
>>> p2.x
10.3
>>> p1.y = 100

[Example 3, sortedlist.py] ********************************************

class SortedList:
def __init__(self):
self.values = []

def append(self, value):
self.values.append(value)

def __getitem__(self, index):
self.values.sort()
return self.values[index]

def __len__(self):
return len(self.values)

>>> import sortedlist as sl
>>> x = sl.SortedList()
>>> x.append("apple")
>>> x.append(3)
>>> x.append("pear")
>>> x.append(7)
>>> for v in x: print v
3
7
apple
pear


[Example 4, sdict.py] *************************************************

class SDict(dict):
'''Dictionary that only accepts case-insensitive string keys'''
def __init__(self, idict = {}):
'''If intializing dict is non-null, examine keys'''
keys = idict.keys()
values = idict.values()
for i in range(len(keys)):
if type(keys[i]) != type(''):
raise TypeError
keys[i] = keys[i].lower()
dict.__init__(self)
for key, value in zip(keys, values):
self[key] = value
def __getitem__(self, key):
if type(key) != type(''):
raise TypeError
return dict.__getitem__(self, key.lower())
def __setitem__(self, key, value):
if type(key) != type(''):
raise TypeError
dict.__setitem__(self, key.lower(), value)

>>> import sdict
>>> sd = sdict.SDict({'Bob':'555-1234','Hubble':'338-4700'})
>>> sd
{'bob': '555-1234', 'hubble': '338-4700'}
>>> sd[3] = 4
[...]
TypeError
>>> sd['BOB']
'555-1234'

[Example 5, spec1.py] *************************************************

import numarray as n

class SourceFunction:
'''Abstract Class representing a source as a function of wavelength


Units are assumed to be Flambda

'''
def __add__(self, other):
return CompositeSourceFunction(self, other, 'add')
# __radd__ not needed

class CompositeSourceFunction(SourceFunction):
'''Source function that is a binary composition of two other functions
'''
def __init__(self, source1, source2, operation):
self.comp1 = source1
self.comp2 = source2
self.operation = operation
def __call__(self, wave):
if self.operation == 'add':
return self.comp1(wave) + self.comp2(wave)

class BlackBody(SourceFunction):
def __init__(self, temperature):
self.temperature=temperature
def __call__(self, wave):
BBCONST =6.625e-34 * 3e8/(1.38e-23 * 1.e-10)
exparg = BBCONST/(n.array(wave)*self.temperature)
exparg[exparg>600] = 600. # to prevent overflows
return 1.e21/(wave**5 * (n.exp(exparg)-1.))

class Gaussian(SourceFunction):
def __init__(self, center, width):
self.width=width
self.center=center
def __call__(self, wave):
return n.exp(-(wave-self.center)**2/(2*self.width**2))

>>> import spec1 as s
>>> from pylab import *
>>> spectrum = s.BlackBody(6000) + s.Gaussian(3000, 50)
>>> wavelengths = arange(7000) + 1.
>>> plot(spectrum(wavelengths))

[Example 6, spec2.py] *************************************************



import numarray as n

class TransmissionFunction:
'''Abstract Class representing a transmission function of wavelength

Unitless'''
def __mul__(self, other):
if isinstance(other, TransmissionFunction):
return CompositeTransmissionFunction(self, other)
if isinstance(other, SourceFunction):
return CompositeSourceFunction(self, other, 'multiply')
if type(other) in [type(1), type(1.)]:
return CompositeTransmissionFunction(
self, ConstTransmission(other))
else:
print "must be product of TransmissionFunction, SourceFunction or
constant"
def __rmul__(self, other):
return self.__mul__(other)

class CompositeTransmissionFunction(TransmissionFunction):
'''Transmission function that is a product of two other transmission
functions'''
def __init__(self, tran1, tran2):
if (not isinstance(tran1, TransmissionFunction) or
not isinstance(tran2, TransmissionFunction)):
print "Arguments must be TransmissionFunctions"
raise TypeError
self.tran1 = tran1
self.tran2 = tran2
def __call__(self, wave):
return self.tran1(wave) * self.tran2(wave)

class ConstTransmission(TransmissionFunction):
def __init__(self, value):
self.value = value
def __call__(self, wave):
return 0.*wave + self.value

class GaussianAbsorption(TransmissionFunction):
def __init__(self, center, width, depth):
self.center = center
self.width = width
self.depth = depth
def __call__(self, wave):
return 1. - self.depth*n.exp(-(wave-self.center)**2/(2*self.width**2))

class SourceFunction:
'''Abstract Class representing a source as a function of wavelength

Units are assumed to be Flambda
'''
def __add__(self, other):
if not isinstance(other, SourceFunction):
print "Can only add SourceFunctions"
raise TypeError
return CompositeSourceFunction(self, other, 'add')
# __radd__ not needed
def __mul__(self, other):
if type(other) in [type(1), type(1.)]:
other = ConstTransmission(other)
if not isinstance(other, TransmissionFunction):
print 'Source functions can only be '+ \
'multiplied by Transmission Functions or constants'
raise TypeError
return CompositeSourceFunction(self, other, 'multiply')
def __rmul__(self, other):
return self.__mul__(other)

class CompositeSourceFunction(SourceFunction):
'''Source function that is a binary composition of two other functions
'''
def __init__(self, source1, source2, operation):
self.comp1 = source1
self.comp2 = source2
self.operation = operation
def __call__(self, wave):
if self.operation == 'add':
return self.comp1(wave) + self.comp2(wave)
if self.operation == 'multiply':
return self.comp1(wave) * self.comp2(wave)

class BlackBody(SourceFunction):
def __init__(self, temperature):
'''Temperature in degrees Kelvin'''
self.temperature=temperature
def __call__(self, wave):
BBCONST =6.625e-34 * 3e8/(1.38e-23 * 1.e-10)
exparg = BBCONST/(n.array(wave)*self.temperature)
exparg[exparg>600] = 600. # to prevent overflows
return 1.e21/(wave**5 * (n.exp(exparg)-1.))


class Gaussian(SourceFunction):
def __init__(self, center, width):
self.width=width
self.center=center
def __call__(self, wave):
return n.exp(-(wave-self.center)**2/(2*self.width**2))

>>> spectrum = s.GaussianAbsorption(4000,20,0.8) *\
... (s.Gaussian(3000,100)+2.*s.BackBody(6000))
>>> plot(spectrum(wavelengths))

[Integration] *********************************************************


>>> source = GaussianAbsorption(4000,20,0.8) * \
... (Gaussian(3000,100) + 1.e10*BlackBody(6000))
>>> source.integrate() # returns integrated flux

>>> source = BlackBody(6000).normalize(VMag(23.3))
>>> source = (Gaussian(3000,50) +
... 1.e10*BlackBody(6000)).normalize(Jy(3.1),
... trans=JohnsonV)

[Empirical Spectra] ***************************************************

>>> data = pyfits.getdata('fuse.fits')
>>> source = TableSource(flux=data.field('flux'),
... wavelength=data.field('wave'))

[Valid Range] *********************************************************

>>> source.waverange()
[985., 1085.]
>>> BlackBody(6000).waverange()
[None, None]

[Component normalization] *********************************************

>>> source = BlackBody(6000).normalize(VMag(23.3))
>>> source = (Gaussian(3000,50) +
... 1.e10*Blackbody(6000)).normalize(Jy(3.1), trans=JohnsonV)

[Redshift] ************************************************************

class SourceFunction:
[...]
def __call__(self, wavelengths):
return self.resteval(invZ(wavelengths, self.z))/(1.+self.z)
def waveset(self):
return Z(self.restwaveset(), self.z)
What had previously been defined as __call__ and waveset in the concrete
function classes now are renamed resteval and restwaveset respectively. Since
validrange is only defined for the base class, there is little reason to depend
on such indirection.

The following shows how redshift would be used.

>>> source = BlackBody(6000,z=1.3) # or
>>> source = BlackBody(6000).z(1.3)
>>> source = (Gaussian(3000,20)+Blackbody(6000)).z(1.3) # or
>>> source = Z(Gaussian(3000,20)+Blackbody(6000), 1.3)
>>> source = (GaussianAbsorption(3000,20,0.8,z=.3)* \
BlackBody(6000,.5)).z(.8)

[Unit systems] ********************************************************

>>> asJy(BlackBody(6000)(NM(300)) # evaluate at 300 nm, return in Janskys
>>> source = GaussianSource(EV(0.5),EV(0.1)) # centered at .5 electron volts
>>> source(NM(10), funits=Fnu) # or
>>> asFnu(source(NM(10), NM(10)))