示例#1
0
class Atlas(Image):
    label_description_file = models.FileField(
        upload_to=upload_img_to,
        null=False,
        blank=False,
        storage=NiftiGzStorage(),
        verbose_name='FSL compatible label description file (.xml)')

    class Meta:
        verbose_name_plural = "Atlases"
示例#2
0
class StatMap(models.Model):
    study = models.ForeignKey(Study)
    name = models.CharField(max_length=200, null=False, blank=False)
    description = models.CharField(max_length=200, blank=True)
    file = models.FileField(upload_to=upload_to,
                            null=False,
                            blank=False,
                            storage=NiftiGzStorage())
    hdr_file = models.FileField(upload_to=upload_to,
                                blank=True,
                                storage=NiftiGzStorage())
    json_path = models.CharField(max_length=200, null=False, blank=True)
    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)

    def __unicode__(self):
        return self.name

    class Meta:
        unique_together = ("study", "name")

    def save(self):

        # Save the file before the rest of the data so we can convert it to json
        if self.file and not os.path.exists(self.file.path):
            self.file.save(self.file.name, self.file, save=False)
        if self.hdr_file and not os.path.exists(self.hdr_file.path):
            self.file.save(self.hdr_file.name, self.hdr_file, save=False)
        # Convert binary image to JSON using neurosynth
#         try:
        if os.path.exists(self.file.path):
            json_file = self.file.path + '.json'
            #                 try:
            imageutils.img_to_json(self.file.path, swap=True, save=json_file)
            self.json_path = self.file.url + '.json'
#                 except Exception, e:
#                     pass
#         except Exception, e:
#             pass
        super(StatMap, self).save()
示例#3
0
class Image(BaseCollectionItem):
    file = models.FileField(
        upload_to=upload_img_to,
        null=False,
        blank=False,
        storage=NiftiGzStorage(),
        verbose_name='File with the unthresholded map (.img, .nii, .nii.gz)')
    figure = models.CharField(
        help_text=
        "Which figure in the corresponding paper was this map displayed in?",
        verbose_name="Corresponding figure",
        max_length=200,
        null=True,
        blank=True)
    thumbnail = models.FileField(
        help_text="The orthogonal view thumbnail path of the nifti image",
        null=True,
        blank=True,
        upload_to=upload_img_to,
        verbose_name='Image orthogonal view thumbnail 2D bitmap',
        storage=NiftiGzStorage())
    reduced_representation = models.FileField(
        help_text=
        ("Binary file with the vector of in brain values resampled to lower resolution"
         ),
        verbose_name="Reduced representation of the image",
        null=True,
        blank=True,
        upload_to=upload_img_to,
        storage=OverwriteStorage())
    data = hstore.DictionaryField(blank=True, null=True)
    hstore_objects = hstore.HStoreManager()

    def get_absolute_url(self):
        return_args = [str(self.id)]
        url_name = 'image_details'
        if self.collection.private:
            return_args.insert(0, str(self.collection.private_token))
            url_name = 'private_image_details'
        return reverse(url_name, args=return_args)

    def get_thumbnail_url(self):
        try:
            url = self.thumbnail.url
        except ValueError:
            url = os.path.abspath(
                os.path.join("/static", "images", "glass_brain_empty.jpg"))
        return url

    @classmethod
    def create(cls, my_file, my_file_name, my_name, my_desc, my_collection_pk,
               my_map_type):
        my_collection = Collection.objects.get(pk=my_collection_pk)

        # Copy the nifti file into the proper location
        image = cls(description=my_desc,
                    name=my_name,
                    collection=my_collection)
        f = open(my_file)
        niftiFile = File(f)
        image.file.save(my_file_name, niftiFile)

        # If a .img file was loaded then load the correspoding .hdr file as well
        _, ext = os.path.splitext(my_file_name)
        print ext
        if ext in ['.img']:
            f = open(my_file[:-3] + "hdr")
            hdrFile = File(f)
            image.hdr_file.save(my_file_name[:-3] + "hdr", hdrFile)

        image.map_type = my_map_type

        # create JSON file for neurosynth viewer
        if os.path.exists(image.file.path):
            nifti_gz_file = ".".join(
                image.file.path.split(".")[:-1]) + '.nii.gz'
            nii = nb.load(image.file.path)
            nb.save(nii, nifti_gz_file)
            f = open(nifti_gz_file)
            image.nifti_gz_file.save(nifti_gz_file.split(os.path.sep)[-1],
                                     File(f),
                                     save=False)

        image.save()

        return image

    # Celery task to generate glass brain image on new/update
    def save(self):
        file_changed = False
        collection_changed = False
        if self.pk is not None:
            old_pk = Image.objects.get(pk=self.pk)
            if old_pk.file != self.file:
                file_changed = True
            if old_pk.collection != self.collection:
                collection_changed = True

        do_update = True if file_changed else False
        new_image = True if self.pk is None else False
        super(Image, self).save()

        if (do_update or new_image
            ) and self.collection and self.collection.private == False:
            # Generate glass brain image
            generate_glassbrain_image.apply_async([self.pk])

        if collection_changed:
            for field_name in self._meta.get_all_field_names():
                field_instance = getattr(self, field_name)
                if field_instance and isinstance(field_instance, FieldFile):
                    old_path = field_instance.path
                    new_name = upload_img_to(
                        self,
                        field_instance.name.split("/")[-1])
                    new_name = field_instance.storage.get_available_name(
                        new_name)
                    new_path = field_instance.storage.path(new_name)
                    if not os.path.exists(os.path.dirname(new_path)):
                        os.mkdir(os.path.dirname(new_path))
                    shutil.copy(old_path, new_path)
                    field_instance.name = new_name
                    assert (old_path != new_path)
                    os.remove(old_path)
            super(Image, self).save()