-
Notifications
You must be signed in to change notification settings - Fork 64
/
models.py
1685 lines (1538 loc) · 56.1 KB
/
models.py
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
# -*- coding: utf-8 -*-
import os
import shutil
import stat
from datetime import datetime
from gzip import GzipFile
import uuid
import nibabel as nb
from django.contrib.auth.models import User
from django.core.files import File
from django.urls import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models import Q
from django.db.models.fields.files import FieldFile
from django.db.models.signals import m2m_changed, post_delete, post_save
from django.dispatch.dispatcher import receiver
from django.utils import timezone
from guardian.shortcuts import assign_perm, get_users_with_perms, remove_perm
from polymorphic.models import PolymorphicModel
from taggit.managers import TaggableManager
from taggit.models import GenericTaggedItemBase, TagBase
from neurovault.apps.statmaps.storage import (
DoubleExtensionStorage,
NIDMStorage,
OverwriteStorage,
)
# from neurovault.apps.statmaps.tasks import run_voxelwise_pearson_similarity, process_map
from neurovault.apps.statmaps.tasks import process_map
from neurovault.settings import PRIVATE_MEDIA_ROOT
# possible templates
POSSIBLE_TEMPLATES = {
"GenericMNI": {
"name": "Human (Generic/Unknown MNI)",
"species": "homo sapiens",
"pycortex_enabled": True,
"image_search_enabled": True,
"mask": "MNI152_T1_2mm_brain_mask.nii.gz",
},
"Dorr2008": {
"name": "Mouse (Dorr 2008 space)",
"species": "mus musculus",
"pycortex_enabled": False,
"image_search_enabled": False,
"mask": None,
},
"NMT": {
"name": "Rhesus - macacca mulatta (NMT)",
"species": "macaca mulatta",
"pycortex_enabled": False,
"image_search_enabled": False,
"mask": None,
},
"MNI152NLin2009cAsym": {
"name": "Human (MNI152 NLin 2009c Asym)",
"species": "homo sapiens",
"pycortex_enabled": True,
"image_search_enabled": True,
"mask": None,
},
}
DEFAULT_TEMPLATE = "GenericMNI"
def get_possible_templates():
return POSSIBLE_TEMPLATES
def get_target_template_list():
return [
(template, POSSIBLE_TEMPLATES[template]["name"])
for template in POSSIBLE_TEMPLATES
]
COMMUNITIES = {
"developmental": {"short_desc": "Developmental Neuroscience"},
"nutrition": {"short_desc": "Nutrition Neuroscience"},
}
community_choices = []
for k in list(COMMUNITIES.keys()):
community_choices.append((k, COMMUNITIES[k]["short_desc"]))
class Community(models.Model):
label = models.CharField(
max_length=200,
unique=True,
null=False,
verbose_name="Lexical label of the community",
)
short_desc = models.CharField(
max_length=200, null=False, verbose_name="Short description of the community"
)
def __str__(self):
return self.short_desc
def __unicode__(self):
return self.short_desc
class Collection(models.Model):
name = models.CharField(
max_length=200, unique=True, null=False, verbose_name="Name of collection"
)
DOI = models.CharField(
max_length=200,
unique=True,
blank=True,
null=True,
default=None,
verbose_name="DOI of the corresponding paper",
help_text="Required if you want your maps to be archived in Stanford Digital Repository",
)
authors = models.CharField(max_length=5000, blank=True, null=True)
paper_url = models.CharField(max_length=200, blank=True, null=True)
journal_name = models.CharField(max_length=200, blank=True, null=True, default=None)
description = models.TextField(blank=True, null=True)
full_dataset_url = models.URLField(
max_length=200,
blank=True,
null=True,
verbose_name="Full dataset URL",
help_text='Link to an external dataset the maps in this collection have been generated from (for example: "https://openfmri.org/dataset/ds000001" or "http://dx.doi.org/10.15387/fcp_indi.corr.mpg1")',
)
owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
contributors = models.ManyToManyField(
User,
related_name="collection_contributors",
related_query_name="contributor",
blank=True,
help_text="Select other NeuroVault users to add as contributes to the collection. Contributors can add, edit and delete images in the collection.",
verbose_name="Contributors",
)
private = models.BooleanField(
choices=(
(
False,
"Public (The collection will be accessible by anyone and all the data in it will be distributed under CC0 license)",
),
(
True,
"Private (The collection will be not listed in the NeuroVault index. It will be possible to shared it with others at a private URL.)",
),
),
default=False,
verbose_name="Accessibility",
)
private_token = models.CharField(
max_length=8, blank=True, null=True, unique=True, db_index=True, default=None
)
add_date = models.DateTimeField("date published", auto_now_add=True)
modify_date = models.DateTimeField("date modified", auto_now=True)
doi_add_date = models.DateTimeField(
"date the DOI was added", editable=False, blank=True, null=True, db_index=True
)
communities = models.ManyToManyField(
Community,
related_name="collections",
related_query_name="collection",
blank=True,
help_text="Is this collection part of any special Community?",
verbose_name="Communities",
default=None,
)
type_of_design = models.CharField(
choices=[
("blocked", "blocked"),
("eventrelated", "event_related"),
("hybridblockevent", "hybrid block/event"),
("other", "other"),
],
max_length=200,
blank=True,
help_text="Blocked, event-related, hybrid, or other",
null=True,
verbose_name="Type of design",
)
number_of_imaging_runs = models.IntegerField(
help_text="Number of imaging runs acquired",
null=True,
verbose_name="No. of imaging runs",
blank=True,
)
number_of_experimental_units = models.IntegerField(
help_text="Number of blocks, trials or experimental units per imaging run",
null=True,
verbose_name="No. of experimental units",
blank=True,
)
length_of_runs = models.FloatField(
help_text="Length of each imaging run in seconds",
null=True,
verbose_name="Length of runs",
blank=True,
)
length_of_blocks = models.FloatField(
help_text="For blocked designs, length of blocks in seconds",
null=True,
verbose_name="Length of blocks",
blank=True,
)
length_of_trials = models.CharField(
help_text="Length of individual trials in seconds. If length varies across trials, enter 'variable'. ",
max_length=200,
null=True,
verbose_name="Length of trials",
blank=True,
)
optimization = models.BooleanField(
help_text="Was the design optimized for efficiency",
null=True,
verbose_name="Optimization?",
blank=True,
)
optimization_method = models.CharField(
help_text="What method was used for optimization?",
verbose_name="Optimization method",
max_length=200,
null=True,
blank=True,
)
subject_age_mean = models.FloatField(
help_text="Mean age of subjects",
null=True,
verbose_name="Subject age mean",
blank=True,
)
subject_age_min = models.FloatField(
help_text="Minimum age of subjects",
null=True,
verbose_name="Subject age min",
blank=True,
)
subject_age_max = models.FloatField(
help_text="Maximum age of subjects",
null=True,
verbose_name="Subject age max",
blank=True,
)
handedness = models.CharField(
choices=[("right", "right"), ("left", "left"), ("both", "both")],
max_length=200,
blank=True,
help_text="Handedness of subjects",
null=True,
verbose_name="Handedness",
)
proportion_male_subjects = models.FloatField(
validators=[MinValueValidator(0.0), MaxValueValidator(1.0)],
help_text="The proportion (not percentage) of subjects who were male",
null=True,
verbose_name="Prop. male subjects",
blank=True,
)
inclusion_exclusion_criteria = models.CharField(
help_text="Additional inclusion/exclusion criteria, if any (including specific sampling strategies that limit inclusion to a specific group, such as laboratory members)",
verbose_name="Inclusion / exclusion criteria",
max_length=200,
null=True,
blank=True,
)
number_of_rejected_subjects = models.IntegerField(
help_text="Number of subjects scanned but rejected from analysis",
null=True,
verbose_name="No. of rejected subjects",
blank=True,
)
group_comparison = models.BooleanField(
help_text="Was this study a comparison between subject groups?",
null=True,
verbose_name="Group comparison?",
blank=True,
)
group_description = models.CharField(
help_text="A description of the groups being compared",
verbose_name="Group description",
max_length=200,
null=True,
blank=True,
)
scanner_make = models.CharField(
help_text="Manufacturer of MRI scanner",
verbose_name="Scanner make",
max_length=200,
null=True,
blank=True,
)
scanner_model = models.CharField(
help_text="Model of MRI scanner",
verbose_name="Scanner model",
max_length=200,
null=True,
blank=True,
)
field_strength = models.FloatField(
help_text="Field strength of MRI scanner (in Tesla)",
null=True,
verbose_name="Field strength",
blank=True,
)
pulse_sequence = models.CharField(
help_text="Description of pulse sequence used for fMRI",
verbose_name="Pulse sequence",
max_length=200,
null=True,
blank=True,
)
parallel_imaging = models.CharField(
help_text="Description of parallel imaging method and parameters",
verbose_name="Parallel imaging",
max_length=200,
null=True,
blank=True,
)
field_of_view = models.FloatField(
help_text="Imaging field of view in millimeters",
null=True,
verbose_name="Field of view",
blank=True,
)
matrix_size = models.IntegerField(
help_text="Matrix size for MRI acquisition",
null=True,
verbose_name="Matrix size",
blank=True,
)
slice_thickness = models.FloatField(
help_text="Distance between slices (includes skip or distance factor) in millimeters",
null=True,
verbose_name="Slice thickness",
blank=True,
)
skip_distance = models.FloatField(
help_text="The size of the skipped area between slices in millimeters",
null=True,
verbose_name="Skip distance",
blank=True,
)
acquisition_orientation = models.CharField(
help_text="The orientation of slices",
verbose_name="Acquisition orientation",
max_length=200,
null=True,
blank=True,
)
order_of_acquisition = models.CharField(
choices=[
("ascending", "ascending"),
("descending", "descending"),
("interleaved", "interleaved"),
],
max_length=200,
blank=True,
help_text="Order of acquisition of slices (ascending, descending, or interleaved)",
null=True,
verbose_name="Order of acquisition",
)
repetition_time = models.FloatField(
help_text="Repetition time (TR) in milliseconds",
null=True,
verbose_name="Repetition time",
blank=True,
)
echo_time = models.FloatField(
help_text="Echo time (TE) in milliseconds",
null=True,
verbose_name="Echo time",
blank=True,
)
flip_angle = models.FloatField(
help_text="Flip angle in degrees",
null=True,
verbose_name="Flip angle",
blank=True,
)
software_package = models.CharField(
help_text="If a single software package was used for all analyses, specify that here",
verbose_name="Software package",
max_length=200,
null=True,
blank=True,
)
software_version = models.CharField(
help_text="Version of software package used",
verbose_name="Software version",
max_length=200,
null=True,
blank=True,
)
order_of_preprocessing_operations = models.CharField(
help_text="Specify order of preprocessing operations",
verbose_name="Order of preprocessing",
max_length=200,
null=True,
blank=True,
)
quality_control = models.CharField(
help_text="Describe quality control measures",
verbose_name="Quality control",
max_length=200,
null=True,
blank=True,
)
used_b0_unwarping = models.BooleanField(
help_text="Was B0 distortion correction used?",
null=True,
verbose_name="Used B0 unwarping?",
blank=True,
)
b0_unwarping_software = models.CharField(
help_text="Specify software used for distortion correction if different from the main package",
verbose_name="B0 unwarping software",
max_length=200,
null=True,
blank=True,
)
used_slice_timing_correction = models.BooleanField(
help_text="Was slice timing correction used?",
null=True,
verbose_name="Slice timing correction?",
blank=True,
)
slice_timing_correction_software = models.CharField(
help_text="Specify software used for slice timing correction if different from the main package",
verbose_name="Slice timing correction software",
max_length=200,
null=True,
blank=True,
)
used_motion_correction = models.BooleanField(
help_text="Was motion correction used?",
null=True,
verbose_name="Motion correction?",
blank=True,
)
motion_correction_software = models.CharField(
help_text="Specify software used for motion correction if different from the main package",
verbose_name="Motion correction software",
max_length=200,
null=True,
blank=True,
)
motion_correction_reference = models.CharField(
help_text="Reference scan used for motion correction",
verbose_name="Motion correction reference",
max_length=200,
null=True,
blank=True,
)
motion_correction_metric = models.CharField(
help_text="Similarity metric used for motion correction",
verbose_name="Motion correction metric",
max_length=200,
null=True,
blank=True,
)
motion_correction_interpolation = models.CharField(
help_text="Interpolation method used for motion correction",
verbose_name="Motion correction interpolation",
max_length=200,
null=True,
blank=True,
)
used_motion_susceptibiity_correction = models.BooleanField(
help_text="Was motion-susceptibility correction used?",
null=True,
verbose_name="Motion susceptibility correction?",
blank=True,
)
used_intersubject_registration = models.BooleanField(
help_text="Were subjects registered to a common stereotactic space?",
null=True,
verbose_name="Intersubject registration?",
blank=True,
)
intersubject_registration_software = models.CharField(
help_text="Specify software used for intersubject registration if different from main package",
verbose_name="Registration software",
max_length=200,
null=True,
blank=True,
)
intersubject_transformation_type = models.CharField(
choices=[("linear", "linear"), ("nonlinear", "nonlinear")],
max_length=200,
blank=True,
help_text="Was linear or nonlinear registration used?",
null=True,
verbose_name="Intersubject transformation type",
)
nonlinear_transform_type = models.CharField(
help_text="If nonlinear registration was used, describe transform method",
verbose_name="Nonlinear transform type",
max_length=200,
null=True,
blank=True,
)
transform_similarity_metric = models.CharField(
help_text="Similarity metric used for intersubject registration",
verbose_name="Transform similarity metric",
max_length=200,
null=True,
blank=True,
)
interpolation_method = models.CharField(
help_text="Interpolation method used for intersubject registration",
verbose_name="Interpolation method",
max_length=200,
null=True,
blank=True,
)
object_image_type = models.CharField(
help_text="What type of image was used to determine the transformation to the atlas? (e.g. T1, T2, EPI)",
verbose_name="Object image type",
max_length=200,
null=True,
blank=True,
)
functional_coregistered_to_structural = models.BooleanField(
help_text="Were the functional images coregistered to the subject's structural image?",
null=True,
verbose_name="Coregistered to structural?",
blank=True,
)
functional_coregistration_method = models.CharField(
help_text="Method used to coregister functional to structural images",
verbose_name="Coregistration method",
max_length=200,
null=True,
blank=True,
)
coordinate_space = models.CharField(
choices=[
("mni", "MNI"),
("talairach", "Talairach"),
("mni2tal", "MNI2Tal"),
("other", "other"),
],
max_length=200,
blank=True,
help_text="Name of coordinate space for registration target",
null=True,
verbose_name="Coordinate space",
)
target_template_image = models.CharField(
help_text="Name of target template image",
verbose_name="Target template image",
max_length=200,
null=True,
blank=True,
)
target_resolution = models.FloatField(
help_text="Voxel size of target template in millimeters",
null=True,
verbose_name="Target resolution",
blank=True,
)
used_smoothing = models.BooleanField(
help_text="Was spatial smoothing applied?",
null=True,
verbose_name="Used smoothing?",
blank=True,
)
smoothing_type = models.CharField(
help_text="Describe the type of smoothing applied",
verbose_name="Type of smoothing",
max_length=200,
null=True,
blank=True,
)
smoothing_fwhm = models.FloatField(
help_text="The full-width at half-maximum of the smoothing kernel in millimeters",
null=True,
verbose_name="Smoothing FWHM",
blank=True,
)
resampled_voxel_size = models.FloatField(
help_text="Voxel size in mm of the resampled, atlas-space images",
null=True,
verbose_name="Resampled voxel size",
blank=True,
)
intrasubject_model_type = models.CharField(
help_text="Type of model used (e.g., regression)",
verbose_name="Model type",
max_length=200,
null=True,
blank=True,
)
intrasubject_estimation_type = models.CharField(
help_text="Estimation method used for model (e.g., OLS, generalized least squares)",
verbose_name="Estimation type",
max_length=200,
null=True,
blank=True,
)
intrasubject_modeling_software = models.CharField(
help_text="Software used for intrasubject modeling if different from overall package",
verbose_name="Modeling software",
max_length=200,
null=True,
blank=True,
)
hemodynamic_response_function = models.CharField(
help_text="Nature of HRF model",
verbose_name="Hemodynamic response function",
max_length=200,
null=True,
blank=True,
)
used_temporal_derivatives = models.BooleanField(
help_text="Were temporal derivatives included?",
null=True,
verbose_name="Temporal derivatives?",
blank=True,
)
used_dispersion_derivatives = models.BooleanField(
help_text="Were dispersion derivatives included?",
null=True,
verbose_name="Dispersion derivatives?",
blank=True,
)
used_motion_regressors = models.BooleanField(
help_text="Were motion regressors included?",
null=True,
verbose_name="Motion regressors?",
blank=True,
)
used_reaction_time_regressor = models.BooleanField(
help_text="Was a reaction time regressor included?",
null=True,
verbose_name="Reaction time regressor?",
blank=True,
)
used_orthogonalization = models.BooleanField(
help_text="Were any regressors specifically orthogonalized with respect to others?",
null=True,
verbose_name="Orthogonalization?",
blank=True,
)
orthogonalization_description = models.CharField(
help_text="If orthogonalization was used, describe here",
verbose_name="Orthogonalization description",
max_length=200,
null=True,
blank=True,
)
used_high_pass_filter = models.BooleanField(
help_text="Was high pass filtering applied?",
null=True,
verbose_name="High-pass filter?",
blank=True,
)
high_pass_filter_method = models.CharField(
help_text="Describe method used for high pass filtering",
verbose_name="High-pass filtering method",
max_length=200,
null=True,
blank=True,
)
autocorrelation_model = models.CharField(
help_text="What autocorrelation model was used (or 'none' of none was used)",
verbose_name="Autocorrelation method",
max_length=200,
null=True,
blank=True,
)
group_model_type = models.CharField(
help_text="Type of group model used (e.g., regression)",
verbose_name="Group model type",
max_length=200,
null=True,
blank=True,
)
group_estimation_type = models.CharField(
help_text="Estimation method used for group model (e.g., OLS, generalized least squares)",
verbose_name="Group estimation type",
max_length=200,
null=True,
blank=True,
)
group_modeling_software = models.CharField(
help_text="Software used for group modeling if different from overall package",
verbose_name="Group modeling software",
max_length=200,
null=True,
blank=True,
)
group_inference_type = models.CharField(
choices=[
("randommixedeffects", "random/mixed effects"),
("fixedeffects", "fixed effects"),
],
max_length=200,
blank=True,
help_text="Type of inference for group model",
null=True,
verbose_name="Group inference type",
)
group_model_multilevel = models.CharField(
help_text="If more than 2-levels, describe the levels and assumptions of the model (e.g. are variances assumed equal between groups)",
verbose_name="Multilevel modeling",
max_length=200,
null=True,
blank=True,
)
group_repeated_measures = models.BooleanField(
help_text="Was this a repeated measures design at the group level?",
null=True,
verbose_name="Repeated measures",
blank=True,
)
group_repeated_measures_method = models.CharField(
help_text="If multiple measurements per subject, list method to account for within subject correlation, exact assumptions made about correlation/variance",
verbose_name="Repeated measures method",
max_length=200,
null=True,
blank=True,
)
nutbrain_hunger_state = models.CharField(
choices=[
("I", "Fed (<1h after meal)"),
("II", "2-3 h fasted"),
("III", "4-6 h fasted"),
("IV", "7-9h fasted"),
("V", "fasted overnight (> 10h)"),
("VI", "36h fast"),
],
max_length=200,
blank=True,
null=True,
verbose_name="Hunger state",
)
nutbrain_food_viewing_conditions = models.CharField(
max_length=200,
blank=True,
null=True,
verbose_name="Food viewing conditions",
help_text="Image categories",
)
nutbrain_food_choice_type = models.CharField(
max_length=200,
blank=True,
null=True,
verbose_name="Food choice type",
help_text="Choice conditions/image types",
)
nutbrain_taste_conditions = models.CharField(
max_length=200, blank=True, null=True, verbose_name="Taste conditions"
)
nutbrain_odor_conditions = models.CharField(
max_length=200, blank=True, null=True, verbose_name="Odor conditions"
)
@property
def is_statisticmap_set(self):
return all(
(isinstance(i, StatisticMap) for i in self.basecollectionitem_set.all())
)
def get_absolute_url(self):
return_cid = self.id
if self.private:
if self.private_token is None:
self.private_token = str(uuid.uuid4())[:8]
self.save()
return_cid = self.private_token
return reverse("statmaps:collection_details", args=[str(return_cid)])
def __unicode__(self):
return self.name
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if self.DOI is not None and self.DOI.strip() == "":
self.DOI = None
if self.private_token is not None and self.private_token.strip() == "":
self.private_token = None
if self.DOI and not self.private and not self.doi_add_date:
self.doi_add_date = timezone.now()
# run calculations when collection turns public
privacy_changed = False
DOI_changed = False
if self.pk is not None:
old_object = Collection.objects.get(pk=self.pk)
old_is_private = old_object.private
old_has_DOI = old_object.DOI is not None
privacy_changed = old_is_private != self.private
DOI_changed = old_has_DOI != (self.DOI is not None)
super(Collection, self).save(*args, **kwargs)
"""
if (privacy_changed and not self.private) or (DOI_changed and self.DOI is not None):
for image in self.basecollectionitem_set.instance_of(Image).all():
if image.pk:
run_voxelwise_pearson_similarity.apply_async([image.pk])
"""
class Meta:
app_label = "statmaps"
def delete(self, using=None):
cid = self.pk
for image in self.basecollectionitem_set.instance_of(Image):
image.delete()
for nidmresult in self.basecollectionitem_set.instance_of(NIDMResults):
nidmresult.delete()
ret = super(Collection, self).delete(using=using)
collDir = os.path.join(PRIVATE_MEDIA_ROOT, "images", str(cid))
try:
shutil.rmtree(collDir)
except OSError:
print("Image directory for collection %s does not exist" % cid)
return ret
@receiver(post_save, sender=Collection)
def collection_created(sender, instance, created, **kwargs):
if created:
assign_perm("delete_collection", instance.owner, instance)
assign_perm("change_collection", instance.owner, instance)
for image in instance.basecollectionitem_set.all():
assign_perm("change_basecollectionitem", instance.owner, image)
assign_perm("delete_basecollectionitem", instance.owner, image)
def contributors_changed(sender, instance, action, **kwargs):
if action in ["post_remove", "post_add", "post_clear"]:
current_contributors = set([user.pk for user in get_users_with_perms(instance)])
new_contributors = set(
[
user.pk
for user in [
instance.owner,
]
+ list(instance.contributors.all())
]
)
for contributor in list(new_contributors - current_contributors):
contributor = User.objects.get(pk=contributor)
assign_perm("change_collection", contributor, instance)
for image in instance.basecollectionitem_set.all():
assign_perm("change_basecollectionitem", contributor, image)
assign_perm("delete_basecollectionitem", contributor, image)
for contributor in current_contributors - new_contributors:
contributor = User.objects.get(pk=contributor)
remove_perm("change_collection", contributor, instance)
for image in instance.basecollectionitem_set.all():
remove_perm("change_basecollectionitem", contributor, image)
remove_perm("delete_basecollectionitem", contributor, image)
m2m_changed.connect(contributors_changed, sender=Collection.contributors.through)
class CognitiveAtlasTask(models.Model):
name = models.CharField(max_length=200, null=False, blank=False, db_index=True)
cog_atlas_id = models.CharField(
primary_key=True, max_length=200, null=False, blank=False
)
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def get_absolute_url(self):
cog_atlas_id = self.cog_atlas_id
return reverse("statmaps:view_task", args=[str(cog_atlas_id)])
class Meta:
ordering = ["name"]
class CognitiveAtlasContrast(models.Model):
name = models.CharField(max_length=200, null=False, blank=False)
cog_atlas_id = models.CharField(
primary_key=True, max_length=200, null=False, blank=False
)
task = models.ForeignKey(CognitiveAtlasTask, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
def __unicode__(self):
return self.name
class Meta:
ordering = ["name"]
def upload_nidm_to(instance, filename):
base_subdir = os.path.split(instance.zip_file.name)[-1].replace(".zip", "")
return os.path.join("images", str(instance.collection.id), base_subdir, filename)
def upload_img_to(instance, filename):
nidm_types = ["nidmresultstatisticmap"]
if (
hasattr(instance, "polymorphic_ctype")
and instance.polymorphic_ctype.model in nidm_types
):
return upload_nidm_to(instance.nidm_results, filename)
return os.path.join("images", str(instance.collection.id), filename)
upload_to = upload_img_to # for migration backwards compat.
class KeyValueTag(TagBase):
value = models.CharField(max_length=200, blank=True)
class ValueTaggedItem(GenericTaggedItemBase):
tag = models.ForeignKey(
KeyValueTag, related_name="tagged_items", on_delete=models.CASCADE
)
class BaseCollectionItem(PolymorphicModel, models.Model):
name = models.CharField(max_length=200, null=False, blank=False, db_index=True)
description = models.TextField(blank=True)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
add_date = models.DateTimeField("date published", auto_now_add=True)
modify_date = models.DateTimeField("date modified", auto_now=True)
tags = TaggableManager(through=ValueTaggedItem, blank=True)
is_valid = models.BooleanField(default=True)
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def set_name(self, new_name):
self.name = new_name
def save(self):
self.collection.modify_date = timezone.now()
self.collection.save()
super(BaseCollectionItem, self).save()
def delete(self):
self.collection.modify_date = timezone.now()
self.collection.save()
super(BaseCollectionItem, self).delete()
@classmethod
def get_fixed_fields(cls):
return ("name", "description", "figure")
# sadly signals are not emitted for base classes so we need to connect this to every class separately
def basecollectionitem_created(sender, instance, created, **kwargs):
if created:
for user in [
instance.collection.owner,
] + list(instance.collection.contributors.all()):
assign_perm("change_basecollectionitem", user, instance)
assign_perm("delete_basecollectionitem", user, instance)
class Image(BaseCollectionItem):
file = models.FileField(
upload_to=upload_img_to,
null=False,
blank=False,
storage=DoubleExtensionStorage(),
max_length=500,
verbose_name="File with the unthresholded volume map (.img, .nii, .nii.gz)",
)
surface_left_file = models.FileField(
upload_to=upload_img_to,
null=True,
blank=True,
storage=DoubleExtensionStorage(),
verbose_name="File with the unthresholded LEFT hemisphere fsaverage surface map (.mgh, .curv, .gii)",
)
surface_right_file = models.FileField(
upload_to=upload_img_to,
null=True,
blank=True,
storage=DoubleExtensionStorage(),
verbose_name="File with the unthresholded RIGHT hemisphere fsaverage surface map (.mgh, .curv, .gii)",