2012/06/12

スペクトル有効面積補正ツール

広がった天体のスペクトル解析をする際には、source と background での有効面積のちがいが重要になる場合があります。

たとえば右図のように視野中心付近からsource領域を、視野の端からbackgroundをえらぶ場合、off-axis anglesに大きく依存するvignetting effectにより2領域間の有効面積が数十%も変わります。この効果はenergy dependentなため、high energy側ほど「落ち」が著しくなるという厄介な性質をもちます。

右図の場合、background領域でhigh energy側の有効面積をunder estimateしてしまうので、なにも考えず差し引くと、ありもしないhard emissionが浮かび上がってきてしまうことになり、非常に危険です。実際にそういう場面を目撃したことが何度もあります。

これを避けるには、各領域で作成したarf fileをもちいて、有効面積 (specresp) の比を計算し、backgroundの pi fileを補正してやる必要があります。

残念ながら、実際にこの補正をするための公式なftoolは存在しません。

というわけで書きました。

土台となっているのは学生の頃に某先輩が書いてくれたスクリプトですが (Hyodo et al. 2008)、細かいbugを修正し、すざくXIS以外でも (原理的には) つかえるようにし、pythonに移植しました。使用した結果の責任は一切とりませんが、ご自由にお使い下さい。Bugがあれば連絡ください。

使用上の注意:
pythonのmodule, numpyとpyfitsが必要。
結果のまとめをqdp形式で出力するので、そのplotにはqdpが必要 (出力例を下に示します)。
望遠鏡を経ない成分 (=NXB) はあらかじめ引いておくこと。
補正後のbackground spectrumをsource spectrumから引く際、source regionからもNXBを引くことをお忘れなく。


#!/usr/bin/env python

u'''

Written by Makoto Sawada
Version 0.1 (2012/06/12)

mularfratio scales the background spectrum with 
the energy-dependent arf ratio between 
the source and background regions.

ARGUMENTS
bgdarf          ... arf for background
srcarf          ... arf for source
bgdrmf          ... rmf for background
bgdpi           ... original background pi
corrected_bgdpi ... corrected background pi

NOTE
An nxb-subtracted background spectrum is needed.
The pi file must have a RATE column in the 1st extension.

The script requires the pyfits module for FITS I/O 
and the numpy module for calculations.
You need qdp to plot the results.

This is primarily made for Suzaku/XIS spectra, 
although it may work for others.

'''

import pyfits
import numpy as np

eb_acc = 3 #in unit of -log10(E/eV). 1e-{eb_acc} eV accuracy.

def load_arf(arffile):

    hdulist = pyfits.open(arffile)
    arfdata = hdulist[1].data
    en_lo = np.round(arfdata.field('ENERG_LO') * 1e3, eb_acc)
    en_hi = np.round(arfdata.field('ENERG_HI') * 1e3, eb_acc)
    specresp = arfdata.field('SPECRESP')
    hdulist.close()

    return([en_lo,en_hi,specresp])    

def load_rmf(rmffile):

    hdulist = pyfits.open(rmffile)
    extnames = [hdulist[i].name for i in range(len(hdulist))]
    extnum = extnames.index('EBOUNDS')
    ebounds = hdulist[extnum].data
    channel = ebounds.field('CHANNEL')
    e_min = np.round(ebounds.field('E_MIN') * 1e3, eb_acc)
    e_max = np.round(ebounds.field('E_MAX') * 1e3, eb_acc)
    hdulist.close()

    return([channel,e_min,e_max])

def load_pi(pifile):

    pi_hdulist = pyfits.open(pifile)
    pidata = pi_hdulist[1].data
    channel = pidata.field('CHANNEL')
    rate = pidata.field('RATE')

    return([channel,rate,pi_hdulist])

def save_pi(newpifile,newrate,hdulist):

    pidata = hdulist[1].data
    pidata.field('RATE')[:] = newrate
    hdulist.writeto(newpifile,clobber=True)
    hdulist.close()

    return(0)

def result_qdp(src_srs,bgd_srs,bgd_e1s,bgd_e2s,arf_ratios,rmf_e1s,rmf_e2s,corrected_bgdpi):

    emin = min(np.min(bgd_e1s),np.min(rmf_e1s))
    emax = max(np.max(bgd_e2s),np.max(rmf_e2s))

    qdpfile = corrected_bgdpi.replace('.pi','.qdp')
    f = open(qdpfile,'w')

    f.write(
        'skip sing\n'
        'fo r\n cs 1.5\n lw 4\n ti off\n la rot\n'
        'win 1\n'
        'yplot 1 2\n'
        'loc 0.05 0.05 1 0.55\n'
        'la x Energy (eV)\n'
        'la oy SPECRESP (cm\u2\d)\n'
        'r x '+str(emin)+' '+str(emax)+'\n'
        'la f Black: source, Red: background\n'
        'win 2\n'
        'yplot 3 4\n'
        'loc 0.05 0.5 1 1\n'
        'la oy Scaling factor\n'
        'r x '+str(emin)+' '+str(emax)+'\n'
        'la f Green: in arf bin, Blue: in rmf bin\n'
        'lab nx off\n'
        'win all\n'
        )

    for src_sr,bgd_e1,bgd_e2 in zip(src_srs,bgd_e1s,bgd_e2s):
        f.write('%f %f\n' % (bgd_e1,src_sr))
        f.write('%f %f\n' % (bgd_e2,src_sr))
    f.write('no\n')
    for bgd_sr,bgd_e1,bgd_e2 in zip(bgd_srs,bgd_e1s,bgd_e2s):
        f.write('%f %f\n' % (bgd_e1,bgd_sr))
        f.write('%f %f\n' % (bgd_e2,bgd_sr))
    f.write('no\n')
    for src_sr,bgd_sr,bgd_e1,bgd_e2 in zip(src_srs,bgd_srs,bgd_e1s,bgd_e2s):
        f.write('%f %f\n' % (bgd_e1,src_sr/bgd_sr))
        f.write('%f %f\n' % (bgd_e2,src_sr/bgd_sr))
    f.write('no\n')
    for arf_ratio,rmf_e1,rmf_e2 in zip(arf_ratios,rmf_e1s,rmf_e2s):
        f.write('%f %f\n' % (rmf_e1,arf_ratio))
        f.write('%f %f\n' % (rmf_e2,arf_ratio))

    f.close()

    return(0)

