科学計測システムの構築・コンサルティング

ISAAC Newtonのページに天体の出没グラフを出力してくれる便利なWebアプリケーションがあります。

このままでも十分便利なのですが、Pythonのurllibを使ったスクリプトを書くと自分のアプリケーションに組み込んで簡単に出没グラフの生成を自動化することができるようになります。昔作ったスクリプトがまだ使えるようだったので、直接実行できるようにまとめなおして公開しました。モジュールとして読み込んでクラスを使うことも可能です。Python 2.7で動作確認しています。

ISAAC Newton側の仕様が変更になると使えなくなる可能性もありますのでご注意ください。修正BSDライセンスで公開します。

直接実行する場合の使い方:

staralt.py test.dat

test.datに記述された天体の、神山天文台における今日のビジビリティグラフが生成されます。

test.datの中身の例:
Vega 18:36:56.54 38:47:05.6
Capella 05:16:41.44 45:59:46.5
Fomalhaut 22:57:39.37 -29:37:22.5

その他のオプションは、–helpスイッチを付けると表示されます。

モジュールとして使うときはソースコード内の例(test_staralt()関数)を参照してください。

#!/usr/bin/env python
"""
staralt - http://catserver.ing.iac.es/staralt/index.php

Copyright (c) 2014, Tomohiro Yoshikawa
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, 
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Kyoto-Nijicoubou, Co., Ltd., Edechs nor the 
  names of its contributors may be used to endorse or promote
  products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL TOMOHIRO YOSHIKAWA BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import urllib
import re
import string
import time
import argparse

class URLget(object):
    def __init__(self, url):
        self.url = url
        self.data = ''
    def setdata(self, append=False, **data):
        if append:
            self.data = self.data + '&' + urllib.urlencode(data)
        else:
            self.data = urllib.urlencode(data)
    def _urlstring(self, **data):
        if len(data) > 0:
            self.setdata(**data)
        if len(self.data) > 0:
            return self.url + '?' + self.data
        else:
            return self.url
    def urlstring(self):
        return self._urlstring(**self.list)

class StarAlt(URLget):
    def __init__(self):
        URLget.__init__(self, 'http://catserver.ing.iac.es/staralt/index.php')
        self.list = {'form[mode]': '1', # 1:Staralt, 2: Startrack, 3: Starobs, 4: Starmult
                     'form[day]': '',
                     'form[month]': '',
                     'form[year]': '',
                     'form[observatory]': '23', #Mauna Kea
                     'form[sitecoord]': '',
                     'form[coordlist]': '',
                     'form[coordfile]': '',
                     'action': 'showImage',
                     'form[format]': 'gif',
                     'form[paramdist]': 2, # Moon Distance
                     'form[minangle]': 10,
                     'submit': ' Retrieve '
                     }
        self.object = []
    def setsite(self,
                observatory=None,
                longitude=135.7577689,
                latitude=35.0698818,
                altitude=150,
                utc_offset=None):
        if observatory is not None:
            self.list['form[observatory]'] = '%1d'%(observatory)
            self.list['form[sitecoord]'] = ''
        else:
            if utc_offset is None:
                utc_offset = -time.timezone/3600
            self.list['form[observatory]'] = ''
            self.list['form[sitecoord]'] = '%.7f %.7f %.1f %1d'%(longitude, latitude, altitude, utc_offset)
    def setmode(self, mode):
        self.list['form[mode]'] = '%1d'%(mode)
    def setdate(self, year, month, day):
        self.list['form[year]'] = '%04d'%(year)
        self.list['form[month]'] = '%02d'%(month)
        self.list['form[day]'] = '%02d'%(day)
    def addobject(self, ra, dec, name=None):
        ra1 = re.sub(":", " ", ra)
        dec1 = re.sub(":", " ", dec)
        if name == None:
            self.object.append(ra1 + ' ' + dec1)
        else:
            self.object.append(name + ' ' + ra1 + ' ' + dec1)
        
    def urlstring(self, ra=None, dec=None, name=None):
        if ra != None and dec != None:
            ra1 = re.sub(":", " ", ra)
            dec1 = re.sub(":", " ", dec)
            if name == None:
                self.list['form[coordlist]'] = ra1 + ' ' + dec1
            else:
                self.list['form[coordlist]'] = name + ' ' + ra1 + ' ' + dec1
        else:
            self.list['form[coordlist]'] = string.join(self.object, '\r\n')
        return self._urlstring(**self.list)
        
def test_staralt():
    sa = StarAlt()
    sa.setdate(2014, 10, 06)
    sa.setsite() # Koyama Astronomical Observatory
    sa.addobject('18:36:56.54', '38:47:05.6', name='Vega')
    sa.addobject('05:16:41.44', '45:59:46.5', name='Capella')
    sa.addobject('22:57:39.37', '-29:37:22.5', name='Fomalhaut')

    urllib.urlretrieve(sa.urlstring(), 'test.gif')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-d', '--date', default='',
                        help='date (YYYY:MM:DD)')
    parser.add_argument('-x', '--longitude', default=135.7577689,
                        help='longitude of the observatory (deg)')
    parser.add_argument('-y', '--latitude', default=35.0698818,
                        help='latitude of the observatory (deg)')
    parser.add_argument('-a', '--altitude', default=150,
                        help='altitude of the observatory (m)')
    parser.add_argument('-u', '--utc_offset', default=None)
    parser.add_argument('-m', '--mode', default=1,
                        help='mode (1:Staralt, 2: Startrack, 3: Starobs, 4: Starmult)')
    parser.add_argument('-o', '--output', default='out.gif',
                        help='output file name')
    parser.add_argument('input',
                        help='input file name (name RA[HH:MM:SS.SS] Dec[DD:MM:SS.S] in each line)')
    
    args = parser.parse_args()
    
    sa = StarAlt()
    if args.date == '':
        t = time.localtime()
        sa.setdate(t.tm_year, t.tm_mon, t.tm_mday)
    else:
        t = [int(_t) for _t in args.date.split(':')]
        sa.setdate(t[0], t[1], t[2])
    if args.utc_offset is None:
        utc_offset = None
    else:
        utc_offset = float(args.utc_offset)
    sa.setsite(longitude=float(args.longitude),
               latitude=float(args.latitude),
               altitude=float(args.altitude),
               utc_offset=utc_offset)
    sa.setmode(int(args.mode))
    for line in open(args.input):
        if line[0] == '#':
            continue
        name, ra, dec = line.split()
        sa.addobject(ra, dec, name=name)
    
    urllib.urlretrieve(sa.urlstring(), args.output)