Beispiel #1
0
 def get_data(self):
     result_table = Simbad()
     # Extended timeout to search for 1000 rows
     result_table.TIMEOUT = 120
     result_table.ROW_LIMIT = 1000
     result_table.add_votable_fields(
         "flux(V)",
         "mt",
         "otype",
         "ra",
         "dec",
         "dim",
         "flux(U)",
         "flux(B)",
         "flux(R)",
         "flux(I)",
         "flux(J)",
         "flux(H)",
         "flux(K)",
         "flux(u)",
         "flux(g)",
         "flux(r)",
         "flux(i)",
         "flux(z)",
         *self.args
     )
     result_table = result_table.query_object(self.name, **self.kwargs)
     return result_table
Beispiel #2
0
def get_ngc_name(galaxy_name, delimiter=" "):

    """
    This function ...
    :param galaxy_name:
    :param delimiter:
    :return:
    """

    # The Simbad querying object
    simbad = Simbad()
    simbad.ROW_LIMIT = -1

    result = simbad.query_objectids(galaxy_name)
    for name in result["ID"]:

        if "NGC" in name:

            splitted = name.split("NGC")
            if splitted[0] == "":
                number = int(splitted[1])
                return "NGC" + delimiter + str(number)

    # If nothing is found, return None
    return None
Beispiel #3
0
def get_ngc_name(galaxy_name, delimiter=" "):

    """
    This function ...
    :param galaxy_name:
    :param delimiter:
    :return:
    """

    # The Simbad querying object
    simbad = Simbad()
    simbad.ROW_LIMIT = -1

    result = simbad.query_objectids(galaxy_name)
    for name in result["ID"]:

        if "NGC" in name:

            splitted = name.split("NGC")
            if splitted[0] == "":
                number = int(splitted[1])
                return "NGC" + delimiter + str(number)

    # If nothing is found, return None
    return None
Beispiel #4
0
 def test_query_bibobj(self, temp_dir):
     simbad = Simbad()
     simbad.ROW_LIMIT = 5
     simbad.cache_location = temp_dir
     result = simbad.query_bibobj('2005A&A.430.165F')
     assert isinstance(result, Table)
     assert len(result) == 5
Beispiel #5
0
def get_ngc_name(galaxy_name, delimiter=" "):

    """
    This function ...
    :param galaxy_name:
    :param delimiter:
    :return:
    """

    # The Simbad querying object
    simbad = Simbad()
    simbad.ROW_LIMIT = -1

    result = simbad.query_objectids(galaxy_name)
    if result is None or len(result) == 0: raise ValueError("Galaxy name '" + galaxy_name + "' could not be recognized")

    # Loop over the results
    for name in result["ID"]:

        if "NGC" in name:

            splitted = name.split("NGC")
            if splitted[0] == "":
                number = int(splitted[1])
                return "NGC" + delimiter + str(number)

    # If nothing is found, return None
    return None
Beispiel #6
0
def query_from_simbad(targetName: str):
    limitedSimbad = Simbad()
    limitedSimbad.ROW_LIMIT = 5

    result_table = limitedSimbad.query_object(targetName)

    if result_table:
        ra = result_table[0][1]
        dec = result_table[0][2]

        ra_split = ra.split(" ")
        dec_split = dec.split(" ")

        len_ra = len(ra_split)
        len_dec = len(dec_split)

        # transfer the unit of ra/dec from hms/dms to degrees
        if len_ra == 1:
            ra_degree = float(ra_split[0]) * 15
        elif len_ra == 2:
            ra_degree = (float(ra_split[0]) + float(ra_split[1]) / 60) * 15
        else:
            ra_degree = (float(ra_split[0]) + float(ra_split[1]) / 60 +
                         float(ra_split[2]) / 3600) * 15

        if len_dec == 1:
            dec_degree = float(dec_split[0])
        elif len_dec == 2:
            dec_degree = float(dec_split[0]) + float(dec_split[1]) / 60
        else:
            dec_degree = float(dec_split[0]) + float(
                dec_split[1]) / 60 + float(dec_split[2]) / 3600

        webbrowser.open("https://simbad.u-strasbg.fr/simbad/sim-basic?Ident=" +
                        targetName + "&submit=SIMBAD+search")

        # check if the target exist in target table
        if (not get_targetDetails(targetName)):
            # create the target
            count = graph.run(
                "MATCH (t:target) return t.TID  order by t.TID DESC limit 1 "
            ).data()

            target = Target()
            if len(count) == 0:
                target.TID = 0
            else:
                target.TID = count[0]['t.TID'] + 1
            target.name = targetName
            target.longitude = ra_degree
            target.latitude = dec_degree
            graph.create(target)
            print("NAME", target.name)

            return [{'name': target.name}]
        else:
            print("Target is already in the target table")
            return [{'name': targetName}]
    else:
        print("Target doesn't exist.")