def main(bgdarf,srcarf,bgdrmf,bgdpi,corrected_bgdpi):

    ### Loading input files.
    src_e1s,src_e2s,src_srs = load_arf(srcarf)
    bgd_e1s,bgd_e2s,bgd_srs = load_arf(bgdarf)
    rmf_chs,rmf_e1s,rmf_e2s = load_rmf(bgdrmf)
    channels,rates,pi_hdulist = load_pi(bgdpi)

    ### Checking channel consistency of arf files.
    if not np.all(src_e1s == bgd_e1s) or not np.all(src_e2s == bgd_e2s):
        print('Inconsistent channels between the source and background arf files.')
        exit()
        
    ### Checking channel consistency between rmf and pi files.
    if not np.all(channels == rmf_chs):
        print('Inconsistent channels between the rmf and pi files.')
        exit()

    arf_ratios = np.ones(len(channels))

    ### Calculating arf_ratio for each pi channel.
    for channel in channels:
        
        rmf_e1 = rmf_e1s[channel]
        rmf_e2 = rmf_e2s[channel]

        inside_index = np.greater(bgd_e1s, rmf_e1) * np.less(bgd_e1s, rmf_e2)
        arf_inside_es = bgd_e1s[inside_index]
        arf_inside_chs = np.arange(len(inside_index))[inside_index]
        split_num = len(arf_inside_es) + 1
        #print('ch=%f, rmf_ebounds=[%f,%f], split_num=%s' % (channel,rmf_e1,rmf_e2,split_num))

        if split_num == 1:
            ### No arf bin defined.
            arf_ratios[channel] = 1.0

        else:

            if arf_inside_chs[0] == 0:
                arf_ratios[channel] = 1.0
                continue

            arf_prev_ch = arf_inside_chs[0] - 1
            arf_next_ch = arf_inside_chs[-1] + 1
            
            arf_about_chs = np.concatenate([np.array([arf_prev_ch]),arf_inside_chs,np.array([arf_next_ch])])
            arf_about_es = bgd_e1s[arf_about_chs]
            split_ebounds = np.concatenate([np.array([rmf_e1]),arf_inside_es,np.array([rmf_e2])])

            weights = np.ones(split_num)
            src_arfs = np.ones(split_num)
            bgd_arfs = np.ones(split_num)

            for i in range(split_num):

                arf_ch = arf_about_chs[i]
                weights[i] = (split_ebounds[i+1] - split_ebounds[i]) / (rmf_e2 - rmf_e1)
                src_arfs[i] = src_srs[arf_ch]
                bgd_arfs[i] = bgd_srs[arf_ch]

            arf_ratios[channel] = np.sum(weights * src_arfs) / np.sum(weights * bgd_arfs)

        #print('Channel=%d, Ratio=%1.5f' % (channel,arf_ratios[channel]))

    corrected_rates = rates * arf_ratios

    save_pi(corrected_bgdpi,corrected_rates,pi_hdulist)

    result_qdp(src_srs,bgd_srs,bgd_e1s,bgd_e2s,arf_ratios,rmf_e1s,rmf_e2s,corrected_bgdpi)

    return(0)

if __name__ == '__main__':

    import sys

    try:
        bgdarf,srcarf,bgdrmf,bgdpi,corrected_bgdpi = sys.argv[1:]
    except:
        print('bgdarf srcarf bgdrmf bgdpi corrected_bgdpi')
        exit()

    main(bgdarf,srcarf,bgdrmf,bgdpi,corrected_bgdpi)

2012/05/06

多段sshを介したMacの画面共有

gateway-Aの下にあるlocal-Aの画面を、gateway-Bの下にあるlocal-B (=目の前の端末)で画面共有したいとき。多段sshをつかいましょう。

参考: SSH多段トンネリング接続でMacを画面共有する

gateway-Bへのsshを介す必要がなければ、上記の参考ページの方法そのままでいけます。 僕の環境では目の前の端末から外に直接出られないので、もう1段sshが必要ですが、基本的にはおなじ方法で大丈夫です。

具体的には以下のようになります。
ssh -t -L 10000:127.0.0.1:5900 \
username@gateway-B "ssh -t -L 5900:127.0.0.1:5900 \
username@gateway-A "ssh  -L 5900:127.0.0.1:5900 username@local-A""
あとは画面共有.appを起動してlocalhost:10000を叩けばokです。 もちろんserver (local-A)での画面共有の許可、sshごとのpassword/passphraseの入力が必要ですのでお気をつけを。

2012/01/02

D論お役立ち?スクリプト

○Labelのチェックをおこなう

Thesis全体で使用されている\labelコマンドを列挙し、chapter間の重複をしらべる。
\label{labtype:labname}という形式を仮定。labels.txtにchapter, labtype, labname, 重複の有無を列記。重複がなければ最後のcolumnは'ok'、あれば該当するchapter名がcsvで書かれる。重複がある場合も、初出時は'ok'になる仕様。

#!/usr/bin/env python

skipnames = [] #List tex filenames which should be excluded label search.
outfile = 'labels.txt'
maintex = 'ms.tex' #The main tex filename in which your articles are included.

def add_elem(elem,key,dic):

    if dic.has_key(key):

        dic[key].append(elem)

    else:
        
        dic[key] = [elem]

    return(0)

texnames = []
labels = {}

for line in open(maintex,'r'):

    if line.startswith('\include{') or line.startswith('%\include{'):
        texname = line.replace('\include{','').replace('}\n','').replace('%','')
        if not texname in skipnames:
            texnames.append(texname)

f = open(outfile,'w')

for texname in texnames:

    texfile = texname+'.tex'

    for line in open(texfile,'r'):

        if line.find('\label{') != -1:

            templine = line[line.find('\label{')+len('\label{'):]
            label = templine[:templine.find('}')]
            labtype, labname = label.split(':')
            add_elem(label,texname,labels)
            dupflag = 'ok'
            for texkey in labels.keys():
                if texkey == texname:
                    continue
                lablist = labels[texkey]
                if label in lablist:
                    if dupflag == 'ok':
                        dupflag = texkey
                    else:
                        dupflag += ','+texkey
                else:
                    pass
            f.write('%10s %10s %15s %20s\n' % (texname, labtype, labname, dupflag))
f.close()

