예제 #1
0
    def update_ra_dec_options(self, *event):

        self.auto_target_ra_dec.set('----------')
        self.target_ra_dec_choice_0['state'] = self.DISABLED
        auto_found = False

        ra = None
        for key in self.log.get_param('target_ra_key').split(','):
            if key in self.science_header:
                ra = self.science_header[key]
                break

        dec = None
        for key in self.log.get_param('target_dec_key').split(','):
            if key in self.science_header:
                dec = self.science_header[key]
                break

        if ra and dec:
            try:
                if isinstance(ra, str):
                    target = plc.Target(plc.Hours(ra.replace(',', '.')),
                                        plc.Degrees(dec.replace(',', '.')))
                    self.auto_target_ra_dec.set(target.coord)
                    self.target_ra_dec_choice_0['state'] = self.NORMAL
                    auto_found = True
                elif isinstance(ra, float):
                    target = plc.Target(plc.Degrees(ra), plc.Degrees(dec))
                    self.auto_target_ra_dec.set(target.coord)
                    self.target_ra_dec_choice_0['state'] = self.NORMAL
                    auto_found = True
            except:
                pass

        if not auto_found:
            self.auto_target_ra_dec_check.set('Not found')
        else:
            self.auto_target_ra_dec_check.set('')

        if not auto_found and self.target_ra_dec_choice.get() == 0:
            self.target_ra_dec_choice.set(1)

        try:
            urlopen('http://www.google.com', timeout=2)
            self.target_ra_dec_choice_1['state'] = self.NORMAL
            self.simbad_target_name.activate()
            auto_found = True
            self.simbad_target_name_check.set('')
        except:
            self.target_ra_dec_choice_1['state'] = self.DISABLED
            self.simbad_target_name.disable()
            auto_found = False
            self.simbad_target_name_check.set('No connection')

        if not auto_found and self.target_ra_dec_choice.get() == 1:
            self.target_ra_dec_choice.set(2)

        self.update_ra_dec()
        self.target_window.show()
def test_coordinates2(ra_string, dec_string):

    try:
        coord = plc.Target(plc.Hours(ra_string), plc.Degrees(dec_string))
        return [True, 'Coordinates\naccepted']
    except:
        return [False, 'Wrong\ncoordinates']
예제 #3
0
def test_coordinates(ra_dec_string, single_line=False):

    try:
        ra_dec_string = ra_dec_string.split(' ')[0].split(
            ':') + ra_dec_string.split(' ')[1].split(':')
        target = plc.Target(
            plc.Hours(ra_dec_string[0], ra_dec_string[1], ra_dec_string[2]),
            plc.Degrees(ra_dec_string[3], ra_dec_string[4], ra_dec_string[5]))
        if single_line:
            return [True, 'Coordinates accepted']
        else:
            return [True, 'Coordinates\naccepted']
    except:
        if single_line:
            return [False, 'Wrong coordinates']
        else:
            return [False, 'Wrong\ncoordinates']
