def get_comparison_star_descriptions(comparison_stars_1):
    logging.info(f'Getting star description of comparison star: {comparison_stars_1}')
    comp_star_description = do_calibration.get_star_descriptions(comparison_stars_1)
    comparison_stars_1_desc = do_calibration.add_ucac4_to_star_descriptions(comp_star_description)
    logging.info(f'Added apass info to comparison stars: {comparison_stars_1_desc}')

    if np.isnan(comparison_stars_1_desc[0].vmag):
        logging.info("Comparison star has nan vmag, will screw up everything coming after")
        exit()
    return comparison_stars_1_desc
def run_standard_field_charts(vsx_star_descr, wcs):
    trash_and_recreate_dir(settings.fieldchartsdirs)
    # reference_frame, reference_frame_index=reading.read_reference_frame()
    # reference_fits_frame=settings.convfitsdir+reference_frame
    reference_fits_frame=settings.reference_header
    SHOW_UPSILON = False

    # if SHOW_UPSILON:
    #     candidates = do_calibration.get_candidates(0.5)

    # TODO hand labeled stars
    # hand_candidates_descr = do_calibration.get_star_descriptions(init.wwcra_certain_candidates)
    all_stars_descr = do_calibration.get_star_descriptions()

    # if SHOW_UPSILON:
    #     big_green = set_custom_label(comparison_  star_descr, 'comp')
    #     small_red = set_custom_label(apass_star_descr, [o.vmag for o in apass_star_descr])
    #     big_green = set_custom_label(vsx_star_descr, [o.match['catalog_dict']['name'] for o in vsx_star_descr])
    #     small_red = set_custom_label(hand_candidates_descr, [o.local_id for o in hand_candidates_descr])
    #     big_green = set_aavso_id_label(vsx_star_descr)
    #     small_red = set_local_id_label(hand_candidates_descr)

    all_stars_labeled = set_custom_label(all_stars_descr, '')
    vsx_labeled = set_aavso_id_label(vsx_star_descr)
    #vsx_labeled = set_custom_label(vsx_star_descr, [o.local_id for o in vsx_star_descr])

    # TODO hand labeled stars
    # hand_candidates_labeled = set_local_id_label(hand_candidates_descr)

    # default fields
    empty = []

    # field chart with all detections
    logging.info("Plotting field chart with all detected stars...")
    big_green = empty
    small_red = all_stars_labeled
    fig = plot_it(big_green, small_red, reference_fits_frame, wcs, "All detected stars", PADDING)
    save(fig, settings.fieldchartsdirs + 'all_detections_for_{}_stars'.format(len(small_red)))

    # field chart with all vsx stars
    logging.info("Plotting field chart with all VSX variable stars...")
    big_green = vsx_labeled
    small_red = empty
    fig = plot_it(big_green, small_red, reference_fits_frame, wcs, "All VSX variable stars", PADDING)
    save(fig, settings.fieldchartsdirs + 'all_vsx_stars_{}'.format(len(big_green)))

    # field chart with all vsx stars
    logging.info("Plotting field chart with all VSX variable stars + hand picked vars...")
    big_green = vsx_labeled
    # TODO hand labeled stars
    small_red = [] # hand_candidates_labeled
    fig = plot_it(big_green, small_red, reference_fits_frame, wcs, "VSX variable stars + detected variables", PADDING)
    save(fig, settings.fieldchartsdirs + 'all_vsx_stars_{}_hand_picked_{}'.format(len(big_green), len(small_red)))