Beispiel #7
0
def do_simbad_novae(catalog):
	task_str = catalog.get_current_task_str()	
	simbad_mirrors = ['http://simbad.harvard.edu/simbad/sim-script',
					'http://simbad.u-strasbg.fr/simbad/sim-script']

	customSimbad = Simbad()
	customSimbad.ROW_LIMIT = -1
	customSimbad.TIMEOUT = 120

	for mirror in simbad_mirrors:
		customSimbad.SIMBAD_URL = mirror
		try:
			table = customSimbad.query_criteria('maintype=No* | maintype="No?"')
		except:
			continue
		else:
			break

	if not table:
		catalog.log.warning('SIMBAD unable to load, probably offline.')

	
	
	for name in pbar(catalog.entries, task_str):
		try:
			nova_name = "V* " + get_nova_name(name)
			aliases = customSimbad.query_objectids(nova_name)
		except:
			#THROW WARNING HERE
			tprint("Could not find " + nova_name)
			continue
		
		table = customSimbad.query_object(nova_name)
		
		name = catalog.add_entry(name)
		
		bibcode = table[0]['COO_BIBCODE'].decode()
		ra = str(table[0]['RA'])
		dec = str(table[0]['DEC'])
		
		source = catalog.entries[name].add_source(name='SIMBAD astronomical database',
													bibcode=bibcode,
													url="http://simbad.u-strasbg.fr/",
                              						secondary=True)
		catalog.entries[name].add_quantity(NOVA.RA, ra, source)
		catalog.entries[name].add_quantity(NOVA.DEC, dec, source)

		for i in range(len(aliases)):
			try: alias = aliases[i][0].decode()
			except:	alias = str(aliases[i][0])
						
			catalog.entries[name].add_quantity(NOVA.ALIAS, alias, source)
		
		catalog.journal_entries()
def simbad_object_skycoord(target):
    """Return a SkyCoord object for a target"""
    cs = Simbad()
    cs.ROW_LIMIT = 1
    cs.TIMEOUT = 5

    result = cs.query_object(target)
    try:
        assert len(result) == 1
    except:
        raise LookupError("Simbad Object Query failed")
    result = result[0]

    return SkyCoord(result['RA'], result['DEC'], unit=(u.hourangle, u.degree))
