Exemplo n.º 1
0
    def import_stars_hip():
        # I/239/hip_main
        Stars._create_stardb(Stars.STARDB_HIP)
        conn = sqlite3.connect(Stars.STARDB_HIP)
        cursor = conn.cursor()

        from astroquery.vizier import Vizier
        Vizier.ROW_LIMIT = -1

        cols = ["HIP", "HD", "_RA.icrs", "_DE.icrs", "Vmag", "B-V"]
        r = Vizier(catalog="I/239/hip_main", columns=cols,
                   row_limit=-1).query_constraints()[0]

        for i, row in enumerate(r):
            hip, hd, ra, dec, mag_v, b_v = [row[f] for f in cols]
            if np.any(list(map(np.ma.is_masked, (ra, dec, mag_v)))):
                continue
            hd = 'null' if np.ma.is_masked(hd) else hd
            mag_b = 'null' if np.ma.is_masked(b_v) or np.isnan(
                b_v) else b_v + mag_v
            x, y, z = tools.spherical2cartesian(math.radians(dec),
                                                math.radians(ra), 1)
            cursor.execute("""
                INSERT INTO deep_sky_objects (hip, hd, ra, dec, x, y, z, mag_v, mag_b)
                VALUES (%s, %s, %f, %f, %f, %f, %f, %f, %s)""" %
                           (hip, hd, ra, dec, x, y, z, mag_v, mag_b))
            if i % 100 == 0:
                conn.commit()
                tools.show_progress(len(r), i)

        conn.commit()
        conn.close()
Exemplo n.º 2
0
    def import_stars_tyc():
        assert False, 'not supported anymore'
        Stars._create_stardb(Stars.STARDB_TYC, 12)
        conn = sqlite3.connect(Stars.STARDB_TYC)
        cursor = conn.cursor()

        # Tycho-2 catalogue, from http://archive.eso.org/ASTROM/TYC-2/data/
        for file in ('catalog.dat', 'suppl_1.dat'):
            with open(os.path.join(DATA_DIR, file), 'r') as fh:
                line = fh.readline()
                while line:
                    c = line
                    line = fh.readline()

                    # mean position, ICRS, at epoch 2000.0
                    # proper motion milliarcsecond/year
                    # apparent magnitude
                    if file == 'catalog.dat':
                        # main catalog
                        epoch = 2000.0
                        tycho, ra, dec, pmra, pmdec, mag_bt, mag_vt = c[
                            0:12], c[15:27], c[28:40], c[41:48], c[49:56], c[
                                110:116], c[123:129]
                        mag_b, mag_v = Stars.tycho_to_johnson(
                            float(mag_bt), float(mag_vt))
                    else:
                        # supplement-1 has the brightest stars, from hipparcos and tycho-1
                        epoch = 1991.25
                        tycho, ra, dec, pmra, pmdec, mag_bt, mag_vt, flag, hip = \
                            c[0:12], c[15:27], c[28:40], c[41:48], c[49:56], c[83:89], c[96:102], c[81:82], c[115:120]
                        if flag in ('H', 'V', 'B'):
                            if len(hip.strip()) > 0:
                                mag_b, mag_v = Stars.get_hip_mag_bv(hip)
                            else:
                                continue
                        else:
                            mag_b, mag_v = Stars.tycho_to_johnson(
                                float(mag_bt), float(mag_vt))

                    tycho = tycho.replace(' ', '-')
                    if np.all(list(map(tools.numeric, (ra, dec)))):
                        ra, dec = list(map(float, (ra, dec)))
                        if -10 < mag_v < Stars.MAG_CUTOFF:
                            curr_epoch = datetime.now().year + \
                                         (datetime.now().timestamp()
                                            - datetime.strptime(str(datetime.now().year),'%Y').timestamp()
                                          )/365.25/24/3600
                            years = curr_epoch - epoch

                            # TODO: (1) adjust to current epoch using proper motion and years since epoch

                            x, y, z = tools.spherical2cartesian(
                                math.radians(dec), math.radians(ra), 1)
                            cursor.execute(
                                "INSERT INTO deep_sky_objects (tycho,ra,dec,x,y,z,mag_b,mag_v) VALUES (?,?,?,?,?,?,?,?)",
                                (tycho,
                                 (ra + 360) % 360, dec, x, y, z, mag_b, mag_v))
        conn.commit()
        conn.close()