○Referenceをsortする

reference.texに記述したreference listをアルファベット順にsortする。
コメントアウトしたものは消されます。Archiveは残すので間違えて消したりしても安心のはず。

#!/usr/bin/env python

import os,datetime

archive = 'ref_archives'
if not os.path.exists(archive):
    os.mkdir(archive)
else:
    pass

reffile = 'reference.tex'
date  = datetime.date.today().isoformat().replace('-','')
biblist = []

i = 0
row = 0
for line in open(reffile,'r'):

    if line.startswith('%') or line.startswith('\\begin') or line.startswith('\\end') or line == '\n':
        pass
    elif line.startswith('\\bibitem'):
        try:
            biblist.append(line.replace('\n',''))
        except:
            print(line)
            exit()
        i += 1
    else:
        try:
            biblist[i-1] = biblist[i-1]+line.replace('\n','')
        except:
            print(line)
            exit()
        pass
    row += 1

os.system('mv '+reffile+' '+archive+'/'+reffile.replace('.tex','_'+date+'.tex'))

f = open(reffile,'w')

bibdoc = {}

for bib in biblist:

    title = bib.replace(']','[').split('[')[1]
    citekey = bib.replace(']','[').split('[')[-1].replace('}','{').split('{')[1]
    content = bib.replace('\\bibitem[','').replace(title,'').replace(']{','').replace(citekey+'} ','')
    author = title.split('(')[0]
    year = title.replace(')','(').split('(')[1]

    bibdoc[title] = bib

keys = bibdoc.keys()

keys.sort()

f.write('\\begin{thebibliography}{}\n')
for key in keys:
    f.write(bibdoc[key]+'\n')
f.write('\end{thebibliography}\n')
f.close()

print('Done.')

○Abbreviationの各章での引用回数をcheckする

description環境で書かれたabbreviation listに各章での略語および元の用語の引用回数をコメントで追記します。
元の用語に関しては複数行にまたがるものは数え落とします。先頭の語のcapitalizeの有無はどっちでも拾います。

#!/usr/bin/env python

import os,datetime

skipnames = [
    'abbreviations',
    'reference',
    'acknowledgement',
    ] #List tex filenames which should be excluded label search.

maintex = 'ms.tex' #The main tex filename in which your articles are included.

texnames = []

for line in open(maintex,'r'):

    if line.startswith('\include{') or line.startswith('%\include{'):
        texname = line.replace('\include{','').replace('}\n','').replace('%','')
        if not texname in skipnames:
            texnames.append(texname)

archive = 'abb_archives'
if not os.path.exists(archive):
    os.mkdir(archive)
else:
    pass

def find_keyinchaps(key):

    chaplab = ''
    ch = 1
    for texname in texnames:
        if texname in skipnames:
            continue
        count = 0
        texfile = texname+'.tex'
        for line in open(texfile,'r'):
            if line.find(key+' ') != -1 or line.find(key+'s ') != -1 or line.find(key+')') != -1:
                count += 1
        if count != 0:
            chaplab += str(ch)+' x'+str(count)+', '
        ch += 1
    return(chaplab[:-2])

def find_continchaps(content):

    content = content.replace('-',' ').lower()

    chaplab = ''
    ch = 1
    for texname in texnames:
        if texname in skipnames:
            continue
        count = 0
        texfile = texname+'.tex'
        for line in open(texfile,'r'):
            line = line.replace('-',' ').lower()
            if line.find(content) != -1:
                count += 1
        if count != 0:
            chaplab += str(ch)+' x'+str(count)+', '
        ch += 1
    return(chaplab[:-2])

abbfile = 'abbreviations.tex'
date  = datetime.date.today().isoformat().replace('-','')
abblist = []

i = 0
row = 0
for line in open(abbfile,'r'):

    if line.startswith('\\chapter') or line.startswith('\\begin') or line.startswith('\\end') or line == '\n':
        pass
    elif line.startswith('\\item'):
        try:
            abblist.append(line.replace('\n',''))
        except:
            print(line)
            exit()
        i += 1
    else:
        try:
            abblist[i-1] = abblist[i-1]+line.replace('\n','')
        except:
            print(line)
            exit()
        pass
    row += 1

os.system('mv '+abbfile+' '+archive+'/'+abbfile.replace('.tex','_'+date+'.tex'))

f = open(abbfile,'w')

abbdoc = {}

for abb in abblist:

    abbkey = abb[abb.find('[')+1:abb.find(']')]
    maxnum = abb.find('%')
    if maxnum == -1:
        maxnum = len(abb)
    content = abb[abb.find('$\\ldots$')+len('$\\ldots$'):maxnum].strip(' ')

    abbdoc[abbkey] = content

keys = abbdoc.keys()

keys.sort()

f.write('\\chapter{Abbreviation}\n')
f.write('\\begin{description}\n')
for key in keys:
    usedchaps = find_keyinchaps(key)
    usedchaps2 = find_continchaps(abbdoc[key])

    f.write('\\item [%s] $\\ldots$ %s %s\n' % (key, abbdoc[key], '% '+usedchaps+' ; '+usedchaps2))

f.write('\\end{description}\n')
f.close()

print('Done.')

2011/12/05

Surface brightness of the Galactic diffuse X-ray emission

系内、特に銀河面付近のソースを扱うX線屋さんが避けて通れない背景拡散放射 (GDXE)。
その輝度の見積もりがむずかしくbackground estimationで苦労することもしばしば。

すざくの良質なスペクトルを元にH. Uchiyamaさんがその表面輝度をモデル化しています。
H. Uchiyama PhD (2010) PDFはこちら

Sgr A*を中心とする2つの2-D exponentialの和を用いたモデル (eq.4.2) は特に便利なので、
銀河座標を放り込むと表面輝度を表示するかんたんなスクリプトを書きました。
座標を2セットいれると2領域間での輝度の比を表示します。
無駄にnumpyつかってるのはご愛嬌。。

※初期版にひどいバグ:
l0, b0で絶対値とるの忘れてました!
12/5に参照した方は修正した下記をご覧下さい。

#!/usr/bin/env python

