fits.py 4.78 KB
Newer Older
Wei Shoulin's avatar
Wei Shoulin committed
1
2

import logging
Xie Zhou's avatar
update    
Xie Zhou committed
3
4
5
6
7
8
import os
import shutil
from glob import glob

from astropy.io import fits

Wei Shoulin's avatar
Wei Shoulin committed
9
from ..common.db import DBClient
Xie Zhou's avatar
update    
Xie Zhou committed
10
from ..common.utils import get_parameter
Wei Shoulin's avatar
Wei Shoulin committed
11
12
13

log = logging.getLogger('csst')

Xie Zhou's avatar
update    
Xie Zhou committed
14

Wei Shoulin's avatar
Wei Shoulin committed
15
16
17
18
19
20
21
22
23
24
class FitsApi(object):
    def __init__(self):
        self.root_dir = os.getenv("CSST_LOCAL_FILE_ROOT", "/opt/temp/csst")
        self.check_dir()
        self.db = DBClient()

    def check_dir(self):
        if not os.path.exists(self.root_dir):
            os.mkdir(self.root_dir)
            log.info("using [%s] as root directory", self.root_dir)
Xie Zhou's avatar
Xie Zhou committed
25
26
27
28
29
30
        # if not os.path.exists(os.path.join(self.root_dir, "fits")):
        #     os.mkdir(os.path.join(self.root_dir, "fits"))
        # if not os.path.exists(os.path.join(self.root_dir, "refs")):
        #     os.mkdir(os.path.join(self.root_dir, "refs"))
        # if not os.path.exists(os.path.join(self.root_dir, "results")):
        #     os.mkdir(os.path.join(self.root_dir, "results"))
Wei Shoulin's avatar
Wei Shoulin committed
31
32
33
34

    def find(self, **kwargs):
        '''
        parameter kwargs:
Xie Zhou's avatar
update    
Xie Zhou committed
35
36
37
        obs_time = [int]
        type = [str]
        fits_id = [str]
Wei Shoulin's avatar
Wei Shoulin committed
38

Xie Zhou's avatar
update    
Xie Zhou committed
39
        return list of paths
Wei Shoulin's avatar
Wei Shoulin committed
40
        '''
Xie Zhou's avatar
update    
Xie Zhou committed
41
        paths = []
Xie Zhou's avatar
Xie Zhou committed
42
        
Xie Zhou's avatar
update    
Xie Zhou committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        obs_time = get_parameter(kwargs, "obs_time")
        type = get_parameter(kwargs, "type")
        fits_id = get_parameter(kwargs, "fits_id")

        if (obs_time is None or type is None) and fits_id is None:
            raise Exception('obs_time and type need to be defind')

        if fits_id is None:
            c, r = self.db.select_many(
                'select * from t_rawfits where obs_time=? and type=?',
                (obs_time, type)
            )
            if len(r) < 1:
                raise Exception('not found')
            for items in r:
Xie Zhou's avatar
Xie Zhou committed
58
59
60
61
62
63
64
65
66
                paths.append(os.path.join(self.root_dir, items['path']))
        else:
            c, r = self.db.select_many(
                'select * from t_rawfits where id=?',
                (fits_id,),
            )
            if len(r) < 1:
                raise Exception('not found')
            return os.path.join(self.root_dir, r[0]['path'])
Wei Shoulin's avatar
Wei Shoulin committed
67
68
69
70
71
72
73
        return paths

    def read(self, **kwargs):
        '''
        parameter kwargs:
        fits_id = [str] 
        file_path = [str] 
Xie Zhou's avatar
update    
Xie Zhou committed
74
75
        chunk_size = [int]

Wei Shoulin's avatar
Wei Shoulin committed
76
77
78
79
80
81
82
83
84
        yield bytes of fits file
        '''
        fits_id = get_parameter(kwargs, "fits_id")
        file_path = get_parameter(kwargs, "file_path")

        if fits_id is None and file_path is None:
            raise Exception("fits_id or file_path need to be defined")

        if fits_id is not None:
Xie Zhou's avatar
update    
Xie Zhou committed
85
86
            c, r = self.db.select_one(
                "select * from t_rawfits where id=?", (fits_id))
Wei Shoulin's avatar
Wei Shoulin committed
87
            if c == 1:
Xie Zhou's avatar
Xie Zhou committed
88
                file_path = os.path.join(self.root_dir, r["path"])
Wei Shoulin's avatar
Wei Shoulin committed
89
90

        if file_path is not None:
Xie Zhou's avatar
Xie Zhou committed
91
            path = os.path.join(self.root_dir, file_path)
Wei Shoulin's avatar
Wei Shoulin committed
92
            chunk_size = get_parameter(kwargs, "chunk_size", 1024)
Xie Zhou's avatar
Xie Zhou committed
93
            with open(path, 'r') as f:
Wei Shoulin's avatar
Wei Shoulin committed
94
95
96
97
98
99
100
101
102
                while True:
                    data = f.read(chunk_size)
                    if not data:
                        break
                    yield data

    def update_status(self, **kwargs):
        pass

Xie Zhou's avatar
update    
Xie Zhou committed
103
104
105
106
107
108
109
110
111
112
113
114
115
    def upload(self, **kwargs):
        '''
        parameter kwargs:
        file_path = [str]

        upload to database and copy to csstpath
        '''
        file_path = get_parameter(kwargs, "file_path")

        if file_path is None:
            raise Exception("file_path need to be defined")

        basename = os.path.basename(file_path)
Xie Zhou's avatar
Xie Zhou committed
116
        name = basename.split('.fits')[0].lower()
Xie Zhou's avatar
update    
Xie Zhou committed
117
118
119
120
121
        c, r = self.db.select_many(
            "select * from t_rawfits where id=?",
            (name,)
        )
        if len(r) >= 1:
Xie Zhou's avatar
Xie Zhou committed
122
            print('already upload', basename)
Xie Zhou's avatar
update    
Xie Zhou committed
123
124
            return

Xie Zhou's avatar
Xie Zhou committed
125
126
127
        hu = fits.getheader(os.path.join(self.root_dir, file_path))
        obs_time = hu['obst'] if 'obst' in hu else 0
        ccd_num = hu['ccd_num'] if 'ccd_num' in hu else 0
Xie Zhou's avatar
update    
Xie Zhou committed
128
        # print(obs_time, ccd_num)
Xie Zhou's avatar
Xie Zhou committed
129
130
131
132
133
134
135
136
137
138
139
140
141
        if 'obs' in name:
            type = 'obs'
        elif 'flat' in name:
            type = 'flat'
        elif 'bias' in name:
            type = 'bias'
        elif 'hgar' in name:
            type = 'arc'
        elif 'sky' in name:
            type = 'sky'
        else:
            type = 'None'
        
Xie Zhou's avatar
update    
Xie Zhou committed
142
143
144

        self.db.execute(
            'INSERT INTO t_rawfits VALUES(?,?,?,?,?)',
Xie Zhou's avatar
Xie Zhou committed
145
            (basename, obs_time, ccd_num, type, file_path)
Xie Zhou's avatar
update    
Xie Zhou committed
146
147
        )
        self.db._conn.commit()
Xie Zhou's avatar
Xie Zhou committed
148
        log.info("%s imported.", file_path)
Xie Zhou's avatar
update    
Xie Zhou committed
149

Wei Shoulin's avatar
Wei Shoulin committed
150
151
    def scan2db(self):
        paths = {}
Xie Zhou's avatar
update    
Xie Zhou committed
152

Xie Zhou's avatar
Xie Zhou committed
153
        for (path, _, file_names) in os.walk(self.root_dir):
Wei Shoulin's avatar
Wei Shoulin committed
154
155
            for filename in file_names:
                if filename.find(".fits") > 0:
Xie Zhou's avatar
Xie Zhou committed
156
157
                    filename = os.path.join(path, filename)
                    self.upload(file_path=filename.replace(self.root_dir, ''))
Xie Zhou's avatar
update    
Xie Zhou committed
158
        return paths