def construct_star_descriptions(args, do_compstars_flag):
    # Start with the list of all detected stars
    star_descriptions = do_calibration.get_star_descriptions(init.star_list)
    if args.laststars:
        file_to_load = settings.basedir + 'star_descriptions_to_chart.bin'
        logging.info(f"Loading premade star_descriptions: {file_to_load}")
        with open(file_to_load, 'rb') as fp:
            star_descriptions = pickle.load(fp)
    else:
        if args.upsilon:
            # now we generate a list of StarDescriptions, with which all further processing will be done
            logging.info("Setting star_descriptions to upsilon candidates")
            star_descriptions = do_calibration.add_candidates_to_star_descriptions(
                star_descriptions, 0.1)

        if args.vsx:
            logging.info("Adding vsx names to star_descriptions")
            star_descriptions = do_calibration.add_vsx_names_to_star_descriptions(
                star_descriptions, 0.01)

        # compstar data is added to star descriptions
        if do_compstars_flag:
            logging.info("Getting comparison stars...")
            # getting compstars
            comparison_stars_1, comparison_stars_1_desc = do_compstars.get_fixed_compstars(
            )
            logging.info(f"Comparison stars_1: {comparison_stars_1}")
            np.savetxt(settings.basedir + "comparison_stars_1.txt",
                       comparison_stars_1,
                       fmt='%d',
                       delimiter=';')
            with open(settings.basedir + 'comparison_stars_1_desc.bin',
                      'wb') as compfile:
                pickle.dump(comparison_stars_1_desc, compfile)
        else:
            logging.info("Loading best compstars...")
            comparison_stars_1, comparison_stars_1_desc = reading.read_compstars(
            )
            logging.info(f"comparison stars: {comparison_stars_1}")

        logging.info("Writing star_descriptions_to_chart.bin...")
        with open(settings.basedir + 'star_descriptions_to_chart.bin',
                  'wb') as fp:
            pickle.dump(star_descriptions, fp)
    return comparison_stars_1, comparison_stars_1_desc, star_descriptions
def get_fixed_compstars(star_descriptions=None):
    logging.info(f"Using fixed compstars {init.comparison_stars}")
    if star_descriptions is None:
        star_descriptions = do_calibration.get_star_descriptions(init.star_list)
    star_ids_1 = []
    star_desc_result = []
    star_catalog = do_calibration.create_star_descriptions_catalog(star_descriptions)
    for ucac_id in init.comparison_stars:
        # getting star_id_1
        df = do_calibration.get_ucac4_id_as_dataframe(ucac_id)
        star_id_1 = do_calibration.get_starid_1_for_radec(df['RAJ2000'], df['DEJ2000'], star_catalog)
        star_ids_1.append(star_id_1)
        # adding info to star_description
        star = star_descriptions[star_id_1 - 1]
        coord_catalog = SkyCoord(df['RAJ2000'], df['DEJ2000'], unit='deg')
        logging.info(df.info())
        # df['e_Vmag'] is not present !!!
        logging.info(df['UCAC4'].iloc(0)[0])
        vmag = df['Vmag'].iloc(0)[0]
        do_calibration.add_info_to_star_description(star, vmag, np.nan, df['UCAC4'].iloc(0)[0].decode("utf-8"),
                                                    "UCAC4", coord_catalog)
        star_desc_result.append(star)
        logging.debug(f"Using fixed compstar '{ucac_id}' with Vmag: '{vmag}' and star id: {star_id_1}")
    return star_ids_1, star_desc_result
        logging.warning(f"Returned result from vizier for object {object_name} is empty.")
    df = result[0].to_pandas()
    df2 = df.loc[df['UCAC4'] == object_name.split()[1].encode('UTF-8')]
    return df2


def get_vizier_field(center_coord, radius, catalog, row_limit=2):
    # Select all columns (this is a generic function so has to be all)
    v = Vizier(columns=['all'])

    # Limit the number of rows returned to row_limit
    v.ROW_LIMIT = row_limit

    result = v.query_region(center_coord,
                            radius=radius,
                            catalog=[catalog])
    logging.info(f"result of getting vizier field: {result}")
    try:
        df = result[0].to_pandas() if len(result) > 0 else None
    except:
        logging.error("Error processing vizier results in do_calibration")
        return None
    return df


if __name__ == '__main__':
    star_descriptions = do_calibration.get_star_descriptions(init.star_list)
    star_catalog = create_star_descriptions_catalog(star_descriptions)
    result = get_starid_1_for_radec(star_catalog, [271.234735], [-43.845816])
    logging.info(f"calibration result: {result}")