Beispiel #9
0
def do_simbad(catalog):
    task_str = catalog.get_current_task_str()
    keys = list(catalog.entries.keys())

    customSimbad = Simbad()
    customSimbad.ROW_LIMIT = -1
    customSimbad.TIMEOUT = 120
    customSimbad.add_votable_fields('otype', 'sptype', 'sp_bibcode', 'id')

    warnings.filterwarnings("ignore")

    Mnames, Mradec = [], []
    for oname in pbar(keys, task_str):
        # Some events may be merged in cleanup process, skip them if
        # non-existent.
        try:
            name = catalog.add_entry(oname)
        except Exception:
            catalog.log.warning(
                '"{}" was not found, suggests merge occurred in cleanup '
                'process.'.format(oname))
            continue

        if (FASTSTARS.RA not in catalog.entries[name]
                or FASTSTARS.DEC not in catalog.entries[name]):
            continue
        else:
            Mnames.append(name)
            radec = str(catalog.entries[name][FASTSTARS.RA][0]['value']) + str(
                catalog.entries[name][FASTSTARS.DEC][0]['value'])
            c = coord(radec, unit=(un.hourangle, un.deg), frame='icrs')

            cnttry = 0
            foundstar = False
            while foundstar == False and cnttry < 10:
                try:
                    cnttry += 1
                    time.sleep(0.1)
                    result = customSimbad.query_region(c, radius='0d0m5s')
                    aliases = re.sub(r'b\'(.*)\'', r'\1',
                                     str(result['ID'].tolist()[0])).split(',')
                except TypeError:
                    #print(radec,cnttry)
                    continue
                foundstar = True

            if foundstar == True:
                source = (catalog.entries[name].add_source(
                    name='SIMBAD astronomical database',
                    bibcode="2000A&AS..143....9W",
                    url="http://simbad.u-strasbg.fr/",
                    secondary=True))
                for alias in aliases:
                    ali = single_spaces(
                        re.sub(r'\[[^)]*\]', '', alias).strip())
                    if is_number(ali.replace(' ', '')):
                        continue
                    if ali[:4] == "HVS ":
                        continue
                    ali = name_clean(ali)
                    catalog.entries[name].add_quantity(FASTSTARS.ALIAS, ali,
                                                       source)

    catalog.journal_entries()
    return
Beispiel #10
0
 def _get_simbad(self):
     s = Simbad()
     s.ROW_LIMIT = 0
     return s
Beispiel #11
0
def do_simbad(catalog):
    # Simbad.list_votable_fields()
    # Some coordinates that SIMBAD claims belong to the SNe actually belong to
    # the host.
    task_str = catalog.get_current_task_str()
    simbadmirrors = ['http://simbad.harvard.edu/simbad/sim-script',
                     'http://simbad.u-strasbg.fr/simbad/sim-script']
    simbadbadcoordbib = ['2013ApJ...770..107C']
    simbadbadnamebib = ['2004AJ....127.2809W', '2005MNRAS.364.1419Z',
                        '2015A&A...574A.112D', '2011MNRAS.417..916G',
                        '2002ApJ...566..880G']
    simbadbannedcats = ['[TBV2008]', 'OGLE-MBR']
    customSimbad = Simbad()
    customSimbad.ROW_LIMIT = -1
    customSimbad.TIMEOUT = 120
    customSimbad.add_votable_fields('otype', 'sptype', 'sp_bibcode', 'id')
    table = []
    for mirror in simbadmirrors:
        customSimbad.SIMBAD_URL = mirror
        try:
            table = customSimbad.query_criteria('maintype=No* | maintype="No?"')
        except:
            continue
        else:
            break

    if not table:
        catalog.log.warning('SIMBAD unable to load, probably offline.')

    # 2000A&AS..143....9W
    for brow in pbar(table, task_str):
        row = {x: re.sub(r'b\'(.*)\'', r'\1',
                         str(brow[x])) for x in brow.colnames}
        # Skip items with no bibliographic info aside from SIMBAD, too
        # error-prone
        if row['OTYPE'] == 'Candidate_No*' and not row['SP_TYPE']:
            continue
        if (not row['COO_BIBCODE'] and not row['SP_BIBCODE'] and
                not row['SP_BIBCODE_2']):
            continue
        if any([x in row['MAIN_ID'] for x in simbadbannedcats]):
            continue
        if row['COO_BIBCODE'] and row['COO_BIBCODE'] in simbadbadnamebib:
            continue
        name = single_spaces(re.sub(r'\[[^)]*\]', '', row['MAIN_ID']).strip())
        if name == 'SN':
            continue
        if is_number(name):
            continue
        name = catalog.add_entry(name)
        source = (catalog.entries[name]
                  .add_source(name='SIMBAD astronomical database',
                              bibcode="2000A&AS..143....9W",
                              url="http://simbad.u-strasbg.fr/",
                              secondary=True))
        aliases = row['ID'].split(',')
        for alias in aliases:
            if any([x in alias for x in simbadbannedcats]):
                continue
            ali = single_spaces(re.sub(r'\[[^)]*\]', '', alias).strip())
            if is_number(ali):
                continue
            ali = name_clean(ali)
            catalog.entries[name].add_quantity(NOVA.ALIAS,
                                               ali, source)
        if row['COO_BIBCODE'] and row['COO_BIBCODE'] not in simbadbadcoordbib:
            csources = ','.join(
                [source, catalog.entries[name].add_source(
                    bibcode=row['COO_BIBCODE'])])
            catalog.entries[name].add_quantity(NOVA.RA,
                                               row['RA'], csources)
            catalog.entries[name].add_quantity(NOVA.DEC,
                                               row['DEC'], csources)
        if row['SP_BIBCODE']:
            ssources = uniq_cdl([source,
                                 catalog.entries[name]
                                 .add_source(bibcode=row['SP_BIBCODE'])] +
                                ([catalog.entries[name]
                                  .add_source(bibcode=row['SP_BIBCODE_2'])] if
                                 row['SP_BIBCODE_2'] else []))
            catalog.entries[name].add_quantity(
                NOVA.CLAIMED_TYPE,
                (row['SP_TYPE']
                 .replace('SN.', '')
                 .replace('SN', '')
                 .replace('(~)', '')
                 .strip(': ')), ssources)
    catalog.journal_entries()
    return