'''
The model expression and the parameters are respectively 
taken from eq.4.2 and table 4.11 of H. Uchiyama 2010, PhD Thesis
http://repository.tksc.jaxa.jp/pl/dr/IS8000028000/en
The parameters were measured with the K-alpha lines from FeXXV 
and FeXXVI and the 5-10 keV continuum bands.
The unit of surface brightness is 1e-7 ph/s/cm2/am2 for 
Fe Ka lines and 1e-13 erg/s/cm2/am2 for 5-10keV continuum.
'''

import numpy as np

gpos_SgrAs = np.array([-0.056, -0.046])

a1 = (26.3, 10.0, 3.4)
a2 = (1.6, 0.25, 0.20)

hl1 = (0.47, 0.51, 0.48)
hb1 = (0.22, 0.22, 0.19)

hl2 = (30, 47, 55)
hb2 = (1.7, 17, 2.5)

band2colnum = {
    'FeXXV':0,
    'FeXXVI':1,
    'hard':2
    }

def calc_sb(l, b, band):

    i = band2colnum[band]

    l0, b0 = np.abs(np.array([l, b]) - gpos_SgrAs)
    sb1 = a1[i] * np.exp(-l0/hl1[i]) * np.exp(-b0/hb1[i])
    sb2 = a2[i] * np.exp(-l0/hl2[i]) * np.exp(-b0/hb2[i])
    sb = sb1 + sb2

    return(sb)

def calc_ratio(l1,b1, l2,b2, band):

    sb1 = calc_sb(l1, b1, band)
    sb2 = calc_sb(l2, b2, band)
    ratio = sb1 / sb2

    return(ratio)

if __name__ == '__main__':

    import sys

    argvs = sys.argv

    try:
        l, b, band = argvs[1:4]
        cnum = band2colnum[band]
        sb = calc_sb(float(l), float(b), band)
        print(sb)
    except:
        try:
            l1, b1, l2, b2, band = argvs[1:6]
            cnum = band2colnum[band]
            rt = calc_ratio(float(l1), float(b1), float(l2), float(b2), band)
            print(rt)
        except:
            print('Usage1 calc sb : calcgdxe.py l b band')
            print('Usage2 calc sb ratio : calcgdxe.py l1 b1 l2 b2 band')
            print('band should be selected from FeXXV, FeXXVI, or hard')
            exit()


追記。

標準で入ってないないnumpyというライブラリを使っているので、
import numpyでこける場合は以下の3点を修正すれば動くと思います。
めんどくさいので動作みかくにん。

1)
import numpy as np
gpos_SgrAs = np.array([-0.056, -0.046])
↓
import math
l_SgrAs = -0.056
b_SgrAs = -0.046

2)
l0, b0 = np.abs(np.array([l, b]) - gpos_SgrAs)
↓
l0 = abs(l - l_SgrAs)
b0 = abs(b - b_SgrAs)

3)
np.exp()
↓
math.exp()

2011/11/17

All sky map in various wavelengths

  • Longer wavelengths: LAMBDA Foreground
    • FITS images http://lambda.gsfc.nasa.gov/product/foreground/f_products.cfm
    • PNG images http://lambda.gsfc.nasa.gov/product/foreground/f_images.cfm
    • Contents: 
      • Composite H-alpha 
      • Haslam 408MHz
      • N(HI) 
      • LAB HI survey
      • Predicted dust emission at 94GHz
      • Derived E(B-V)
      • W(CO) at 115GHz
      • IRAS/ISSA at 12, 25, 60, and 100um
  • X-rays
    • ROSAT All Sky Survey 
      • Ref: http://iopscience.iop.org/0004-637X/485/1/125/35274.text.html
    • MAXI
  • Fermi LAT map http://astrometry.fas.harvard.edu/skymaps/fermi/


Plotting All-Sky Map with matplotlib+pywcsgrid2
http://leejjoon.github.com/matplotlib_astronomy_gallery/allsky/allsky.html

2011/09/09

理研 基礎科学特別研究員 選考結果

採用内定いただきました。正直、非常に精神的に楽になりました。
書類や面接の指導をしてくださった方々(面接練習には実に3回も
つきあって頂きました。。)、twitterなどで応援の言葉をかけて
くださった方々に、深くお礼申し上げます。

結果として内定をいただきましたが、反省点は山のようにあります。
ところで学振とちがって、評点などは教えてもらえないみたい??
参考にしたかったのだけれど。

いずれにしても、、

つぎはD論!

さわだ

Troubleshooting the installation of AtomDB in the HEASoft 6.11 source-code package [updated]

※revised on 2011/09/09 10:00 pm (JST)
※日本語版が下にあります。