Exemplo n.º 3
0
    def _render_params(self, discretize_tol=False, center_model=False):
        # called at self.render, override based on hidden field values

        #qfin = tools.fdb_relrot_to_render_q(self._sc_ast_lat, self._sc_ast_lon)
        qfin = tools.ypr_to_q(self._sc_ast_lat, 0, self._sc_ast_lon)
        #light_v = tools.fdb_light_to_render_light(self._light_lat, self._light_lon)
        light_v = tools.spherical2cartesian(self._light_lat, self._light_lon,
                                            1)

        # if qfin & light_v not reasonable, e.g. because solar elong < 45 deg:
        # seems that not needed, left here in case later notice that useful
        # raise InvalidSceneException()

        return (0, 0, self.render_z), qfin, light_v
Exemplo n.º 4
0
    def scene_features(self, feat, maxmem, i1, i2):
        try:
            ref_img, depth = self.render_scene(i1, i2)
        except InvalidSceneException:
            return None

        # get keypoints and descriptors
        ref_kp, ref_desc, self._latest_detector = KeypointAlgo.detect_features(
            ref_img,
            feat,
            maxmem=maxmem,
            max_feats=self.MAX_FEATURES,
            for_ref=True)

        # save only 2d image coordinates, scrap scale, orientation etc
        ref_kp_2d = np.array([p.pt for p in ref_kp], dtype='float32')

        # get 3d coordinates
        ref_kp_3d = KeypointAlgo.inverse_project(self.system_model, ref_kp_2d,
                                                 depth, self.render_z,
                                                 self._ref_img_sc)

        if False:
            mm_dist = self.system_model.min_med_distance
            if False:
                pos = (0, 0, -mm_dist)
                qfin = tools.ypr_to_q(sc_ast_lat, 0, sc_ast_lon)
                light_v = tools.spherical2cartesian(light_lat, light_lon, 1)
                reimg = self.render_engine.render(self.obj_idx, pos, qfin,
                                                  light_v)
                img = np.concatenate(
                    (cv2.resize(ref_img,
                                (self.system_model.view_width,
                                 self.system_model.view_height)), reimg),
                    axis=1)
            else:
                ref_kp = [
                    cv2.KeyPoint(*self._cam.calc_img_xy(x, -y, -z - mm_dist),
                                 1) for x, y, z in ref_kp_3d
                ]
                img = cv2.drawKeypoints(ref_img,
                                        ref_kp,
                                        ref_img.copy(), (0, 0, 255),
                                        flags=cv2.DRAW_MATCHES_FLAGS_DEFAULT)
            cv2.imshow('res', img)
            cv2.waitKey()

        return np.array(ref_desc), ref_kp_2d, ref_kp_3d
