Newer
Older
Branson Stephens
committed
from django.db import models, IntegrityError

Tanner Prestegard
committed
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from model_utils.managers import InheritanceManager

Tanner Prestegard
committed
#from django.contrib.auth.models import User as DjangoUser
#from django.contrib.auth.models import Group

Tanner Prestegard
committed
from django.contrib.auth import get_user_model

Branson Craig Stephens
committed
from django.contrib.contenttypes.models import ContentType

Tanner Prestegard
committed
from guardian.models import GroupObjectPermission
import logging; log = logging.getLogger(__name__)
import glue
import glue.ligolw
import glue.ligolw.utils
import glue.ligolw.table
import glue.ligolw.lsctables
from glue.ligolw.ligolw import LIGOLWContentHandler

Tanner Prestegard
committed
import json, re

Branson Craig Stephens
committed

Tanner Prestegard
committed
from core.models import AutoIncrementModel, CleanSaveModel
from core.models import LogBase, m2mThroughBase
from django.conf import settings
import pytz
import calendar
from cStringIO import StringIO
from hashlib import sha1

Tanner Prestegard
committed
import shutil

Tanner Prestegard
committed
UserModel = get_user_model()
SERVER_TZ = pytz.timezone(settings.TIME_ZONE)
# Let's say we start here on schema versions
#
# 1.0 -> 1.1 changed EventLog.comment from CharField(length=200) -> TextField
#
schema_version = "1.1"
#class User(models.Model):
#name = models.CharField(max_length=100)
#email = models.EmailField()
#principal = models.CharField(max_length=100)
#dn = models.CharField(max_length=100)
#unixid = models.CharField(max_length=25)
#class Meta:
#ordering = ["name"]
#def __unicode__(self):
#return self.name
class Group(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Pipeline(models.Model):
name = models.CharField(max_length=100)
# XXX Need any additional fields? Like a librarian email? Or perhaps even fk?
def __unicode__(self):
return self.name
class Search(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
# XXX Need any additional fields? Like a PI email? Or perhaps even fk?
def __unicode__(self):
return self.name
# Label color will be used in CSS, see
# https://www.w3schools.com/colors/colors_names.asp for
# allowed color choices
name = models.CharField(max_length=20, unique=True)
# XXX really, does this belong here? probably not.

Tanner Prestegard
committed
defaultColor = models.CharField(max_length=20, unique=False,
default="black")
description = models.TextField(blank=False)

Tanner Prestegard
committed
DEFAULT_PIPELINE_ID = 1
objects = InheritanceManager() # Queries can return subclasses, if available.
# ANALYSIS_TYPE_CHOICES = (
# ("LM", "LowMass"),
# ("HM", "HighMass"),
# ("GRB", "GRB"),
# ("RD", "Ringdown"),
# ("OM", "Omega"),
# ("Q", "Q"),
# ("X", "X"),
# ("CWB", "CWB"),
# ("MBTA", "MBTAOnline"),
# ("HWINJ", "HardwareInjection"),
# )
DEFAULT_EVENT_NEIGHBORHOOD = (-5,5)

Tanner Prestegard
committed
submitter = models.ForeignKey(UserModel)
created = models.DateTimeField(auto_now_add=True)
group = models.ForeignKey(Group)
#uid = models.CharField(max_length=20, default="") # XXX deprecated. should be removed.
#analysisType = models.CharField(max_length=20, choices=ANALYSIS_TYPE_CHOICES)

Tanner Prestegard
committed
# Events aren't required to be part of a superevent. If the superevent is
# deleted, don't delete the event; just set this FK to null.
superevent = models.ForeignKey('superevents.Superevent', null=True,
related_name='events', on_delete=models.SET_NULL)

Tanner Prestegard
committed
# Note: a default value is needed only during the schema migration
# that creates this column. After that, we can safely remove it.
# The presence or absence of the default value has no effect on the DB
# tables, so removing it does not necessitate a migration.
#pipeline = models.ForeignKey(Pipeline, default=DEFAULT_PIPELINE_ID)
pipeline = models.ForeignKey(Pipeline)
search = models.ForeignKey(Search, null=True)
instruments = models.CharField(max_length=20, default="")
nevents = models.PositiveIntegerField(null=True)
likelihood = models.FloatField(null=True)
# NOT from coinc_event, but so, so common.
# Note that the semantics for this is different depending
# on search type, so in some sense, querying on this may
# be considered, umm, wrong? But it is a starting point.
#gpstime = models.PositiveIntegerField(null=True)
gpstime = models.DecimalField(max_digits=16, decimal_places=6, null=True)
labels = models.ManyToManyField(Label, through="Labelling")

Branson Craig Stephens
committed
# This field will store a JSON-serialized list of permissions, of the
# form <group name>_can_<permission codename>
# This obviously duplicates information that is already in the database
# in the form of GroupObjectPermission objects. Such duplication is
# normally a bad thing, as it can lead to divergence. But we're going
# to try really hard to avoid that. And it may help speed up the
# searches quite considerably.
perms = models.TextField(null=True)

Tanner Prestegard
committed
# Boolean which determines whether the event was submitted by an offline
# analysis (True) or an online/low-latency analysis (False). Because this
# is being implemented during a run (O2), we use a default value of False
# so as to ensure backwards-compatibility; i.e., all events treated as
# "online" by default.
offline = models.BooleanField(default=False)
class Meta:
ordering = ["-id"]
def graceid(self):
if self.group.name == "Test":
elif str(self.search) == str("MDC"):
return "M%04d" % self.id

Branson Craig Stephens
committed
elif self.pipeline.name == "HardwareInjection":
return "H%04d" % self.id
elif self.group.name == "External":
Branson Stephens
committed
return "E%04d" % self.id
return "G%04d" % self.id
# XXX Not good. But then, it never was.
return reverse('file_list', args=[self.graceid()])
@property
def datadir(self):
# Create a file-like object which is the SHA-1 hexdigest of the Event's primary key
hdf = StringIO(sha1(str(self.id)).hexdigest())
# Build up the nodes of the directory structure
nodes = [hdf.read(i) for i in settings.GRACEDB_DIR_DIGITS]
# Read whatever is left over. This is the 'leaf' directory.
nodes.append(hdf.read())
return os.path.join(settings.GRACEDB_DATA_DIR, *nodes)
def reportingLatency(self):
if self.gpstime:
dt = self.created
if not dt.tzinfo:
dt = SERVER_TZ.localize(dt)
dt = dt.astimezone(pytz.utc)
posix_time = calendar.timegm(dt.timetuple())
gps_time = int(posixToGpsTime(posix_time))
return gps_time - self.gpstime
def neighbors(self, neighborhood=None):
if not self.gpstime:
return []
if self.group.name == 'Test':
nearby = Event.objects.filter(group__name='Test')
else:
nearby = Event.objects.exclude(group__name='Test')
delta1, delta2 = neighborhood or self.DEFAULT_EVENT_NEIGHBORHOOD
nearby = nearby.filter(gpstime__range=(self.gpstime+delta1, self.gpstime+delta2))
nearby = nearby.exclude(id=self.id)
nearby = nearby.distinct()
nearby = nearby.order_by('gpstime')
return nearby
@classmethod
def getTypeLabel(cls, code):
for key, label in cls.ANALYSIS_TYPE_CHOICES:
if (key == code) or (code == label):
return label
raise KeyError("Unknown analysis type code: %s" % code)
try:
e = cls.objects.filter(id=int(id[1:])).select_subclasses()[0]
except IndexError:
raise cls.DoesNotExist("Event matching query does not exist")
if (id[0] == "T") and (e.group.name == "Test"):
return e
if (id[0] == "H") and (e.pipeline.name == "HardwareInjection"):
if (id[0] == "E") and (e.group.name == "External"):
Branson Stephens
committed
return e
if (id[0] == "M") and (e.search and e.search.name == "MDC"):
if (id[0] == "G"):
return e
raise cls.DoesNotExist("Event matching query does not exist")
def __unicode__(self):
return self.graceid()
# Return a list of distinct tags associated with the log messages of this
# event.
def getAvailableTags(self):

Tanner Prestegard
committed
tagset_list = [log.tags.all() for log in self.eventlog_set.all()]
taglist = []
for tagset in tagset_list:
for tag in tagset:
taglist.append(tag)
# Eliminate duplicates
taglist = list(set(taglist))
# Ordering should match the ordering of blessed tags list.
# XXX Possibly, there are smarter ways of doing this.
if settings.BLESSED_TAGS:
availableTags = []
for blessed_tag in settings.BLESSED_TAGS:
for tag in taglist:
if tag.name == blessed_tag:
taglist.remove(tag)
availableTags.append(tag)
# Append any remaining tags at the end of the list
if len(taglist)>0:
for tag in taglist:
availableTags.append(tag)
else:
availableTags = taglist
return availableTags
def getLogsForTag(self,tagname):
loglist = []
for log in self.eventlog_set.all():

Tanner Prestegard
committed
for tag in log.tags.all():
if tag.name==tagname:
loglist.append(log)
return loglist

Tanner Prestegard
committed
# A method to update the permissions according to the permission objects in

Branson Craig Stephens
committed
# the database.
def refresh_perms(self):
# Content type is 'Event', obvs.
Loading
Loading full blame...