I met a trouble on the installation of HEASoft-6.11. The trouble is related to apec/AtomDB data loaded in Xspec and divided into two different factors:
  • AtomDB v.2.0.0 has a serious bug. (http://www.atomdb.org/bug_201.php)
  • The corrected version of AtomDB (v.2.0.1) is not included in the source-code package of HEASoft until yesterday (2011/09/08 JST).

I've discussed with Bryan K. Irby, the HEASoft developer.
The problem and solution seem to be different depending on the download date of the package.

  • 2011/06/29 -- 2011/09/08 (yesterday)
    • The package does not include the corrected version of AtomDB (2.0.1) thus you will see an error message when you load apec in Xspec. 
    • Download a patch file and install it from http://heasarc.nasa.gov/docs/software/lheasoft/bugs.html . 
    • Never use the older AtomDB v.2.0.0 files included in the package (at ${HEADAS}/Xspec/src/spectral/modelData ) because it has a serious bug. See http://www.atomdb.org/bug_201.phpfor for detail.
      • NOTE: Until now (2011/09/09 JST), the HEASoft bug list page does not have any information of the lacking AtomDB v.2.0.1 in the source-code package downloaded during 2011/06/29--2011/09/08. 
      • Thanks to Bryan's quick response, we are now able to get sufficient information to deal with the problem on this version of the HEASoft source-code distribution. 
      • The updated information is available at http://heasarc.nasa.gov/docs/software/lheasoft/bugs.html .
  • 2011/09/09 (today) --
    • Bryan has revised the source-code package.
    • The package correctly includes the latest AtomDB (v.2.0.1) and users can load it in Xspec without installing any patch. (I confirmed this by downloading/installing the source-code package for the MacOSX 10.6.)
---

HEASoft-6.11に入っているAtomDB v.2とそのインストールが少し面倒なことになっているのでまとめます。

問題は以下の2点。

  • v.2.0.0にバグがある
  • v.2.0.1が最近まで出回ってたsource-code packageに含まれてない

Bryan K. Irbyとやりとりをした結果、状況が整理できました。
Packageをdownloadした時期によって問題と取るべき対応が異なります。

  • -- 2011/06/28
    • バグがある2.0.0が入ってた。パッチをあてましょう。
  • 2011/06/29 -- 2011/09/08 (昨日)
    • バグがある2.0.0はのぞいた。でも、修正版2.0.1を入れるの忘れた。
    • よって、やっぱりパッチをあてましょう (上のリンク参照) 。
      • ** これに関する情報がいま現在もHeasoftの頁に無いせいでだいぶ混乱。
      • ** 実際京都だけじゃなくて多くの人が状況を理解できなくて
      • ** わざわざv.2.0.0をひっぱってきて使ってた模様。
      • ** Bryanにwebpageの修正を要求中。
      • その後Bryanがそっこーでwebpageを修正してくれました。
      • http://heasarc.nasa.gov/docs/software/lheasoft/bugs.html を参照ください。
  • 2011/09/09 (今日) --
    • Bryanが直してくれました。
    • ちゃんと2.0.1が入ってます。ふつうにインストールすれば
    • そのままつかえます。(さわだcheck済み)
--- 

さわだ%言ってみるもんだ



2011/08/28

海外学振結果

不採用Aでした。

項目別評価は、
①研究業績 3.67
②研究計画 3.50
③外国の機関で研究することの意義 3.67
④総合評価 3.34
総合評価のTスコアは3.156。

特別な弱点も長所もなく、全体的に点が足りないということですね。
個人的には、乏しい研究業績(*)よりも研究計画の評価が低かったのは意外だったので、見直して今後に活かさなければなりません。といっても今年度の主だった書類はすでに申請ずみなのですが。

(*)=主著3報(PASJ×2, NIM A×1)+共著2報(ApJ 2nd×1, PASJ 3rd×1)+国際会議口頭×1+その他

2011/08/22

simxのinstallのtrouble shooting

1. fortranコンパイラをみつけられない問題

=configureで以下のwarningが出るとき。
configure: WARNING: cfitsio: == No acceptable f77 found in $PATH
configure: WARNING: cfitsio: == Cfitsio will be built without Fortran wrapper su


simx-1.1.2/configureの中で実行されるsimx-1.1.2/libsrc/cfitsio/configureはg77を探す。
おそらく多くのMac userはfortranコンパイラを持っていないか、HEASoftのコンパイルのために持っていたとしてもg77ではなくgfortran。てっとり早い対処はgfortranをg77として使わせること。
参考: http://monteboo.blogspot.com/2007/12/cfitsio-fortran-wrap.html
1-0. gfortranを入手。
1-0-1. finkを入れる。

    • Must be installed from source code at this time (2010/04)
    • After downloading a tarball,
      •    $ cd ~/Download
           $ tar -xvf fink-0.29.10.tar
           $ cd fink-0.29.10/
           $ ./bootstrap   
      • Choose [1: Default (mostly 32bit)], [1: Use sudo], [/sw] in the bootstrap.
      • Choose defaults for the others
    • After installation, add source /sw/bin/init.csh to .cshrc
    • and do $ sudo fink selfupdate once

          (なぜか外から閲覧できなくなってる?wikiから転載: http://byakko.scphys.kyoto-u.ac.jp:8830/MSworklog/iMacSetUpLog#General)

1-0-2. sudo fink install gcc4.4でgfortran4.4.1を入れる。
1-1. $PATHに/sw/lib/gcc4.4/lib追加
1-2. sudo ln -s /sw/bin/gfortran /sw/bin/g77
1-3. sudo ln -s /Users/sawada/Downloads/simx-1.1.2/libsrc/cfitsio/* /sw/lib/gcc4.4/lib
(1-3.が必須かどうか未確認。)

2. src/libsimx.a のtableができない問題

=makeで以下のerrorが出るとき。
ld: in ../src/libsimx.a, archive has no table of contents
collect2: ld returned 1 exit status
make[1]: *** [simx] Error 1
make: *** [all] Error 2


2-a. arのoptionを変更する
/Users/sawada/Downloads/simx-1.1.2/src/MakefileのL33を
$(AR) rv $@ $(OBJS)
から
$(AR) srv $@ $(OBJS)
に修正
参考: http://hidemon-memo.blogspot.com/2009/01/mac-os-ar-commandmode.html
2-b. (未試行) Randollの示した対処法
"cd src ; ranlib libsimx.a ; cd .."
参考: http://hea-www.harvard.edu/simx/install.html の末尾

2011/08/09

SPEX cie codeで計算に含まれる元素

SPEXのプラズマモデルはZ=1-30までの元素について組成比をパラメータとして持っていますが、実際のところCr, Mnなどは組成をどれだけ増やしてもHe-like Kα輝線とかが出てくることはありません。なぜならパラメータがあるだけで計算してないから!組成や電離度をちゃんと計算している元素がどれかは、ascdumpコマンドを叩けばわかります。

SPEX> com cie
 You have defined    1 component.
SPEX> calc
SPEX> ascd term 1 1 abund
 number of layer lines :        4076           0
 Atomic   Element  Abundance      Abundance     Average charge
 number   name     (solar units)  (absolute)
 -------------------------------------------------------------
  1        H       1.000          1.000             1.000
  2        He      1.000         9.7051E-02         2.000
  6        C       1.000         2.7733E-04         5.999
  7        N       1.000         8.1658E-05         6.996
  8        O       1.000         6.0534E-04         7.988
 10        Ne      1.000         1.2677E-04         9.923
 11        Na      1.000         2.2233E-06         10.82
 12        Mg      1.000         3.9719E-05         11.60
 13        Al      1.000         3.2584E-06         12.25
 14        Si      1.000         3.8548E-05         12.81
 16        S       1.000         1.6218E-05         14.21
 18        Ar      1.000         3.5727E-06         15.99
 20        Ca      1.000         2.3281E-06         17.87
 26        Fe      1.000         3.2659E-05         20.60
 28        Ni      1.000         1.8880E-06         22.38
てことで、N, Na, Alをのぞくodd Zの元素 (含 Mn)、Be, Ti, Crは計算してくれませんのでお気をつけを。

ちなみにlast columnのAverage chargeは楽しいですね。rtとか変えればもちろん値が変わっていきます。

SPEXのelectron densityについて

SPEXのいいところは (manualでも自画自賛の文章があるけど) データを再現する温度や元素組成比といった「表の」パラメータだけじゃなく、イオン存在比や各放射プロセスごとの寄与といった「裏の」プラズマの物理状態を知ることができる点だ。また単純な電離平衡プラズマでもAPECとは比べ物にならないほど高い自由度を持ってる。その分よくわかってないことに出くわす頻度も高く、遊んでるとなんだこりゃって思う部分も多々ある。

今日でくわしたのは密度に関する話。

cieを初めとするプラズマモデルでは電子密度(n_e)を陽に指定することができる。放射強度は電子密度とイオン密度の積(n_e * n_X)に比例するが、これとemissivityに効く電子温度(T_e)を一定に保っている限り、電子密度自体はCCDクオリティの分光ではスペクトルの形状をほんの少ししか変えない。(マイクロカロリメータ-クラスの分解能があればtripletのR ratioが変わるのが見える。)

でもよくよく考えると、n_e * n_X, T_e不変でn_eをいじるってことはn_Xいじってるんじゃね?ってことになって、そうだとすると電離の進行度とかが影響されちゃう。SPEXのascdumpコマンドではn_e / n_Hを教えてくれるので、n_eを変えてこの比がどう変わるか見てみた。すると、

SPEX> com cie
 You have defined    1 component.
SPEX> pa 1 1 ed s t
SPEX> pa 1 1 ed v 1e-14
SPEX> calc
SPEX> pa sh fr
--------------------------------------------------------------------------------------------------
sect comp mod  acro parameter with unit     value      status    minimum   maximum lsec lcom lpar

   1    1 cie  norm ne nX V (1E64/m**3)   1.000000     thawn     0.0      1.00E+20
   1    1 cie  t    Temperature (keV)     1.000000     thawn    5.00E-04  1.00E+03
   1    1 cie  ed   El  dens (1E20/m**3) 9.9999998E-15 thawn    1.00E-22  1.00E+10



--------------------------------------------------------------------------------
 Fluxes and restframe luminosities between   2.0000     and    10.000     keV

 sect comp mod   photon flux   energy flux nr of photons    luminosity
              (phot/m**2/s)      (W/m**2)   (photons/s)           (W)
    1    1 cie   3.732456E-03  1.568204E-18  4.690343E+42  1.970663E+27

SPEX> ascd term 1 1 plas
 number of layer lines :        4076           0
 Plasma parameters
 -----------------
 Electron temperature     :   1.0000     keV
 Electron density/1E20    :  1.00000E-14 /m**3
 Hydrogen density/1E20    :  8.30225E-15 /m**3
 Electron/Hydrogen density:   1.2045
SPEX> pa 1 1 ed v 1e-13
SPEX> calc
SPEX> pa sh fr
--------------------------------------------------------------------------------------------------
sect comp mod  acro parameter with unit     value      status    minimum   maximum lsec lcom lpar

   1    1 cie  norm ne nX V (1E64/m**3)   1.000000     thawn     0.0      1.00E+20
   1    1 cie  t    Temperature (keV)     1.000000     thawn    5.00E-04  1.00E+03
   1    1 cie  ed   El  dens (1E20/m**3) 9.9999998E-14 thawn    1.00E-22  1.00E+10



--------------------------------------------------------------------------------
 Fluxes and restframe luminosities between   2.0000     and    10.000     keV

 sect comp mod   photon flux   energy flux nr of photons    luminosity
              (phot/m**2/s)      (W/m**2)   (photons/s)           (W)
    1    1 cie   3.732456E-03  1.568204E-18  4.690343E+42  1.970663E+27

SPEX> ascd term 1 1 plas
 number of layer lines :        4076           0
 Plasma parameters
 -----------------
 Electron temperature     :   1.0000     keV
 Electron density/1E20    :  1.00000E-13 /m**3
 Hydrogen density/1E20    :  8.30225E-14 /m**3
 Electron/Hydrogen density:   1.2045

はい、変わってませんね。n_e/n_H不変。よくよく考えると放射強度はn_e * n_X * Vに比例なので、n_e増やしたらn_Xも同じだけ増やして、Vはその逆2乗で減らす、ということになてるんですね。イオンと電子の密度の比は不変に保たれるので、電離の進行度が変にn_eに左右されることはないと安心できます。

ところで、refパラメータをいじってH以外の元素(ここではHe)に対する組成比の計算に切り替えた上でHの組成比を0にしてやると、、
SPEX> pa 1 1 ed v 1e-14
SPEX> pa 1 1 ref v 02
SPEX> pa 1 1 01 v 0
SPEX> calc
SPEX> pa sh fr
--------------------------------------------------------------------------------------------------
sect comp mod  acro parameter with unit     value      status    minimum   maximum lsec lcom lpar

   1    1 cie  norm ne nX V (1E64/m**3)   1.000000     thawn     0.0      1.00E+20
   1    1 cie  t    Temperature (keV)     1.000000     thawn    5.00E-04  1.00E+03
   1    1 cie  ed   El  dens (1E20/m**3) 9.9999998E-15 thawn    1.00E-22  1.00E+10



--------------------------------------------------------------------------------
 Fluxes and restframe luminosities between   2.0000     and    10.000     keV

 sect comp mod   photon flux   energy flux nr of photons    luminosity
              (phot/m**2/s)      (W/m**2)   (photons/s)           (W)
    1    1 cie   2.904043E-03  1.210261E-18  3.649328E+42  1.520860E+27

SPEX> ascd term 1 1 plas
 number of layer lines :        4071           0
 Plasma parameters
 -----------------
 Electron temperature     :   1.0000     keV
 Electron density/1E20    :  1.00000E-14 /m**3
 Hydrogen density/1E20    :  4.89013E-14 /m**3
 Electron/Hydrogen density:  0.20449
ってなるんですが。。つまりascdumpで出てくるn_e/n_Hってほんとはn_e/(Σ{Z}{n_elem(Z)})だよね多分って突っ込み。実際計算してるのがどういう物理量なのかは現在問い合わせ中。。

2011/08/05

Python for shellscripters

解析フリークのみなさま、

High energy astro系の解析はNASAのHEASoftが主流だと思います。HEASoftに含まれるXSpecや各種ftoolsを使う上で、多くの人がshell scriptを書いていると思うのですが、個人的にshell scriptはクソだと思うので、即刻これを捨てて便利なpythonに移行しましょー!、というのが本ポストの趣旨です。

Pythonはちょいちょい使うものの、いざshell scriptを完全に置き換えたい、というとき具体的にどうすればいいんだー、と悩んだ個人的経験から、解析で頻出しそうなshell script的用法をまとめたいと思います。


 1. Shell commandや外部スクリプトの実行


os.systemを使います。
import os
os.system('cp aho1.txt aho2.txt')

()内はただのstringなのでpythonで使ってる変数も使えます。
import os
infile = 'aho1.txt'
outfile = 'aho2.txt'
os.system('cat '+infile+' > '+outfile)

これより複雑なことをしたければsubprocess.Popenを使います。

2. コマンドを実行して標準出力を返り値として得る


.communicate()を使います。
import subprocess
PIPE=subprocess.PIPE
eventfile = subprocess.Popen(['ls', 'temp.evt'], stdin=None, stdout=PIPE, shell=False).communicate()[0]
Popenの引数1つ目は実行するコマンドとその引数からなるリスト。shell=Trueにすれば、
import subprocess
PIPE=subprocess.PIPE
eventfile = subprocess.Popen('ls temp.evt', stdin=None, stdout=PIPE, shell=True).communicate()[0]
とベタ書きしてもok。また、shell=Trueではwild cardが使えるので、
eventfiles = subprocess.Popen('ls *_xis?.evt', stdin=None, stdout=PIPE, shell=True).communicate()[0]
なおこのままだと使い勝手がわるいし、最後に改行('\n')まで付いてきちゃうので、
eventfiles = subprocess.Popen('ls *_xis?.evt', stdin=None, stdout=PIPE, shell=True).communicate()[0].split()
としてリストにしておくと便利。こう来ると大抵
eventfiles = subprocess.Popen('ls *_xis?.evt', stdin=None, stdout=PIPE, shell=True).communicate()[0].split()
for eventfile in eventfiles:
とつづく。。

3. コマンド、プログラムを実行し、その標準入力とやり取りする

stdin.writeを使います。いわゆるhere documentです。XSpecやxselectを使うとき便利。
入力する各行末尾の改行を忘れずに。
import subprocess
PIPE=subprocess.PIPE
xsp = subprocess.Popen('xpec',stdin=PIPE,stdout=None,shell=False)
xsp.stdin.write(
    #ここにコマンド
    )
xsp.wait()
途中でfor回したりもできて便利。
import subprocess
PIPE=subprocess.PIPE
xse = subprocess.Popen('xselect',stdin=PIPE,stdout=None,shell=False)
xse.stdin.write(
    '\n'
    'no\n'
    'read event eventlist.txt\n'
    '.\n'
    'set image det\n'
    'set xybin 1\n'
    )

for seg in segs:

    subdir = 'xis'+xis+'_seg'+seg

    for grade in grades:
        qdpfile = str(tobs)+'_'+subdir+'_g'+grade+'.qdp'
        pifile = str(tobs)+'_'+subdir+'_g'+grade+'.pi'

        xse.stdin.write(
            'filter column "grade='+graderanges[grade]+' segment='+seg+':'+seg+' status=65536:131071 196608:262143 327680:393215 458752:524287"\n'
            'extract spec\n'
            'plot spec\n'
            'we '+subdir+'/'+qdpfile+'\n'
            'quit\n'
            'save spec '+subdir+'/'+pifile+'\n'
            'no\n'
            'clear column\n'
            )
xse.stdin.write(
    'exit\n'
    'no\n'
    '\n'
    )
xse.wait()

あとは得られたデータをnumpy, scipyで料理してmatplotlibでお絵描き、って流れです。
そこはまたおいおい。とりあえずここまでー。

さわだ

2011/08/03

Heasoft 6.11でのftools仕様変更

解析フリークのみなさま、

Heasoftを6.11にversion upしたところいくつか瑣末な仕様変更で面倒な目に遭遇したので情報共有します。

Heasoft 6.11 Release Note

1. Xspec->iplot->wenvironでのqdp出力

変更:
.pcoにいままでなかったViewから始まる行が追加される。

問題:
こいつはLocationと独立にwindowの図の表示範囲を指定するので、scriptでLocationのみでwinの調整している場合、予想と違う配置にされてしまう。

対処:
.pcoのViewの行を消すか、引数をかえて
View 0.1 0.1 0.9 0.9
とするとこれまでと同じ見た目になる。

2. mathphaのerrmeth, properrのデフォルト値

変更:
errmeth: POISS-1 -> POISS-0
properr: yes -> no

問題:
properrがnoだと誤差伝播しない上、演算した結果
負値を取った場合勝手に誤差を0に、bin quality
を5 (bad)にしてしまう。

対処:
mathphaを使用する際オプション
properr='yes'
をつける。
errmethに関しても新デフォルトではまずい場合は露に指定すべし。

仕様変更に気づかずに解析してしまっている恐れがあれば、fdumpなどで値を確認。
ちなみにfhelp mathphaで見られるヘルプファイルの記述にはこの変更が反映されてない。。

さわだ

2011/03/06

TeXで好きなフォントを使おう

TeXで好きなフォントを使いたい!特にD論でGaramondを使いたい!という欲求を満たすべく調査開始。ざっくり見た感じでは、特定のフォントを使用可能にするものと、OSが認識しているフォントすべてを使用可能にしようというものがありますね。そりゃあ後者の方が断然いいな、というわけで使うのがこちらXeTeX (ずぃーてふ:  本家/日本語wiki)。マカーなので、以下ではMacでの作業手順のみを記録しますが、LinuxやWin32でもいけるみたいですね。
  1. XeTeXのインストール
  2. fontspecのインストール
  3. TeXshop (GUI front end; if needed) のインストール
という感じで必要なものを入れて行きます。が、全部MacTeXに入っているので、これ1つインストールすればいいです。ほとんど1-clickで作業完了ですが、細かいところはBallRWさんのサイトが詳しいので参考にしてください。TeXshopで文章を書く場合、最後に環境設定でエンコードをUTF-8にし、タイプセットコマンドをXeLaTeXに変更すれば準備完了。

というわけで凡例。こちらのサイトから拝借したひな形を少しいじったものです。

% !TEX encoding = UTF-8 Unicode
%%% XeLaTeX sample%%%

\documentclass{book}

%%%%%%%%%%%%%%%%%%%%%
\usepackage{fontspec,xltxtra,xunicode}

\setmainfont{AGaramondPro-Regular}

\usepackage{setspace}
\setstretch{1.2}
\usepackage{indentfirst}
\XeTeXlinebreaklocale "ja"
\XeTeXlinebreakskip=0em plus 0.1em minus 0.01em
\XeTeXlinebreakpenalty=0
\renewcommand{\baselinestretch}{1.4}
\settowidth{\parindent}{あ}
%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\chapter{Font availability with \XeLaTeX}

\section{Examples}

This page is mainly written with Adobe Garamond Pro.

\subsection{Roman letters}

\begin{itemize}

\item $G(x) = A \times \exp{(-\frac{1}{2}\cdot \frac{{(x-x_{0})}^2}{\sigma_x^2})}$: Not applied to equations by default.

\item $\it G(x) = A \times \exp{(-\frac{\rm1}{\rm2}\cdot \frac{{(x-x_{\rm0})}^2}{\sigma_x^2})}$: Can be written with Garamond by some tricks.

\item $\rm{ABCDEFG}$: In equations, letters escaped by $\backslash$rm or $\backslash$it are written with Garamond.

\item ABCDEFG: In plain text, regular style.

\item \textbf{ABCDEFG}: In plain text, bold style.

\item \textit{ABCDEFG}: In plain text, italic style.

\end{itemize}

\subsection{Japanese/Chinese letters}

\fontspec{Hiragino Mincho Pro W3}

ヒラギノ明朝 Pro W3 は、こんな感じ。

\fontspec{Hiragino Kaku Gothic Pro W3}

ヒラギノ角ゴシック Pro W3 は、こんな感じ。

\end{document}


コンパイル結果はこんな感じになりました。デフォルトでは数式にフォントの変更が適用されないみたいですねぇ。今回はちょっとズルをしましたが、正攻法でもどうにかできるはずだよなぁ。まぁこれはおいおい。


追記。

上記のサンプルだとendash (--)やemdash (---)などのコマンドがつうじない。

\defaultfontfeatures{Scale=MatchLowercase,Mapping=tex-text}
を追記するとこれらもうまく動くようになる。

参考↓
http://www.latex-community.org/forum/viewtopic.php?f=40&t=1398
さわだ

2011/03/05

BloggerへのSyntax Highlighterの導入

Bloggerのポストはdefaultではcode syntaxをきれいに整形表示してくれる機能がないようです。これを後から追加するためには、以下のjavascriptのいずれかを利用すればいいようです。
それぞれのdemoを眺めてみて、後者の方が好みだったので今回はそちらを使います。

具体的なBloggerへの導入は、Web2Bloggingの解説ページがわかりやすいです。手順としては、

  1. 上記解説ページのGeneratorでscriptを作成
  2. scriptをbloggerのtemplateに埋め込む
  3. codeつきのpostをしてみる

だけです。

まずはgeneratorでのscript作成。以下のようにTheme (見た目) をひとつ選んで、Brushes (syntax highlightさせたい言語のリスト) を選びます。Themeごとに表示がどのように変わるかはここを参照。
で、"Get Code"ボタンを押して出て来た文字列をcopyしておきます。

次はbloggerのtemplateへの埋め込み。自分のBlogger accountにloginした上で、右上からデザインの編集ページへ移動します。
左上のちょい下にあるボタンから"HTMLの編集"へ。HTMLの文章がずらっと並んでいる最後の"</head>"の直前に、さきほどcopyしておいたscriptをpaste、保存すれば準備は完了。

あとはcodeを含んだ文章をpostすればきれいに表示されます。
例えばこんなかんじ。

code部分は
<pre class="brush:language name;">
ほにゃらら
</pre>
と囲ってやります。記述するcodeにあわせ"language name"をpythonだったりc#だったり適当に変えるのと、ほにゃららはHTML文法からescapeさせる必要があるので、"<"などはそのまま書けない、という点だけ注意です。あ、それからものすごくしょうもないことですが、2つある編集モードのうち、code部分書くときは上記画像の例のように、"HTMLの編集"ってところを選択して書いてくださいね。でないとうまく表示されません。

結果例はこんな感じになります。

さわだ

Code highlight表示のテスト

この下にcodeが出るはず。

print('Hello, world!')

2011/03/04

Pythonによるデータ解析

天文業界は、比較的解析ツールが整備されていると思います。
波長によって使うツールは違って、例えばX線業界ならNASAのHeasoft。
可視•赤外ならIRAFとかでしょうか?(僕は使った事ありません。)

そんな恵まれた状況にあっても、思いついたアイディア(解析)を自分の手でさくっと試せるってのは、大事だと思うのです。用意されたツールだけでは、できる解析も限られてしまうので。既存の良くできたツールたちを有効利用しつつ、足りないところは自前で用意。コードのデバグに費やす時間を最小にし、手軽さ重視。

そういうわけで僕はPythonを使います。

実験バリバリな場合スクリプト言語は速度面でどうしても力不足ですが、天体データ解析ではどっちみちfits fileのread/writeなどが速度のボトルネックになるので (これ、なんとかならない?)、Python程度で十分です。なので、実行速度より大事なのは書く速度。

さすがに裸一貫にPythonだけでは心もとないので、
 * Numpy (数値計算ライブラリ)
 * Scipy (もう少し豪華な数値計算ライブラリ)
 * pyfits (fits fileを扱うためのモジュール)
 * matplotlib (いろいろ高機能なプロッタモジュール)
を一緒に使います。IRAF使いの人にはPyRAFなんてものもあるようです。それから、僕のデフォルトシェルは
 * IPython
です。正確には、デフォルトシェルのrcで最後にIPythonを起動しています。terminalから使うコマンドとpythonが同時に使えるシロモノで、ちょっとしたpythonの動作を調べたいときや、matplotlibを呼び出してさくっと何かplotしたいときに非常に便利です。

たぶんこのブログの半分くらいは、上にリストした人たちに関する話題になるでしょう。たまに誰かの役に立ったり、たまにツッコまれて僕の役に立ったりすれば本望です。

さわだ