Skip to content
Snippets Groups Projects
Commit 64ac7193 authored by Marco Frailis's avatar Marco Frailis
Browse files

Adding first prototype example with django

parent 10451a1a
No related branches found
No related tags found
No related merge requests found
File added
from django.contrib import admin
from .models import(Instrument, NispRawFrame, NispDetector, Astrometry)
# Register your models here.
admin.site.register(Instrument)
admin.site.register(NispRawFrame)
admin.site.register(NispDetector)
admin.site.register(Astrometry)
from django.apps import AppConfig
class ImagedbConfig(AppConfig):
name = 'imagedb'
from django.db import models
from composite_field import CompositeField
# Create your models here.
IMAGE_CATEGORY = (
'SCIENCE',
'CALIBRATION',
'SIMULATION'
)
IMAGE_FIRST_GROUP = (
'OBJECT',
'STD',
'BIAS',
'DARK',
'FLAT',
'LINEARITY',
'OTHER'
)
IMAGE_SECOND_GROUP = (
'SKY',
'LAMP',
'DOME',
'OTHER'
)
class ImageType(CompositeField):
category = models.CharField(
max_length=20,
choices=[(d, d) for d in IMAGE_CATEGORY]
)
firstType = models.CharField(
max_length=20,
choices=[(d,d) for d in IMAGE_FIRST_GROUP]
)
secondType = models.CharField(
max_length=20,
choices=[(d,d) for d in IMAGE_SECOND_GROUP]
)
class ImageBaseFrame(models.Model):
exposureTime = models.FloatField()
imgNumber = models.PositiveSmallIntegerField()
naxis1 = models.PositiveIntegerField()
naxis2 = models.PositiveIntegerField()
imageType = ImageType()
class Meta:
abstract = True
class Instrument(models.Model):
instrumentName = models.CharField(max_length=100)
telescopeName = models.CharField(max_length=100)
class Pointing(CompositeField):
rightAscension = models.FloatField()
declination = models.FloatField()
pointingAngle = models.FloatField()
class ImageSpaceFrame(ImageBaseFrame):
observationDateTime = models.DateTimeField()
instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE)
commandedPointing = Pointing()
class Meta:
abstract = True
NISP_DETECTOR_ID = (
'11','12','13','14',
'21','22','23','24',
'31','32','33','34',
'41','42','43','44'
)
class NispDetector(models.Model):
detectorId = models.CharField(
max_length=2,
choices = [(d,d) for d in NISP_DETECTOR_ID]
)
gain = models.FloatField()
readoutNoise = models.FloatField()
rawFrame = models.ForeignKey('NispRawFrame',
related_name='detectors',
on_delete=models.CASCADE)
WCS_COORDINATE_TYPE = (
'RA',
'DEC',
'GLON',
'GLAT',
'ELON',
'ELAT'
)
WCS_PROJECTION_TYPE = (
'LOG',
'TAN',
'SIN'
)
class CtypeWcs(CompositeField):
coordinateType = models.CharField(
max_length=4,
choices = [(d,d) for d in WCS_COORDINATE_TYPE]
)
projectionType = models.CharField(
max_length=3,
choices = [(d,d) for d in WCS_PROJECTION_TYPE]
)
class Astrometry(models.Model):
ctpye1 = CtypeWcs()
ctype2 = CtypeWcs()
crval1 = models.FloatField()
crval2 = models.FloatField()
crpix1 = models.FloatField()
crpix2 = models.FloatField()
cd1_1 = models.FloatField()
cd1_2 = models.FloatField()
cd2_1 = models.FloatField()
cd2_2 = models.FloatField()
detector = models.OneToOneField(NispDetector,
related_name='astrometry',
blank=True,
null=True,
on_delete=models.CASCADE)
NISP_FILTER_WHEEL = (
'Y',
'J',
'H',
'OPEN',
'CLOSE'
)
NISP_GRISM_WHEEL = (
'BLUE0',
'RED0',
'RED90',
'RED180'
'OPEN'
'CLOSE'
)
class NispRawFrame(ImageSpaceFrame):
filterWheelPosition = models.CharField(
max_length=10,
choices = [(d,d) for d in NISP_FILTER_WHEEL]
)
grismWheelPosition = models.CharField(
max_length=10,
choices = [(d,d) for d in NISP_GRISM_WHEEL]
)
from composite_field.rest_framework_support import CompositeFieldSerializer
from rest_framework import serializers
from imagedb.models import Instrument, NispDetector, NispRawFrame
class InstrumentSerializer(serializers.ModelSerializer):
class Meta:
model = Instrument
fields = '__all__'
class NispDetectorSerializer(serializers.ModelSerializer):
class Meta:
model = NispDetector
exclude = ('rawFrame',)
class NispRawFrameSerializer(serializers.ModelSerializer):
detectors = NispDetectorSerializer(many = True, read_only = True)
commandedPointing = CompositeFieldSerializer()
imageType = CompositeFieldSerializer()
class Meta:
model = NispRawFrame
exclude = ('commandedPointing_rightAscension',
'commandedPointing_declination',
'commandedPointing_pointingAngle',
'imageType_category',
'imageType_firstType',
'imageType_secondType')
depth = 2
from django.test import TestCase
# Create your tests here.
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from imagedb import views
router = DefaultRouter()
router.register(r'instruments', views.InstrumentViewSet)
router.register(r'nisprawframes', views.NispRawFrameViewSet)
router.register(r'nispdetectors', views.NispDetectorViewSet)
urlpatterns = [
url(r'^', include(router.urls))
]
from rest_framework import viewsets
from imagedb.serializers import InstrumentSerializer, NispDetectorSerializer, NispRawFrameSerializer
from imagedb.models import Instrument, NispDetector, NispRawFrame
from url_filter.filtersets import ModelFilterSet
class InstrumentViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Instrument.objects.all()
serializer_class = InstrumentSerializer
class NispDetectorViewSet(viewsets.ReadOnlyModelViewSet):
queryset = NispDetector.objects.all()
serializer_class = NispDetectorSerializer
class NispRawFrameFilterSet(ModelFilterSet):
class Meta:
model = NispRawFrame
fields = ['id','imageType_category']
class NispRawFrameViewSet(viewsets.ReadOnlyModelViewSet):
queryset = NispRawFrame.objects.all()
serializer_class = NispRawFrameSerializer
filter_class = NispRawFrameFilterSet
%% Cell type:code id: tags:
``` python
from imagedb.models import Instrument
instrument = Instrument.objects.get(instrumentName='NISP')
```
%% Cell type:code id: tags:
``` python
print(instrument.instrumentName)
```
%% Output
NISP
%% Cell type:code id: tags:
``` python
from imagedb.models import ImageType, Pointing, NispDetector, NispRawFrame
from datetime import datetime
image = NispRawFrame(exposureTime = 105,
imgNumber = 16,
naxis1 = 2040,
naxis2 = 2040,
imageType = {'category':'SCIENCE',
'firstType':'OBJECT',
'secondType':'STD'},
observationDateTime = datetime.strptime("2025-06-21T18:27:23.000001",
"%Y-%m-%dT%H:%M:%S.%f"),
instrument = instrument,
commandedPointing = {'rightAscension':8.48223045516,
'declination':8.48223045516,
'pointingAngle':64.8793517547},
filterWheelPosition = "Y",
grismWheelPosition = "OPEN"
)
```
%% Cell type:code id: tags:
``` python
image.commandedPointing
```
%% Output
Pointing(rightAscension=8.48223045516, declination=8.48223045516, pointingAngle=64.8793517547)
%% Cell type:code id: tags:
``` python
image.commandedPointing.rightAscension
```
%% Output
8.48223045516
%% Cell type:code id: tags:
``` python
image = NispRawFrame.objects.filter(commandedPointing_rightAscension__lte=8.48223045516)[0]
```
%% Cell type:code id: tags:
``` python
d = NispDetector(detectorId = "11", gain = 1.0, readoutNoise = 0.0, rawFrame = image)
```
%% Cell type:code id: tags:
``` python
it = image.imageType
repr(it)
it.to_dict()
```
%% Output
{'category': 'SCIENCE', 'firstType': 'OBJECT', 'secondType': 'STD'}
%% Cell type:code id: tags:
``` python
from imagedb.serializers import NispRawFrameSerializer
s = NispRawFrameSerializer()
```
%% Cell type:code id: tags:
``` python
s.get_fields()
```
%% Output
OrderedDict([('id', IntegerField(label='ID', read_only=True)),
('detectors', NispDetectorSerializer(many=True, read_only=True):
id = IntegerField(label='ID', read_only=True)
detectorId = ChoiceField(choices=[('11', '11'), ('12', '12'), ('13', '13'), ('14', '14'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('31', '31'), ('32', '32'), ('33', '33'), ('34', '34'), ('41', '41'), ('42', '42'), ('43', '43'), ('44', '44')], label='DetectorId')
gain = FloatField()
readoutNoise = FloatField(label='ReadoutNoise')),
('exposureTime', FloatField(label='ExposureTime')),
('imgNumber', IntegerField(label='ImgNumber')),
('naxis1', IntegerField()),
('naxis2', IntegerField()),
('imageType_category',
ChoiceField(choices=[('SCIENCE', 'SCIENCE'), ('CALIBRATION', 'CALIBRATION'), ('SIMULATION', 'SIMULATION')], label='ImageType category')),
('imageType_firstType',
ChoiceField(choices=[('OBJECT', 'OBJECT'), ('STD', 'STD'), ('BIAS', 'BIAS'), ('DARK', 'DARK'), ('FLAT', 'FLAT'), ('LINEARITY', 'LINEARITY'), ('OTHER', 'OTHER')], label='ImageType firstType')),
('imageType_secondType',
ChoiceField(choices=[('SKY', 'SKY'), ('LAMP', 'LAMP'), ('DOME', 'DOME'), ('OTHER', 'OTHER')], label='ImageType secondType')),
('observationDateTime',
DateTimeField(label='ObservationDateTime')),
('commandedPointing_rightAscension',
FloatField(label='CommandedPointing rightAscension')),
('commandedPointing_declination',
FloatField(label='CommandedPointing declination')),
('commandedPointing_pointingAngle',
FloatField(label='CommandedPointing pointingAngle')),
('filterWheelPosition',
ChoiceField(choices=[('Y', 'Y'), ('J', 'J'), ('H', 'H'), ('OPEN', 'OPEN'), ('CLOSE', 'CLOSE')], label='FilterWheelPosition')),
('grismWheelPosition',
ChoiceField(choices=[('BLUE0', 'BLUE0'), ('RED0', 'RED0'), ('RED90', 'RED90'), ('RED180OPENCLOSE', 'RED180OPENCLOSE')], label='GrismWheelPosition')),
('instrument', NestedSerializer(read_only=True):
id = IntegerField(label='ID', read_only=True)
instrumentName = CharField(label='InstrumentName', max_length=100)
telescopeName = CharField(label='TelescopeName', max_length=100))])
%% Cell type:code id: tags:
``` python
from composite_field.rest_framework_support import CompositeFieldSerializer
c = CompositeFieldSerializer()
```
%% Cell type:code id: tags:
``` python
c.to_representation(it)
```
%% Output
{'category': 'SCIENCE', 'firstType': 'OBJECT', 'secondType': 'STD'}
%% Cell type:code id: tags:
``` python
m = NispRawFrameSerializer.Meta.model
```
%% Cell type:code id: tags:
``` python
m._meta.concrete_model._meta.fields[15].serialize
```
%% Output
False
%% Cell type:code id: tags:
``` python
type(p)
```
%% Output
imagedb.models.Pointing
%% Cell type:code id: tags:
``` python
from composite_field import CompositeField
```
%% Cell type:code id: tags:
``` python
isinstance(p, CompositeField)
```
%% Output
True
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'orm_example.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
"""
Django settings for orm_example project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5yu24^zybby@-q_x%ry-nit^!%o8oc2oxmos7d3_d@hf(+qo5k'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'imagedb',
'rest_framework',
'url_filter',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': [
'url_filter.integrations.drf.DjangoFilterBackend',
]
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'orm_example.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'orm_example.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
"""orm_example URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('imagedb/', include('imagedb.urls')),
path('admin/', admin.site.urls),
]
"""
WSGI config for orm_example project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'orm_example.settings')
application = get_wsgi_application()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment