-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathmodels.py
More file actions
2176 lines (1973 loc) · 73.3 KB
/
models.py
File metadata and controls
2176 lines (1973 loc) · 73.3 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 datetime
import logging
import math
from actstream.actions import follow, unfollow
from dateutil.relativedelta import relativedelta
from dateutil.utils import today
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.validators import MinValueValidator, validate_slug
from django.db import models
from django.db.models import (
BooleanField,
Case,
Count,
ExpressionWrapper,
F,
Q,
Sum,
Value,
When,
)
from django.db.models.signals import post_delete
from django.db.transaction import on_commit
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.utils.functional import cached_property
from django.utils.html import format_html
from django.utils.module_loading import import_string
from django.utils.text import get_valid_filename
from django.utils.timezone import now, timedelta
from django.utils.translation import gettext_lazy as _
from guardian.compat import get_user_model
from guardian.shortcuts import assign_perm, remove_perm
from guardian.utils import get_anonymous_user
from pictures.models import PictureField
from grandchallenge.anatomy.models import BodyStructure
from grandchallenge.challenges.emails import (
send_challenge_request_processed_update_email,
send_challenge_requested_email_to_requester,
send_challenge_requested_email_to_reviewers,
send_email_percent_budget_consumed_alert,
)
from grandchallenge.challenges.utils import ChallengeTypeChoices
from grandchallenge.components.models import APIMethodChoices
from grandchallenge.components.schemas import GPUTypeChoices
from grandchallenge.core.guardian import (
GroupObjectPermissionBase,
UserObjectPermissionBase,
filter_by_permission,
)
from grandchallenge.core.models import FieldChangeMixin, UUIDModel
from grandchallenge.core.storage import (
get_banner_path,
get_logo_path,
get_social_image_path,
protected_s3_storage,
public_s3_storage,
)
from grandchallenge.core.utils.access_requests import (
AccessRequestHandlingOptions,
)
from grandchallenge.core.validators import (
ExtensionValidator,
JSONValidator,
MimeTypeValidator,
)
from grandchallenge.discussion_forums import models as discussion_forum_models
from grandchallenge.evaluation.tasks import assign_evaluation_permissions
from grandchallenge.evaluation.utils import (
StatusChoices,
SubmissionKindChoices,
)
from grandchallenge.forge.models import ForgeChallenge
from grandchallenge.incentives.models import Incentive
from grandchallenge.invoices.models import (
PaymentStatusChoices,
PaymentTypeChoices,
)
from grandchallenge.modalities.models import ImagingModality
from grandchallenge.organizations.models import Organization
from grandchallenge.pages.models import Page
from grandchallenge.publications.fields import IdentifierField
from grandchallenge.publications.models import Publication
from grandchallenge.subdomains.utils import reverse
from grandchallenge.task_categories.models import TaskType
logger = logging.getLogger(__name__)
class ChallengeQuerySet(models.QuerySet):
def with_available_compute(self):
return self.annotate(
complimentary_compute_costs_euros=(
Sum(
"invoices__compute_costs_euros",
filter=Q(
invoices__payment_type=PaymentTypeChoices.COMPLIMENTARY
),
output_field=models.PositiveBigIntegerField(),
default=0,
)
),
prepaid_compute_costs_euros=(
Sum(
"invoices__compute_costs_euros",
filter=Q(
invoices__payment_type=PaymentTypeChoices.PREPAID,
invoices__payment_status=PaymentStatusChoices.PAID,
),
output_field=models.PositiveBigIntegerField(),
default=0,
)
),
postpaid_compute_costs_euros_if_anything_paid=(
Case(
When(
prepaid_compute_costs_euros__gt=0,
then=Sum(
"invoices__compute_costs_euros",
filter=Q(
invoices__payment_type=PaymentTypeChoices.POSTPAID
)
& ~Q(
invoices__payment_status=PaymentStatusChoices.CANCELLED
),
output_field=models.PositiveBigIntegerField(),
default=0,
),
),
default=0,
output_field=models.PositiveBigIntegerField(),
)
),
approved_compute_costs_euro_millicents=ExpressionWrapper(
(
F("complimentary_compute_costs_euros")
+ F("prepaid_compute_costs_euros")
+ F("postpaid_compute_costs_euros_if_anything_paid")
)
* 1000
* 100,
output_field=models.PositiveBigIntegerField(),
),
available_compute_euro_millicents=ExpressionWrapper(
F("approved_compute_costs_euro_millicents")
- F("compute_cost_euro_millicents"),
output_field=models.BigIntegerField(),
),
)
def with_user_roles(self, *, user):
User = get_user_model() # noqa: N806
return self.annotate(
user_is_challenge_admin=models.Exists(
User.objects.filter(
groups=models.OuterRef("admins_group"),
pk=user.pk,
)
),
user_is_challenge_participant=models.Exists(
User.objects.filter(
groups=models.OuterRef("participants_group"),
pk=user.pk,
)
),
)
def validate_nounderscores(value):
if "_" in value:
raise ValidationError("Underscores (_) are not allowed.")
def validate_short_name(value):
if value.lower() in settings.DISALLOWED_CHALLENGE_NAMES:
raise ValidationError("That name is not allowed.")
if Challenge.objects.filter(short_name__iexact=value).exists():
raise ValidationError("Challenge with this slug already exists")
class ChallengeSeries(models.Model):
name = models.CharField(max_length=64, blank=False, unique=True)
url = models.URLField(blank=True)
class Meta:
ordering = ("name",)
verbose_name_plural = "Challenge Series"
def __str__(self):
return f"{self.name}"
@property
def badge(self):
return format_html(
(
'<span class="badge badge-info above-stretched-link" '
'title="Associated with {0}"><i class="fas fa-globe fa-fw">'
"</i> {0}</span>"
),
self.name,
)
class ChallengeBase(models.Model):
StatusChoices = StatusChoices
creator = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL
)
short_name = models.CharField(
max_length=50,
blank=False,
help_text=(
"short name used in url, specific css, files etc. "
"No spaces allowed"
),
validators=[
validate_nounderscores,
validate_slug,
validate_short_name,
],
unique=True,
)
title = models.CharField(
max_length=64,
blank=True,
default="",
help_text=(
"The name of the challenge that is displayed on the All Challenges"
" page. If this is blank the short name of the challenge will be "
"used."
),
)
task_types = models.ManyToManyField(
TaskType, blank=True, help_text="What type of task is this challenge?"
)
modalities = models.ManyToManyField(
ImagingModality,
blank=True,
help_text="What imaging modalities are used in this challenge?",
)
structures = models.ManyToManyField(
BodyStructure,
blank=True,
help_text="What structures are used in this challenge?",
)
incentives = models.ManyToManyField(
Incentive,
blank=True,
help_text="What incentives are there for users to participate in this challenge?",
)
class Meta:
abstract = True
def get_default_percent_budget_consumed_warning_thresholds():
return [70, 90, 100]
class Challenge(ChallengeBase, FieldChangeMixin):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
description = models.CharField(
max_length=1024,
default="",
blank=True,
help_text="Short summary of this project, max 1024 characters.",
)
logo = PictureField(
upload_to=get_logo_path,
storage=public_s3_storage,
blank=True,
help_text="A logo for this challenge. Should be square with a resolution of 640x640 px or higher.",
aspect_ratios=["1/1"],
width_field="logo_width",
height_field="logo_height",
max_length=255,
)
logo_width = models.PositiveSmallIntegerField(editable=False, null=True)
logo_height = models.PositiveSmallIntegerField(editable=False, null=True)
social_image = PictureField(
upload_to=get_social_image_path,
storage=public_s3_storage,
blank=True,
help_text="An image for this challenge which is displayed when you post the link on social media. Should have a resolution of 640x320 px (1280x640 px for best display).",
aspect_ratios=[None],
width_field="social_image_width",
height_field="social_image_height",
max_length=255,
)
social_image_width = models.PositiveSmallIntegerField(
editable=False, null=True
)
social_image_height = models.PositiveSmallIntegerField(
editable=False, null=True
)
banner = PictureField(
upload_to=get_banner_path,
storage=public_s3_storage,
blank=True,
help_text=(
"Image that gets displayed at the top of each page. "
"Recommended resolution 2200x440 px."
),
aspect_ratios=[None],
width_field="banner_width",
height_field="banner_height",
max_length=255,
)
banner_width = models.PositiveSmallIntegerField(editable=False, null=True)
banner_height = models.PositiveSmallIntegerField(editable=False, null=True)
hidden = models.BooleanField(
default=True,
help_text="Do not display this Challenge in any public overview",
)
is_suspended = models.BooleanField(
default=False,
help_text="Challenge is suspended and not accepting submissions",
)
is_active_until = models.DateField(
help_text="The date at which the challenge becomes inactive",
)
workshop_date = models.DateField(
null=True,
blank=True,
help_text=(
"Date on which the workshop belonging to this project will be held"
),
)
event_name = models.CharField(
max_length=1024,
default="",
blank=True,
null=True,
help_text="The name of the event the workshop will be held at",
)
event_url = models.URLField(
blank=True,
null=True,
help_text="Website of the event which will host the workshop",
)
publications = models.ManyToManyField(
Publication,
blank=True,
help_text="Which publications are associated with this challenge?",
)
data_license_agreement = models.TextField(
blank=True,
help_text="What is the data license agreement for this challenge?",
)
series = models.ManyToManyField(
ChallengeSeries,
blank=True,
help_text="Which challenge series is this associated with?",
)
organizations = models.ManyToManyField(
Organization,
blank=True,
help_text="The organizations associated with this challenge",
related_name="%(class)ss",
)
number_of_training_cases = models.IntegerField(blank=True, null=True)
number_of_test_cases = models.IntegerField(blank=True, null=True)
highlight = models.BooleanField(
default=False,
help_text="Should this challenge be advertised on the home page?",
)
disclaimer = models.CharField(
max_length=2048,
default="",
blank=True,
null=True,
help_text=(
"Optional text to show on each page in the project. "
"For showing 'under construction' type messages"
),
)
access_request_handling = models.CharField(
max_length=25,
choices=AccessRequestHandlingOptions.choices,
default=AccessRequestHandlingOptions.MANUAL_REVIEW,
help_text=("How would you like to handle access requests?"),
)
use_registration_page = models.BooleanField(
default=True,
help_text="If true, show a registration page on the challenge site.",
)
registration_page_markdown = models.TextField(
blank=True,
help_text=(
"Markdown to include on the registration page to provide "
"more context to users registering for the challenge."
),
)
use_teams = models.BooleanField(
default=False,
help_text=(
"If true, users are able to form teams to participate in "
"this challenge together."
),
)
admins_group = models.OneToOneField(
Group,
editable=False,
on_delete=models.PROTECT,
related_name="admins_of_challenge",
)
participants_group = models.OneToOneField(
Group,
editable=False,
on_delete=models.PROTECT,
related_name="participants_of_challenge",
)
external_evaluators_group = models.OneToOneField(
Group,
editable=False,
on_delete=models.PROTECT,
related_name="external_evaluators_of_challenge",
)
discussion_forum = models.OneToOneField(
discussion_forum_models.Forum,
related_name="linked_challenge",
null=True,
editable=False,
on_delete=models.PROTECT,
)
display_forum_link = models.BooleanField(
default=False,
help_text="Display a link to the challenge forum in the nav bar.",
)
cached_num_participants = models.PositiveIntegerField(
editable=False, default=0
)
cached_num_results = models.PositiveIntegerField(editable=False, default=0)
cached_latest_result = models.DateTimeField(
editable=False, blank=True, null=True
)
contact_email = models.EmailField(
blank=True,
default="",
help_text="This email will be listed as the contact email for the challenge and will be visible to all users of Grand Challenge.",
)
percent_budget_consumed_warning_thresholds = models.JSONField(
default=get_default_percent_budget_consumed_warning_thresholds,
validators=[
JSONValidator(
schema={
"$schema": "http://json-schema.org/draft-07/schema",
"type": "array",
"items": {
"type": "integer",
"exclusiveMinimum": 0,
"maximum": 100,
},
"uniqueItems": True,
}
)
],
)
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 challenge in Euro Cents, including Tax",
)
size_in_storage = models.PositiveBigIntegerField(
editable=False,
default=0,
help_text="The number of bytes stored in the storage backend",
)
size_in_registry = models.PositiveBigIntegerField(
editable=False,
default=0,
help_text="The number of bytes stored in the registry",
)
objects = ChallengeQuerySet.as_manager()
class Meta:
verbose_name = "challenge"
verbose_name_plural = "challenges"
ordering = ("pk",)
permissions = [
("add_registration_question", "Can add registration questions"),
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._hidden_orig = self.hidden
def __str__(self):
return self.short_name
@property
def public(self) -> bool:
"""Helper property for consistency with other objects"""
return not self.hidden
@property
def year(self):
if self.workshop_date:
return self.workshop_date.year
else:
return self.created.year
@property
def upcoming_workshop_date(self):
if self.workshop_date and self.workshop_date > datetime.date.today():
return self.workshop_date
@property
def slug(self) -> str:
return self.short_name
@property
def api_url(self) -> str:
return reverse("api:challenge-detail", kwargs={"slug": self.slug})
@cached_property
def is_active(self):
return today().date() < self.is_active_until
def save(self, *args, **kwargs):
adding = self._state.adding
if adding:
self.create_groups()
self.create_forum()
self.is_active_until = today().date() + relativedelta(
months=settings.CHALLENGES_DEFAULT_ACTIVE_MONTHS
)
super().save(*args, **kwargs)
self.assign_permissions()
if adding:
if self.creator:
self.add_admin(user=self.creator)
self.create_default_pages()
self.create_default_onboarding_tasks()
if adding or self.hidden != self._hidden_orig:
on_commit(
assign_evaluation_permissions.signature(
kwargs={
"phase_pks": list(
self.phase_set.values_list("id", flat=True)
)
}
).apply_async
)
if self.has_changed("compute_cost_euro_millicents"):
self.send_alert_if_budget_consumed_warning_threshold_exceeded()
def assign_permissions(self):
# Editors and users can view this challenge
assign_perm("view_challenge", self.admins_group, self)
assign_perm("view_challenge", self.participants_group, self)
# Admins can change this challenge
assign_perm("change_challenge", self.admins_group, self)
# Admin can add registration questions
assign_perm("add_registration_question", self.admins_group, self)
reg_and_anon = Group.objects.get(
name=settings.REGISTERED_AND_ANON_USERS_GROUP_NAME
)
if self.public:
assign_perm("view_challenge", reg_and_anon, self)
else:
remove_perm("view_challenge", reg_and_anon, self)
self.assign_discussion_forum_permissions()
def assign_discussion_forum_permissions(self):
if self.display_forum_link:
assign_perm(
"discussion_forums.view_forum",
self.admins_group,
self.discussion_forum,
)
assign_perm(
"discussion_forums.view_forum",
self.participants_group,
self.discussion_forum,
)
assign_perm(
"discussion_forums.create_forum_topic",
self.admins_group,
self.discussion_forum,
)
assign_perm(
"discussion_forums.create_forum_topic",
self.participants_group,
self.discussion_forum,
)
assign_perm(
"discussion_forums.create_sticky_and_announcement_topic",
self.admins_group,
self.discussion_forum,
)
else:
remove_perm(
"discussion_forums.view_forum",
self.admins_group,
self.discussion_forum,
)
remove_perm(
"discussion_forums.view_forum",
self.participants_group,
self.discussion_forum,
)
remove_perm(
"discussion_forums.create_forum_topic",
self.admins_group,
self.discussion_forum,
)
remove_perm(
"discussion_forums.create_forum_topic",
self.participants_group,
self.discussion_forum,
)
remove_perm(
"discussion_forums.create_sticky_and_announcement_topic",
self.admins_group,
self.discussion_forum,
)
def create_groups(self):
# Create the groups only on first save
admins_group = Group.objects.create(name=f"{self.short_name}_admins")
participants_group = Group.objects.create(
name=f"{self.short_name}_participants"
)
external_evaluators_group = Group.objects.create(
name=f"{self.short_name}_external_evaluators"
)
self.admins_group = admins_group
self.participants_group = participants_group
self.external_evaluators_group = external_evaluators_group
def create_forum(self):
self.discussion_forum = discussion_forum_models.Forum.objects.create()
def create_default_pages(self):
Page.objects.create(
display_title=self.short_name,
content_markdown=render_to_string(
"pages/defaults/home.md", {"challenge": self}
),
challenge=self,
permission_level=Page.ALL,
)
def create_default_onboarding_tasks(self):
OnboardingTask.objects.create(
challenge=self,
title="Create Phases",
description="Create and configure the different phases of the challenge.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=1),
)
OnboardingTask.objects.create(
challenge=self,
title="Define Inputs and Outputs",
description=format_html(
"E-mail {support_email} and communicate the required input and output data formats for participant's algorithms.",
support_email=settings.SUPPORT_EMAIL,
),
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=2),
)
OnboardingTask.objects.create(
challenge=self,
title="Plan Onboarding Meeting",
description="Have an onboarding meeting with challenge organizers.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.SUPPORT,
deadline=self.created + timedelta(weeks=2),
)
OnboardingTask.objects.create(
challenge=self,
title="Have Onboarding Meeting",
description="Download the phase starter kits and have an onboarding meeting with support staff.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=3),
)
OnboardingTask.objects.create(
challenge=self,
title="Create Archives",
description="Create an archive per algorithm-type phase for the challenge.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.SUPPORT,
deadline=self.created + timedelta(weeks=3),
)
OnboardingTask.objects.create(
challenge=self,
title="Upload Data to Archives",
description=format_html(
"Add data to the relevant archives. Archives must be created by support. Please e-mail {support_email} if that is delayed.",
support_email=settings.SUPPORT_EMAIL,
),
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=5),
)
OnboardingTask.objects.create(
challenge=self,
title="Create Example Algorithm",
description="Implement and document a baseline example algorithm for participants to use as a reference. "
"Use the provided phase pack as a starting point.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=6, seconds=0),
)
OnboardingTask.objects.create(
challenge=self,
title="Create Evaluation Method",
description="Implement and document the evaluation method for assessing participant submissions. "
"Use the provided phase pack as a starting point.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=6, seconds=1),
)
OnboardingTask.objects.create(
challenge=self,
title="Configure Scoring",
description="Configure the leaderboard scoring to accurately interpret the evaluation results.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=6, seconds=2),
)
OnboardingTask.objects.create(
challenge=self,
title="Test Evaluation",
description="Run test evaluations using sample submissions to ensure the scoring system and "
"evaluation method function correctly before launching the challenge.",
responsible_party=OnboardingTask.ResponsiblePartyChoices.CHALLENGE_ORGANIZERS,
deadline=self.created + timedelta(weeks=6, seconds=3),
)
def is_admin(self, user) -> bool:
"""Determines if this user is an admin of this challenge."""
return (
user.is_superuser
or user.groups.filter(pk=self.admins_group.pk).exists()
)
def is_participant(self, user) -> bool:
"""Determines if this user is a participant of this challenge."""
return (
user.is_superuser
or user.groups.filter(pk=self.participants_group.pk).exists()
)
def get_admins(self):
"""Return all admins of this challenge."""
return self.admins_group.user_set.all()
def get_participants(self):
"""Return all participants of this challenge."""
return self.participants_group.user_set.all()
def get_absolute_url(self):
return reverse(
"pages:home", kwargs={"challenge_short_name": self.short_name}
)
def add_participant(self, user):
if user != get_anonymous_user():
user.groups.add(self.participants_group)
follow(
user=user,
obj=self.discussion_forum,
actor_only=False,
send_action=False,
)
else:
raise ValueError("You cannot add the anonymous user to this group")
def remove_participant(self, user):
user.groups.remove(self.participants_group)
unfollow(user=user, obj=self.discussion_forum, send_action=False)
def add_admin(self, user):
if user != get_anonymous_user():
user.groups.add(self.admins_group)
follow(
user=user,
obj=self.discussion_forum,
actor_only=False,
send_action=False,
)
else:
raise ValueError("You cannot add the anonymous user to this group")
def remove_admin(self, user):
user.groups.remove(self.admins_group)
unfollow(user=user, obj=self.discussion_forum, send_action=False)
@cached_property
def status(self) -> str:
phase_status = {phase.status for phase in self.visible_phases}
if StatusChoices.OPEN in phase_status:
status = StatusChoices.OPEN
elif {StatusChoices.COMPLETED} == phase_status:
status = StatusChoices.COMPLETED
elif StatusChoices.OPENING_SOON in phase_status:
status = StatusChoices.OPENING_SOON
else:
status = StatusChoices.CLOSED
return status
@cached_property
def should_be_open_but_is_over_budget(self):
return self.available_compute_euro_millicents <= 0 and any(
phase.submission_period_is_open_now
and phase.submissions_limit_per_user_per_period > 0
for phase in self.phase_set.all()
)
@cached_property
def percent_budget_consumed(self):
if self.approved_compute_costs_euro_millicents:
return int(
100
* self.compute_cost_euro_millicents
/ self.approved_compute_costs_euro_millicents
)
else:
return None
def send_alert_if_budget_consumed_warning_threshold_exceeded(self):
for percent_threshold in sorted(
self.percent_budget_consumed_warning_thresholds, reverse=True
):
previous_cost = self.initial_value("compute_cost_euro_millicents")
threshold = (
self.approved_compute_costs_euro_millicents
* percent_threshold
/ 100
)
current_cost = self.compute_cost_euro_millicents
if previous_cost <= threshold < current_cost:
send_email_percent_budget_consumed_alert(
self, percent_threshold
)
break
@cached_property
def challenge_type(self):
phase_types = {phase.submission_kind for phase in self.visible_phases}
# as long as one of the phases is type 2,
# the challenge is classified as type 2
if SubmissionKindChoices.ALGORITHM in phase_types:
challenge_type = ChallengeTypeChoices.T2
else:
challenge_type = ChallengeTypeChoices.T1
return challenge_type
@property
def status_badge_string(self):
if self.status == StatusChoices.OPEN:
detail = [
phase.submission_status_string
for phase in self.visible_phases
if phase.status == StatusChoices.OPEN
]
if len(detail) > 1:
# if there are multiple open phases it is unclear which
# status to print, so stay vague
detail = ["Accepting submissions"]
elif self.status == StatusChoices.COMPLETED:
detail = ["Challenge completed"]
elif self.status == StatusChoices.CLOSED:
detail = ["Not accepting submissions"]
elif self.status == StatusChoices.OPENING_SOON:
start_date = min(
(
phase.submissions_open_at
for phase in self.visible_phases
if phase.status == StatusChoices.OPENING_SOON
),
default=None,
)
phase = (
self.phase_set.filter(
submissions_open_at=start_date,
public=True,
)
.order_by("-created")
.first()
)
detail = [phase.submission_status_string]
else:
raise NotImplementedError(f"{self.status} not handled")
return detail[0]
@cached_property
def visible_phases(self):
# For use in list views where the phases have been prefetched
return [phase for phase in self.phase_set.all() if phase.public]
@cached_property
def first_visible_phase(self):
try:
return self.visible_phases[0]
except IndexError:
return None
@cached_property
def forge_model(self):
return ForgeChallenge(
slug=self.slug,
url=self.get_absolute_url(),
)
class ChallengeUserObjectPermission(UserObjectPermissionBase):
allowed_permissions = frozenset()
content_object = models.ForeignKey(Challenge, on_delete=models.CASCADE)
class ChallengeGroupObjectPermission(GroupObjectPermissionBase):
allowed_permissions = frozenset(
{"change_challenge", "add_registration_question", "view_challenge"}
)
content_object = models.ForeignKey(Challenge, on_delete=models.CASCADE)
@receiver(post_delete, sender=Challenge)
def delete_challenge_groups_hook(*_, instance: Challenge, using, **__):
"""
Deletes the related groups.
We use a signal rather than overriding delete() to catch usages of
bulk_delete.
"""
try:
instance.admins_group.delete(using=using)
except ObjectDoesNotExist:
pass
try:
instance.participants_group.delete(using=using)
except ObjectDoesNotExist:
pass
try:
instance.external_evaluators_group.delete(using=using)
except ObjectDoesNotExist:
pass
def submission_pdf_path(instance, filename):
return (
f"{instance._meta.app_label.lower()}/"
f"{instance._meta.model_name.lower()}/"
f"{instance.pk}/"
f"{get_valid_filename(filename)}"
)
class ChallengeRequestStatusChoices(models.TextChoices):
ACCEPTED = "ACPT", _("Accepted")
REJECTED = "RJCT", _("Rejected")
PENDING = "PEND", _("Pending")
DRAFT = "DRFT", _("Draft")
CANCELLED = "CNCL", _("Cancelled")
budget_field_names = (
"task_ids",
"algorithm_selectable_gpu_type_choices_for_tasks",
"algorithm_maximum_settable_memory_gb_for_tasks",
"average_size_test_case_mb_for_tasks",
"average_size_job_output_mb_for_tasks",
"inference_time_average_minutes_for_tasks",
"task_id_for_phases",
"number_of_teams_for_phases",
"number_of_submissions_per_team_for_phases",
"number_of_test_cases_for_phases",
)