srg/artsurvey/views.py
2024-04-26 12:43:00 +03:00

3481 lines
136 KiB
Python

import json
import csv
import time
from math import pi
import math
from collections import OrderedDict
import numpy as np
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.db.models import IntegerField, BooleanField
from django.db.models import F
from django.db.models import Q
from django.db.models import DecimalField, Value
from django.db.models import Max, Subquery, OuterRef, Min, Case, When, Min, Func
from django.db.models.functions.math import Sqrt, Cos, Power, Abs
from django.contrib.auth.models import User
from django.utils import timezone
from django.db.models import OuterRef, Exists
from django.db.models import Count
from django.core.files.base import ContentFile
from django.core.exceptions import PermissionDenied, FieldDoesNotExist
from django.db.models import BooleanField, DecimalField, CharField, Value
from astroquery.vizier import Vizier
from astroquery.skyview import SkyView
from django.utils.encoding import smart_str
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.coordinates import ICRS, Galactic, FK5
from astropy.coordinates import BarycentricTrueEcliptic
from astropy.coordinates import HeliocentricTrueEcliptic
from astropy.coordinates import GeocentricTrueEcliptic
from astropy_healpix import HEALPix
from astropy.coordinates.name_resolve import get_icrs_coordinates
from srglib.utils import srg_auth, srg_group_auth, srg_group_auth_stats, status_code
from srglib.utils import crossmatch
from srglib.utils import make_source_name
from srglib.utils import transfer_data
from artsurvey.models import MetaSource
from artsurvey.models import MetaComment
from artsurvey.models import ArtSurvey
from artsurvey.models import ArtSurveySource
from artsurvey.models import ArtSurveyParams
from artsurvey.models import ArtSurveyMatchParams
from artsurvey.models import OpticalCounterpart
from artsurvey.models import Category
from artsurvey.models import OtherName
from artsurvey.models import EnergyBand
from artsurvey.models import WiseCounterpart
from artsurvey.models import Catalog
from artsurvey.models import Upload
from artsurvey.models import ArtSelection
from artsurvey.models import ArtBasket, ArtBasketForm
from artsurvey.utils import get_artsurvey
from artsurvey.utils import get_energy_band
from artsurvey.utils import search_by_coords_artsurvey
from artsurvey.utils import search_by_name_artsurvey
from artsurvey.utils import get_sources_sorted
from artsurvey.utils import get_sources
from artsurvey.utils import get_heasarc_around
from artsurvey.utils import get_skymap_by_coords
from artsurvey.utils import ps1_getcolorim
from artsurvey.utils import ps1_getgrayim
from artsurvey.utils import ps1_fitsim
from artsurvey.utils import skyview_query
from artsurvey.forms import OpticalCounterpartForm
from artsurvey.forms import OtherNameForm
from artsurvey.forms import NotesForm
from artsurvey.forms import NotesSurveyForm
from artsurvey.forms import CnameForm
from artsurvey.forms import ArtSurveySourceForm
from artsurvey.forms import ArtSurveyParamsForm
from artsurvey.forms import ArtSurveyMatchParamsForm
from artsurvey.forms import CategoryForm
from artsurvey.forms import UploadForm
from artsurvey.forms import SearchCoordsForm
from artsurvey.forms import SearchNameForm
from artsurvey.forms import ResolveNameForm
from artsurvey.forms import MetaCommentForm
from artsurvey.forms import UserArtBasketListForm
from srgcat.models import SkyMapSource
from srgcat.models import SkyMaps
from heasarc.models import HeasarcSimpleClass, Heasarc4XMMDR9
from heasarc.models import GreenSNR
from heasarc.models import HeasarcUserCat, HeasarcUserCatForm
from astrobasis.models import GAIADR2
from astrobasis.models import GAIADR3 # this is in fact EDR3
from astrobasis.models import AllWise
from astrobasis.models import NVSS
from astrobasis.models import FIRST
from astrobasis.models import SUMSS
from astrobasis.models import VLASSfromVizieR
from astrobasis.models import BJfromVizieR
from astrobasis.models import GAIADR3fromVizieR # this is real DR3
from heasarc.models import HeasarcALLWISEAGN
from heasarc.models import HeasarcBase
from heasarc.utils import healpix_usercat
from heasarc.utils import match_usercat_all
from nasa.models import Category as AdsCategory
from nasa.models import Ads
def write_history(request, record):
user = get_object_or_404(User, pk=request.user.id)
params = get_object_or_404(ArtSurveyParams, owner=user)
now = timezone.localtime(timezone.now())
params.history+="<strong>{} (MSK)</strong> [{}] {}<br>".format(now.strftime("%d.%m.%Y %H:%M"),
request.user, record)
params.save()
def history(request):
users = User.objects.filter(groups__name__exact='srg-artxc-catalog').distinct()
return render(request,'artsurvey/history.html', {'users':users,})
def update_selected(user):
repeat = 0
srcs = user.artselection.sources.all()
for src in srcs:
print("Finding latest children for {}".format(src))
try:
child=src.children.all().filter(survey__name__exact=src.survey.name).latest()
""" latest child in the same survey """
except Exception as e:
print("--- {} {}".format(src,e))
continue
if(child):
user.artselection.sources.remove(src)
user.artselection.sources.add(child)
repeat = repeat + child.children.all().count()
return repeat
def profile(request):
while True:
repeat = update_selected(request.user)
if not repeat:
break
return render(request,'artsurvey/profile.html', {'user':request.user,})
def resolve_name(request,name):
srcs = ArtSurveySource.objects.filter(name__contains=name)
return HttpResponse("<h1>{}</h1>".format(name))
#return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
# Create your views here.
def bad_button(request):
if request.method =="POST":
if request.POST.get("operation") == "bad_submit" and request.is_ajax():
content_id=request.POST.get("content_id",None)
content=get_object_or_404(ArtSurveySource,pk=content_id)
print("AJAX Request: bad_submit for {}".format(content))
bad_category = get_object_or_404(Category,slug='false')
if content.category:
badmarked=False
else:
content.category=bad_category
content.save()
badmarked=True
ctx={"badmarked":badmarked,"content_id":content_id}
return HttpResponse(json.dumps(ctx), content_type='application/json')
else:
ctx={"badmarked":False,"content_id":content_id}
return HttpResponse(json.dumps(ctx), content_type='application/json')
def custom_error_403(request, exception):
return render(request, '403.html', {'exception':exception})
def custom_error_404(request, exception):
return render(request, '404.html', {})
def HttpResponseCSV(srcs, key=''):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.csv".format(key,time.strftime("%Y%m%d-%H%M%S"))
writer = csv.writer(response, csv.excel, delimiter=",")
#response.write(u'\ufeff'.encode('utf8'))
#response.write(u''.encode('utf8'))
#response.write(smart_str(u"#updated,2015-10-17T00:00:00Z"))
writer.writerow([
smart_str(u"NAME"),
smart_str(u"RA"),
smart_str(u"Dec"),
smart_str(u"GLON"),
smart_str(u"GLAT"),
smart_str(u"ELON"),
smart_str(u"ELAT"),
smart_str(u"EXT"),
smart_str(u"CNTS"),
smart_str(u"CNTS_ERR"),
smart_str(u"CNTS_BG"),
smart_str(u"EXPTIME"),
smart_str(u"FLUX"),
smart_str(u"FLUXERR_LO"),
smart_str(u"FLUXERR_UP"),
smart_str(u"SIG"),
smart_str(u"LOG_NFALSE"),
smart_str(u"DETLIKE"),
smart_str(u"ML_SIG"),
smart_str(u"ML_DETLIKE"),
smart_str(u"ML_NFALSE"),
smart_str(u"LOG_ML_NFALSE"),
smart_str(u"ML_RA"),
smart_str(u"ML_DEC"),
smart_str(u"ML_RADEC_ERR_90"),
smart_str(u"ML_RADEC_ERR_98"),
smart_str(u"ML_FLUX"),
smart_str(u"ML_FLUX_ERR"),
smart_str(u"ML_EXP"),
smart_str(u"class_id"),
smart_str(u"object_class"),
smart_str(u"redshift"),
smart_str(u"cname"),
smart_str(u"category"),
# smart_str(u"erosita data"),
# smart_str(u"erosita match"),
# smart_str(u"erosita match soft"),
# smart_str(u"erosita match med"),
# smart_str(u"erosita match hard"),
# smart_str(u"erosita soft"),
# smart_str(u"erosita med"),
# smart_str(u"erosita hard"),
# smart_str(u"erosita sep soft"),
# smart_str(u"erosita sep med"),
# smart_str(u"erosita sep hard"),
smart_str(u"notes"),
smart_str(u"paper_notes"),
smart_str(u"follow-up"),
# smart_str(u"bibcode"),
smart_str(u"turkish"),
smart_str(u"4XMM_count"),
smart_str(u"4XMM(offset, name, ra, dec, ep_5_flux)"),
smart_str(u"tentative"),
smart_str(u"gaia_primary"),
smart_str(u"gaia_ra"),
smart_str(u"gaia_dec"),
smart_str(u"gaia_sep"),
])
for src in srcs:
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
bibcode=[]
bibcode_notes=[]
for b in src.ads.all():
bibcode.append(b.bibcode)
bibcode_notes.append(b.notes)
bibcode_szip = zip(bibcode, bibcode_notes)
xmm = src.heasarc.instance_of(Heasarc4XMMDR9)
xmm_name=[]
xmm_separation=[]
xmm_ra=[]
xmm_dec=[]
xmm_ep_5_flux=[]
xmm_ep_5_flux_err=[]
xmm_count=xmm.count()
for xmmsrc in xmm:
xmm_name.append(xmmsrc.name)
xmm_ra.append(xmmsrc.ra)
xmm_dec.append(xmmsrc.dec)
xmm_ep_5_flux.append(xmmsrc.EP_5_FLUX)
xmm_ep_5_flux_err.append(xmmsrc.EP_5_FLUX_ERR)
xmm_separation.append(crd.separation(SkyCoord(xmmsrc.ra, xmmsrc.dec, frame="fk5", unit="deg")).arcsecond)
xmm_szip = sorted(zip(xmm_separation, xmm_name, xmm_ra, xmm_dec, xmm_ep_5_flux, xmm_ep_5_flux_err))
#crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
ecl_l=crd.transform_to(BarycentricTrueEcliptic).lon.value
ecl_b=crd.transform_to(BarycentricTrueEcliptic).lat.value
erosita_sep_soft=None
erosita_sep_med=None
erosita_sep_hard=None
erosita_match_soft=None
erosita_match_med=None
erosita_match_hard=None
erosita_soft=None
erosita_med=None
erosita_hard=None
erositamatch=hasattr(src, 'erositamatch')
if(erositamatch):
erosita_match_soft=src.erositamatch.match_soft
erosita_match_med=src.erositamatch.match_med
erosita_match_hard=src.erositamatch.match_hard
erosita_soft=src.erositamatch.ML_FLUX_0_soft
erosita_med=src.erositamatch.ML_FLUX_0_med
erosita_hard=src.erositamatch.ML_FLUX_0_hard
if(src.erositamatch.RA_fin_soft):
erosita_sep_soft = crd.separation(SkyCoord(src.erositamatch.RA_fin_soft, src.erositamatch.DEC_fin_soft, frame="fk5", unit="deg")).arcsecond
if(src.erositamatch.RA_fin_med):
erosita_sep_med = crd.separation(SkyCoord(src.erositamatch.RA_fin_med, src.erositamatch.DEC_fin_med, frame="fk5", unit="deg")).arcsecond
if(src.erositamatch.RA_fin_hard):
erosita_sep_hard = crd.separation(SkyCoord(src.erositamatch.RA_fin_hard, src.erositamatch.DEC_fin_hard, frame="fk5", unit="deg")).arcsecond
gaia_primary=False
gaia_ra=False
gaia_dec=False
gaia_sep=False
if not src.gaia3_primary is None:
gaia_primary=True
gaia_ra=src.gaia3_primary.ra
gaia_dec=src.gaia3_primary.dec
gaia_crd = SkyCoord(gaia_ra, gaia_dec, frame="fk5", unit="deg")
gaia_sep=gaia_crd.separation(crd).arcsecond
writer.writerow([
smart_str(src.name),
smart_str(src.ra),
smart_str(src.dec),
smart_str(src.lii),
smart_str(src.bii),
smart_str(ecl_l),
smart_str(ecl_b),
smart_str(src.ext),
smart_str(src.cnts),
smart_str(src.cnts_err),
smart_str(src.cnts_bg),
smart_str(src.exptime),
smart_str(src.flux),
smart_str(src.fluxerr_lo),
smart_str(src.fluxerr_up),
smart_str(src.sig),
smart_str(src.log_nfalse),
smart_str(src.detlike),
smart_str(src.ml_sig ),
smart_str(src.ml_detlike ),
smart_str(src.ml_nfalse),
smart_str(src.log_ml_nfalse),
smart_str(src.ml_ra),
smart_str(src.ml_dec),
smart_str(src.ml_radec_err_90),
smart_str(src.ml_radec_err_98),
smart_str(src.ml_flux),
smart_str(src.ml_flux_err),
smart_str(src.ml_exp),
smart_str(src.class_id),
smart_str(src.object_class),
smart_str(src.redshift),
smart_str(src.cname),
smart_str(src.category),
# smart_str(src.erosita_data),
# smart_str(erositamatch),
# smart_str(erosita_match_soft),
# smart_str(erosita_match_med),
# smart_str(erosita_match_hard),
# smart_str(erosita_soft),
# smart_str(erosita_med),
# smart_str(erosita_hard),
# smart_str(erosita_sep_soft),
# smart_str(erosita_sep_med),
# smart_str(erosita_sep_hard),
smart_str(src.notes),
smart_str(src.notes_paper),
smart_str(src.follow_up),
# smart_str([bibcode for bibcode in bibcode_szip]),
smart_str(src.turkish),
smart_str(xmm_count),
smart_str([xmm_name for xmm_name in xmm_szip]),
smart_str(src.class_tentative),
smart_str(gaia_primary),
smart_str(gaia_ra),
smart_str(gaia_dec),
smart_str(gaia_sep),
])
return response
def print_head(reg):
reg.append("#\n# SRG/ART-XC X-ray catalog system; Author: Roman Krivonos, email: krivonos@cosmos.ru\n")
reg.append("# (c) Space Research Institute, Moscow, Russia\n#\n")
reg.append("# Generated on {}\n#\n".format(time.strftime("%Y-%m-%d %H:%M:%S")))
reg.append("""# Description of region colours:
# Green colour represents SRG/ART-XC source with 15 arcsec radius (solid, for convenience) and 40 arcsec radius (dash, selection radius)
# Yellow color shows HEASARC counterparts with _their_ counterparts in magenta colour.\n#\n""")
def append_ds9_region_primary(reg,cntp):
if(cntp):
if (cntp.error_radius>0.0 and np.isnan(cntp.error_radius) == False):
reg.append("fk5;circle({}, {}, {}) # color=magenta text={{{}}}\n".format(cntp.ra,cntp.dec,cntp.error_radius/60/60,cntp.name))
else:
reg.append("fk5;point({}, {}) # point=cross color=magenta text={{{}}}\n".format(cntp.ra,cntp.dec,cntp.name))
def HttpResponseDS9_catalog(srcs, key='', print_flux=False):
reg=[]
print_head(reg)
reg.append("# This catalog contains SRGA sources and \"linked\" HEASARC sources with their associated (\"primary\") optical/radio counterparts\n#\n")
for src in srcs:
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
name = src.cname if(src.cname) else src.name
if(name == 'NEW X-RAY SOURCE'):
name = src.name
if(print_flux):
otype=src.get_otype()
otype = "?" if not (otype) else otype
reg.append("fk5;circle({}, {}, {}) # width=2 color=green text={{{} ({:.1E} {})}}\n".format(src.ra,src.dec,15/60/60,name,src.flux,otype))
else:
reg.append("fk5;circle({}, {}, {}) # width=2 color=green text={{{}}}\n".format(src.ra,src.dec,15/60/60,name))
for heasarc in src.heasarc_linked.all():
if (heasarc.error_radius>0.0):
reg.append("fk5;circle({}, {}, {}) # color=yellow text={{{}}}\n".format(heasarc.ra,
heasarc.dec,
heasarc.error_radius/60/60,
heasarc.name))
else:
reg.append("fk5;point({}, {}) # color=yellow text={{{}}}\n".format(heasarc.ra,
heasarc.dec,
heasarc.name))
append_ds9_region_primary(reg,heasarc.glimpse_primary)
append_ds9_region_primary(reg,heasarc.vlass_primary)
append_ds9_region_primary(reg,heasarc.gaia3_primary)
append_ds9_region_primary(reg,heasarc.twomass_primary)
append_ds9_region_primary(reg,heasarc.allwise_primary)
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.reg".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseDS9_catalog_paper(srcs, key=''):
reg=[]
print_head(reg)
reg.append("# This catalog contains SRGA sources\n#\n")
for src in srcs:
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
name = src.cname if(src.cname) else src.name
if(name == 'NEW X-RAY SOURCE'):
name = src.name
reg.append("fk5;circle({}, {}, {}) # width=2 color=green text={{{}}}\n".format(src.ra,src.dec,3/60,name))
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.reg".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseDS9_catalog_paper2(srcs, key=''):
reg=[]
print_head(reg)
reg.append("# This catalog contains SRGA sources\n#\n")
for src in srcs:
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
name = src.cname if(src.cname) else src.name
if(name == 'NEW X-RAY SOURCE'):
name = src.name
reg.append("fk5;circle({}, {}, {}) # width=2 color=green\n".format(src.ra,src.dec,3/60))
reg.append("fk5;text({}, {}) # color=green textrotate=0 text={{{}}}\n".format(src.ra,src.dec,name))
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.reg".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseDS9_catalog_paper_newonly(srcs, key=''):
reg=[]
print_head(reg)
reg.append("# This catalog contains SRGA NEW X-RAY sources\n#\n")
for src in srcs:
name = src.cname if(src.cname) else src.name
if(name == 'NEW X-RAY SOURCE'):
name = src.name
reg.append("fk5;circle({}, {}, {}) # width=2 color=green text={{{}}}\n".format(src.ra,src.dec,3/60,name))
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.reg".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseDS9_catalog_paper_known(srcs, key=''):
reg=[]
print_head(reg)
reg.append("# This catalog contains SRGA known sources\n#\n")
for src in srcs:
if not (src.cname == 'NEW X-RAY SOURCE'):
reg.append("fk5;circle({}, {}, {}) # width=2 color=magenta text={{{}}}\n".format(src.ra,src.dec,3/60,src.cname))
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.reg".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def append_ds9_region_m2m(reg,cntps):
for cntp in cntps:
if (cntp.error_radius>0.0):
reg.append("fk5;circle({}, {}, {}) # color=magenta text={{{}}}\n".format(cntp.ra,cntp.dec,cntp.error_radius/60/60,cntp.name))
else:
reg.append("fk5;point({}, {}) # point=cross color=magenta text={{{}}}\n".format(cntp.ra,cntp.dec,cntp.name))
def HttpResponseDS9_source(src, key=''):
reg=[]
print_head(reg)
reg.append("# {} from {} version {}\n#\n".format(src.name,src.survey.name,src.survey.version))
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
name = src.cname if(src.cname) else src.name
reg.append("fk5;circle({}, {}, {}) # color=green text={{{}}}\n".format(src.ra,src.dec,15/60/60,name))
reg.append("fk5;circle({}, {}, {}) # width=2 color=green dash=1 text={{{}}}\n".format(src.ra,src.dec,40/60/60,name))
for heasarc in src.heasarc.all():
if (heasarc.error_radius>0.0):
reg.append("fk5;circle({}, {}, {}) # color=yellow text={{{}}}\n".format(heasarc.ra,
heasarc.dec,
heasarc.error_radius/60/60,
heasarc.name))
else:
reg.append("fk5;point({}, {}) # color=yellow text={{{}}}\n".format(heasarc.ra,
heasarc.dec,
heasarc.name))
append_ds9_region_m2m(reg,heasarc.glimpse.all())
append_ds9_region_m2m(reg,heasarc.vlass.all())
append_ds9_region_m2m(reg,heasarc.gaia3.all())
append_ds9_region_m2m(reg,heasarc.twomass.all())
append_ds9_region_m2m(reg,heasarc.allwise.all())
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_all_{}.reg".format(src.name.replace(" ", "_"),time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseDS9_source_linked(src, key=''):
reg=[]
print_head(reg)
reg.append("# {} from {} version {}\n#\n".format(src.name,src.survey.name,src.survey.version))
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
name = src.cname if(src.cname) else src.name
reg.append("fk5;circle({}, {}, {}) # color=green text={{{}}}\n".format(src.ra,src.dec,15/60/60,name))
reg.append("fk5;circle({}, {}, {}) # width=2 color=green dash=1 text={{{}}}\n".format(src.ra,src.dec,40/60/60,name))
for heasarc in src.heasarc_linked.all():
if (heasarc.error_radius>0.0):
reg.append("fk5;circle({}, {}, {}) # color=yellow text={{{}}}\n".format(heasarc.ra,
heasarc.dec,
heasarc.error_radius/60/60,
heasarc.name))
else:
reg.append("fk5;point({}, {}) # color=yellow text={{{}}}\n".format(heasarc.ra,
heasarc.dec,
heasarc.name))
append_ds9_region_primary(reg,heasarc.glimpse_primary)
append_ds9_region_primary(reg,heasarc.vlass_primary)
append_ds9_region_primary(reg,heasarc.gaia3_primary)
append_ds9_region_primary(reg,heasarc.twomass_primary)
append_ds9_region_primary(reg,heasarc.allwise_primary)
response = HttpResponse(reg,content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+"{}_linked_{}.reg".format(src.name.replace(" ", "_"),time.strftime("%Y%m%d-%H%M%S"))
return response
"""
S1E0_log_nfalse
S1E0_flux
S1E0_err
S2E0_log_nfalse
S2E0_flux
S2E0_err
S1S2E0_log_nfalse
S1S2E0_flux
S1S2E0_err
S1S2E1_log_nfalse
S1S2E1_flux
S1S2E1_err
S1S2E2_log_nfalse
S1S2E2_flux
S1S2E2_err
S1S2E3_log_nfalse
S1S2E3_flux
S1S2E3_err
EXTENDED YES/NO
TYPE
"""
def HttpResponseCSV_catalog(srcs, key=''):
s12=get_artsurvey(12.5, archived=True)
s1=get_artsurvey(1.7)
s2=get_artsurvey(2.7)
e0=get_energy_band('E0')
e1=get_energy_band('E1')
e2=get_energy_band('E2')
e3=get_energy_band('E3')
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.csv".format(key,time.strftime("%Y%m%d-%H%M%S"))
writer = csv.writer(response, csv.excel)
writer.writerow([
smart_str(u"SRCID"),
smart_str(u"NAME"),
smart_str(u"RA"),
smart_str(u"DEC"),
#smart_str(u"GLON"),
#smart_str(u"GLAT"),bg
#smart_str(u"ELON"),
#smart_str(u"ELAT"),
#smart_str(u"S1E0_flux"),
#smart_str(u"S1E0_error"),
#smart_str(u"S1E0_ml"),
#smart_str(u"S2E0_flux"),
#smart_str(u"S2E0_error"),
#smart_str(u"S2E0_ml"),
smart_str(u"SNR"),
smart_str(u"Flux"),
smart_str(u"Flux_err_lo"),
smart_str(u"Flux_err_up"),
#smart_str(u"S1S2E0_ml"),
#smart_str(u"S1S2E1_flux"),
#smart_str(u"S1S2E1_error"),
#smart_str(u"S1S2E1_ml"),
#smart_str(u"S1S2E2_flux"),
#smart_str(u"S1S2E2_error"),
#smart_str(u"S1S2E2_ml"),
#smart_str(u"S1S2E3_flux"),
#smart_str(u"S1S2E3_error"),
#smart_str(u"S1S2E3_ml"),
smart_str(u"EXTENDED"),
smart_str(u"CNAME"),
smart_str(u"NEWXRAY"),
smart_str(u"OTYPE"),
smart_str(u"NOTES"),
])
counter=0
for src in srcs:
counter=counter+1
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
ecl_l=crd.transform_to(BarycentricTrueEcliptic).lon.value
ecl_b=crd.transform_to(BarycentricTrueEcliptic).lat.value
lii=crd.transform_to(Galactic).l.value
bii=crd.transform_to(Galactic).b.value
notes=''
cname=''
otype=''
extended=False
try:
s1e0=src.artsurveysource_set.all().get(survey=s1,band=e0,catalog__in=[src.catalog])
S1E0_ml=s1e0.log_nfalse
S1E0_flux=s1e0.flux
S1E0_error=s1e0.flux_err
cname=s.cname
otype=s.get_otype()
except:
S1E0_ml=None
S1E0_flux=None
S1E0_error=None
try:
s2e0=src.artsurveysource_set.all().get(survey=s2,band=e0,catalog__in=[src.catalog])
S2E0_ml=s2e0.log_nfalse
S2E0_flux=s2e0.flux
S2E0_error=s2e0.flux_err
cname=s.cname
otype=s.get_otype()
except:
S2E0_ml=None
S2E0_flux=None
S2E0_error=None
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e0,catalog__in=[src.catalog])
S12E0_ml=s.log_nfalse
S12E0_flux=s.flux
S12E0_err_lo=None
S12E0_err_up=None
cname=s.cname
otype=s.get_otype()
extended = True if (s.ext>1) else False
notes=s.notes_paper
if(notes==None):
notes=''
if(cname=='NEW X-RAY SOURCE'):
newxray=True
cname=''
else:
newxray=False
k=1e-12
err_up = s.fluxerr_up/k
err_lo = s.fluxerr_lo/k
if (s.ext>1):
extended = True
sign=None
flux0=s.flux/k
if(flux0>=10 and flux0<100):
flux=round(flux0/10)*10
if(flux0>=100 and flux0<1000):
flux=round(flux0/100)*100
if(flux0>=1000):
flux=flux0
S12E0_flux="{:.1f}".format(flux)
else:
extended = False
sign = "{:.1f}".format(s.sig)
S12E0_flux="{:.1f}".format(s.flux/k)
S12E0_err_lo="{:.1f}".format(err_lo)
S12E0_err_up="{:.1f}".format(err_up)
except Exception as e:
print("{} {}".format(src,e))
S12E0_ml=None
S12E0_flux=None
S12E0_err_lo=None
S12E0_err_up=None
sign=None
newxray=False
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e1,catalog__in=[src.catalog])
S12E1_ml=s.log_nfalse
S12E1_flux=s.flux
S12E1_error=s.flux_err
cname=s.cname
otype=s.get_otype()
except:
S12E1_ml=None
S12E1_flux=None
S12E1_error=None
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e2,catalog__in=[src.catalog])
S12E2_ml=s.log_nfalse
S12E2_flux=s.flux
S12E2_error=s.flux_err
cname=s.cname
otype=s.get_otype()
except:
S12E2_ml=None
S12E2_flux=None
S12E2_error=None
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e3,catalog__in=[src.catalog])
S12E3_ml=s.log_nfalse
S12E3_flux=s.flux
S12E3_error=s.flux_err
cname=s.cname
otype=s.get_otype()
except:
S12E3_ml=None
S12E3_flux=None
S12E3_error=None
if not cname.isprintable():
cname="*** NON-PRINTABLE *** {}".format(cname)
if not notes.isprintable():
notes="*** NON-PRINTABLE *** {}".format(notes)
writer.writerow([
smart_str(counter),
smart_str(src.name),
smart_str(src.ra),
smart_str(src.dec),
#smart_str(lii),
#smart_str(bii),
#smart_str(ecl_l),
#smart_str(ecl_b),
#smart_str(S1E0_flux),
#smart_str(S1E0_error),
#smart_str(S1E0_ml),
#smart_str(S2E0_flux),
#smart_str(S2E0_error),
#smart_str(S2E0_ml),
smart_str(sign),
smart_str(S12E0_flux),
smart_str(S12E0_err_lo),
smart_str(S12E0_err_up),
#smart_str(S12E0_ml),
#smart_str(S12E1_flux),
#smart_str(S12E1_error),
#smart_str(S12E1_ml),
#smart_str(S12E2_flux),
#smart_str(S12E2_error),
#smart_str(S12E2_ml),
#smart_str(S12E3_flux),
#smart_str(S12E3_error),
#smart_str(S12E3_ml),
smart_str(extended),
smart_str(cname),
smart_str(newxray),
smart_str(otype),
smart_str(notes),
])
return response
def HttpResponseCSV_catalog_paper2(srcs, key=''):
s15=get_artsurvey(12345.14, archived=True)
e5=get_energy_band('E5')
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.csv".format(key,time.strftime("%Y%m%d-%H%M%S"))
writer = csv.writer(response, csv.excel)
writer.writerow([
smart_str(u"SRCID"),
smart_str(u"NAME"),
smart_str(u"ML RA"),
smart_str(u"ML DEC"),
smart_str(u"ML R98"),
smart_str(u"ML SNR"),
smart_str(u"ML LOG_NFALSE"),
smart_str(u"ML Flux"),
smart_str(u"ML Flux_err"),
smart_str(u"CNAME"),
smart_str(u"NEWXRAY"),
smart_str(u"OTYPE"),
])
counter=0
for src in srcs:
counter=counter+1
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
ecl_l=crd.transform_to(BarycentricTrueEcliptic).lon.value
ecl_b=crd.transform_to(BarycentricTrueEcliptic).lat.value
lii=crd.transform_to(Galactic).l.value
bii=crd.transform_to(Galactic).b.value
notes=''
cname=''
otype=''
otype=src.get_otype()
cname=src.cname
if(src.cname=='NEW X-RAY SOURCE'):
newxray=True
cname=''
else:
newxray=False
k=1e-12
if not cname.isprintable():
cname="*** NON-PRINTABLE *** {}".format(cname)
if not notes.isprintable():
notes="*** NON-PRINTABLE *** {}".format(notes)
writer.writerow([
smart_str(counter),
smart_str(src.name),
smart_str(src.ml_ra),
smart_str(src.ml_dec),
smart_str(src.ml_radec_err_98),
smart_str(src.ml_sig),
smart_str(src.log_ml_nfalse),
smart_str(src.ml_flux/k),
smart_str(src.ml_flux_err/k),
smart_str(cname),
smart_str(newxray),
smart_str(otype),
])
return response
def HttpResponseTEX_catalog(srcs, key=''):
s12=get_artsurvey(12.5, archived=True)
s1=get_artsurvey(1.7)
s2=get_artsurvey(2.7)
e0=get_energy_band('E0')
e1=get_energy_band('E1')
e2=get_energy_band('E2')
e3=get_energy_band('E3')
response = HttpResponse(content_type='application/x-latex')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.tex".format(key,time.strftime("%Y%m%d-%H%M%S"))
writer = csv.writer(response, csv.excel, delimiter='&')
negative_flux_counter=0
counter=0
for src in srcs:
counter+=1
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
cname=''
otype=''
bands=''
halfs=''
notes_paper=''
extended=False
redshift=0.0
k=1e-12
# survey 1
try:
s=src.artsurveysource_set.all().get(survey=s1,band=e0,catalog=src.catalog)
err_up = s.fluxerr_up/k
err_lo = s.fluxerr_lo/k if(s.flux > s.fluxerr_lo) else s.flux
S1E0="${:.1f} -{:.1f} +{:.1f}$".format(s.flux/k,err_lo,err_up)
if(s.redshift):
redshift=s.redshift
cname=s.cname
otype=s.get_otype()
halfs+='1,'
except Exception as e:
print("{} {}".format(src,e))
S1E0=''
# survey 2
try:
s=src.artsurveysource_set.all().get(survey=s2,band=e0,catalog=src.catalog)
S2E0="${:.1f} -{:.1f} +{:.1f}$".format(s.flux/k,s.fluxerr_lo/k,s.fluxerr_up/k)
if(s.redshift):
redshift=s.redshift
cname=s.cname
otype=s.get_otype()
halfs+='2,'
except:
S2E0=''
# survey 1+2
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e0,catalog=src.catalog)
err_up = s.fluxerr_up/k
err_lo = s.fluxerr_lo/k
if(s.flux < s.fluxerr_lo):
err_lo = s.flux/k
negative_flux_counter=negative_flux_counter+1
print("{}: {}, sign: {:.1f}, flux: {:.1f} -{:.1f} +{:.1f}".format(negative_flux_counter,s,s.sig,s.flux/k,s.fluxerr_lo/k,s.fluxerr_up/k))
if(s.redshift):
redshift=s.redshift
if(s.notes_paper):
notes_paper='$^{c)}$'
cname=s.cname
otype="{}{}".format(s.get_otype(),notes_paper)
# extended information is only available in S12!
if (s.ext>1):
extended = True
sign=""
flux0=s.flux/k
if(flux0>=10 and flux0<100):
flux=round(flux0/10)*10
if(flux0>=100 and flux0<1000):
flux=round(flux0/100)*100
S12E0="${{\\sim}}{}$".format(int(flux))
else:
extended = False
sign = "{:.1f}".format(s.sig)
S12E0="${:.1f} (-{:.1f} +{:.1f})$".format(s.flux/k,err_lo,err_up)
except:
S12E0=''
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e1,catalog=src.catalog)
S12E1="${:.1f} -{:.1f} +{:.1f}$".format(s.flux/k,s.fluxerr_lo/k,s.fluxerr_up/k)
if not redshift>0.0:
redshift=s.redshift
if not cname:
cname=s.cname
if not otype:
otype=s.get_otype()
bands+='1,'
except:
S12E1=''
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e2,catalog=src.catalog)
S12E2="${:.1f} -{:.1f} +{:.1f}$".format(s.flux/k,s.fluxerr_lo/k,s.fluxerr_up/k)
if not redshift>0.0:
redshift=s.redshift
if not cname:
cname=s.cname
if not otype:
otype=s.get_otype()
bands+='2,'
except:
S12E2=''
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e3,catalog__in=[src.catalog])
S12E3="${:.1f} -{:.1f} +{:.1f}$".format(s.flux/k,s.fluxerr_lo/k,s.fluxerr_up/k)
if not redshift>0.0:
redshift=s.redshift
if not cname:
cname=s.cname
if not otype:
otype=s.get_otype()
bands+='3,'
except:
S12E3=''
if(bands):
bands="E{}".format(bands)[:-1]
if(halfs):
halfs="S{}".format(halfs)[:-1]
name=src.name.replace('SRGA','').replace('-','--')
if(cname=='NEW X-RAY SOURCE'):
name="{{\\bf {} }}".format(name)
cname=''
if(extended):
name="{}$^{{b)}}$".format(name)
if(redshift>0.0):
print_redshift="{:.4f}".format(redshift)
else:
print_redshift=''
writer.writerow([
smart_str("{:03d}".format(counter)),
smart_str(name),
smart_str("{:.4f}".format(src.ra)),
smart_str("{:.4f}".format(src.dec)),
##smart_str(S1E0),
##smart_str(S2E0),
smart_str(sign),
smart_str(S12E0),
##smart_str(S12E1),
##smart_str(S12E2),
##smart_str(S12E3),
#smart_str(bands),
#smart_str(halfs),
smart_str(cname),
smart_str(print_redshift),
smart_str(otype+'\\\\'),
])
return response
def HttpResponseTEX_notes(srcs, key=''):
s12=get_artsurvey(12.5, archived=True)
s1=get_artsurvey(1.7)
s2=get_artsurvey(2.7)
e0=get_energy_band('E0')
e1=get_energy_band('E1')
e2=get_energy_band('E2')
e3=get_energy_band('E3')
file_data=''
counter=0
for src in srcs:
counter+=1
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
notes=''
# survey 1
try:
s=src.artsurveysource_set.all().get(survey=s1,band=e0,catalog=src.catalog)
cname=s.notes_paper
except Exception as e:
print("{} {}".format(src,e))
pass
# survey 2
try:
s=src.artsurveysource_set.all().get(survey=s2,band=e0,catalog=src.catalog)
notes=s.notes_paper
except:
pass
# survey 1+2
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e0,catalog=src.catalog)
notes=s.notes_paper
except:
pass
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e1,catalog=src.catalog)
notes=s.notes_paper
except:
pass
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e2,catalog=src.catalog)
notes=s.notes_paper
except:
pass
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e3,catalog__in=[src.catalog])
notes=s.notes_paper
except:
pass
if(notes):
file_data+="\\subsection*{{ {} }}\n".format(src.name)
file_data+="{}\n".format(notes)
response = HttpResponse(file_data, content_type='application/text charset=utf-8')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.tex".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseTEX_notes_paper2(srcs, key=''):
file_data=''
for src in srcs:
notes=''
notes=src.notes_paper
if(notes):
file_data+="\\subsection*{{ {} }}\n".format(src.name)
file_data+="{}\n".format(notes)
response = HttpResponse(file_data, content_type='application/text charset=utf-8')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.tex".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def HttpResponseTEX_catalog_paper2(srcs, key=''):
response = HttpResponse(content_type='application/x-latex')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.tex".format(key,time.strftime("%Y%m%d-%H%M%S"))
writer = csv.writer(response, csv.excel, delimiter='&')
negative_flux_counter=0
counter=0
for src in srcs:
counter+=1
crd = SkyCoord(src.ml_ra, src.ml_dec, frame="fk5", unit="deg")
cname=''
otype=''
bands=''
halfs=''
notes_paper=''
redshift=0.0
k=1e-12
cname=src.cname
otype=src.get_otype()
if(src.redshift):
redshift=src.redshift
if(src.notes_paper):
notes_paper='$^{c)}$'
cname=src.cname
otype="{}{}".format(src.get_otype(),notes_paper)
#name=src.name.replace('SRGA','').replace('-','--')
name=src.name.replace('SRGA','').replace('-','$-$')
if(cname=='NEW X-RAY SOURCE'):
#name="{{\\bf {} }}".format(name)
name="{}$^{{b)}}$".format(name)
cname=''
if(redshift>0.0):
print_redshift="{:.4f}".format(redshift)
else:
print_redshift=''
if not cname.isprintable():
cname="*** NON-PRINTABLE *** {}".format(cname)
sign_str = '$-$' if(src.ml_dec<0.0) else ''
writer.writerow([
smart_str("N{:03d}".format(counter)),
smart_str(name),
smart_str("{:.4f}".format(src.ml_ra)),
smart_str("{}{:.4f}".format(sign_str,abs(src.ml_dec))),# make $-$ !!!
smart_str("{:.1f}".format(src.ml_radec_err_98)),
smart_str("{:.2f}".format(src.ml_sig)),
smart_str("{:.2f} $\\pm$ {:.2f}".format(src.ml_flux/k,src.ml_flux_err/k)),
smart_str(cname),
smart_str(print_redshift),
smart_str(otype+'\\\\'),
])
return response
def HttpResponseTEX_notes(srcs, key=''):
s12=get_artsurvey(12.5, archived=True)
s1=get_artsurvey(1.7)
s2=get_artsurvey(2.7)
e0=get_energy_band('E0')
e1=get_energy_band('E1')
e2=get_energy_band('E2')
e3=get_energy_band('E3')
file_data=''
counter=0
for src in srcs:
counter+=1
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
notes=''
# survey 1
try:
s=src.artsurveysource_set.all().get(survey=s1,band=e0,catalog=src.catalog)
cname=s.notes_paper
except Exception as e:
print("{} {}".format(src,e))
pass
# survey 2
try:
s=src.artsurveysource_set.all().get(survey=s2,band=e0,catalog=src.catalog)
notes=s.notes_paper
except:
pass
# survey 1+2
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e0,catalog=src.catalog)
notes=s.notes_paper
except:
pass
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e1,catalog=src.catalog)
notes=s.notes_paper
except:
pass
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e2,catalog=src.catalog)
notes=s.notes_paper
except:
pass
try:
s=src.artsurveysource_set.all().get(survey=s12,band=e3,catalog__in=[src.catalog])
notes=s.notes_paper
except:
pass
if(notes):
file_data+="\\subsection*{{ {} }}\n".format(src.name)
file_data+="{}\n".format(notes)
response = HttpResponse(file_data, content_type='application/text charset=utf-8')
response['Content-Disposition'] = 'attachment; filename='+"{}_{}.tex".format(key,time.strftime("%Y%m%d-%H%M%S"))
return response
def annotate_separation(srcs, erosita, erosita_crd, source_crd):
srcs = srcs.annotate(separation=Value(0.0, output_field=DecimalField()))
srcs = srcs.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for src in srcs:
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
src.separation=source_crd.separation(crd).arcsecond
if not erosita is None:
src.erosita_separation=erosita_crd.separation(crd).arcsecond
return srcs
def get_csv_selection(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseCSV(srcs, key='artsurvey_selection')
def get_csv_catalog(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2021)
bands = EnergyBand.objects.all()
srcs = MetaSource.objects.filter(catalog=catalog).order_by("ra")
return HttpResponseCSV_catalog(srcs, key='artxc_catalog')
def get_csv_catalog_paper2(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2023)
srcs = ArtSurveySource.objects.all().filter(catalog=catalog).order_by("ra")
return HttpResponseCSV_catalog_paper2(srcs, key='artxc_catalog_paper2')
def get_tex_paper2_catalog(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2023)
srcs = ArtSurveySource.objects.all().filter(catalog=catalog).order_by("ra")
return HttpResponseTEX_catalog_paper2(srcs, key='artxc_paper2_catalog')
def get_tex_paper2_notes(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2023)
srcs = ArtSurveySource.objects.all().filter(catalog=catalog).order_by("ra")
return HttpResponseTEX_notes_paper2(srcs, key='artxc_paper2_notes')
def get_tex_catalog(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2021)
bands = EnergyBand.objects.all()
srcs = MetaSource.objects.filter(catalog=catalog).order_by("ra")
return HttpResponseTEX_catalog(srcs, key='artsurvey_catalog')
def get_tex_notes(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2021)
bands = EnergyBand.objects.all()
srcs = MetaSource.objects.filter(catalog=catalog).order_by("ra")
return HttpResponseTEX_notes(srcs, key='artsurvey_notes')
def get_csv_all(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseCSV(srcs, key='artsurvey_catalog')
def get_ds9_all(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseDS9_catalog(srcs, key='artxc_catalog')
def get_ds9_all_flux(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseDS9_catalog(srcs, key='artxc_catalog_extended',print_flux=True)
def get_ds9_all_paper(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseDS9_catalog_paper(srcs, key='artxc_catalog_paper')
def get_ds9_all_paper2(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseDS9_catalog_paper2(srcs, key='artxc_catalog_paper2')
def get_ds9_all_paper_newonly(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseDS9_catalog_paper_newonly(srcs, key='artxc_catalog_paper_newonly')
def get_ds9_all_paper_known(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return HttpResponseDS9_catalog_paper_known(srcs, key='artxc_catalog_paper_known')
def get_artsurvey_source_ds9(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
return HttpResponseDS9_source(src, key='artxc_source')
def get_artsurvey_source_ds9_linked(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
return HttpResponseDS9_source_linked(src, key='artxc_source')
"""
def get_sources2(owner):
try:
params = ArtSurveyParams.objects.get(owner=owner)
if not params.sign_threshold is None:
return ArtSurveySource.objects.all().filter(sig__gt=params.sign_threshold)
except ArtSurveyParams.DoesNotExist:
pass
return ArtSurveySource.objects.all()
"""
def types(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
params = get_object_or_404(ArtSurveyParams, owner=request.user)
survey = params.survey
band = get_object_or_404(EnergyBand, slug=params.band)
types = HeasarcSimpleClass.objects.all()
return render(request,'artsurvey/types.html', {'types':types,'survey':survey,})
def summary(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
surveys = ArtSurvey.objects.all()#.filter(name__startswith="GP").exclude(hidden=True)
bands = EnergyBand.objects.all()
return render(request,'artsurvey/summary.html', {'surveys':surveys,'bands':bands,})
"""
def show_turkish(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = ArtSurveySource.objects.all().filter(Q(turkish=True)&Q(survey__hidden=False))
return render(request,'artsurvey/turkish.html', {'srcs':srcs,'ntotal':srcs.count(),'categories':Category.objects.all(),})
"""
def show_turkish(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs=MetaSource.objects.filter(artsurveysource__turkish=True).distinct().order_by("ra")
#srcs = MetaSource.objects.filter(catalog=catalog).order_by("ra")
return render(request,'artsurvey/turkish.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra").annotate(allwiseagn=Value(0, output_field=IntegerField()))
for src in srcs:
src.allwiseagn=src.heasarc.all().instance_of(HeasarcALLWISEAGN).count()
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'categories':Category.objects.all(),})
def tex(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
srcs = srcs.annotate(refs=Value('', output_field=CharField()))
refdict = {}
counter=1
for src in srcs:
if(src.object_class):
#src.otype=fixtype(src.catalog.object_class)
src.otype=src.get_otype()
for ref in src.ads.all():
if(ref in src.ads_hidden.all()):
continue
"""
if(ref.hidden):
continue
"""
k="\cite{%s}" % ref.bibcode
if k in refdict:
pass
else:
refdict[k]=counter
counter=counter+1
src.refs=src.refs+"{},".format(refdict[k])
if(src.refs):
src.refs = src.refs[:-1]
src.refs=src.refs+';'
bibtex = []
bibtex_paper = []
for src in srcs:
for ref in src.ads.all():
if ref.bibtex:
bibtex.append(ref.bibtex)
if src.bibtex_paper:
bibtex_paper.append(src.bibtex_paper)
return render(request,'artsurvey/tex.html', {'srcs':srcs,'ntotal':srcs.count(),'refdict':refdict,'bibtex':bibtex,'bibtex_paper':bibtex_paper})
def show_type(request, type_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(object_class__class_id=type_id).order_by("ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'categories':Category.objects.all(),})
def artsurvey_crossmatch(request):
""" Edit user session parameters """
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
if request.method == 'POST':
form = ArtSurveyMatchParamsForm(request.POST)
if form.is_valid():
band1 = form.cleaned_data['band1']
survey1 = form.cleaned_data['survey1']
band2 = form.cleaned_data['band2']
survey2 = form.cleaned_data['survey2']
#log_nfalse_min1 = form.cleaned_data['log_nfalse_min1']
sign_min1 = form.cleaned_data['sign_min1']
sign_max1 = form.cleaned_data['sign_max1']
log_ml_nfalse_min1 = form.cleaned_data['log_ml_nfalse_min1']
log_ml_nfalse_max1 = form.cleaned_data['log_ml_nfalse_max1']
#log_nfalse_min2 = form.cleaned_data['log_nfalse_min2']
sign_min2 = form.cleaned_data['sign_min2']
sign_max2 = form.cleaned_data['sign_max2']
log_ml_nfalse_min2 = form.cleaned_data['log_ml_nfalse_min2']
log_ml_nfalse_max2 = form.cleaned_data['log_ml_nfalse_max2']
Rmax = form.cleaned_data['Rmax']
maxdist = form.cleaned_data['maxdist']
f2f1_ratio_min = form.cleaned_data['f2f1_ratio_min']
f2f1_ratio_max = form.cleaned_data['f2f1_ratio_max']
try:
params = ArtSurveyMatchParams.objects.get(owner=request.user)
except ArtSurveyMatchParams.DoesNotExist:
params=form.save(commit=False)
params.owner=request.user
params.save()
params.survey1=survey1
params.band1=band1
params.survey2=survey2
params.band2=band2
#params.log_nfalse_min1=log_nfalse_min1
params.sign_max1=sign_max1
params.sign_min1=sign_min1
params.log_ml_nfalse_min1=log_ml_nfalse_min1
params.log_ml_nfalse_max1=log_ml_nfalse_max1
#params.log_nfalse_min2=log_nfalse_min2
params.sign_max2=sign_max2
params.sign_min2=sign_min2
params.log_ml_nfalse_min2=log_ml_nfalse_min2
params.log_ml_nfalse_max2=log_ml_nfalse_max2
if(Rmax):
params.Rmax=Rmax
else:
params.Rmax=40
if(maxdist):
params.maxdist=maxdist
else:
params.maxdist=120
params.f1f2_ratio_min=f2f1_ratio_min
params.f1f2_ratio_max=f2f1_ratio_max
params.save()
b1 = get_object_or_404(EnergyBand, slug=band1)
b2 = get_object_or_404(EnergyBand, slug=band2)
srcs1=survey1.artsurveysource_set.all().filter(band=b1)
"""
if not params.log_ml_nfalse_min is None:
q=q.filter(Q(log_ml_nfalse__lte=params.log_ml_nfalse_min) | Q(ext__gte=1))
if not params.log_ml_nfalse_max is None:
q=q.filter(Q(log_ml_nfalse__gt=params.log_ml_nfalse_max) | Q(ext__gte=1))
"""
try:
if(sign_min1):
srcs1=srcs1.filter(sig__gt=sign_min1)
if(log_ml_nfalse_min1):
srcs1=srcs1.filter(log_ml_nfalse__lte=log_ml_nfalse_min1)
if(log_ml_nfalse_max1):
srcs1=srcs1.filter(log_ml_nfalse__gt=log_ml_nfalse_max1)
if(sign_max1):
srcs1=srcs1.filter(sig__lt=sign_max1)
except:
pass
srcs2=survey2.artsurveysource_set.all().filter(band=b2)
try:
if(sign_min2):
srcs2=srcs2.filter(sig__gt=sign_min2)
if(sign_max1):
srcs2=srcs2.filter(sig__lt=sign_max2)
if(log_ml_nfalse_min2):
srcs2=srcs2.filter(log_ml_nfalse__lte=log_ml_nfalse_min2)
if(log_ml_nfalse_max2):
srcs2=srcs2.filter(log_ml_nfalse__gt=log_ml_nfalse_max2)
except:
pass
match_count, match1_count,match2_count,match3_count,match4_count, match_list, missed_count1, missed_list1, missed_count2, missed_list2, match_count2,match1_count2, match2_count2,match3_count2,match4_count2 = crossmatch(srcs1, srcs2, minrad=Rmax, maxdist=maxdist, ratio_min=f2f1_ratio_min, ratio_max=f2f1_ratio_max)
return render(request, 'artsurvey/crossmatch.html', {'form':form,'params':params,
'nrows1':srcs1.count(),
'nrows2':srcs2.count(),
'match_count':match_count,
'match_count2':match_count2,
'match1_count':match1_count,
'match2_count':match2_count,
'match3_count':match3_count,
'match4_count':match4_count,
'match1_count2':match1_count2,
'match2_count2':match2_count2,
'match3_count2':match3_count2,
'match4_count2':match4_count2,
'match_list':match_list,
'missed_count1':missed_count1,
'missed_list1':missed_list1,
'missed_count2':missed_count2,
'missed_list2':missed_list2,})
else:
pass
try:
params = ArtSurveyMatchParams.objects.get(owner=request.user)
except ArtSurveyMatchParams.DoesNotExist:
params = ArtSurveyMatchParams()
params.owner=request.user
params.save()
form = ArtSurveyMatchParamsForm(instance=params)
return render(request, 'artsurvey/crossmatch.html', {'form': form,'params':params,})
def get_heasarc_statistics(srcs):
histogram = {}
for s in srcs:
cnt = s.count_heasarc
if not cnt in histogram.keys():
histogram[cnt] = {'total': 0,}
histogram[cnt]['total'] += 1
return OrderedDict(sorted(histogram.items()))
def get_reverse_matching_statistics(srcs,class_name):
my_filter = {}
my_filter["{}__isnull".format(class_name)] = False
reverse_match={}
for s in srcs:
already_taken=[]
heasarcs = s.heasarc.filter(**my_filter)
for h in heasarcs:
if not h.name in reverse_match.keys():
reverse_match[h.name] = {'total': 1,'list': "<a href={}>{}</a>".format(s.get_absolute_url(),s.name)}
already_taken.append(s.pk)
else:
if not s.pk in already_taken:
reverse_match[h.name]['total'] += 1
reverse_match[h.name]['list'] += ", <a href={}>{}</a>".format(s.get_absolute_url(),s.name)
already_taken.append(s.pk)
return reverse_match
def swiftbat105m_filter(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcswiftbat105m__isnull=False).annotate(count_heasarc=Count('heasarc')).order_by("-ra")
#.distinct('name')#.order_by("-ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcswiftbat105m"),})
def swiftbat105m_exclude(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).exclude(heasarc__heasarcswiftbat105m__isnull=False).annotate(count_heasarc=Count('heasarc')).order_by("-ra")
#.distinct('name')#.order_by("-ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcswiftbat105m"),})
def swiftbat105m_filter_csv(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcswiftbat105m__isnull=False).annotate(count_heasarc=Count('heasarc')).order_by("-ra")
#.distinct('name')#.order_by("-ra")
return HttpResponseCSV(srcs, key='artsurvey_filter_bat105m')
def swiftbat105m_exclude_csv(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).exclude(heasarc__heasarcswiftbat105m__isnull=False).annotate(count_heasarc=Count('heasarc')).order_by("-ra")
#.distinct('name')#.order_by("-ra")
return HttpResponseCSV(srcs, key='artsurvey_exclude_bat105m')
def rass2rxs_filter(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcrass2rxs__isnull=False).annotate(count_heasarc=Count('heasarc'))
#.distinct('name')#.order_by("-ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcrass2rxs"),})
def rass2rxs_exclude(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).exclude(heasarc__heasarcrass2rxs__isnull=False).annotate(count_heasarc=Count('heasarc'))
#.distinct('name')#.order_by("-ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcrass2rxs"),})
def rass2rxs_filter_csv(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcrass2rxs__isnull=False).annotate(count_heasarc=Count('heasarc'))
return HttpResponseCSV(srcs, key='artsurvey_filter_rass')
def rass2rxs_exclude_csv(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).exclude(heasarc__heasarcrass2rxs__isnull=False).annotate(count_heasarc=Count('heasarc'))
return HttpResponseCSV(srcs, key='artsurvey_exclude_rass')
def xmmdr10(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarc4xmmdr10__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def xmmdr12(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarc4xmmdr12__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def xmmsl2(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcxmmsl2__isnull=False).annotate(count_heasarc=Count('heasarc'))
srcs = srcs.annotate(count_heasarc=Count('heasarc'))
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcxmmsl2"),})
def intrefcat(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcintrefcat__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def maxigsc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcmaxigschgl__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def maxi3(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarc3maxi__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def maxi7yr(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcmaxi7yr__isnull=False).annotate(count_heasarc=Count('heasarc'))
#.distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcmaxi7yr"),})
def fermi(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarc4fgl__isnull=False).annotate(count_heasarc=Count('heasarc')).order_by("-ra")
#.distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarc4fgl"),})
def exclude_xray(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).exclude(xrays__exact=True)
""" see 00_artsurvey_mark_xrays script """
#srcs=srcs.exclude(heasarc__heasarc4fgl__isnull=False)
#srcs = srcs.exclude(heasarc__heasarcrass2rxs__isnull=False)
#srcs = srcs.exclude(heasarc__heasarcswiftbat105m__isnull=False)
#srcs = srcs.exclude(heasarc__heasarcxmmsl2__isnull=False)
#srcs = srcs.exclude(heasarc__heasarcmaxi7yr__isnull=False)
#srcs = srcs.exclude(heasarc__heasarcintegral2020__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def filter_xray(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(xrays__exact=True).filter(cname__contains='NEW X-RAY SOURCE')
#.distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def rxte(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcxteasscat__isnull=False).distinct('name')
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def integral2020(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).filter(heasarc__heasarcintegral2020__isnull=False).annotate(count_heasarc=Count('heasarc')).order_by("-ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'histogram':get_heasarc_statistics(srcs),
'reverse':get_reverse_matching_statistics(srcs,"heasarcintegral2020"),})
def index_sort_ra_desc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("-ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_ra_asc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count()})
def index_sort_nfalse_desc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("-log_ml_nfalse")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_nfalse_asc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("log_ml_nfalse")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count()})
def index_sort_dec_desc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("-dec")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_dec_asc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).all().order_by("dec")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_sign_desc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("-ml_sig")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_sign_asc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ml_sig")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_flux_desc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("-ml_flux")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_sort_flux_asc(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
srcs = get_sources(request.user).order_by("ml_flux")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def index_catalog(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2021)
bands = EnergyBand.objects.all()
srcs = MetaSource.objects.filter(catalog=catalog).order_by("ra")
return render(request,'artsurvey/catalog.html', {'srcs':srcs,'bands':bands,'ntotal':srcs.count(),})
def index_catalog_paper2(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
catalog=Catalog.objects.get(year=2023)
#bands = EnergyBand.objects.all()
survey = get_object_or_404(ArtSurvey, version=12345.14)
band = EnergyBand.objects.get(slug='E5')
srcs = ArtSurveySource.objects.all().filter(survey=survey).filter(band=band).filter(catalog=catalog).order_by("ra")
return render(request,'artsurvey/catalog_paper2.html', {'srcs':srcs,'ntotal':srcs.count(),})
def create_artsurvey(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
try:
src = SkyMapSource.objects.get(pk=source_id)
except:
return HttpResponse("This SkyMapSource was not found")
if not (src.artsurvey_source):
artsource = ArtSurveySource.objects.create_source(src)
artsource.save()
srcs = get_sources(request.user)
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),})
def show_metasource(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(MetaSource, pk=source_id)
srcs = src.artsurveysource_set.all().order_by("-modified")#.order_by("survey__version")
bands = EnergyBand.objects.all()
comment_form = MetaCommentForm()
comments = src.comments.all()
if request.method == 'POST':
comment_form = MetaCommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.metasource = src
new_comment.owner = request.user
new_comment.save()
else:
pass
comment_form = MetaCommentForm()
return render(request,'artsurvey/metasource.html', {'comments':comments,'comment_form':comment_form,'src':src,'srcs':srcs,'bands':bands,})
def show_metasource_band(request, source_id, band_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(MetaSource, pk=source_id)
band = get_object_or_404(EnergyBand, pk=band_id)
srcs = src.artsurveysource_set.all().filter(band=band).order_by("survey__version")
bands = EnergyBand.objects.all()
comment_form = MetaCommentForm()
comments = src.comments.all()
if request.method == 'POST':
comment_form = MetaCommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.metasource = src
new_comment.owner = request.user
new_comment.save()
else:
comment_form = MetaCommentForm()
return render(request,'artsurvey/metasource.html', {'comments':comments,'comment_form':comment_form,'src':src,'srcs':srcs,'bands':bands,})
def markbad_artsurvey_source(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
write_history(request, 'Source {} <span style="color:red">MARK BAD</span>'.format(src))
bad_category = get_object_or_404(Category,slug='false')
src.category=bad_category
src.save()
return HttpResponseRedirect(src.get_absolute_url())
#return HttpResponseRedirect(reverse('artsurvey index'))
def delete_artsurvey_source(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
write_history(request, 'Source {} <span style="color:red">DELETE</span>'.format(src))
src.delete()
#bad_category = get_object_or_404(Category,slug='false')
#src.category=bad_category
#src.save()
#return HttpResponseRedirect(src.get_absolute_url())
return HttpResponseRedirect(reverse('artsurvey index'))
def delete_metasource(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(MetaSource, pk=source_id)
write_history(request, 'MetaSource {} <span style="color:red">DELETE</span>'.format(src))
src.delete()
return HttpResponseRedirect(reverse('artsurvey index'))
def delete_paper_metasource(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(MetaSource, pk=source_id)
write_history(request, 'MetaSource {} <span style="color:red">DELETE</span> Paper'.format(src))
srcs = src.artsurveysource_set.all().order_by("survey__version")
bands = EnergyBand.objects.all()
src.catalog = None
src.save()
return render(request,'artsurvey/metasource.html', {'src':src,'srcs':srcs,'bands':bands,})
def show_artsurvey_source(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
c = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
try:
erosita = src.erositamatch
erosita_crd = SkyCoord(erosita.RA_fin_soft, erosita.DEC_fin_soft, frame="fk5", unit="deg")
except Exception as e:
print("{} {}".format(src,e))
erosita = None
erosita_crd = None
heasarcs = src.heasarc.all().annotate(separation=Value(0.0, output_field=DecimalField()))
heasarcs = heasarcs.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for heasarc in heasarcs:
c0 = SkyCoord(heasarc.ra, heasarc.dec, frame="fk5", unit="deg")
heasarc.separation=c.separation(c0).arcsecond
if not erosita is None:
heasarc.erosita_separation=erosita_crd.separation(c0).arcsecond
simbad = src.simbad.all().annotate(separation=Value(0.0, output_field=DecimalField()))
simbad = simbad.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for simsrc in simbad:
simbad_crd=SkyCoord(simsrc.ra, simsrc.dec, frame="fk5", unit="deg")
simsrc.separation=c.separation(simbad_crd).arcsecond
if not erosita is None:
simsrc.erosita_separation=erosita_crd.separation(simbad_crd).arcsecond
allwise = src.allwise.all().annotate(separation=Value(0.0, output_field=DecimalField()))
allwise = allwise.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for asrc in allwise:
allwise_crd = SkyCoord(asrc.ra, asrc.dec, frame="fk5", unit="deg")
asrc.separation=c.separation(allwise_crd).arcsecond
if not erosita is None:
asrc.erosita_separation=erosita_crd.separation(allwise_crd).arcsecond
first = annotate_separation(src.first.all(), erosita, erosita_crd, c)
nvss = annotate_separation(src.nvss.all(), erosita, erosita_crd, c)
sumss = annotate_separation(src.sumss.all(), erosita, erosita_crd, c)
vlass = annotate_separation(src.vlass.all(), erosita, erosita_crd, c)
bj2021 = annotate_separation(src.bj2021.all(), erosita, erosita_crd, c)
gaiadr3 = annotate_separation(src.gaiadr3.all(), erosita, erosita_crd, c)
wise = src.wisecounterpart_set.all().order_by('sep')
wise = wise.annotate(separation=Value(0.0, output_field=DecimalField()))
wise = wise.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for w in wise:
if not (w.raStack < -90.0 or w.decStack < -90.0):
wise_crd = SkyCoord(w.raStack, w.decStack, frame="fk5", unit="deg")
w.separation=c.separation(wise_crd).arcsecond
if not erosita is None:
w.erosita_separation=erosita_crd.separation(wise_crd).arcsecond
gaia = src.gaia3.all()
gaia_ex = gaia.exclude(Q(pmra__abs__gt=F("pmra_error")*Value(4.)) | Q(pmdec__abs__gt=F("pmdec_error")*Value(4.)) | Q(parallax__abs__gt=F("parallax_error")*Value(4.)))
gaia_ex = gaia_ex.annotate(separation=Value(0.0, output_field=DecimalField()))
gaia_ex = gaia_ex.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for gaiasrc in gaia_ex:
gaia_crd=SkyCoord(gaiasrc.ra, gaiasrc.dec, frame="fk5", unit="deg")
gaiasrc.separation=c.separation(SkyCoord(gaiasrc.ra, gaiasrc.dec, frame="fk5", unit="deg")).arcsecond
if not erosita is None:
gaiasrc.erosita_separation=erosita_crd.separation(gaia_crd).arcsecond
gaia_pm = gaia.filter(Q(pmra__abs__gt=F("pmra_error")*Value(4.)) | Q(pmdec__abs__gt=F("pmdec_error")*Value(4.)))
gaia_pm = gaia_pm.annotate(separation=Value(0.0, output_field=DecimalField()))
gaia_pm = gaia_pm.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for gaiasrc in gaia_pm:
gaia_crd=SkyCoord(gaiasrc.ra, gaiasrc.dec, frame="fk5", unit="deg")
gaiasrc.separation=c.separation(gaia_crd).arcsecond
if not erosita is None:
gaiasrc.erosita_separation=erosita_crd.separation(gaia_crd).arcsecond
gaia_plx = gaia.filter(Q(parallax__abs__gt=F("parallax_error")*Value(4.)))
gaia_plx = gaia_plx.annotate(separation=Value(0.0, output_field=DecimalField()))
gaia_plx = gaia_plx.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for gaiasrc in gaia_plx:
gaia_crd=SkyCoord(gaiasrc.ra, gaiasrc.dec, frame="fk5", unit="deg")
gaiasrc.separation=c.separation(SkyCoord(gaiasrc.ra, gaiasrc.dec, frame="fk5", unit="deg")).arcsecond
if not erosita is None:
gaiasrc.erosita_separation=erosita_crd.separation(gaia_crd).arcsecond
""" find original source """
try:
orig = SkyMapSource.objects.get(artsurvey_source=src)
#plate = get_object_or_404(SkyMaps, SMAPNR=orig.skymap.SMAPNR)
#neib=[orig.skymap.SMAPNR]
#for p in plate.neighbours.all():
# neib.append(p.SMAPNR)
srcs = get_sources_sorted(request.user, src)
heasarc_around = get_heasarc_around(request.user, src)
##s1 = ArtSurvey.objects.get(version=1.7)
##s2 = ArtSurvey.objects.get(version=2.7)
##s12 = ArtSurvey.objects.get(Q(version=12.5) & Q(archived=True))
# all_sources = ArtSurveySource.objects.filter(survey__in=[s1,s2,s12]).filter(SMAPNR__in=neib).order_by("ra")
all_sources=[]
#all_sources0 = ArtSurveySource.objects.filter(SMAPNR__in=neib).order_by("ra")
#for s in all_sources0:
# s_crd=SkyCoord(s.ra, s.dec, frame="fk5", unit="deg")
# if(s_crd.separation(c).arcmin < 60):
# all_sources.append(s)
#print("Heasarc around {}".format(heasarc_around.count()))
except Exception as e:
print("{} --> {}".format(src,e))
orig = None
srcs = None
all_sources = None
heasarc_around = None
if(orig==None and src.parent):
""" if orig is not found, take it from parent """
try:
orig = SkyMapSource.objects.get(artsurvey_source=src.parent)
plate = get_object_or_404(SkyMaps, SMAPNR=orig.skymap.SMAPNR)
except Exception as e:
print("{} --> {}".format(src,e))
pass
if(src.metasource):
metasource_list = src.metasource.artsurveysource_set.all()#.sort_by("version")
else:
metasource_list=None
skyview = OrderedDict(sorted(SkyView.survey_dict.items()))
basketform=UserArtBasketListForm()
basketform.fields["folder"].queryset=request.user.artbasket_set.all()
baskets = src.artbasket_set.all().filter(owner=request.user)
if request.method == 'POST': # If the form has been submitted...
form = UserArtBasketListForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
selection = form.cleaned_data['folder']
selection.sources.add(src)
pass
#return HttpResponseForbidden("<html><body>{}</body></html>".format(baskets))
else:
pass
return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,'wise':wise,'srcs': srcs,
'basketform': basketform,'baskets': baskets,
'all_sources': all_sources,
'erosita':erosita,
'heasarcs':heasarcs,'heasarc_around':heasarc_around,
'simbad':simbad,'bj2021':bj2021,'gaiadr3':gaiadr3,
'allwise':allwise,
'nvss':nvss,'first':first,'sumss':sumss,'vlass':vlass,
'gaia_ex':gaia_ex,
'gaia_pm':gaia_pm,
'gaia_plx':gaia_plx,
'orig':orig,'skyview':skyview,
'metasource_list':metasource_list,})
def type_artsurvey_source(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
try:
src = ArtSurveySource.objects.get(pk=source_id)
except:
return HttpResponse("This ArtSurveySource was not found")
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def set_galplane_survey(request, survey_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
survey = get_object_or_404(ArtSurvey, pk=survey_id)
params = get_object_or_404(ArtSurveyParams, owner=request.user)
params.survey=survey
params.save()
return HttpResponseRedirect(reverse('artsurvey index'))
def clean_class(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.class_id = 0
src.object_class = None
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def mark_tentative(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.class_tentative=True
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def remove_tentative(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.class_tentative=False
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def mark_newxray(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.cname='NEW X-RAY SOURCE'
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def remove_newxray(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.cname=None
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def mark_turkish(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.turkish=True
src.turkish_date=timezone.localtime(timezone.now())
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def remove_turkish(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.turkish=False
src.turkish_date=None
src.save()
#return render(request,'artsurvey/show_artsurvey_source.html', {'src':src,})
return HttpResponseRedirect(src.get_absolute_url())
def ajax_autocomplete(request):
if request.is_ajax():
q = request.GET.get('term', '').upper()
search_qs = HeasarcSimpleClass.objects.filter(class_name__startswith=q)
results = []
print(q)
for r in search_qs:
results.append(r.class_name)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
def update_type(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
text=request.POST['txtSearch']
try:
object_class = HeasarcSimpleClass.objects.get(class_name=text)
except:
return HttpResponse("Error when trying to find HeasarcSimpleClass {}".format(text))
src.object_class=object_class
src.class_id=object_class.class_id
src.owner=request.user
src.save()
print("CHANGE TYPE: >{}<".format(text))
return HttpResponseRedirect(src.get_absolute_url())
else:
return HttpResponseRedirect(reverse('art survey index'))
def notes(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
form = NotesForm(request.POST)
if form.is_valid():
src.notes=form.cleaned_data['notes']
src.notes_paper=form.cleaned_data['notes_paper']
src.bibtex_paper=form.cleaned_data['bibtex_paper']
src.follow_up=form.cleaned_data['follow_up']
src.redshift=form.cleaned_data['redshift']
src.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
initial = {'redshift': src.redshift, 'notes': src.notes,'notes_paper': src.notes_paper, 'bibtex_paper':src.bibtex_paper,'follow_up': src.follow_up}
form = NotesForm(initial=initial)
return render(request, 'artsurvey/notes.html', {'form': form,'src':src,})
def notes_survey(request, survey_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
survey = get_object_or_404(ArtSurvey, pk=survey_id)
if request.method == 'POST':
form = NotesSurveyForm(request.POST)
if form.is_valid():
survey.notes=form.cleaned_data['notes']
survey.save()
return HttpResponseRedirect(reverse('artsurvey index'))
else:
pass
initial = {'notes': survey.notes,}
form = NotesSurveyForm(initial=initial)
return render(request, 'artsurvey/notes.html', {'form': form,})
def cname(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
form = CnameForm(request.POST)
if form.is_valid():
src.cname=form.cleaned_data['cname']
src.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
initial = {'cname': src.cname}
form = CnameForm(initial=initial)
return render(request, 'artsurvey/cname.html', {'form': form,'src':src,})
def update_artsurveysource(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
form = ArtSurveySourceForm(request.POST)
if form.is_valid():
src.name=form.cleaned_data['name']
src.ra=form.cleaned_data['ra']
src.dec=form.cleaned_data['dec']
crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
src.ecl_l=crd.transform_to(BarycentricTrueEcliptic).lon.value
src.ecl_b=crd.transform_to(BarycentricTrueEcliptic).lat.value
src.lii = crd.galactic.l.value
src.bii = crd.galactic.b.value
src.flux=form.cleaned_data['flux']
src.fluxerr_lo=form.cleaned_data['fluxerr_lo']
src.fluxerr_up=form.cleaned_data['fluxerr_up']
src.ext=form.cleaned_data['ext']
src.nfalse=form.cleaned_data['nfalse']
src.sig=form.cleaned_data['sig']
log10 = -100.0
if(src.nfalse > 0.0):
src.log_nfalse = math.log10(src.nfalse)
src.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
initial = {'name': src.name,'ra':src.ra,'dec':src.dec,
'flux':src.flux,'fluxerr_lo':src.fluxerr_lo,'fluxerr_up':src.fluxerr_up,
'nfalse':src.nfalse,'sig':src.sig}
form = ArtSurveySourceForm(initial=initial)
return render(request, 'artsurvey/update_artsurvey_source.html', {'form': form,'src':src,})
def artsurvey_params(request):
""" Edit user session parameters """
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
if request.method == 'POST':
form = ArtSurveyParamsForm(request.POST)
if form.is_valid():
gaia_primary = form.cleaned_data['gaia_primary']
allwise_primary = form.cleaned_data['allwise_primary']
log_nfalse_min = form.cleaned_data['log_nfalse_min']
log_nfalse_max = form.cleaned_data['log_nfalse_max']
log_ml_nfalse_min = form.cleaned_data['log_ml_nfalse_min']
log_ml_nfalse_max = form.cleaned_data['log_ml_nfalse_max']
detlike_min = form.cleaned_data['detlike_min']
detlike_max = form.cleaned_data['detlike_max']
dec_min = form.cleaned_data['dec_min']
dec_max = form.cleaned_data['dec_max']
sign_ml_min = form.cleaned_data['sign_ml_min']
sign_ml_max = form.cleaned_data['sign_ml_max']
exposure_min = form.cleaned_data['exposure_min']
ext_min = form.cleaned_data['ext_min']
ext_max = form.cleaned_data['ext_max']
class_startswith = form.cleaned_data['class_startswith']
cname_contains = form.cleaned_data['cname_contains']
sky = form.cleaned_data['sky']
marshall = form.cleaned_data['marshall']
band = form.cleaned_data['band']
exclude_band = form.cleaned_data['exclude_band']
exclude_log_nfalse = form.cleaned_data['exclude_log_nfalse']
exclude_log_ml_nfalse = form.cleaned_data['exclude_log_ml_nfalse']
survey = form.cleaned_data['survey']
exclude_survey = form.cleaned_data['exclude_survey']
category = form.cleaned_data['category']
exclude_category = form.cleaned_data['exclude_category']
category_unclassified = form.cleaned_data['category_unclassified']
ecl_lat_min = form.cleaned_data['ecl_lat_min']
ecl_lat_max = form.cleaned_data['ecl_lat_max']
glat_min = form.cleaned_data['glat_min']
glat_max = form.cleaned_data['glat_max']
turk_possible = form.cleaned_data['turk_possible']
try:
params = ArtSurveyParams.objects.get(owner=request.user)
except ArtSurveyParams.DoesNotExist:
params=form.save(commit=False)
params.owner=request.user
params.save()
params.dec_min = dec_min
params.dec_max = dec_max
params.ext_min = ext_min
params.ext_max = ext_max
params.detlike_min = detlike_min
params.detlike_max = detlike_max
params.log_nfalse_min = log_nfalse_min
params.log_nfalse_max = log_nfalse_max
params.log_ml_nfalse_min = log_ml_nfalse_min
params.log_ml_nfalse_max = log_ml_nfalse_max
params.exposure_min = exposure_min
params.sign_ml_min = sign_ml_min
params.sign_ml_max = sign_ml_max
params.class_startswith = class_startswith
params.cname_contains = cname_contains
params.survey=survey
params.exclude_survey=exclude_survey
params.category=category
params.exclude_category=exclude_category
params.category_unclassified=category_unclassified
params.sky=sky
params.marshall=marshall
params.band=band
params.gaia_primary=gaia_primary
params.allwise_primary=allwise_primary
params.exclude_band=exclude_band
params.exclude_log_nfalse=exclude_log_nfalse
params.exclude_log_ml_nfalse=exclude_log_ml_nfalse
params.ecl_lat_min = ecl_lat_min
params.ecl_lat_max = ecl_lat_max
params.glat_min = glat_min
params.glat_max = glat_max
params.turk_possible = turk_possible
params.save()
ntotal = get_sources(request.user).count()
return render(request, 'artsurvey/params.html', {'form':form,'params':params,'ntotal':ntotal,})
else:
#form = UserSessionParametersForm()
pass
try:
params = ArtSurveyParams.objects.get(owner=request.user)
except ArtSurveyParams.DoesNotExist:
params = ArtSurveyParams()
params.owner=request.user
params.save()
form = ArtSurveyParamsForm(instance=params)
return render(request, 'artsurvey/params.html', {'form': form,'params':params,})
def artsurvey_params_reset(request):
""" Edit user session parameters """
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
params = get_object_or_404(ArtSurveyParams, owner=request.user)
params.ext_min = ArtSurveyParams._meta.get_field('ext_min').get_default()
params.ext_max = ArtSurveyParams._meta.get_field('ext_max').get_default()
params.dec_min = ArtSurveyParams._meta.get_field('dec_min').get_default()
params.dec_max = ArtSurveyParams._meta.get_field('dec_max').get_default()
params.log_nfalse_min = ArtSurveyParams._meta.get_field('log_nfalse_min').get_default()
params.log_nfalse_max = ArtSurveyParams._meta.get_field('log_nfalse_max').get_default()
params.log_ml_nfalse_min = ArtSurveyParams._meta.get_field('log_ml_nfalse_min').get_default()
params.log_ml_nfalse_max = ArtSurveyParams._meta.get_field('log_ml_nfalse_max').get_default()
params.detlike_min = ArtSurveyParams._meta.get_field('detlike_min').get_default()
params.detlike_max = ArtSurveyParams._meta.get_field('detlike_max').get_default()
params.sign_ml_min = ArtSurveyParams._meta.get_field('sign_ml_min').get_default()
params.sign_ml_max = ArtSurveyParams._meta.get_field('sign_ml_max').get_default()
params.exposure_min = ArtSurveyParams._meta.get_field('exposure_min').get_default()
params.class_startswith = ArtSurveyParams._meta.get_field('class_startswith').get_default()
params.cname_contains = ArtSurveyParams._meta.get_field('cname_contains').get_default()
params.exclude_survey = ArtSurveyParams._meta.get_field('exclude_survey').get_default()
params.category = ArtSurveyParams._meta.get_field('category').get_default()
params.exclude_category = ArtSurveyParams._meta.get_field('exclude_category').get_default()
params.category_unclassified = ArtSurveyParams._meta.get_field('category_unclassified').get_default()
params.sky = ArtSurveyParams._meta.get_field('sky').get_default()
params.marshall = ArtSurveyParams._meta.get_field('marshall').get_default()
params.band = ArtSurveyParams._meta.get_field('band').get_default()
params.gaia_primary = ArtSurveyParams._meta.get_field('gaia_primary').get_default()
params.allwise_primary = ArtSurveyParams._meta.get_field('allwise_primary').get_default()
params.exclude_band = ArtSurveyParams._meta.get_field('exclude_band').get_default()
params.exclude_log_nfalse = ArtSurveyParams._meta.get_field('exclude_log_nfalse').get_default()
params.ecl_lat_min = ArtSurveyParams._meta.get_field('ecl_lat_min').get_default()
params.ecl_lat_max = ArtSurveyParams._meta.get_field('ecl_lat_max').get_default()
params.glat_min = ArtSurveyParams._meta.get_field('glat_min').get_default()
params.glat_max = ArtSurveyParams._meta.get_field('glat_max').get_default()
params.turk_possible = ArtSurveyParams._meta.get_field('turk_possible').get_default()
params.save()
return HttpResponseRedirect(reverse('artsurvey params'))
#form = ArtSurveyParamsForm(instance=params)
#ntotal = get_sources(request.user).count()
#return render(request, 'artsurvey/params.html', {'form':form,'params':params,'ntotal':ntotal,})
def counterpart(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
form = OpticalCounterpartForm(request.POST)
if form.is_valid():
c=form.save(commit=False)
c.source=src
c.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
form = OpticalCounterpartForm()
return render(request, 'artsurvey/counterpart.html', {'form': form,'src':src,})
def show_category(request,category_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
category = get_object_or_404(Category, pk=category_id)
srcs = get_sources(request.user).filter(category=category).order_by("ra")
return render(request,'artsurvey/index.html', {'srcs':srcs,'ntotal':srcs.count(),'categories':Category.objects.all(),})
def update_category(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST': # If the form has been submitted...
form = CategoryForm(request.POST,instance=src) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_form=form.save(commit=False)
category = form.cleaned_data['category']
new_form.category=category
new_form.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
return render(request,'artsurvey/category.html', {'form':form,'src':src,})
else:
form = CategoryForm(instance=src)
return render(request,'artsurvey/category.html', {'form':form,'src':src,})
def vizier(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
return render(request, 'artsurvey/vizier.html', {'src':src,})
def set_artsurvey_gaia(request,source_id,gaia_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.gaia3_primary = get_object_or_404(GAIADR3, pk=gaia_id)
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_allwise(request,source_id,allwise_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
allwise = get_object_or_404(AllWise, pk=allwise_id)
src.allwise_primary=allwise
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_nvss(request,source_id,nvss_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
nvss=get_object_or_404(NVSS, pk=nvss_id)
src.nvss_primary=nvss
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_vlass(request,source_id,vlass_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
vlass=get_object_or_404(VLASSfromVizieR, pk=vlass_id)
src.vlass_primary=vlass
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_gaiadr3(request,source_id,gaiadr3_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
gaiadr3=get_object_or_404(GAIADR3fromVizieR, pk=gaiadr3_id)
src.gaiadr3_primary=gaiadr3
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_bj2021(request,source_id,bj2021_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
bj2021=get_object_or_404(BJfromVizieR, pk=bj2021_id)
src.bj2021_primary=bj2021
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_first(request,source_id,first_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.first_primary=get_object_or_404(FIRST, pk=first_id)
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_sumss(request,source_id,sumss_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.sumss_primary=get_object_or_404(SUMSS, pk=sumss_id)
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def set_artsurvey_wise(request,source_id,wise_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
wise = get_object_or_404(WiseCounterpart, pk=wise_id)
wise_all = src.wisecounterpart_set.all()
for w in wise_all:
w.primary=False
w.save()
wise.primary=True
wise.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_wise(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
wise_all = src.wisecounterpart_set.all()
for w in wise_all:
w.primary=False
w.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_gaia(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.gaia3_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_allwise(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.allwise_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_nvss(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.nvss_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_gaiadr3(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.gaiadr3_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_bj2021(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.bj2021_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_vlass(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.vlass_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_first(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.first_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def clean_artsurvey_sumss(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.sumss_primary=None
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def other_name_add(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
form = OtherNameForm(request.POST)
if form.is_valid():
oname=form.save(commit=False)
oname.source=src
oname.owner=request.user
oname.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
form = OtherNameForm()
return render(request, 'artsurvey/other_name.html', {'form': form,'src':src,})
def other_name_delete(request, othername_id):
oname = get_object_or_404(OtherName, pk=othername_id)
src=oname.source
oname.delete()
return HttpResponseRedirect(src.get_absolute_url())
def other_name_update(request, othername_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
oname = get_object_or_404(OtherName, pk=othername_id)
src=oname.source
if request.method == 'POST':
form = OtherNameForm(request.POST)
if form.is_valid():
oname.name=form.cleaned_data['name']
oname.owner=request.user
oname.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
initial = {'name':oname.name,}
form = OtherNameForm(initial=initial)
return render(request, 'artsurvey/other_name.html', {'form': form,'src':src,})
def link_heasarc(request,source_id,heasarc_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
heasarc = get_object_or_404(HeasarcBase, pk=heasarc_id)
src.heasarc_linked.add(heasarc)
src.save()
if(heasarc.ads):
src.ads.add(heasarc.ads)
return HttpResponseRedirect(src.get_absolute_url())
def unlink_heasarc(request,source_id,heasarc_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
heasarc = get_object_or_404(HeasarcBase, pk=heasarc_id)
src.heasarc_linked.remove(heasarc)
src.save()
if(heasarc.ads):
src.ads.remove(heasarc.ads)
return HttpResponseRedirect(src.get_absolute_url())
def unlink_heasarc_all(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
src.heasarc_linked.clear()
src.save()
return HttpResponseRedirect(src.get_absolute_url())
def load_skyview_image(request, source_id, survey):
src = get_object_or_404(ArtSurveySource, pk=source_id)
print("Loading SkyView survey {}".format(survey))
try:
im = skyview_query(src.ra, src.dec, size=1440, survey=survey)
except Exception as e:
print("{} {}".format(src,e))
return HttpResponseRedirect(src.get_absolute_url())
upload = Upload(owner=request.user,title="{}".format(survey),filename="skyview_image.fits",
notes="Loaded from the SkyView server via astroquery")
new_file = ContentFile(im)
new_file.name = upload.filename
upload.filefield = new_file
upload.save()
upload.artsources.add(src)
return HttpResponseRedirect(src.get_absolute_url())
def load_ps1_color_image(request, source_id):
src = get_object_or_404(ArtSurveySource, pk=source_id)
try:
im = ps1_getcolorim(src.ra, src.dec, size=1440)
except Exception as e:
print("{} {}".format(src,e))
return HttpResponseRedirect(src.get_absolute_url())
upload = Upload(owner=request.user,title='PS1 color image',filename="ps1_color_image.jpg",
notes="Loaded from the PS1 image server")
new_file = ContentFile(im)
new_file.name = upload.filename
upload.filefield = new_file
upload.save()
upload.artsources.add(src)
return HttpResponseRedirect(src.get_absolute_url())
def load_ps1_gray_image(request, source_id):
src = get_object_or_404(ArtSurveySource, pk=source_id)
try:
im = ps1_getgrayim(src.ra, src.dec, size=1440)
except Exception as e:
print("{} {}".format(src,e))
return HttpResponseRedirect(src.get_absolute_url())
upload = Upload(owner=request.user,title='PS1 gray image',filename="ps1_gray_image.jpg",
notes="Loaded from the PS1 image server")
new_file = ContentFile(im)
new_file.name = upload.filename
upload.filefield = new_file
upload.save()
upload.artsources.add(src)
return HttpResponseRedirect(src.get_absolute_url())
def load_ps1_fits_image(request, source_id, filtername):
src = get_object_or_404(ArtSurveySource, pk=source_id)
try:
im = ps1_fitsim(src.ra, src.dec, size=1440, format="fits", filter=filtername)
except Exception as e:
print("{} {}".format(src,e))
return HttpResponseRedirect(src.get_absolute_url())
upload = Upload(owner=request.user,
title="PS1 filter {}".format(filtername),
filename="ps1_image_{}.fits".format(filtername),
notes="Loaded from the PS1 image server")
new_file = ContentFile(im)
new_file.name = upload.filename
upload.filefield = new_file
upload.save()
upload.artsources.add(src)
return HttpResponseRedirect(src.get_absolute_url())
def artsource_upload(request, source_id):
src = get_object_or_404(ArtSurveySource, pk=source_id)
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = form.save(commit=False)
upload.owner=request.user
upload.save()
upload.artsources.add(src)
"""
if(src.metasource):
upload.metasource=src.metasource
"""
upload.title=form.cleaned_data['title']
upload.filename = request.FILES['filefield'].name#.encode('utf-8')
upload.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
form = UploadForm()
return render(request,'artsurvey/upload.html', {'source':src, 'form': form,})
def artsource_upload_survey(request, survey_id):
survey = get_object_or_404(ArtSurvey, pk=survey_id)
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = form.save(commit=False)
upload.owner=request.user
upload.save()
upload.survey = survey
upload.title=form.cleaned_data['title']
upload.filename = request.FILES['filefield'].name#.encode('utf-8')
upload.save()
return HttpResponseRedirect(reverse('artsurvey catalog'))
else:
form = UploadForm()
return render(request,'artsurvey/upload.html', {'src':survey, 'form': form,})
def metasource_upload(request, source_id):
src = get_object_or_404(MetaSource, pk=source_id)
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = form.save(commit=False)
upload.owner=request.user
upload.save()
upload.metasource=src
upload.title=form.cleaned_data['title']
upload.filename = request.FILES['filefield'].name#.encode('utf-8')
upload.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
form = UploadForm()
return render(request,'artsurvey/upload.html', {'src':src, 'form': form,})
def set_primary_upload_survey(request, survey_id, upload_id):
survey = get_object_or_404(ArtSurvey, pk=survey_id)
for upload in survey.uploads.all():
upload.primary = False
upload.save()
upload = get_object_or_404(Upload, pk=upload_id)
upload.primary=True
upload.save()
return HttpResponseRedirect(reverse('artsurvey catalog'))
def clean_primary_upload_survey(request, survey_id):
survey = get_object_or_404(ArtSurvey, pk=survey_id)
for upload in survey.uploads.all():
upload.primary = False
upload.save()
return HttpResponseRedirect(reverse('artsurvey catalog'))
def delete_upload(request, source_id, upload_id):
src = get_object_or_404(ArtSurveySource, pk=source_id)
upload = get_object_or_404(Upload, pk=upload_id)
upload.delete()
return HttpResponseRedirect(src.get_absolute_url())
def delete_upload_survey(request, survey_id, upload_id):
survey = get_object_or_404(ArtSurvey, pk=survey_id)
upload = get_object_or_404(Upload, pk=upload_id)
upload.delete()
return HttpResponseRedirect(reverse('artsurvey catalog'))
def delete_upload_metasource(request, source_id, upload_id):
src = get_object_or_404(MetaSource, pk=source_id)
upload = get_object_or_404(Upload, pk=upload_id)
upload.delete()
return HttpResponseRedirect(src.get_absolute_url())
def new_heasarc_source(request, source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
c = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
try:
erosita = src.erositamatch
erosita_crd = SkyCoord(erosita.RA_fin_soft, erosita.DEC_fin_soft, frame="fk5", unit="deg")
except Exception as e:
print("{} {}".format(src,e))
erosita = None
erosita_crd = None
heasarcs = src.heasarc.all().annotate(separation=Value(0.0, output_field=DecimalField()))
heasarcs = heasarcs.annotate(erosita_separation=Value(0.0, output_field=DecimalField()))
for heasarc in heasarcs:
c0 = SkyCoord(heasarc.ra, heasarc.dec, frame="fk5", unit="deg")
heasarc.separation=c.separation(c0).arcsecond
if not erosita is None:
heasarc.erosita_separation=erosita_crd.separation(c0).arcsecond
if request.method == 'POST':
form = HeasarcUserCatForm(request.POST)
if form.is_valid():
new_form=form.save(commit=False)
#bibcode=form.cleaned_data['bibcode']
#notes=form.cleaned_data['notes']
ra=float(form.cleaned_data['ra'])
dec=float(form.cleaned_data['dec'])
name=form.cleaned_data['name']
autoname=form.cleaned_data['autoname']
if(autoname):
new_form.name=make_source_name(name,ra,dec)
new_form.autoname=False
new_form.save()
if(form.cleaned_data['bibcode']):
category_open = AdsCategory.objects.get(slug="open")
ads = Ads(bibcode=form.cleaned_data['bibcode'])
ads.save()
ads.category.add(category_open)
src.ads.add(ads)
new_form.ads=ads
new_form.save()
healpix_usercat(new_form)
match_usercat_all(new_form)
src.heasarc.add(new_form)
src.heasarc_linked.add(new_form)
return HttpResponseRedirect(src.get_absolute_url())
else:
pass
form = HeasarcUserCatForm()
return render(request, 'artsurvey/usercat.html', {'form': form,'src':src,})
def resolve_name(request):
if request.method == 'POST':
form = ResolveNameForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
rmax = float(form.cleaned_data['rmax'])
maxdist = float(form.cleaned_data['maxdist'])
try:
cord=get_icrs_coordinates(name)
cord=cord.fk5
except:
return render(request, 'artsurvey/search_coords.html', {'form':form, 'notresolved':True,})
skymap = get_skymap_by_coords(cord.ra.value, cord.dec.value)
srcs = search_by_coords_artsurvey(cord.ra.value, cord.dec.value, rmax=rmax, maxdist=maxdist)
return render(request, 'artsurvey/search_coords.html', {'form':form,'srcs':srcs,'skymap':skymap,'ra':cord.ra.value,'dec':cord.dec.value,})
else:
form = ResolveNameForm()
return render(request, 'artsurvey/search_coords.html', {'form':form,})
def search_coords_form(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = SearchCoordsForm(request.POST)
# check whether it's valid:
if form.is_valid():
ra = float(form.cleaned_data['ra'])
dec = float(form.cleaned_data['dec'])
rmax = float(form.cleaned_data['rmax'])
maxdist = float(form.cleaned_data['maxdist'])
skymap = get_skymap_by_coords(ra, dec)
srcs = search_by_coords_artsurvey(ra, dec, rmax=rmax, maxdist=maxdist)
return render(request, 'artsurvey/search_coords.html', {'form':form,'srcs':srcs,'skymap':skymap,'ra':ra,'dec':dec,})
else:
form = SearchCoordsForm()
return render(request, 'artsurvey/search_coords.html', {'form':form,})
def search_name_form(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = SearchNameForm(request.POST)
# check whether it's valid:
if form.is_valid():
name = form.cleaned_data['name']
srcs = search_by_name_artsurvey(name)
return render(request, 'artsurvey/search_name.html', {'form':form,'srcs':srcs,})
else:
form = SearchNameForm()
return render(request, 'artsurvey/search_name.html', {'form':form,})
def edit_upload(request,source_id,upload_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
upload = get_object_or_404(Upload, pk=upload_id)
if request.method == 'POST': # If the form has been submitted...
form = UploadForm(request.POST,instance=upload) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_form=form.save(commit=False)
#category = form.cleaned_data['category']
#new_form.category=category
new_form.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
return render(request,'artsurvey/upload.html', {'form':form,'src':src,})
else:
form = UploadForm(instance=upload)
return render(request,'artsurvey/upload.html', {'form':form,'src':src,})
def edit_upload_survey(request,survey_id,upload_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
survey = get_object_or_404(ArtSurvey, pk=survey_id)
upload = get_object_or_404(Upload, pk=upload_id)
if request.method == 'POST': # If the form has been submitted...
form = UploadForm(request.POST,instance=upload) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_form=form.save(commit=False)
#category = form.cleaned_data['category']
#new_form.category=category
new_form.save()
return HttpResponseRedirect(survey.get_absolute_url())
else:
return render(request,'artsurvey/upload.html', {'form':form,'src':survey,})
else:
form = UploadForm(instance=upload)
return render(request,'artsurvey/upload.html', {'form':form,'src':survey,})
def edit_upload_metasource(request,source_id,upload_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(MetaSource, pk=source_id)
upload = get_object_or_404(Upload, pk=upload_id)
if request.method == 'POST': # If the form has been submitted...
form = UploadForm(request.POST,instance=upload) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_form=form.save(commit=False)
#category = form.cleaned_data['category']
#new_form.category=category
new_form.save()
return HttpResponseRedirect(src.get_absolute_url())
else:
return render(request,'artsurvey/upload.html', {'form':form,'src':src,})
else:
form = UploadForm(instance=upload)
return render(request,'artsurvey/upload.html', {'form':form,'src':src,})
def add_to_selection(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
try:
selection = request.user.artselection
except:
selection = ArtSelection(owner=request.user)
selection.save()
selection.sources.add(src)
selection.save()
return HttpResponseRedirect(src.get_absolute_url())
def remove_from_selection(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
try:
selection = request.user.artselection
except:
return HttpResponse("Source Selection was not found")
selection.sources.remove(src)
selection.save()
return HttpResponseRedirect(src.get_absolute_url())
def remove_from_selection_profile(request,source_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
try:
selection = request.user.artselection
except:
return HttpResponse("Source Selection was not found")
selection.sources.remove(src)
selection.save()
return HttpResponseRedirect(reverse('artsurvey profile'))
def remove_from_basket(request,source_id,basket_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
src = get_object_or_404(ArtSurveySource, pk=source_id)
basket = get_object_or_404(ArtBasket, pk=basket_id)
basket.sources.remove(src)
return HttpResponseRedirect(basket.get_absolute_url())
def delete_comment(request, comment_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
comment = get_object_or_404(MetaComment, pk=comment_id)
metasource = comment.metasource
if(request.user == comment.owner):
comment.delete()
else:
raise PermissionDenied("You don't have rights to delete this comment. Go back to <a href={}>{}</a>.".format(metasource.get_absolute_url(),metasource))
return HttpResponseRedirect(metasource.get_absolute_url())
def metasource_group(request, source_id, friend_id):
src = get_object_or_404(ArtSurveySource, pk=source_id)
friend = get_object_or_404(ArtSurveySource, pk=friend_id)
if not src.metasource:
raise PermissionDenied("(main) <a href='{}'>{}</a> <b>has no MetaSource</b>".format(src.get_absolute_url(),src))
if not friend.metasource:
raise PermissionDenied("(friend) <a href='{}'>{}</a> <b>has no MetaSource</b>".format(friend.get_absolute_url(),friend))
src_crd = SkyCoord(src.ra, src.dec, frame="fk5", unit="deg")
meta_crd = SkyCoord(src.metasource.ra, src.metasource.dec, frame="fk5", unit="deg")
friend_crd = SkyCoord(friend.ra, friend.dec, frame="fk5", unit="deg")
if friend.metasource == src.metasource:
raise PermissionDenied("<a href='{}'>{}</a> <b>MetaSource has been already added ({} == {})</b>".format(src.get_absolute_url(),src,friend.metasource,src.metasource))
devmax=3600
metasource_sep=friend_crd.separation(meta_crd).arcsecond
if metasource_sep > devmax:
raise PermissionDenied("<a href='{}'>{}</a> <b>too far away ({:.2f} > {} arcseconds)</b>".format(src.get_absolute_url(),src,metasource_sep, devmax))
srcs = src.metasource.artsurveysource_set.all()
for s in srcs:
s.metasource_primary = None
s.save()
src.metasource_primary=src.metasource
src.save()
friend.metasource_primary=None
friend.metasource=src.metasource
friend.metasource_sep=metasource_sep
friend.save()
return HttpResponseRedirect(src.get_absolute_url())
def transfer(request,source_id,transfer_from_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
destination = get_object_or_404(ArtSurveySource, pk=source_id)
source = get_object_or_404(ArtSurveySource, pk=transfer_from_id)
destination.parent=source
destination.save()
transfer_data(destination,clean_ads=False)
return HttpResponseRedirect(destination.get_absolute_url())
def basket_create(request):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
if request.method == 'POST': # If the form has been submitted...
form = ArtBasketForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_form=form.save(commit=False)
new_form.owner=request.user
new_form.save()
return HttpResponseRedirect(reverse('artsurvey index'))
else:
return render(request,'artsurvey/basket.html', {'form':form,})
else:
form = ArtBasketForm()
return render(request,'artsurvey/basket.html', {'form':form,})
def basket_update(request, basket_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
basket = get_object_or_404(ArtBasket, pk=basket_id)
if request.method == 'POST': # If the form has been submitted...
form = ArtBasketForm(request.POST,instance=basket) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_form=form.save(commit=False)
new_form.owner=request.user
new_form.save()
return HttpResponseRedirect(new_form.get_absolute_url())
else:
return render(request,'artsurvey/basket.html', {'form':form,'basket':basket,})
else:
form = ArtBasketForm(instance=basket)
return render(request,'artsurvey/basket.html', {'form':form,'basket':basket,})
def basket_show(request, basket_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
basket = get_object_or_404(ArtBasket, pk=basket_id)
"""
baskets = ArtBasket.objects.all()
if not basket in user_profile.baskets.all():
write_history(request, "Trying to access not allowed basket {}.".format(basket))
return HttpResponseForbidden("<html><body>You are really bad guy!</body></html>")
"""
return render(request,'artsurvey/basket.html', {'basket':basket,})
def basket_delete(request, basket_id):
status=srg_group_auth_stats(request, "srg-artxc-catalog")
if status != 0:
return HttpResponse(status_code[status])
basket = get_object_or_404(ArtBasket, pk=basket_id)
basket.delete()
return HttpResponseRedirect(reverse('artsurvey index'))