Beispiel #12
0
def do_simbad(catalog):
    # Simbad.list_votable_fields()
    # Some coordinates that SIMBAD claims belong to the SNe actually belong to
    # the host.
    task_str = catalog.get_current_task_str()
    simbadmirrors = ['http://simbad.harvard.edu/simbad/sim-script',
                     'http://simbad.u-strasbg.fr/simbad/sim-script']
    simbadbadcoordbib = ['2013ApJ...770..107C']
    simbadbadtypebib = ['2014ApJ...796...87I', '2015MNRAS.448.1206M',
                        '2015ApJ...807L..18N']
    simbadbadnamebib = ['2004AJ....127.2809W', '2005MNRAS.364.1419Z',
                        '2015A&A...574A.112D', '2011MNRAS.417..916G',
                        '2002ApJ...566..880G']
    simbadbannedcats = ['[TBV2008]', 'OGLE-MBR']
    simbadbannednames = ['SN']
    customSimbad = Simbad()
    customSimbad.ROW_LIMIT = -1
    customSimbad.TIMEOUT = 120
    customSimbad.add_votable_fields('otype', 'sptype', 'sp_bibcode', 'id')
    table = []
    print(customSimbad.SIMBAD_URL)
    for mirror in simbadmirrors:
        customSimbad.SIMBAD_URL = mirror
        try:
            table = customSimbad.query_criteria('maintype=SN | maintype="SN?"')
        except Exception:
            continue
        else:
            if not table:
                continue
            break

    if not table:
        catalog.log.warning('SIMBAD unable to load, probably offline.')

    # 2000A&AS..143....9W
    for brow in pbar(table, task_str):
        row = {x: re.sub(r'b\'(.*)\'', r'\1',
                         str(brow[x])) for x in brow.colnames}
        # Skip items with no bibliographic info aside from SIMBAD, too
        # error-prone
        if row['OTYPE'] == 'Candidate_SN*' and not row['SP_TYPE']:
            continue
        if (not row['COO_BIBCODE'] and not row['SP_BIBCODE'] and
                not row['SP_BIBCODE_2']):
            continue
        if any([x in row['MAIN_ID'] for x in simbadbannedcats]):
            continue
        if row['COO_BIBCODE'] and row['COO_BIBCODE'] in simbadbadnamebib:
            continue
        name = single_spaces(re.sub(r'\[[^)]*\]', '', row['MAIN_ID']).strip())
        if name in simbadbannednames:
            continue
        if is_number(name.replace(' ', '')):
            continue
        name = catalog.add_entry(name)
        source = (catalog.entries[name]
                  .add_source(name='SIMBAD astronomical database',
                              bibcode="2000A&AS..143....9W",
                              url="http://simbad.u-strasbg.fr/",
                              secondary=True))
        aliases = row['ID'].split(',')
        for alias in aliases:
            if any([x in alias for x in simbadbannedcats]):
                continue
            ali = single_spaces(re.sub(r'\[[^)]*\]', '', alias).strip())
            if is_number(ali.replace(' ', '')):
                continue
            if ali in simbadbannednames:
                continue
            ali = name_clean(ali)
            catalog.entries[name].add_quantity(SUPERNOVA.ALIAS,
                                               ali, source)
        if row['COO_BIBCODE'] and row['COO_BIBCODE'] not in simbadbadcoordbib:
            csources = ','.join(
                [source, catalog.entries[name].add_source(
                    bibcode=row['COO_BIBCODE'])])
            catalog.entries[name].add_quantity(SUPERNOVA.RA,
                                               row['RA'], csources)
            catalog.entries[name].add_quantity(SUPERNOVA.DEC,
                                               row['DEC'], csources)
        if row['SP_BIBCODE'] and row['SP_BIBCODE'] not in simbadbadtypebib:
            ssources = uniq_cdl([source,
                                 catalog.entries[name]
                                 .add_source(bibcode=row['SP_BIBCODE'])] +
                                ([catalog.entries[name]
                                  .add_source(bibcode=row['SP_BIBCODE_2'])] if
                                 row['SP_BIBCODE_2'] else []))
            catalog.entries[name].add_quantity(
                SUPERNOVA.CLAIMED_TYPE,
                (row['SP_TYPE']
                 .replace('SN.', '')
                 .replace('SN', '')
                 .replace('(~)', '')
                 .strip(': ')), ssources)
    catalog.journal_entries()
    return
    '''
    Check if directory exists - if it doesn't, make it, if it does, clear it out
    '''
    if os.path.isdir(dirname) == True:
        flist = glob.glob(dirname + "/*")
        for f in flist:
            os.remove(f)
    else:
        os.mkdir(dirname)


