26f901f0242aaf1b432496999b14c0ddea6741a3
[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 Process(object):
68         NONE = ''
69         CMD = 'c'
70         SCRIPT = 's'
71
72         CHOICES = (
73             (NONE, u'Brak'),
74             (CMD, u'Polecenie'),
75             (SCRIPT, u'Skrypt'),
76         )
77
78
79     APPLICATION_CHOICES = (
80         CHOICES_PLACEHOLDER,
81         ('unres-gab', 'UNRES GAB'),
82         ('unres-e0ll2y', 'UNRES E0LL2Y'),
83     )
84         
85
86     QUEUE_CHOICES = (
87         CHOICES_PLACEHOLDER,
88         ('plgrid', 'plgrid'),
89         ('plgrid-long', 'plgrid-long'),
90         ('plgrid-testing', 'plgrid-testing'),
91     )
92
93     PROTOCOL_CHOICES = (
94         ('', u'Brak'),
95         ('mailto', u'E-mail'),
96         ('xmpp', u'XMPP'),
97     )
98
99
100     FORCE_FIELD_CHOICES = (
101         ('GAB', u'GAB'),
102         ('E0LL2Y', u'E0LL2Y'),
103     )
104
105     nstep = forms.IntegerField(label=u"NSTEP", help_text=u"Liczba kroków w trajektorii", min_value=1, initial=500000, required=False)
106     ntwe = forms.IntegerField(label=u"NTWE", help_text=u"Częstość zapisu energii w krokach", min_value=0, initial=100, required=False)
107     ntwx = forms.IntegerField(label=u"NTWX", help_text=u"Częstość zapisu współrzędnych w krokach", min_value=0, initial=1000, required=False)
108     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)
109     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)
110     force_field = forms.ChoiceField(choices=FORCE_FIELD_CHOICES, label=u"Pole siłowe", required=False, initial='GAB')
111
112     pdb_file = forms.CharField(label=u"Plik PDB", max_length=500, required=False)
113     #retmin = forms.IntegerField(label=u"RETMIN", help_text=u"Dolny zakres temparatur dla wymiany replik", min_value=2, initial=250, required=False)
114     #retmax = forms.IntegerField(label=u"RETMAX", help_text=u"Górny zakres temperatur dla wymiany replik", min_value=2, initial=450, required=False)
115     sequence = forms.CharField(label=u"Sekwencja", help_text=u"Sekwencja aminokwasów w zapisie jednoliterowym", widget=forms.Textarea(attrs={'rows': 2, 'cols': 40}), required=False)
116     
117     
118     application = forms.ChoiceField(choices=APPLICATION_CHOICES, label=u"Aplikacja", required=False, initial='unres-gab') 
119     #master_file = forms.CharField(label=u"Plik główny", max_length=500, required=False)
120
121     executable = forms.CharField(label=u"Plik wykonywalny", max_length=500, required=False)
122     script = forms.CharField(label=u"Skrypt", widget=forms.Textarea(attrs={'rows': 2, 'cols': 40}), required=False)
123     arguments = forms.MultipleChoiceField(label=u"Argumenty", required=False)
124     note = forms.CharField(label=u"Opis", widget=forms.Textarea(attrs={'rows': 2, 'cols': 40}), required=False)
125     grant = forms.CharField(label=u"Grant", max_length=100, required=False)
126
127     hosts = forms.MultipleChoiceField(label=u"Host", required=False)
128     properties = forms.CharField(label=u"Właściwości węzłów", required=False)
129     queue = forms.ChoiceField(choices=QUEUE_CHOICES, label=u"Kolejka", required=False)
130     procs = forms.IntegerField(label=u"Liczba procesów", min_value=0, required=False)
131     nodes = forms.CharField(label=u"Topologia węzłów", max_length=10, validators=[nodes_validator], required=False)
132     wall_time = TimeRangeField(label=u"Wall time", required=False)
133     memory = forms.IntegerField(label=u"Pamięć (MB)", min_value=0, required=False)
134     memory_per_slot = forms.IntegerField(label=u"Pamięci per proces (MB)", min_value=0, required=False)
135     modules = forms.MultipleChoiceField(label=u"Moduły", required=False)
136     reservation = forms.CharField(label=u"Rezerwacja", max_length=100, required=False)
137
138     input = forms.CharField(label=u"Standardowe wejście", max_length=500, required=False)
139     stage_in = forms.MultipleChoiceField(label=u"Stage in", required=False)
140
141     monitoring = forms.BooleanField(label=u"Portal QCG-Monitoring", required=False)
142     notify_type = forms.ChoiceField(label=u"Monitorowanie stanu", choices=PROTOCOL_CHOICES, required=False, initial='',
143                                     widget=forms.RadioSelect)
144     notify_address = forms.EmailField(label=u"Adres", required=False)
145     watch_output_type = forms.ChoiceField(label=u"Monitorowanie wyjścia", choices=PROTOCOL_CHOICES, required=False,
146                                           initial='', widget=forms.RadioSelect)
147     watch_output_address = forms.EmailField(label=u"Adres", required=False)
148     watch_output_pattern = forms.CharField(label=u"Wzorzec", max_length=500, required=False)
149
150     preprocess_type = forms.ChoiceField(label=u"Preprocessing", choices=Process.CHOICES, required=False,
151                                         initial=Process.NONE, widget=forms.RadioSelect)
152     preprocess_cmd = forms.CharField(label=u"Polecenie", max_length=1000, required=False)
153     preprocess_script = forms.CharField(label=u"Skrypt", max_length=500, required=False)
154     postprocess_type = forms.ChoiceField(label=u"Postprocessing", choices=Process.CHOICES, required=False,
155                                          initial=Process.NONE, widget=forms.RadioSelect)
156     postprocess_cmd = forms.CharField(label=u"Polecenie", max_length=1000, required=False)
157     postprocess_script = forms.CharField(label=u"Skrypt", max_length=500, required=False)
158     native = forms.MultipleChoiceField(label=u"Opcje systemu kolejkowego", required=False)
159     persistent = forms.BooleanField(label=u"Trwałe", required=False)
160
161     def __init__(self, data=None, initial=None, hosts=(), applications=(), modules=(), *args, **kwargs):
162         super(JobDescriptionForm, self).__init__(data, initial=initial, *args, **kwargs)
163
164         self.fields['hosts'].choices = hosts
165         self.fields['application'].choices = applications
166         self.fields['modules'].choices = modules
167
168         if data or initial:
169             self._init_user_choices('queue', data, initial)
170             self._init_user_choices('arguments', data, initial)
171             self._init_user_choices('native', data, initial)
172             self._init_user_choices('stage_in', data, initial)
173             self._init_user_choices('force_field', data, initial)
174
175     def clean(self):
176         data = super(JobDescriptionForm, self).clean()
177             
178         force_field = data.get('force_field')
179         
180         if force_field == u'GAB':
181             data['application'] = [u'unres-gab']
182         else:
183             data['application'] = [u'unres-e0ll2y']
184
185         if data['pdb_file']== None:
186             self.add_error('pdb_file', u"Należy podać plik PDB.")
187
188         if data['sequence']== '':
189             self.add_error('sequence', u"Należy podać sekwencję aminokwasów.")
190         
191         if data['procs'] and data['nodes']:
192             self.add_error(None, u"Zdefiniuj tylko jedno z pól: liczbę procesów lub topologię węzłów")
193
194         notify_type = data.get('notify_type')
195         data['notify'] = u'{}:{}'.format(notify_type, data['notify_address']) if notify_type else ''
196
197         wo_type = data.get('watch_output_type')
198         data['watch_output'] = u'{}:{}'.format(wo_type, data['watch_output_address']) if wo_type else ''
199
200         preprocess_type = data.get('preprocess_type')
201         if preprocess_type == self.Process.CMD:
202             data['preprocess'] = data['preprocess_cmd']
203         elif preprocess_type == self.Process.SCRIPT:
204             data['preprocess'] = data['preprocess_script']
205         else:
206             data['preprocess'] = ''
207
208         postprocess_type = data.get('postprocess_type')
209         if postprocess_type == self.Process.CMD:
210             data['postprocess'] = data['postprocess_cmd']
211         elif postprocess_type == self.Process.SCRIPT:
212             data['postprocess'] = data['postprocess_script']
213         else:
214             data['postprocess'] = ''
215
216         return data
217
218     def clean_application(self):
219         return self.cleaned_data['application'].split('/', 1) if self.cleaned_data['application'] else ''
220
221     def clean_nodes(self):
222         return map(int, self.cleaned_data['nodes'].split(':', 2)) if self.cleaned_data['nodes'] else ''
223
224     def clean_executable(self):
225         return self._gsiftp_suffix(self.cleaned_data['executable'])
226
227     def clean_master_file(self):
228         return self._gsiftp_suffix(self.cleaned_data['master_file'])
229
230     def clean_input(self):
231         return self._gsiftp_suffix(self.cleaned_data['input'])
232
233     def clean_stage_in(self):
234         return [self._gsiftp_suffix(item) for item in self.cleaned_data['stage_in']]
235
236     def clean_preprocess_script(self):
237         return self._gsiftp_suffix(self.cleaned_data['preprocess_script'])
238
239     def clean_postprocess_script(self):
240         return self._gsiftp_suffix(self.cleaned_data['postprocess_script'])
241
242     def clean_pdb_file(self):
243         return self._gsiftp_suffix(self.cleaned_data['pdb_file'])
244     
245     def clean_sequence(self):
246         return self.cleaned_data['sequence'].strip(' \t\n\r')
247
248     @staticmethod
249     def _gsiftp_suffix(url):
250         if url:
251             return url if url.startswith('gsiftp://') else 'gsiftp://' + url
252
253     def _init_user_choices(self, name, data, initial):
254         initial = initial.get(name) if initial is not None else None
255         choices = data.getlist(name)[:] if data is not None else []
256
257         if initial:
258             choices += initial if isinstance(initial, list) else [initial]
259             self.fields[name].initial = initial
260
261         if choices:
262             self.fields[name].choices += ((v, v) for v in choices)
263
264
265 class EnvForm(forms.Form):
266     name = forms.CharField(label=u"Nazwa", max_length=100, validators=[env_name_validator],
267                            widget=forms.TextInput(attrs={'placeholder': u'Nazwa'}))
268     value = forms.CharField(label=u"Wartość", max_length=500,
269                             widget=forms.TextInput(attrs={'placeholder': u'Wartość'}))
270
271
272 EnvFormSet = forms.formset_factory(EnvForm, can_delete=True, extra=0)
273
274
275 class ColumnsForm(forms.Form):
276     JOB_ID, DESCRIPTION, SUBMISSION, START, END, STATUS, HOST = range(7)
277     COLUMNS_CHOICES = (
278         (JOB_ID, u"Identyfikator zadania"),
279         (DESCRIPTION, u"Opis"),
280         (SUBMISSION, u"Wysłane"),
281         (START, u"Start"),
282         (END, u"Koniec"),
283         (STATUS, u"Status"),
284         (HOST, u"Host"),
285     )
286
287     columns = forms.MultipleChoiceField(choices=COLUMNS_CHOICES, initial=[k for k, v in COLUMNS_CHOICES[1:]],
288                                         label=u"Kolumny", required=False, widget=forms.CheckboxSelectMultiple)
289
290
291 class JobTemplateForm(forms.ModelForm):
292     class Meta:
293         model = JobTemplate
294         fields = ('name',)