예제 #4
0
    def choose_target(self, *event):

        self.target_ra_dec.set(self.target_ra_dec_2.get())
        self.target_name.set(self.target_name_2.get())

        try:

            ra_dec_string = self.target_ra_dec.get().split(' ')[0].split(
                ':') + self.target_ra_dec.get().split(' ')[1].split(':')
            target = plc.Target(
                plc.Hours(ra_dec_string[0], ra_dec_string[1],
                          ra_dec_string[2]),
                plc.Degrees(ra_dec_string[3], ra_dec_string[4],
                            ra_dec_string[5]))
            self.target_ra_dec_test.set('Coordinates accepted - OK')

        except:
            self.target_ra_dec_test.set(
                'Wrong coordinates\nyou cannot proceed')

        self.update_save_button()
        self.target_window.hide()
    def avc_plot(self, latitude, longitude, tmzn, horizon, target_ra,
                 target_dec, year_mont_string, ax, name, observatory_name):
        ax.cla()

        target = plc.Target(plc.Hours(target_ra), plc.Degrees(target_dec))
        observatory = plc.Observatory(plc.Degrees(latitude),
                                      plc.Degrees(longitude), tmzn, horizon)
        observation = plc.Observation(target, observatory)

        year = int(year_mont_string.split()[0])
        month = int(year_mont_string.split()[1])

        months = [
            'xx', 'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ]
        if (year - 2000) / 4.0 - int((year - 2000) / 4.0) == 0:
            days = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        else:
            days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        time_0 = plc.LT('{0}-{1}-1 12:00:00'.format(year, month), observatory)
        jd_0 = time_0.jd

        time_1 = plc.JD(jd_0 + days[month])

        events = []

        # mid-day splits

        for jj in range(days[month] + 1):
            events.append([plc.JD(time_0.jd + jj), 'mid-day'])

        # target rise/set events

        events += observation.rise_set_events(time_0, time_1)

        # sun rise/set events

        for jj in range(days[month]):

            check_time = plc.JD(time_0.jd + jj)
            check_st = check_time.lst(observatory).hours

            sun = check_time.get_sun()

            # sun rise/set

            if -(90 - observatory.latitude.deg_pm
                 ) < sun.dec.deg_pm < 90 - observatory.latitude.deg_pm:

                rise_ha = np.arccos(
                    -sun.dec.tan * observatory.latitude.tan) * 12 / np.pi

                if rise_ha < 12:
                    set_ha = rise_ha
                    rise_ha = 24 - rise_ha
                else:
                    set_ha = 24 - rise_ha

                rise_st = rise_ha + sun.ra.hours
                if rise_st > 24:
                    rise_st -= 24

                set_st = set_ha + sun.ra.hours
                if set_st > 24:
                    set_st -= 24

                if rise_st < check_st:
                    next_rise_in_st_hours = 24 + rise_st - check_st
                else:
                    next_rise_in_st_hours = rise_st - check_st

                if set_st < check_st:
                    next_set_in_st_hours = 24 + set_st - check_st
                else:
                    next_set_in_st_hours = set_st - check_st

                dt = next_rise_in_st_hours * (23.9344696 / 24)
                if dt < 24:
                    events.append(
                        [plc.JD(check_time.jd + dt / 24), 'sun_rise'])

                dt = next_set_in_st_hours * (23.9344696 / 24)
                if dt < 24:
                    events.append([plc.JD(check_time.jd + dt / 24), 'sun_set'])

            # sun -18 rise/set

            if -(90 - observatory.latitude.deg_pm + 18.0
                 ) < sun.dec.deg_pm < 90 - (observatory.latitude.deg_pm + 18):

                rise_ha = np.arccos(
                    np.sin((-18.0) * np.pi / 180) / sun.dec.cos /
                    observatory.latitude.cos -
                    sun.dec.tan * observatory.latitude.tan) * 12 / np.pi
                if rise_ha < 12:
                    set_ha = rise_ha
                    rise_ha = 24 - rise_ha
                else:
                    set_ha = 24 - rise_ha

                rise_st = rise_ha + sun.ra.hours
                if rise_st > 24:
                    rise_st -= 24

                set_st = set_ha + sun.ra.hours
                if set_st > 24:
                    set_st -= 24

                if rise_st < check_st:
                    next_rise_in_st_hours = 24 + rise_st - check_st
                else:
                    next_rise_in_st_hours = rise_st - check_st

                if set_st < check_st:
                    next_set_in_st_hours = 24 + set_st - check_st
                else:
                    next_set_in_st_hours = set_st - check_st

                dt = next_rise_in_st_hours * (23.9344696 / 24)
                if dt < 24:
                    events.append(
                        [plc.JD(check_time.jd + dt / 24), 'sun_rise_18'])

                dt = next_set_in_st_hours * (23.9344696 / 24)
                if dt < 24:
                    events.append(
                        [plc.JD(check_time.jd + dt / 24), 'sun_set_18'])

        events2 = [[ff[0].jd, ff[0], ff[1]] for ff in events]
        events2.sort(key=lambda ff: ff[0])

        #
        maxalt = str(round(observation.max_altitude.deg_pm, 1))

        ax.xaxis.tick_top()

        ax.set_title(observatory_name + '\n' + name + '   ' + months[month] +
                     ' ' + str(year) + '    max. alt. = ' + maxalt +
                     ' degrees')
        ax.set_xlim((0, 1))
        ax.set_xlabel('HOUR (UTC{0:+.1f})'.format(tmzn))
        ax.set_xticks(np.arange(0, 24.5, 1))
        ax.set_xticklabels(('12', '13', '14', '15', '16', '17', '18', '19',
                            '20', '21', '22', '23', '0', '1', '2', '3', '4',
                            '5', '6', '7', '8', '9', '10', '11', '12'))
        ax.set_ylim((0, days[month] + 1))
        ax.set_ylabel('DAY')
        ax.set_yticks(np.arange(1, days[month] + 0.5, 1))
        ax.tick_params(bottom=True,
                       top=True,
                       left=True,
                       right=True,
                       labelbottom=True,
                       labeltop=True,
                       labelright=False,
                       labelleft=True)
        ax.grid(True, axis='y', linestyle='--')

        check_full_moon = plc.UTC('2000-1-21 04:41:00')

        for jj, ii in enumerate(events2[:-1]):

            moonphase = (np.sin(
                (float(ii[0] + 0.5) - float(check_full_moon.jd)) * np.pi /
                29.530589))**2

            test_jd = 0.5 * (ii[0] + events2[jj + 1][0])
            dt_jd = 0.5 * (events2[jj + 1][0] - ii[0])

            day = 1 + int(test_jd - jd_0)

            time_range = [
                (ii[0] - jd_0 - int(ii[0] - jd_0)) * 24,
                (events2[jj + 1][0] - jd_0 - int(events2[jj + 1][0] - jd_0)) *
                24
            ]
            if time_range[1] == 0:
                time_range[1] = 24

            alpha = 1
            if not observation.is_target_visible(plc.JD(ii[0] + dt_jd)):
                color = 'w'
                alpha = 0
            else:
                sun_az, sun_alt = observation.sun_azimuth_altitude(
                    plc.JD(ii[0] + dt_jd))
                if sun_alt.deg_pm > 0:
                    color = 'y'
                elif sun_alt.deg_pm > -18:
                    color = 'r'
                else:
                    color = str(0.8 * (1 - moonphase))

            ax.plot(time_range, [day, day],
                    linewidth=2.5,
                    color=color,
                    alpha=alpha)

            shift = {'left': +0.3, 'right': -0.3}

            if ii[2] == 'target_set':
                ax.plot(time_range[0], day, 'k*', mec='k', markersize=8)
                if time_range[0] > 20.5:
                    align = 'right'
                else:
                    align = 'left'
                ax.text(time_range[0] + shift[align],
                        day + 0.4,
                        'set: ' + (ii[1].utc + datetime.timedelta(
                            days=tmzn / 24)).isoformat().split('T')[1][:5],
                        va='center',
                        ha=align,
                        fontsize=9)

            if ii[2] == 'target_rise':
                ax.plot(time_range[0],
                        day,
                        'w*',
                        mec='k',
                        markersize=8,
                        markeredgewidth=0.5)
                if time_range[0] < 3.5:
                    align = 'left'
                else:
                    align = 'right'
                ax.text(time_range[0] + shift[align],
                        day + 0.4,
                        'rise: ' + (ii[1].utc + datetime.timedelta(
                            days=tmzn / 24)).isoformat().split('T')[1][:5],
                        va='center',
                        ha=align,
                        fontsize=9)
예제 #6
0
    def fit():

        if mid_time_fit:
            mid_time_fit_p = [
                mid_time + mid_time_fit[0], mid_time + mid_time_fit[1]
            ]
        else:
            mid_time_fit_p = False
        if rp_over_rs_fit:
            rp_over_rs_fit_p = [
                rp_over_rs * rp_over_rs_fit[0], rp_over_rs * rp_over_rs_fit[1]
            ]
        else:
            rp_over_rs_fit_p = False
        if sma_over_rs_fit:
            sma_over_rs_fit_p = [
                sma_over_rs * sma_over_rs_fit[0],
                sma_over_rs * sma_over_rs_fit[1]
            ]
        else:
            sma_over_rs_fit_p = False
        if inclination_fit:
            inclination_fit_p = [
                inclination + inclination_fit[0],
                inclination + inclination_fit[1]
            ]
        else:
            inclination_fit_p = False

        science = find_fits_files(os.path.join(reduction_directory, '*'))
        exp_time = pf.open(science[np.random.randint(
            len(science))])[1].header[exposure_time_key]

        light_curve = np.loadtxt(light_curve_file, unpack=True)

        date = plc.JD(light_curve[0][0]).utc.isoformat()[:15].replace('T', ' ')
        obs_duration = round(24 * (light_curve[0][-1] - light_curve[0][0]), 1)

        # filter out outliers

        light_curve_0 = light_curve[0]
        light_curve_1 = light_curve[1]

        light_curve_0 = light_curve_0[np.where(~np.isnan(light_curve_1))]
        light_curve_1 = light_curve_1[np.where(~np.isnan(light_curve_1))]

        moving_average = []
        for i in range(-10, 11):
            moving_average.append(np.roll(light_curve_1, i))

        median = np.median(moving_average, 0)
        med = np.median([np.abs(ff - median) for ff in moving_average], 0)

        flag = np.where((np.abs(light_curve_1 - median) < scatter * med))[0]

        light_curve_0 = light_curve_0[flag]
        light_curve_1 = light_curve_1[flag]

        # fix timing

        ra_dec_string = target_ra_dec.replace(':', ' ').split(' ')
        target = plc.Target(plc.Hours(*ra_dec_string[:3]),
                            plc.Degrees(*ra_dec_string[3:]))
        light_curve_0 = np.array([
            plc.JD(ff + 0.5 * exp_time / 60.0 / 60.0 / 24.0).bjd_tdb(target)
            for ff in light_curve_0
        ])

        # predictions

        limb_darkening_coefficients = plc.clablimb('claret', logg,
                                                   max(4000, temperature),
                                                   metallicity,
                                                   filter_map[phot_filter])

        predicted_mid_time = (mid_time + round(
            (np.mean(light_curve_0) - mid_time) / period) * period)

        # define models

        def mcmc_f(time_array, detrend_zero, detrend_one, detrend_two,
                   model_rp_over_rs, model_mid_time):

            data_delta_t = time_array - light_curve_0[0]

            detrend = detrend_zero * (
                1 + detrend_one * data_delta_t +
                detrend_two * data_delta_t * data_delta_t)
            transit_model = plc.transit_integrated(
                'claret', limb_darkening_coefficients, model_rp_over_rs,
                period, sma_over_rs, eccentricity, inclination,
                periastron, predicted_mid_time + model_mid_time, time_array,
                float(exp_time), max(1, int(float(exp_time) / 10)))

            return detrend * transit_model

        def independent_f(time_array, detrend_zero, detrend_one, detrend_two,
                          model_rp_over_rs, model_mid_time):

            data_delta_t = time_array - light_curve_0[0]

            detrend = detrend_zero * (
                1 + detrend_one * data_delta_t +
                detrend_two * data_delta_t * data_delta_t)
            transit_model = plc.transit_integrated(
                'claret', limb_darkening_coefficients, model_rp_over_rs,
                period, sma_over_rs, eccentricity, inclination,
                periastron, predicted_mid_time + model_mid_time, time_array,
                float(exp_time), max(1, int(float(exp_time) / 10)))

            return detrend, transit_model

        # set noise level

        if len(light_curve) == 3:
            sigma = light_curve[2][flag]
        else:
            sigma = np.array(
                [np.roll(light_curve_1, ff) for ff in range(-10, 10)])
            sigma = np.std(sigma, 0)

        popt, pcov = curve_fit(
            mcmc_f,
            light_curve_0,
            light_curve_1,
            p0=[np.mean(light_curve_1), 1, -1, rp_over_rs, 0],
            sigma=sigma,
            maxfev=10000)

        fit_detrend, fit_transit_model = independent_f(light_curve_0, *popt)

        test = []
        for i in range(-int(len(light_curve_0) / 2),
                       int(len(light_curve_0) / 2)):
            test.append([
                np.sum((light_curve_1 / fit_detrend -
                        np.roll(fit_transit_model, i))**2), i
            ])
        test.sort()

        popt, pcov = curve_fit(
            mcmc_f,
            light_curve_0,
            light_curve_1,
            p0=[
                popt[0], popt[1], popt[2], popt[3],
                popt[4] + (test[0][1]) * exp_time / 60.0 / 60.0 / 24.0
            ],
            sigma=sigma,
            maxfev=10000)

        residuals = light_curve_1 - mcmc_f(light_curve_0, *popt)

        if len(light_curve) == 3:
            sigma *= np.std(residuals) / np.median(sigma)
        else:
            sigma = np.array([np.roll(residuals, ff) for ff in range(-10, 10)])
            sigma = np.std(sigma, 0)

        def function_to_call(counter):

            if counter.update_now:

                progress_bar_1['value'] = counter.percent
                percent_label_1.configure(
                    text='{0} % ({1}h {2}m {3}s left)'.format(
                        counter.percent, int(counter.time_left.split(':')[0]),
                        int(counter.time_left.split(':')[1]),
                        int(counter.time_left.split(':')[2])))
                show_progress.update()

            if show_progress.exit:
                return False
            else:
                return True

        mcmc_fit = HOPSTransitAndPolyFitting(
            [[light_curve_0, light_curve_1, sigma]],
            method='claret',
            limb_darkening_coefficients=limb_darkening_coefficients,
            rp_over_rs=rp_over_rs,
            period=period,
            sma_over_rs=sma_over_rs,
            eccentricity=eccentricity,
            inclination=inclination,
            periastron=periastron,
            mid_time=mid_time,
            fit_rp_over_rs=rp_over_rs_fit_p,
            iterations=iterations,
            walkers=50,
            burn=burn,
            fit_first_order=True,
            fit_second_order=True,
            fit_period=False,
            fit_sma_over_rs=sma_over_rs_fit_p,
            fit_eccentricity=False,
            fit_inclination=inclination_fit_p,
            fit_periastron=False,
            fit_mid_time=mid_time_fit_p,
            precision=3,
            exp_time=round(exp_time, 1),
            time_factor=int(round(exp_time, 1) / 10),
            function_to_call=function_to_call)
        try:
            mcmc_fit.run_mcmc()
        except ValueError:
            show_progress.exit = True

        if not show_progress.exit:

            fitting_directory = fitting_directory_base

            if not os.path.isdir(fitting_directory):
                os.mkdir(fitting_directory)
            else:
                fi = 2
                while os.path.isdir('{0}_{1}'.format(fitting_directory,
                                                     str(fi))):
                    fi += 1
                fitting_directory = '{0}_{1}'.format(fitting_directory,
                                                     str(fi))
                os.mkdir(fitting_directory)

            mcmc_fit.save_results(
                os.path.join(fitting_directory, 'results.txt'))
            mcmc_fit.save_models(os.path.join(fitting_directory, 'model.txt'))
            mcmc_fit.save_detrended_models(
                os.path.join(fitting_directory, 'detrended_model.txt'))
            mcmc_fit.plot_hops_corner(fitting_directory)
            figure = mcmc_fit.plot_hops_output(
                planet, [
                    '{0} (UT)\nDur: {1}h / Exp: {2}s\nFilter: {3}'.format(
                        date, obs_duration, exp_time, phot_filter)
                ], observer, '{0} / {1} / {2}'.format(observatory, telescope,
                                                      camera),
                fitting_directory)
            shutil.copy('log.yaml',
                        '{0}{1}log.yaml'.format(fitting_directory, os.sep))

            shutil.copy(log.fitting_output_description, fitting_directory)

            return figure