-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathmodels.py
More file actions
2725 lines (2430 loc) · 92.5 KB
/
models.py
File metadata and controls
2725 lines (2430 loc) · 92.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
from datetime import timedelta
from statistics import mean, median
from actstream.actions import follow, is_following
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.mail import mail_managers
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Count, Q
from django.db.models.functions import Coalesce
from django.db.transaction import on_commit
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.html import format_html
from django.utils.text import get_valid_filename
from django.utils.timezone import localtime
from django_extensions.db.fields import AutoSlugField
from guardian.shortcuts import assign_perm, remove_perm
from grandchallenge.algorithms.models import (
AlgorithmImage,
AlgorithmInterface,
AlgorithmModel,
Job,
)
from grandchallenge.archives.models import Archive
from grandchallenge.challenges.models import Challenge
from grandchallenge.components.models import (
CIVForObjectMixin,
ComponentImage,
ComponentInterface,
ComponentJob,
ComponentJobManager,
ImportStatusChoices,
Tarball,
)
from grandchallenge.components.schemas import (
SELECTABLE_GPU_TYPES_SCHEMA,
GPUTypeChoices,
get_default_gpu_type_choices,
)
from grandchallenge.core.error_messages import (
EvaluationErrorMessages,
SystemErrorMessages,
)
from grandchallenge.core.guardian import (
GroupObjectPermissionBase,
UserObjectPermissionBase,
)
from grandchallenge.core.models import (
FieldChangeMixin,
TitleSlugDescriptionModel,
UUIDModel,
)
from grandchallenge.core.storage import (
private_s3_storage,
protected_s3_storage,
)
from grandchallenge.core.templatetags.remove_whitespace import oxford_comma
from grandchallenge.core.validators import (
ExtensionValidator,
JSONValidator,
MimeTypeValidator,
)
from grandchallenge.emails.emails import send_standard_email_batch
from grandchallenge.evaluation.tasks import (
assign_evaluation_permissions,
assign_submission_permissions,
calculate_ranks,
check_prerequisites_for_evaluation_execution,
update_combined_leaderboard,
)
from grandchallenge.evaluation.templatetags.evaluation_extras import (
get_jsonpath,
)
from grandchallenge.evaluation.utils import (
Metric,
StatusChoices,
SubmissionKindChoices,
)
from grandchallenge.forge.models import ForgePhase
from grandchallenge.hanging_protocols.models import HangingProtocolMixin
from grandchallenge.notifications.models import (
Notification,
NotificationTypeChoices,
)
from grandchallenge.profiles.models import EmailSubscriptionTypes
from grandchallenge.profiles.tasks import deactivate_user
from grandchallenge.subdomains.utils import reverse
from grandchallenge.uploads.models import UserUpload
from grandchallenge.utilization.models import EvaluationUtilization
from grandchallenge.verifications.models import VerificationUserSet
logger = logging.getLogger(__name__)
EXTRA_RESULT_COLUMNS_SCHEMA = {
"definitions": {},
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "array",
"title": "The Extra Results Columns Schema",
"items": {
"$id": "#/items",
"type": "object",
"title": "The Items Schema",
"required": ["title", "path", "order"],
"additionalProperties": False,
"properties": {
"title": {
"$id": "#/items/properties/title",
"type": "string",
"title": "The Title Schema",
"default": "",
"examples": ["Mean Dice"],
"pattern": "^(.*)$",
},
"path": {
"$id": "#/items/properties/path",
"type": "string",
"title": "The Path Schema",
"default": "",
"examples": ["aggregates.dice.mean"],
"pattern": "^(.*)$",
},
"error_path": {
"$id": "#/items/properties/error_path",
"type": "string",
"title": "The Error Path Schema",
"default": "",
"examples": ["aggregates.dice.std"],
"pattern": "^(.*)$",
},
"order": {
"$id": "#/items/properties/order",
"type": "string",
"enum": ["asc", "desc"],
"title": "The Order Schema",
"default": "",
"examples": ["asc"],
"pattern": "^(asc|desc)$",
},
"exclude_from_ranking": {
"$id": "#/items/properties/exclude_from_ranking",
"type": "boolean",
"title": "The Exclude From Ranking Schema",
"default": False,
},
},
},
}
def get_archive_items_for_interfaces(*, algorithm_interfaces, archive_items):
valid_archive_items_per_interface = {}
for interface in algorithm_interfaces:
inputs = interface.inputs.all()
valid_archive_items_per_interface[interface] = (
archive_items.annotate(
input_count=Count("values", distinct=True),
relevant_input_count=Count(
"values",
filter=Q(values__interface__in=inputs),
distinct=True,
),
)
.filter(input_count=len(inputs), relevant_input_count=len(inputs))
.prefetch_related("values")
)
return valid_archive_items_per_interface
def get_valid_jobs_for_interfaces_and_archive_items(
*,
algorithm_image,
algorithm_interfaces,
valid_archive_items_per_interface,
algorithm_model=None,
subset_by_status=None,
):
if algorithm_model:
extra_filter = {"algorithm_model": algorithm_model}
else:
extra_filter = {"algorithm_model__isnull": True}
if subset_by_status:
extra_filter["status__in"] = subset_by_status
jobs = Job.objects.filter(
algorithm_image=algorithm_image,
creator=None,
**extra_filter,
)
jobs_per_interface = {}
for interface in algorithm_interfaces:
jobs_per_interface[interface] = []
jobs_for_interface = (
jobs.filter(
algorithm_interface=interface,
inputs__archive_items__in=valid_archive_items_per_interface[
interface
],
)
.distinct()
.prefetch_related("inputs")
.select_related("algorithm_image__algorithm")
)
archive_item_value_sets = {
frozenset(value.pk for value in item.values.all())
for item in valid_archive_items_per_interface[interface]
}
for job in jobs_for_interface:
# subset to jobs whose input set exactly matches
# one of the valid archive items' value sets
if (
frozenset(inpt.pk for inpt in job.inputs.all())
in archive_item_value_sets
):
jobs_per_interface[interface].append(job)
return jobs_per_interface
class PhaseManager(models.Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.prefetch_related(
# This should be a select_related, but I cannot find a way
# to use a custom model manager with select_related
models.Prefetch(
"challenge",
queryset=Challenge.objects.with_available_compute(),
)
)
)
SUBMISSION_WINDOW_PARENT_VALIDATION_TEXT = (
"The parent phase needs to open submissions before the current "
"phase since submissions to this phase will only be possible "
"after successful submission to the parent phase."
)
class Phase(FieldChangeMixin, HangingProtocolMixin, UUIDModel):
# This must match the syntax used in jquery datatables
# https://datatables.net/reference/option/order
ASCENDING = "asc"
DESCENDING = "desc"
EVALUATION_SCORE_SORT_CHOICES = (
(ASCENDING, "Ascending"),
(DESCENDING, "Descending"),
)
OFF = "off"
OPTIONAL = "opt"
REQUIRED = "req"
SUPPLEMENTARY_URL_CHOICES = SUPPLEMENTARY_FILE_CHOICES = (
(OFF, "Off"),
(OPTIONAL, "Optional"),
(REQUIRED, "Required"),
)
ALL = "all"
MOST_RECENT = "rec"
BEST = "bst"
RESULT_DISPLAY_CHOICES = (
(ALL, "Display all results"),
(MOST_RECENT, "Only display each users most recent result"),
(BEST, "Only display each users best result"),
)
ABSOLUTE = "abs"
MEAN = "avg"
MEDIAN = "med"
SCORING_CHOICES = (
(ABSOLUTE, "Use the absolute value of the score column"),
(
MEAN,
"Use the mean of the relative ranks of the score and extra result columns",
),
(
MEDIAN,
"Use the median of the relative ranks of the score and extra result columns",
),
)
SubmissionKindChoices = SubmissionKindChoices
StatusChoices = StatusChoices
challenge = models.ForeignKey(
Challenge, on_delete=models.PROTECT, editable=False
)
archive = models.ForeignKey(
Archive,
on_delete=models.SET_NULL,
null=True,
blank=True,
help_text=(
"Which archive should be used as the source dataset for this "
"phase?"
),
)
title = models.CharField(
max_length=64,
help_text="The title of this phase.",
)
slug = AutoSlugField(populate_from="title", max_length=64)
score_title = models.CharField(
max_length=64,
blank=False,
default="Score",
help_text=(
"The name that will be displayed for the scores column, for "
"instance: Score (log-loss)"
),
)
score_jsonpath = models.CharField(
max_length=255,
blank=True,
help_text=(
"The jsonpath of the field in metrics.json that will be used "
"for the overall scores on the results page. See "
"http://goessner.net/articles/JsonPath/ for syntax. For example: "
"dice.mean"
),
)
score_error_jsonpath = models.CharField(
max_length=255,
blank=True,
help_text=(
"The jsonpath for the field in metrics.json that contains the "
"error of the score, eg: dice.std"
),
)
score_default_sort = models.CharField(
max_length=4,
choices=EVALUATION_SCORE_SORT_CHOICES,
default=DESCENDING,
help_text=(
"The default sorting to use for the scores on the results page."
),
)
score_decimal_places = models.PositiveSmallIntegerField(
blank=False,
default=4,
help_text=("The number of decimal places to display for the score"),
)
extra_results_columns = models.JSONField(
default=list,
blank=True,
help_text=(
"A JSON object that contains the extra columns from metrics.json "
"that will be displayed on the results page. An example that will display "
"accuracy score with error would look like this: "
"[{"
'"path": "accuracy.mean",'
'"order": "asc",'
'"title": "ASSD +/- std",'
'"error_path": "accuracy.std",'
'"exclude_from_ranking": true'
"}]"
),
validators=[JSONValidator(schema=EXTRA_RESULT_COLUMNS_SCHEMA)],
)
scoring_method_choice = models.CharField(
max_length=3,
choices=SCORING_CHOICES,
default=ABSOLUTE,
help_text=("How should the rank of each result be calculated?"),
)
result_display_choice = models.CharField(
max_length=3,
choices=RESULT_DISPLAY_CHOICES,
default=ALL,
help_text=("Which results should be displayed on the leaderboard?"),
)
submission_kind = models.PositiveSmallIntegerField(
default=SubmissionKindChoices.CSV,
choices=SubmissionKindChoices.choices,
help_text=(
"Should participants submit a .csv/.zip file of predictions, "
"or an algorithm?"
),
)
allow_submission_comments = models.BooleanField(
default=False,
help_text=(
"Allow users to submit comments as part of their submission."
),
)
display_submission_comments = models.BooleanField(
default=False,
help_text=(
"If true, submission comments are shown on the results page."
),
)
supplementary_file_choice = models.CharField(
max_length=3,
choices=SUPPLEMENTARY_FILE_CHOICES,
default=OFF,
help_text=(
"Show a supplementary file field on the submissions page so that "
"users can upload an additional file along with their predictions "
"file as part of their submission (eg, include a pdf description "
"of their method). Off turns this feature off, Optional means "
"that including the file is optional for the user, Required means "
"that the user must upload a supplementary file."
),
)
supplementary_file_label = models.CharField(
max_length=32,
blank=True,
default="Supplementary File",
help_text=(
"The label that will be used on the submission and results page "
"for the supplementary file. For example: Algorithm Description."
),
)
supplementary_file_help_text = models.CharField(
max_length=128,
blank=True,
default="",
help_text=(
"The help text to include on the submissions page to describe the "
'submissions file. Eg: "A PDF description of the method.".'
),
)
show_supplementary_file_link = models.BooleanField(
default=False,
help_text=(
"Show a link to download the supplementary file on the results "
"page."
),
)
supplementary_url_choice = models.CharField(
max_length=3,
choices=SUPPLEMENTARY_URL_CHOICES,
default=OFF,
help_text=(
"Show a supplementary url field on the submission page so that "
"users can submit a link to a publication that corresponds to "
"their submission. Off turns this feature off, Optional means "
"that including the url is optional for the user, Required means "
"that the user must provide an url."
),
)
supplementary_url_label = models.CharField(
max_length=32,
blank=True,
default="Publication",
help_text=(
"The label that will be used on the submission and results page "
"for the supplementary url. For example: Publication."
),
)
supplementary_url_help_text = models.CharField(
max_length=128,
blank=True,
default="",
help_text=(
"The help text to include on the submissions page to describe the "
'submissions url. Eg: "A link to your publication.".'
),
)
show_supplementary_url = models.BooleanField(
default=False,
help_text=("Show a link to the supplementary url on the results page"),
)
submissions_limit_per_user_per_period = models.PositiveIntegerField(
default=0,
help_text=(
"The limit on the number of times that a user can make a "
"submission over the submission limit period. "
"Set this to 0 to close submissions for this phase."
),
)
submission_limit_period = models.PositiveSmallIntegerField(
default=1,
null=True,
blank=True,
help_text=(
"The number of days to consider for the submission limit period. "
"If this is set to 1, then the submission limit is applied "
"over the previous day. If it is set to 365, then the submission "
"limit is applied over the previous year. If the value is not "
"set, then the limit is applied over all time."
),
validators=[MinValueValidator(limit_value=1)],
)
submissions_open_at = models.DateTimeField(
null=True,
blank=True,
help_text=(
"If set, participants will not be able to make submissions to "
"this phase before this time. Enter the date and time in your local "
"timezone."
),
)
submissions_close_at = models.DateTimeField(
null=True,
blank=True,
help_text=(
"If set, participants will not be able to make submissions to "
"this phase after this time. Enter the date and time in your local "
"timezone."
),
)
submission_page_markdown = models.TextField(
blank=True,
help_text=(
"Markdown to include on the submission page to provide "
"more context to users making a submission to the phase."
),
)
auto_publish_new_results = models.BooleanField(
default=True,
help_text=(
"If true, new results are automatically made public. If false, "
"the challenge administrator must manually publish each new "
"result."
),
)
display_all_metrics = models.BooleanField(
default=True,
help_text=(
"If True, the entire contents of metrics.json is available "
"on the results detail page and over the API. "
"If False, only the metrics used for ranking are available "
"on the results detail page and over the API. "
"Challenge administrators can always access the full "
"metrics.json over the API."
),
)
algorithm_interfaces = models.ManyToManyField(
to=AlgorithmInterface,
through="evaluation.PhaseAlgorithmInterface",
blank=True,
help_text="The interfaces that an algorithm for this phase must implement.",
)
additional_evaluation_inputs = models.ManyToManyField(
to=ComponentInterface,
through="evaluation.PhaseAdditionalEvaluationInput",
related_name="additional_eval_inputs",
blank=True,
)
evaluation_outputs = models.ManyToManyField(
to=ComponentInterface,
related_name="eval_outputs",
through="evaluation.PhaseEvaluationOutput",
)
algorithm_selectable_gpu_type_choices = models.JSONField(
default=get_default_gpu_type_choices,
help_text=(
"The GPU type choices that participants will be able to select for their "
"algorithm inference jobs. The setting on the algorithm will be "
"validated against this on submission. Options are "
f"{GPUTypeChoices.values}.".replace("'", '"')
),
validators=[JSONValidator(schema=SELECTABLE_GPU_TYPES_SCHEMA)],
)
algorithm_maximum_settable_memory_gb = models.PositiveSmallIntegerField(
default=settings.ALGORITHMS_MAX_MEMORY_GB,
help_text=(
"Maximum amount of main memory (DRAM) that participants will be allowed to "
"assign to algorithm inference jobs for submission. The setting on the "
"algorithm will be validated against this on submission."
),
)
algorithm_time_limit = models.PositiveIntegerField(
default=20 * 60,
help_text="Time limit for inference jobs in seconds",
validators=[
MinValueValidator(
limit_value=settings.COMPONENTS_MINIMUM_JOB_DURATION
),
MaxValueValidator(
limit_value=settings.COMPONENTS_MAXIMUM_JOB_DURATION
),
],
)
give_algorithm_editors_job_view_permissions = models.BooleanField(
default=False,
help_text=(
"If set to True algorithm editors (i.e. challenge participants) "
"will automatically be given view permissions to the algorithm "
"jobs and their logs associated with this phase. "
"This saves challenge administrators from having to "
"manually share the logs for each failed submission. "
"<b>Setting this to True will essentially make the data in "
"the linked archive accessible to the participants. "
"Only set this to True for debugging phases, where "
"participants can check that their algorithms are working.</b> "
"Algorithm editors will only be able to access their own "
"logs and predictions, not the logs and predictions from "
"other users. "
),
)
evaluation_time_limit = models.PositiveIntegerField(
default=60 * 60,
help_text="Time limit for evaluation jobs in seconds",
validators=[
MinValueValidator(
limit_value=settings.COMPONENTS_MINIMUM_JOB_DURATION
),
MaxValueValidator(
limit_value=settings.COMPONENTS_MAXIMUM_JOB_DURATION
),
],
)
evaluation_selectable_gpu_type_choices = models.JSONField(
default=get_default_gpu_type_choices,
help_text=(
"The GPU type choices that challenge admins will be able to set for the "
f"evaluation method. Options are {GPUTypeChoices.values}.".replace(
"'", '"'
)
),
validators=[JSONValidator(schema=SELECTABLE_GPU_TYPES_SCHEMA)],
)
evaluation_requires_gpu_type = models.CharField(
max_length=4,
blank=True,
default=GPUTypeChoices.NO_GPU,
choices=GPUTypeChoices.choices,
help_text=(
"What GPU to attach to this phases evaluations. "
"Note that the GPU attached to any algorithm inference jobs "
"is determined by the submitted algorithm."
),
)
evaluation_maximum_settable_memory_gb = models.PositiveSmallIntegerField(
default=settings.ALGORITHMS_MAX_MEMORY_GB,
help_text=(
"Maximum amount of main memory (DRAM) that challenge admins will be able to "
"assign for the evaluation method."
),
)
evaluation_requires_memory_gb = models.PositiveSmallIntegerField(
default=8,
help_text=(
"How much main memory (DRAM) to assign to this phases evaluations. "
"Note that the memory assigned to any algorithm inference jobs "
"is determined by the submitted algorithm."
),
)
public = models.BooleanField(
default=True,
help_text=(
"Uncheck this box to hide this phase's submission page and "
"leaderboard from participants. Participants will then no longer "
"have access to their previous submissions and evaluations from this "
"phase if they exist, and they will no longer see the "
"respective submit and leaderboard tabs for this phase. "
"For you as admin these tabs remain visible. "
"Note that hiding a phase is only possible if submissions for "
"this phase are closed for participants."
),
)
workstation = models.ForeignKey(
"workstations.Workstation",
null=True,
blank=True,
on_delete=models.PROTECT,
)
workstation_config = models.ForeignKey(
"workstation_configs.WorkstationConfig",
null=True,
blank=True,
on_delete=models.SET_NULL,
)
optional_hanging_protocols = models.ManyToManyField(
"hanging_protocols.HangingProtocol",
through="OptionalHangingProtocolPhase",
related_name="optional_for_phase",
blank=True,
help_text="Optional alternative hanging protocols for this phase",
)
average_algorithm_job_duration = models.DurationField(
editable=False,
null=True,
help_text="The average duration of successful algorithm jobs for this phase",
)
compute_cost_euro_millicents = models.PositiveBigIntegerField(
# We store euro here as the costs were incurred at a time when
# the exchange rate may have been different
editable=False,
default=0,
help_text="The total compute cost for this phase in Euro Cents, including Tax",
)
parent = models.ForeignKey(
"self",
on_delete=models.PROTECT,
related_name="children",
null=True,
blank=True,
help_text=(
"Is this phase dependent on another phase? If selected, submissions "
"to the current phase will only be possible after a successful "
"submission has been made to the parent phase. "
"<b>Bear in mind that if you require a successful submission to a "
"sanity check phase in order to submit to a final test phase, "
"it could prevent people from submitting to the test phase on deadline "
"day if the sanity check submission takes a long time to execute. </b>"
),
)
external_evaluation = models.BooleanField(
default=False,
help_text=(
"Are submissions to this phase evaluated externally? "
"If so, it is the responsibility of the external service to "
"claim and evaluate new submissions, download the submitted "
"algorithm models and images and return the results."
),
)
objects = PhaseManager()
class Meta:
unique_together = (("challenge", "title"), ("challenge", "slug"))
ordering = ("challenge", "submissions_open_at", "created")
permissions = (
("create_phase_submission", "Create Phase Submission"),
("configure_algorithm_phase", "Configure Algorithm Phase"),
)
def __str__(self):
return f"{self.title} Evaluation for {self.challenge.short_name}"
def save(self, *args, skip_calculate_ranks=False, **kwargs):
adding = self._state.adding
super().save(*args, **kwargs)
if adding:
self.set_default_interfaces()
self.assign_permissions()
for admin in self.challenge.get_admins():
if not is_following(admin, self):
follow(
user=admin,
obj=self,
actor_only=False,
send_action=False,
)
if self.has_changed("public"):
self.assign_permissions()
on_commit(
assign_evaluation_permissions.signature(
kwargs={"phase_pks": [self.pk]}
).apply_async
)
on_commit(
assign_submission_permissions.signature(
kwargs={"phase_pk": self.pk}
).apply_async
)
if (
self.give_algorithm_editors_job_view_permissions
and self.has_changed("give_algorithm_editors_job_view_permissions")
):
self.send_give_algorithm_editors_job_view_permissions_changed_email()
if not skip_calculate_ranks:
on_commit(
calculate_ranks.signature(
kwargs={"phase_pk": self.pk}
).apply_async
)
def clean(self):
super().clean()
self._clean_submission_kind()
self._clean_algorithm_submission_settings()
self._clean_submission_limits()
self._clean_parent_phase()
self._clean_external_evaluation()
self._clean_evaluation_requirements()
def _clean_submission_kind(self):
if self.has_changed("submission_kind"):
if self.submission_set.exists():
raise ValidationError(
"Cannot change submission kind of Phase with existing submissions"
)
def _clean_algorithm_submission_settings(self):
if self.submission_kind == SubmissionKindChoices.ALGORITHM:
if (
self.submissions_limit_per_user_per_period > 0
and not self.external_evaluation
and (not self.archive or not self.algorithm_interfaces)
):
raise ValidationError(
format_html(
(
"To change the submission limit to above 0, you need to first link an archive containing the secret "
"test data to this phase and define the interfaces (input-output combinations) that the submitted algorithms need to "
"read/write. To configure these settings, please get in touch with {support_email}."
),
support_email=settings.SUPPORT_EMAIL,
)
)
if (
self.give_algorithm_editors_job_view_permissions
and not self.submission_kind
== self.SubmissionKindChoices.ALGORITHM
):
raise ValidationError(
"Give Algorithm Editors Job View Permissions can only be enabled for Algorithm type phases"
)
def _clean_submission_limits(self):
if (
self.submissions_limit_per_user_per_period > 0
and not self.active_image
and not self.external_evaluation
):
raise ValidationError(
"You need to first add a valid method for this phase before you "
"can change the submission limit to above 0."
)
if (
self.submissions_open_at
and self.submissions_close_at
and self.submissions_close_at < self.submissions_open_at
):
raise ValidationError(
"The submissions close date needs to be after "
"the submissions open date."
)
if not self.public and self.open_for_submissions:
raise ValidationError(
"A phase can only be hidden if it is closed for submissions. "
"To close submissions for this phase, either set "
"submissions_limit_per_user_per_period to 0, or set appropriate phase start / end dates."
)
if (
self.submissions_open_at
and self.parent
and self.parent.submissions_open_at
and self.submissions_open_at < self.parent.submissions_open_at
):
raise ValidationError(SUBMISSION_WINDOW_PARENT_VALIDATION_TEXT)
def _clean_external_evaluation(self):
if self.external_evaluation:
if self.method_set.exists():
raise ValidationError(
"Phases that have an evaluation method cannot be turned "
"into external evaluation phases. Remove the method and "
"try again."
)
if not self.submission_kind == SubmissionKindChoices.ALGORITHM:
raise ValidationError(
"External evaluation is only possible for algorithm submission phases."
)
if not self.parent:
raise ValidationError(
"An external evaluation phase must have a parent phase."
)
def _clean_evaluation_requirements(self):
if (
self.evaluation_requires_gpu_type
not in self.evaluation_selectable_gpu_type_choices
):
raise ValidationError(
f"{self.evaluation_requires_gpu_type!r} is not a valid choice "
f"for Evaluation requires gpu type. Either change the choice or "
f"add it to the list of selectable gpu types."
)
if (
self.evaluation_requires_memory_gb
> self.evaluation_maximum_settable_memory_gb
):
raise ValidationError(
f"Ensure the value for Evaluation requires memory gb (currently "
f"{self.evaluation_requires_memory_gb}) is less than or equal "
f"to the maximum settable (currently "
f"{self.evaluation_maximum_settable_memory_gb})."
)
@property
def scoring_method(self):
if self.scoring_method_choice == self.ABSOLUTE:
def scoring_method(x):
return list(x)[0]
elif self.scoring_method_choice == self.MEAN:
scoring_method = mean
elif self.scoring_method_choice == self.MEDIAN:
scoring_method = median
else:
raise NotImplementedError
return scoring_method
@property
def algorithm_interfaces_locked(self):
if self.parent or self.children.exists():
return True
else:
return False
@property
def algorithm_interfaces_locked_message(self):
return "Disabled because this phase is a parent or has a parent phase."
@cached_property
def valid_metrics(self):
return (
Metric(
path=self.score_jsonpath,
reverse=(self.score_default_sort == self.DESCENDING),
),
*[
Metric(
path=col["path"], reverse=col["order"] == self.DESCENDING
)
for col in self.extra_results_columns
if not col.get("exclude_from_ranking", False)
],
)
@property
def read_only_fields_for_dependent_phases(self):
return ["submission_kind"]
def _clean_parent_phase(self):
if self.parent:
if self.parent not in self.parent_phase_choices:
raise ValidationError(
f"This phase cannot be selected as parent phase for the current "
f"phase. The parent phase needs to match the current phase in "
f"all of the following settings: algorithm interfaces, "
f"{oxford_comma(self.read_only_fields_for_dependent_phases)}. "
f"The parent phase cannot have the current phase or any of "
f"the current phase's children set as its parent."
)
if self.parent.jobs_to_schedule_per_submission < 1:
raise ValidationError(
"The parent phase needs to have at least 1 valid archive item."
)
if (
self.submissions_open_at
and self.parent.submissions_open_at
and self.submissions_open_at < self.parent.submissions_open_at
):
raise ValidationError(SUBMISSION_WINDOW_PARENT_VALIDATION_TEXT)
def set_default_interfaces(self):
self.evaluation_outputs.set(
[ComponentInterface.objects.get(slug="metrics-json-file")]
)
@cached_property
def linked_component_interfaces(self):
return (
ComponentInterface.objects.filter(
Q(inputs__in=self.algorithm_interfaces.all())
| Q(outputs__in=self.algorithm_interfaces.all())
)
.distinct()
.order_by("pk")
)
def assign_permissions(self):
assign_perm("view_phase", self.challenge.admins_group, self)
assign_perm("change_phase", self.challenge.admins_group, self)
assign_perm(
"create_phase_submission", self.challenge.admins_group, self
)
if self.public:
assign_perm(
"create_phase_submission",
self.challenge.participants_group,
self,
)
else:
remove_perm(
"create_phase_submission",