Exemplo n.º 5
0
    def correct_supplement_data():
        conn = sqlite3.connect(Stars.STARDB)
        cursor = conn.cursor()

        def insert_mags(hips):
            res = Stars.get_hip_mag_bv([h[0] for h in hips.values()])
            insert = [
                "('%s', %f, %f, %f, %f, %f, %f, %f)" %
                (t, h[1], h[2], h[3], h[4], h[5], res[h[0]][0], res[h[0]][1])
                for t, h in hips.items()
                if h[0] in res and -10 < res[h[0]][1] < Stars.MAG_CUTOFF
            ]
            if len(insert) > 0:
                cursor.execute("""
                    INSERT INTO deep_sky_objects (tycho, ra, dec, x, y, z, mag_b, mag_v) VALUES
                     """ + ','.join(insert) + """
                    ON CONFLICT(tycho) DO UPDATE SET mag_b = excluded.mag_b, mag_v = excluded.mag_v """
                               )
                conn.commit()

        file = 'suppl_1.dat'
        N = 30
        rx = re.compile(r'0*(\d+)')
        with open(os.path.join(DATA_DIR, file), 'r') as fh:
            hips = {}
            line = fh.readline()
            while line:
                c = line
                line = fh.readline()
                tycho, ra, dec, mag_bt, mag_vt, flag, hip = c[0:12], c[
                    15:27], c[28:40], c[83:89], c[96:102], c[81:82], c[115:123]
                tycho = tycho.replace(' ', '-')
                hip = rx.findall(hip)[0] if len(hip.strip()) > 0 else False

                if flag in ('H', 'V', 'B') and hip:
                    ra, dec = float(ra), float(dec)
                    x, y, z = tools.spherical2cartesian(
                        math.radians(dec), math.radians(ra), 1)
                    hips[tycho] = (hip, ra, dec, x, y, z)
                    if len(hips) >= N:
                        insert_mags(hips)
                        hips.clear()
                    else:
                        continue

        if len(hips) > 0:
            insert_mags(hips)
Exemplo n.º 6
0
def load_image_meta(src, sm):
    # params given in equatorial J2000 coordinates, details:
    # https://pds.nasa.gov/ds-view/pds/viewProfile.jsp
    #                                   ?dsid=RO-C-NAVCAM-2-ESC3-MTP021-V1.0

    with open(src, 'r') as f:
        config_data = f.read()

    config_data = '[meta]\n' + config_data
    config_data = re.sub(r'^/\*', '#', config_data, flags=re.M)
    config_data = re.sub(r'^\^', '', config_data, flags=re.M)
    config_data = re.sub(r'^(\w+):(\w+)', r'\1__\2', config_data, flags=re.M)
    config_data = re.sub(r'^END\s*$', '', config_data, flags=re.M)
    config_data = re.sub(r'^NOTE\s*=\s*"[^"]*"', '', config_data, flags=re.M)
    config_data = re.sub(r'^OBJECT\s*=\s*.*?END_OBJECT\s*=\s*\w+',
                         '',
                         config_data,
                         flags=re.M | re.S)
    config_data = re.sub(r' <(DEGREE|SECOND|KILOMETER)>', '', config_data)

    config = ConfigParser(converters={'tuple': literal_eval})
    config.read_string(config_data)

    image_time = config.get('meta', 'START_TIME')

    # spacecraft orientation, equatorial J2000
    sc_rot_ra = config.getfloat('meta', 'RIGHT_ASCENSION')
    sc_rot_dec = config.getfloat('meta', 'DECLINATION')
    sc_rot_cnca = config.getfloat('meta', 'CELESTIAL_NORTH_CLOCK_ANGLE')
    sc_igrf_q = tools.ypr_to_q(
        rads(sc_rot_dec), rads(sc_rot_ra),
        -rads(sc_rot_cnca))  # same with rosetta lbls also

    # from asteroid to spacecraft, asteroid body fixed coordinates
    # TODO: figure out why FOR SOME REASON distance is given ~30x too close
    ast_sc_dist = config.getfloat('meta', 'TARGET_CENTER_DISTANCE') * 30
    ast_sc_lat = config.getfloat('meta', 'SUB_SPACECRAFT_LATITUDE')
    ast_sc_lon = config.getfloat('meta', 'SUB_SPACECRAFT_LONGITUDE')
    ast_sc_bff_r = tools.spherical2cartesian(rads(ast_sc_lat),
                                             rads(ast_sc_lon), ast_sc_dist)

    ast_axis_img_clk_ang = config.getfloat('meta', 'BODY_POLE_CLOCK_ANGLE')
    ast_axis_img_plane_ang = config.getfloat(
        'meta', 'HAY__BODY_POLE_ASPECT_ANGLE')  # what is the use?

    # from sun to spacecraft, equatorial J2000
    ast_sun_dist = config.getfloat('meta', 'TARGET_HELIOCENTRIC_DISTANCE')
    ast_sun_lat = config.getfloat('meta', 'SUB_SOLAR_LATITUDE')
    ast_sun_lon = config.getfloat('meta', 'SUB_SOLAR_LONGITUDE')
    sun_ast_bff_r = -tools.spherical2cartesian(rads(ast_sun_lat),
                                               rads(ast_sun_lon), ast_sun_dist)
    sun_sc_bff_r = sun_ast_bff_r + ast_sc_bff_r

    ast_axis_sun_ang = config.getfloat('meta', 'HAY__BODY_POLE_SUN_ANGLE')
    a = config.getfloat('meta', 'SUB_SOLAR_AZIMUTH')  # what is this!?

    # TODO: continue here
    ast_axis_scf_q = tools.ypr_to_q(-rads(ast_sc_lat), -rads(ast_sc_lon), 0)
    # TODO: figure out: how to get roll as some ast_axis_img_clk_ang come from ast_sc_lat?
    ast_rot_scf_q = tools.ypr_to_q(0, 0, -rads(ast_axis_img_clk_ang))
    ast_scf_q = ast_axis_scf_q  #* ast_rot_scf_q

    dec = 90 - ast_sc_lat
    ra = -ast_sc_lon
    if dec > 90:
        dec = 90 + ast_sc_lat
        ra = tools.wrap_degs(ra + 180)

    print('ra: %f, dec: %f, zlra: %f' % (ra, dec, ast_axis_img_clk_ang))

    ast_igrf_q = ast_scf_q * sc_igrf_q
    sun_ast_igrf_r = tools.q_times_v(ast_igrf_q, sun_ast_bff_r)
    ast_sc_igrf_r = tools.q_times_v(ast_igrf_q, ast_sc_bff_r)
    sun_sc_igrf_r = tools.q_times_v(ast_igrf_q, sun_sc_bff_r)

    z_axis = np.array([0, 0, 1])
    x_axis = np.array([1, 0, 0])
    ast_axis_u = tools.q_times_v(ast_igrf_q, z_axis)
    ast_zlon_u = tools.q_times_v(ast_igrf_q, x_axis)
    ast_axis_dec, ast_axis_ra, _ = tools.cartesian2spherical(*ast_axis_u)
    ast_zlon_proj = tools.vector_rejection(ast_zlon_u, z_axis)
    ast_zlon_ra = tools.angle_between_v(ast_zlon_proj, x_axis)
    ast_zlon_ra *= 1 if np.cross(x_axis, ast_zlon_proj).dot(z_axis) > 0 else -1

    # frame where ast zero lat and lon point towards the sun?
    # ast_axis_ra = -ast_sun_lon
    # ast_axis_dec = 90 - ast_sun_lat
    # ast_axis_zero_lon_ra = 0

    arr2str = lambda arr: '[%s]' % ', '.join(['%f' % v for v in arr])

    print('sun_ast_bff_r: %s' % arr2str(sun_ast_bff_r * 1e3))
    print('sun_sc_bff_r: %s' % arr2str(sun_sc_bff_r * 1e3))
    print('ast_sc_bff_r: %s' % arr2str(ast_sc_bff_r * 1e3))
    # TODO: even the light is wrong, should be right based on the sun_ast and sun_sc vectors!!

    print('sun_ast_igrf_r: %s' % arr2str(sun_ast_igrf_r * 1e3))
    print('sun_sc_igrf_r: %s' % arr2str(sun_sc_igrf_r * 1e3))
    print('ast_sc_igrf_r: %s' % arr2str(ast_sc_igrf_r * 1e3))
    print('ast_axis_ra: %f' % degs(ast_axis_ra))
    print('ast_axis_dec: %f' % degs(ast_axis_dec))
    print('ast_zlon_ra: %f' % degs(ast_zlon_ra))

    aa = quaternion.as_rotation_vector(sc_igrf_q)
    angle = np.linalg.norm(aa)
    sc_angleaxis = [angle] + list(aa / angle)
    print('sc_angleaxis [rad]: %s' % arr2str(sc_angleaxis))