dodane pole z sekwencja
[qcg-portal.git] / qcg / forms.py
1 # coding=utf-8
2 from django import forms
3 from django.core.validators import RegexValidator
4 from django.template.defaultfilters import capfirst
5 from pyqcg.utils import TaskStatus
6
7 from qcg.fields import TimeRangeField
8 from qcg.models import Task, Allocation, JobTemplate
9
10
11 date_range_validator = RegexValidator(r'[0-9]{2}\.[0-9]{2}\.[0-9]{4} - [0-9]{2}\.[0-9]{2}\.[0-9]{4}')
12 nodes_validator = RegexValidator(r'^[0-9]{1,3}:[0-9]{1,2}(:[0-9]{1,2})?$')
13 env_name_validator = RegexValidator(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
14
15 CHOICES_PLACEHOLDER = (None, '')
16
17
18 class FiltersForm(forms.Form):
19     ACTIVE, FINISHED, FAILED = range(3)
20     STATUS_CHOICES = (
21         (ACTIVE, u"Aktywne"),
22         (FINISHED, u"Zakończone"),
23         (FAILED, u"Niepowodzenia"),
24     )
25
26     STATUS_MAP = {
27         ACTIVE: (
28             Task.STATUS_CHOICES_REVERSED[TaskStatus.UNSUBMITTED],
29             Task.STATUS_CHOICES_REVERSED[TaskStatus.UNCOMMITTED],
30             Task.STATUS_CHOICES_REVERSED[TaskStatus.QUEUED],
31             Task.STATUS_CHOICES_REVERSED[TaskStatus.PREPROCESSING],
32             Task.STATUS_CHOICES_REVERSED[TaskStatus.PENDING],
33             Task.STATUS_CHOICES_REVERSED[TaskStatus.RUNNING],
34             Task.STATUS_CHOICES_REVERSED[TaskStatus.STOPPED],
35             Task.STATUS_CHOICES_REVERSED[TaskStatus.POSTPROCESSING],
36         ),
37         FINISHED: (
38             Task.STATUS_CHOICES_REVERSED[TaskStatus.FINISHED],
39         ),
40         FAILED: (
41             Task.STATUS_CHOICES_REVERSED[TaskStatus.FAILED],
42             Task.STATUS_CHOICES_REVERSED[TaskStatus.CANCELED],
43         ),
44     }
45     STATUS_CHOICES_DICT = dict(STATUS_CHOICES)
46
47     keywords = forms.CharField(max_length=100, label=u"Wyszukaj frazę", required=False)
48     status = forms.MultipleChoiceField(choices=STATUS_CHOICES, label=u"Status", required=False,
49                                        widget=forms.CheckboxSelectMultiple)
50
51     # advanced
52     host = forms.MultipleChoiceField(label=u"Host", required=False, widget=forms.CheckboxSelectMultiple)
53     purged = forms.TypedChoiceField(label=u"Istniejący katalog roboczy?", required=False, coerce=lambda x: bool(int(x)),
54                                     choices=((0, 'Tak'), (1, 'Nie')), widget=forms.RadioSelect)
55     submission = forms.CharField(label=u"Data zlecenia", validators=[date_range_validator], required=False)
56     finish = forms.CharField(label=u"Data zakończenia", validators=[date_range_validator], required=False)
57
58     def __init__(self, *args, **kwargs):
59         super(FiltersForm, self).__init__(*args, **kwargs)
60
61         self.fields['host'].choices = tuple(
62             (host, capfirst(host.split('.', 1)[0]))
63             for host in Allocation.objects.values_list('host_name', flat=True).order_by('host_name').distinct())
64
65
66 class JobDescriptionForm(forms.Form):
67     class Host(object):
68         GALERA = 'galera.task.gda.pl'
69         HYDRA = 'hydra.icm.edu.pl'
70         INULA = 'inula.man.poznan.pl'
71         MOSS = 'moss.man.poznan.pl'
72         NOVA = 'nova.wcss.wroc.pl'
73         REEF = 'reef.man.poznan.pl'
74         ZEUS = 'zeus.cyfronet.pl'
75
76         CHOICES = (
77             CHOICES_PLACEHOLDER,
78             (INULA, u'Inula'),
79         )
80
81     class Process(object):
82         NONE = ''
83         CMD = 'c'
84         SCRIPT = 's'
85
86         CHOICES = (
87             (NONE, u'Brak'),
88             (CMD, u'Polecenie'),
89             (SCRIPT, u'Skrypt'),
90         )
91
92     APPLICATION_CHOICES = (
93         CHOICES_PLACEHOLDER,
94         ('unres-gab', 'UNRES GAB'),
95         ('unres-e0ll2y', 'UNRES E0LL2Y'),
96     )
97         
98     QUEUE_CHOICES = (
99         CHOICES_PLACEHOLDER,
100         ('plgrid', 'plgrid'),
101         ('plgrid-long', 'plgrid-long'),
102         ('plgrid-testing', 'plgrid-testing'),
103     )
104     MODULES_CHOICES = (
105         CHOICES_PLACEHOLDER,
106     )
107     PROTOCOL_CHOICES = (
108         ('', u'Brak'),
109         ('mailto', u'E-mail'),
110         ('xmpp', u'XMPP'),
111     )
112
113     FORCE_FIELD_CHOICES = (
114         ('GAB', u'GAB'),
115         ('E0LL2Y', u'E0LL2Y'),
116     )
117
118     nstep = forms.IntegerField(label=u"NSTEP", help_text=u"Liczba kroków w trajektorii", min_value=1, initial=500000, required=False)
119     ntwe = forms.IntegerField(label=u"NTWE", help_text=u"Częstość zapisu energii w krokach", min_value=0, initial=100, required=False)
120     ntwx = forms.IntegerField(label=u"NTWX", help_text=u"Częstość zapisu współrzędnych w krokach", min_value=0, initial=1000, required=False)
121     dt = forms.DecimalField(label=u"DT", help_text=u"Krok czasowy. Wartość kroku równa jedności to 48.9 fs", max_digits=5, decimal_places=2, min_value=0.01, initial=0.1, required=False)
122     damax = forms.DecimalField(label=u"DAMAX", help_text=u"Maksymalna dopuszczalna zmiana przyspieszenia podczas jednego kroku czasowego", max_digits=5, decimal_places=2, min_value=0.01, initial=1.0, required=False)
123     force_field = forms.ChoiceField(choices=FORCE_FIELD_CHOICES, label=u"Pole siłowe", required=False, initial='GAB')
124     nrep = forms.IntegerField(label=u"NREP", help_text=u"Liczba replik", min_value=2, initial=16, required=False)
125     nstex = forms.IntegerField(label=u"NSTEX", help_text=u"Liczba kroków po których następuje wymiana replik", min_value=2, initial=1000, required=False)
126     pdb_file = forms.CharField(label=u"Plik PDB", max_length=500, required=False)
127     retmin = forms.IntegerField(label=u"RETMIN", help_text=u"Dolny zakres temparatur dla wymiany replik", min_value=2, initial=250, required=False)
128     retmax = forms.IntegerField(label=u"RETMAX", help_text=u"Górny zakres temperatur dla wymiany replik", min_value=2, initial=450, required=False)
129     sequence = forms.CharField(label=u"Sekwencja", widget=forms.Textarea(attrs={'rows': 2, 'cols': 40}), required=False)
130     
131     
132     application = forms.ChoiceField(choices=APPLICATION_CHOICES, label=u"Aplikacja", required=False, initial='unres-gab')  # TODO choices
133     master_file = forms.CharField(label=u"Plik główny", max_length=500, required=False)
134     executable = forms.CharField(label=u"Plik wykonywalny", max_length=500, required=False)
135     script = forms.CharField(label=u"Skrypt", widget=forms.Textarea(attrs={'rows': 2, 'cols': 40}), required=False)
136     arguments = forms.MultipleChoiceField(label=u"Argumenty", required=False)
137     note = forms.CharField(label=u"Opis", widget=forms.Textarea(attrs={'rows': 2, 'cols': 40}), required=False)
138     grant = forms.CharField(label=u"Grant", max_length=100, required=False)
139
140     hosts = forms.MultipleChoiceField(label=u"Host", choices=Host.CHOICES, required=False)
141     properties = forms.CharField(label=u"Właściwości węzłów", required=False)
142     queue = forms.ChoiceField(choices=QUEUE_CHOICES, label=u"Kolejka", required=False)
143     procs = forms.IntegerField(label=u"Liczba procesów", min_value=0, required=False)
144     nodes = forms.CharField(label=u"Topologia węzłów", max_length=10, validators=[nodes_validator], required=False)
145     wall_time = TimeRangeField(label=u"Wall time", required=False)
146     memory = forms.IntegerField(label=u"Pamięć (MB)", min_value=0, required=False)
147     memory_per_slot = forms.IntegerField(label=u"Pamięci per proces (MB)", min_value=0, required=False)
148     modules = forms.MultipleChoiceField(label=u"Moduły", choices=MODULES_CHOICES, required=False)  # TODO choices
149     reservation = forms.CharField(label=u"Rezerwacja", max_length=100, required=False)
150
151     input = forms.CharField(label=u"Standardowe wejście", max_length=500, required=False)
152     stage_in = forms.MultipleChoiceField(label=u"Stage in", required=False)
153
154     monitoring = forms.BooleanField(label=u"Portal QCG-Monitoring", required=False)
155     notify_type = forms.ChoiceField(label=u"Monitorowanie stanu", choices=PROTOCOL_CHOICES, required=False, initial='',
156                                     widget=forms.RadioSelect)
157     notify_address = forms.EmailField(label=u"Adres", required=False)
158     watch_output_type = forms.ChoiceField(label=u"Monitorowanie wyjścia", choices=PROTOCOL_CHOICES, required=False,
159                                           initial='', widget=forms.RadioSelect)
160     watch_output_address = forms.EmailField(label=u"Adres", required=False)
161     watch_output_pattern = forms.CharField(label=u"Wzorzec", max_length=500, required=False)
162
163     preprocess_type = forms.ChoiceField(label=u"Preprocessing", choices=Process.CHOICES, required=False,
164                                         initial=Process.NONE, widget=forms.RadioSelect)
165     preprocess_cmd = forms.CharField(label=u"Polecenie", max_length=1000, required=False)
166     preprocess_script = forms.CharField(label=u"Skrypt", max_length=500, required=False)
167     postprocess_type = forms.ChoiceField(label=u"Postprocessing", choices=Process.CHOICES, required=False,
168                                          initial=Process.NONE, widget=forms.RadioSelect)
169     postprocess_cmd = forms.CharField(label=u"Polecenie", max_length=1000, required=False)
170     postprocess_script = forms.CharField(label=u"Skrypt", max_length=500, required=False)
171     native = forms.MultipleChoiceField(label=u"Opcje systemu kolejkowego", required=False)
172     persistent = forms.BooleanField(label=u"Trwałe", required=False)
173
174     def __init__(self, data=None, initial=None, *args, **kwargs):
175         super(JobDescriptionForm, self).__init__(data, initial=initial, *args, **kwargs)
176
177         if data or initial:
178             self._init_user_choices('queue', data, initial)
179             self._init_user_choices('arguments', data, initial)
180             self._init_user_choices('native', data, initial)
181             self._init_user_choices('stage_in', data, initial)
182
183     def clean(self):
184         data = super(JobDescriptionForm, self).clean()
185             
186         force_field = data.get('force_field')
187         
188         if force_field == u'GAB':
189             data['application'] = [u'unres-gab']
190         else:
191             data['application'] = [u'unres-e0ll2y']
192
193         '''if data['master_file']:
194             self.add_error('master_file', u"Należy podać plik główny. :"+data['master_file'])
195         '''
196         if data['procs'] and data['nodes']:
197             self.add_error(None, u"Zdefiniuj tylko jedno z pól: liczbę procesów lub topologię węzłów")
198
199         notify_type = data.get('notify_type')
200         data['notify'] = u'{}:{}'.format(notify_type, data['notify_address']) if notify_type else ''
201
202         wo_type = data.get('watch_output_type')
203         data['watch_output'] = u'{}:{}'.format(wo_type, data['watch_output_address']) if wo_type else ''
204
205         preprocess_type = data.get('preprocess_type')
206         if preprocess_type == self.Process.CMD:
207             data['preprocess'] = data['preprocess_cmd']
208         elif preprocess_type == self.Process.SCRIPT:
209             data['preprocess'] = data['preprocess_script']
210         else:
211             data['preprocess'] = ''
212
213         postprocess_type = data.get('postprocess_type')
214         if postprocess_type == self.Process.CMD:
215             data['postprocess'] = data['postprocess_cmd']
216         elif postprocess_type == self.Process.SCRIPT:
217             data['postprocess'] = data['postprocess_script']
218         else:
219             data['postprocess'] = ''
220
221         return data
222
223     def clean_application(self):
224         return self.cleaned_data['application'].split('/', 1) if self.cleaned_data['application'] else ''
225
226     def clean_nodes(self):
227         return map(int, self.cleaned_data['nodes'].split(':', 2)) if self.cleaned_data['nodes'] else ''
228
229     def clean_executable(self):
230         return self._gsiftp_suffix(self.cleaned_data['executable'])
231
232     def clean_master_file(self):
233         return self._gsiftp_suffix(self.cleaned_data['master_file'])
234
235     def clean_input(self):
236         return self._gsiftp_suffix(self.cleaned_data['input'])
237
238     def clean_stage_in(self):
239         return [self._gsiftp_suffix(item) for item in self.cleaned_data['stage_in']]
240
241     def clean_preprocess_script(self):
242         return self._gsiftp_suffix(self.cleaned_data['preprocess_script'])
243
244     def clean_postprocess_script(self):
245         return self._gsiftp_suffix(self.cleaned_data['postprocess_script'])
246
247     def clean_pdb_file(self):
248         return self._gsiftp_suffix(self.cleaned_data['pdb_file'])
249
250     @staticmethod
251     def _gsiftp_suffix(url):
252         if url:
253             return url if url.startswith('gsiftp://') else 'gsiftp://' + url
254
255     def _init_user_choices(self, name, data, initial):
256         initial = initial.get(name) if initial is not None else None
257         choices = data.getlist(name)[:] if data is not None else []
258
259         if initial:
260             choices += initial if isinstance(initial, list) else [initial]
261             self.fields[name].initial = initial
262
263         if choices:
264             self.fields[name].choices += ((v, v) for v in choices)
265
266
267 class EnvForm(forms.Form):
268     name = forms.CharField(label=u"Nazwa", max_length=100, validators=[env_name_validator],
269                            widget=forms.TextInput(attrs={'placeholder': u'Nazwa'}))
270     value = forms.CharField(label=u"Wartość", max_length=500,
271                             widget=forms.TextInput(attrs={'placeholder': u'Wartość'}))
272
273
274 EnvFormSet = forms.formset_factory(EnvForm, can_delete=True, extra=0)
275
276
277 class ColumnsForm(forms.Form):
278     JOB_ID, DESCRIPTION, SUBMISSION, START, END, STATUS, HOST = range(7)
279     COLUMNS_CHOICES = (
280         (JOB_ID, u"Identyfikator zadania"),
281         (DESCRIPTION, u"Opis"),
282         (SUBMISSION, u"Wysłane"),
283         (START, u"Start"),
284         (END, u"Koniec"),
285         (STATUS, u"Status"),
286         (HOST, u"Host"),
287     )
288
289     columns = forms.MultipleChoiceField(choices=COLUMNS_CHOICES, initial=[k for k, v in COLUMNS_CHOICES[1:]],
290                                         label=u"Kolumny", required=False, widget=forms.CheckboxSelectMultiple)
291
292
293 class JobTemplateForm(forms.ModelForm):
294     class Meta:
295         model = JobTemplate
296         fields = ('name',)