handler = Simbad()
handler.add_votable_fields("mk", "flux(K)", "v*")

### Forces only the closest match to be returned
handler.ROW_LIMIT = 1

crires_cat = Table.read("crires_fulldb.csv")
### Select frames within a given time period
date_init, date_final = (Time("2011-01-01"), Time("2014-12-31"))
timemask = np.logical_and(crires_cat['DATE OBS'] > date_init,
                          crires_cat['DATE OBS'] < date_final)
print("Filter by time: %s of %s targets remain" %
      (np.sum(timemask), len(timemask)))

wavmask = np.logical_and(1520 < crires_cat['INS WLEN CWLEN'],
                         crires_cat['INS WLEN CWLEN'] < 1620)

initmask = np.logical_and(wavmask, timemask)
print("Filter by wavelength: %s of %s targets remain" %
      (np.sum(initmask), len(initmask)))
def do_simbad(catalog):
    # Simbad.list_votable_fields()
    # Some coordinates that SIMBAD claims belong to the SNe actually belong to
    # the host.
    task_str = catalog.get_current_task_str()
    simbadmirrors = [
        'http://simbad.harvard.edu/simbad/sim-script',
        'http://simbad.u-strasbg.fr/simbad/sim-script'
    ]
    simbadbadcoordbib = [
        '2013ApJ...770..107C',
    ]
    simbadbadtypebib = [
        '2014ApJ...796...87I', '2015MNRAS.448.1206M', '2015ApJ...807L..18N'
    ]
    simbadbadnamebib = [
        '2004AJ....127.2809W',
        '2005MNRAS.364.1419Z',
        '2015A&A...574A.112D',
        '2011MNRAS.417..916G',
        '2002ApJ...566..880G',
        'url:CBAT',
        'url:GPSA',
    ]
    badurlbibname = ['url:TNS', 'url:ASASSN', 'url:Lasair', 'url:AAVSO']
    simbadbannedcats = ['[TBV2008]', 'OGLE-MBR']
    simbadbannednames = ['SN']
    customSimbad = Simbad()
    customSimbad.ROW_LIMIT = -1
    customSimbad.TIMEOUT = 120
    customSimbad.add_votable_fields('otype', 'sptype', 'sp_bibcode', 'id')
    table = []
    print(customSimbad.SIMBAD_URL)
    for mirror in simbadmirrors:
        customSimbad.SIMBAD_URL = mirror
        try:
            table = customSimbad.query_criteria(
                'maintypes=CV* | maintypes="CV?" | maintypes=No* | maintypes="No?"'
            )
        except Exception:
            continue
        else:
            if not table:
                continue
            break

    if not table:
        catalog.log.warning('SIMBAD unable to load, probably offline.')

    # 2000A&AS..143....9W
    for brow in pbar(table, task_str):
        row = {
            x: re.sub(r'b\'(.*)\'', r'\1', str(brow[x]))
            for x in brow.colnames
        }
        # Skip items with no bibliographic info aside from SIMBAD, too
        # error-prone
        #        print(row)
        if (not row['COO_BIBCODE'] and not row['SP_BIBCODE']
                and not row['SP_BIBCODE_2'] and not row['OTYPE'] == 'Nova'
                and not row['OTYPE'] == 'DwarfNova'):
            continue
        if any([x in row['MAIN_ID'] for x in simbadbannedcats]):
            continue
        if row['COO_BIBCODE'] and row['COO_BIBCODE'] in simbadbadnamebib:
            continue
        name = single_spaces(re.sub(r'\[[^)]*\]', '',
                                    row['MAIN_ID']).strip()).replace('*', '_')
        if name in simbadbannednames:
            continue
        if is_number(name.replace(' ', '')):
            continue
        name = catalog.add_entry(name)
        source = (catalog.entries[name].add_source(
            name='SIMBAD astronomical database',
            bibcode="2000A&AS..143....9W",
            url="http://simbad.u-strasbg.fr/",
            secondary=True)).replace('*', '_')
        if row['COO_BIBCODE'] == 'url:TNS':
            source = ','.join([
                source, catalog.entries[name].add_source(
                    name='Transient Name Server',
                    url='https://wis-tns.weizmann.ac.il/')
            ])
        if row['COO_BIBCODE'] == 'url:ASASSN':
            source = ','.join([
                source, catalog.entries[name].add_source(
                    name='ASAS-CV Transients',
                    bibcode="2014ApJ...788...48S",
                    url=
                    'http://www.astronomy.ohio-state.edu/~assassin/transients.html'
                )
            ])
        if row['COO_BIBCODE'] == 'url:Lasair':
            source = ','.join([
                source, catalog.entries[name].add_source(
                    name='lASAIR Transients and Variables',
                    bibcode="2019RNAAS...3...26S",
                    url='https://lasair.roe.ac.uk/')
            ])

        aliases = row['ID'].split(',')
        for alias in aliases:
            if any([x in alias for x in simbadbannedcats]):
                continue
            ali = single_spaces(re.sub(r'\[[^)]*\]', '',
                                       alias).strip()).replace('*', '_')
            if is_number(ali.replace(' ', '')):
                continue
            if ali in simbadbannednames:
                continue
            ali = name_clean(ali)
            catalog.entries[name].add_quantity(CATACLYSMIC.ALIAS, ali, source)
            catalog.entries[name].add_quantity(
                CATACLYSMIC.CLAIMED_TYPE,
                (row['OTYPE'].replace('CV.', 'CV').replace('CV', 'CV').replace(
                    '(~)', '').replace('CV?', 'Candidate').replace(
                        '*', '').replace('No?', 'Candidate Nova').strip(': ')),
                source)
        if row['COO_BIBCODE'] and row['COO_BIBCODE'] not in simbadbadcoordbib:
            csources = source
            if row['COO_BIBCODE'] not in badurlbibname:
                csources = ','.join([
                    source, catalog.entries[name].add_source(
                        bibcode=row['COO_BIBCODE'])
                ])
            catalog.entries[name].add_quantity(CATACLYSMIC.RA, row['RA'],
                                               csources)
            catalog.entries[name].add_quantity(CATACLYSMIC.DEC, row['DEC'],
                                               csources)
            catalog.entries[name].add_quantity(
                CATACLYSMIC.CLAIMED_TYPE,
                (row['OTYPE'].replace('CV.', 'CV').replace('CV', 'CV').replace(
                    '(~)', '').replace('CV?', 'Candidate').replace(
                        '*', '').replace('No?', 'Candidate Nova').strip(': ')),
                csources)
        if row['SP_BIBCODE'] and row['SP_BIBCODE'] not in simbadbadtypebib:
            ssources = source
            if row['SP_BIBCODE'] and row['SP_BIBCODE_2'] not in badurlbibname:
                ssources = uniq_cdl([
                    source, catalog.entries[name].add_source(
                        bibcode=row['SP_BIBCODE'])
                ] + ([
                    catalog.entries[name].add_source(
                        bibcode=row['SP_BIBCODE_2'])
                ] if row['SP_BIBCODE_2'] else []))
            catalog.entries[name].add_quantity(
                CATACLYSMIC.CLAIMED_TYPE,
                (row['OTYPE'].replace('CV.', 'CV').replace('CV', 'CV').replace(
                    '(~)', '').replace('CV?', 'Candidate').replace(
                        '*', '').replace('No?', 'Candidate Nova').strip(': ')),
                ssources)
        if row['OTYPE'] == 'Nova' and row['SP_BIBCODE'] == '' and row[
                'COO_BIBCODE'] == '':
            catalog.entries[name].add_quantity(CATACLYSMIC.RA, row['RA'],
                                               source)
            catalog.entries[name].add_quantity(CATACLYSMIC.DEC, row['DEC'],
                                               source)
            catalog.entries[name].add_quantity(CATACLYSMIC.CLAIMED_TYPE,
                                               (row['OTYPE']), source)
        if row['OTYPE'] == 'DwarfNova' and row['SP_BIBCODE'] == '' and row[
                'COO_BIBCODE'] == '':
            catalog.entries[name].add_quantity(CATACLYSMIC.RA, row['RA'],
                                               source)
            catalog.entries[name].add_quantity(CATACLYSMIC.DEC, row['DEC'],
                                               source)
            catalog.entries[name].add_quantity(CATACLYSMIC.CLAIMED_TYPE,
                                               (row['OTYPE']), source)
    catalog.journal_entries()
    return
Beispiel #15
0
def aw_main_process(
    code, day_start, day_end, mpf=12, directory=CATLISTDIR, filename=DEFAULTSETTINGSFILE, progressBar=None
):
    style_string = "font: bold on"
    style = xlwt.easyxf(style_string)

    code_table = loadTableParameters(directory, filename)

    curdate = day_start

    curmonth = curdate.month
    wb = xlwt.Workbook()
    sheetname = curdate.strftime("%h") + " " + str(curdate.year)[-2:]
    sheet_num = 0
    ws = wb.add_sheet(sheetname.decode("utf8"))
    rowx, colx = make_list_header(ws, code, code_table)

    customSimbad = Simbad()
    if len(code_table[code]["columns"]) > 0:
        customSimbad.add_votable_fields("id(" + code + ")")
    if code_table[code]["phi_vec"]:
        customSimbad.add_votable_fields("flux(V)")
    customSimbad.ROW_LIMIT = -1
    # additionalSimbad = {}
    # for x in code_table[code]['columns']:
    #    additionalSimbad[x] = Simbad()
    #    additionalSimbad[x].add_votable_fields('id('+x+')')

    all_days = (day_end - day_start).days
    for numday in xrange(all_days):
        objects_per_day = 0
        if curdate.month != curmonth:
            curmonth = curdate.month
            sheet_num += 1
            if sheet_num == mpf:
                filename = code.upper() + "_"
                filename += day_start.strftime("%d-%m-%Y")
                filename += "--"
                filename += (curdate - datetime.timedelta(days=1)).strftime("%d-%m-%Y")
                filename += ".xls"
                wb.save(OUTPUTDIR + filename)
                wb = xlwt.Workbook()
                sheet_num = 0
                day_start = curdate + datetime.timedelta(days=0)
            sheetname = curdate.strftime("%h") + " " + str(curdate.year)[-2:]
            ws = wb.add_sheet(sheetname.decode("utf8"))
            rowx, colx = make_list_header(ws, code, code_table)

        vphi = code_table[code]["vphi"][0][1]

        [[ra1, dec1], [ra2, dec2]] = ephsun(curdate)
        if dec1.f2s() < dec2.f2s():
            [c, d] = [dec1, dec2]
        else:
            [c, d] = [dec2, dec1]
        phi = coord(vphi, 0, 0, 1, "deg")
        ra_interest = [ra1.f2hd(), ra2.f2hd()]
        dec_interest = [(c - phi).f2hd(), (d + phi).f2hd()]
        query = formulate_query(code, ra_interest, dec_interest)

        result = customSimbad.query_criteria(query)
        if result is not None:
            lenres = len(result)
            result.sort("RA")
        else:
            print "Day %d/%d finished w/o output" % (numday + 1, all_days)
            if progressBar is not None:
                progressBar.setValue((numday + 1.0) / all_days * 100)
            curdate = curdate + datetime.timedelta(days=1)
            continue
        for i in xrange(lenres):
            row = result[i]
            [ra, dec] = [row["RA"], row["DEC"]]

            ra = parse_coord(ra, "ra", " ")
            dec = parse_coord(dec, "deg", " ")
            try:
                t = comp_time(ra1, ra2, ra)
            except:
                print ra1, ra2, ra, row["MAIN_ID"]
                continue
            dist = comp_dist(curdate.day, curdate.month, t, dec)
            hdist = abs(dist.f2s() / 3600.0)
            if code_table[code]["phi_vec"]:
                refuse = True
                vmag = row["FLUX_V"]
                if str(vmag) != "--":
                    for [vml, hdl] in code_table[code]["vphi"]:
                        if vml is None:
                            if hdist >= hdl:
                                break
                            else:
                                refuse = False
                                break
                        elif vmag < vml:
                            if hdist >= hdl:
                                break
                            else:
                                refuse = False
                                break
                if refuse:
                    print "refused: %s" % (row["MAIN_ID"])
                    continue

            line = [curdate.strftime("%d/%m/%Y"), t.__str__(rpar=0)]
            name = row["MAIN_ID"]
            if code_table[code]["use_name"]:
                if name.startswith("NAME "):
                    name = name.replace("NAME ", "")
                line.append(name)
            alt_names = Simbad.query_objectids(row["MAIN_ID"])
            for colname in code_table[code]["columns"]:
                locid = ""
                for an in alt_names:
                    if an["ID"].startswith(colname.upper() + " "):
                        if len(locid) > 0:
                            locid += " / "
                        lname = an["ID"].replace("NAME", "")
                        locid = locid + lname.replace("*", "")
                line.append(locid)
            if code_table[code]["phi_vec"]:
                line.append(str(row["FLUX_V"]))

            line.append(str(dist))
            line.append(str(ra))
            line.append(str(dec))
            rowx, colx = write_row(ws, line, rowx, colx)
            objects_per_day += 1
        curdate = curdate + datetime.timedelta(days=1)
        if objects_per_day > 0:
            rowx, colx = write_row(ws, [""], rowx, colx)
        print "Day %d/%d finished" % (numday + 1, all_days)
        if progressBar is not None:
            progressBar.setValue((numday + 1.0) / all_days * 100)
    filename = code.upper() + "_"
    filename += day_start.strftime("%d-%m-%Y")
    filename += "--"
    filename += day_end.strftime("%d-%m-%Y")
    filename += ".xls"
    full_filename = OUTPUTDIR + filename
    print full_filename
    wb.save(full_filename)
    return