Esempio n. 1
0
class Image(BaseCollectionItem):
    file = models.FileField(
        upload_to=upload_img_to,
        null=False,
        blank=False,
        storage=DoubleExtensionStorage(),
        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=DoubleExtensionStorage())
    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()
Esempio n. 2
0
class Job(CommonFieldsMixin):
    """Job post associated with project."""

    related_name = 'jobs'
    related_query_name = 'job'

    created_by = models.ForeignKey(User,
                                   db_index=True,
                                   related_name='created_jobs',
                                   related_query_name='created_job',
                                   on_delete=models.CASCADE)
    group = models.ForeignKey(Group,
                              null=True,
                              blank=True,
                              related_name=related_name,
                              related_query_name=related_query_name)

    applicants = models.ManyToManyField(User,
                                        through='application.Application',
                                        related_name=related_name,
                                        related_query_name=related_query_name)

    role_position = models.CharField(
        null=True,
        blank=True,
        max_length=255,
        help_text=
        'For eg. lead character, supporting character, background dancer etc.')
    ages = IntegerRangeField(null=True,
                             blank=True,
                             help_text='Age range required for this role.')
    required_gender = models.CharField(max_length=2,
                                       choices=choices.GENDER_CHOICES,
                                       default=choices.NOT_SPECIFIED)
    required_tokens = models.IntegerField(
        default=5,
        help_text='How much tokens user needs to have to apply to this job.')
    location = models.ForeignKey(
        City,
        null=True,
        blank=True,
        help_text="Location of user's project experience.")
    required_information_to_apply = hstore.DictionaryField(null=True,
                                                           blank=True)
    reason_for_rejection = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text='Reason why the job was rejected/unapproved by stageroute.')
    submission_deadline = models.DateField(
        null=True, blank=True, help_text='Date for the job deadline.')

    status = models.CharField(max_length=2,
                              choices=choices.JOB_STATE_CHOICES,
                              default=choices.PENDING_APPROVAL)
    number_of_vacancies = models.IntegerField(
        default=1, help_text='How many positions are open for this job.')
    budgets = IntegerRangeField(
        null=True,
        blank=True,
        help_text='budget range amount to be spent on the job.')
    featured = models.BooleanField(default=False, help_text='Is job featured.')
    skin_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.SKIN_TYPE_CHOICES,
                                 help_text='Preferred skin type.')
    hair_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.HAIR_TYPE_CHOICES,
                                 help_text='Preferred hair type.')
    eye_color = models.CharField(max_length=50,
                                 default=choices.DOES_NOT_MATTER,
                                 null=True,
                                 blank=True,
                                 choices=choices.EYE_COLOR_CHOICES,
                                 help_text='Peferred eye color.')
    hair_color = models.CharField(max_length=50,
                                  default=choices.DOES_NOT_MATTER,
                                  null=True,
                                  blank=True,
                                  choices=choices.HAIR_COLOR_CHOICES,
                                  help_text='Peferred eye color.')
    hair_style = models.CharField(max_length=50,
                                  default=choices.DOES_NOT_MATTER,
                                  null=True,
                                  blank=True,
                                  choices=choices.HAIR_STYLE_CHOICES,
                                  help_text='Peferred eye color.')
    heights = FloatRangeField(null=True,
                              blank=True,
                              help_text='Range of height required.')
    body_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.BODY_TYPES)
    language = models.CharField(max_length=50,
                                null=True,
                                blank=True,
                                default=choices.DOES_NOT_MATTER,
                                choices=choices.LANGUAGE_CHOICES,
                                help_text='Preferred languages.')

    job_type = models.CharField(max_length=50,
                                null=True,
                                blank=True,
                                choices=choices.JOB_TYPE_CHOICES,
                                help_text='Type of job.')
    auditions_per_day = models.IntegerField(
        null=True,
        blank=True,
        help_text='Number of auditions to do per day for this job.')
    audition_range = DateRangeField(null=True,
                                    blank=True,
                                    help_text='Audition range')
    job_owner_email = models.EmailField(
        null=True,
        blank=True,
        help_text='Should be valid email, e.g. [email protected]',
    )
    job_owner_phone = models.CharField(max_length=10,
                                       null=True,
                                       blank=True,
                                       db_index=True,
                                       help_text="User's phone number.")
    notes = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Useful for job posters. A quick note they can refere later."
    )
    field_history = FieldHistoryTracker(['status'])
    related_query_name = 'jobs'

    images = GenericRelation(Image, related_query_name=related_query_name)
    videos = GenericRelation(Video, related_query_name=related_query_name)
    audios = GenericRelation(Audio, related_query_name=related_query_name)
    objects = hstore.HStoreManager()

    def __unicode__(self):
        """unicode."""
        return self.title
class HStoreModel(models.Model):
    objects = hstore.HStoreManager()

    class Meta:
        abstract = True
Esempio n. 4
0
class Account(models.Model):
    """ NAV's basic account model"""

    DEFAULT_ACCOUNT = 0
    ADMIN_ACCOUNT = 1

    # An overview of current preferences.
    # They should start with PREFERENCE_KEY
    PREFERENCE_KEY_LANGUAGE = 'language'  # AlertProfiles
    PREFERENCE_KEY_STATUS = 'status-preferences'
    PREFERENCE_KEY_WIDGET_COLUMNS = 'widget_columns'
    PREFERENCE_KEY_REPORT_PAGE_SIZE = 'report_page_size'
    PREFERENCE_KEY_WIDGET_DISPLAY_DENSITY = 'widget_display_density'

    # FIXME get this from setting.
    MIN_PASSWD_LENGTH = 8

    login = VarcharField(unique=True)
    name = VarcharField()
    password = VarcharField()
    ext_sync = VarcharField()
    preferences = hstore.DictionaryField()

    objects = hstore.HStoreManager()

    organizations = models.ManyToManyField(Organization, db_table='accountorg')

    class Meta(object):
        db_table = u'account'
        ordering = ('login', )

    def __unicode__(self):
        return self.login

    def get_active_profile(self):
        """Returns the account's active alert profile"""
        try:
            return self.alertpreference.active_profile
        except (AlertPreference.DoesNotExist, AlertProfile.DoesNotExist):
            pass

    def get_groups(self):
        """Fetches and returns this users groups.
        Also stores groups in this object for later use.
        """
        try:
            return self._cached_groups
        except AttributeError:
            self._cached_groups = self.accountgroup_set.values_list('id',
                                                                    flat=True)
            return self._cached_groups

    def get_privileges(self):
        """Fetches privileges for this users groups.
        Also stores privileges in this object for later use.
        """
        try:
            return self._cached_privileges
        except AttributeError:
            self._cached_privileges = Privilege.objects.filter(
                group__in=self.get_groups())
            return self._cached_privileges

    def get_tools(self):
        """Get the tool list for this account"""
        return [
            tool for tool in self.accounttool_set.all().order_by('priority')
            if self.has_perm('web_access', tool.tool.uri)
        ]

    def has_perm(self, action, target):
        """Checks if user has permission to do action on target."""
        groups = self.get_groups()
        privileges = self.get_privileges()

        if AccountGroup.ADMIN_GROUP in groups:
            return True
        elif privileges.count() == 0:
            return False
        elif action == 'web_access':
            for privilege in privileges:
                regexp = re.compile(privilege.target)
                if regexp.search(target):
                    return True
            return False
        else:
            return privileges.filter(target=target).count() > 0

    def is_system_account(self):
        """Is this system (undeleteable) account?"""
        return self.id < 1000

    def is_default_account(self):
        """Is this the anonymous user account?"""
        return self.id == self.DEFAULT_ACCOUNT

    def is_admin_account(self):
        """Is this the admin account?"""
        return self.id == self.ADMIN_ACCOUNT

    def is_admin(self):
        """Has this user administrator rights?"""
        return self.has_perm(None, None)

    @sensitive_variables('password')
    def set_password(self, password):
        """Sets user password. Copied from nav.db.navprofiles"""
        if len(password.strip()):
            pw_hash = nav.pwhash.Hash(password=password)
            self.password = str(pw_hash)
        else:
            self.password = ''

    @sensitive_variables('password')
    def check_password(self, password):
        """
        Return True if the submitted authentication tokens are valid
        for this Account.  In simpler terms; when password
        authentication is used, this method compares the given
        password with the one stored for this account and returns true
        if they are equal.  If the stored password is blank, we
        interpret this as: 'The user is not allowed to log in'

        In the future, this could be extended to accept other types of
        authentication tokens, such as personal certificates or
        whatever.

        Copied from nav.db.navprofiles
        """
        # FIXME If password is old style NAV MD5, shouldn't we update the
        # password in the database to be new style password?
        if not self.locked:
            stored_hash = nav.pwhash.Hash()
            try:
                stored_hash.set_hash(self.password)
            except nav.pwhash.InvalidHashStringError:
                # Probably an old style NAV password hash, get out
                # of here and check it the old way
                pass
            else:
                return stored_hash.verify(password)

            # If the stored password looks like an old-style NAV MD5
            # hash we compute the MD5 hash of the supplied password
            # for comparison.
            if self.password[:3] == 'md5':
                pw_hash = md5(password)
                return pw_hash.hexdigest() == self.password[3:]
            else:
                return password == self.password
        else:
            return False

    @property
    def locked(self):
        return not self.password or self.password.startswith('!')

    @locked.setter
    def locked(self, value):
        if not value and self.password.startswith('!'):
            self.password = self.password[1:]
        elif value and not self.password.startswith('!'):
            self.password = '******' + self.password
Esempio n. 5
0
class Order(BaseOrder):

    FEEDBACK_CHOICES = (('UP', 'Happy'), ('DOWN', 'Unhappy'))

    coffee = models.ForeignKey(CoffeeType)

    different = models.BooleanField(verbose_name='Different?', default=False)

    amount = models.DecimalField(verbose_name='Amount',
                                 max_digits=6,
                                 decimal_places=2,
                                 default=18)

    interval = models.PositiveIntegerField(verbose_name='Shipping Interval',
                                           default=14)

    recurrent = models.BooleanField(verbose_name='Recurrent?', default=False)

    # TODO: move existing feedback to review and remove it
    feedback = models.CharField(max_length=16,
                                choices=FEEDBACK_CHOICES,
                                null=True,
                                blank=True)

    brew = models.ForeignKey(BrewMethod)

    package = models.CharField(verbose_name='Packaging method',
                               max_length=16,
                               choices=Preferences.PACKAGE_CHOICES,
                               default=Preferences.GRINDED)

    details = hstore.DictionaryField(default={}, blank=True)
    objects = hstore.HStoreManager()

    resent = models.BooleanField(verbose_name='Resent Order?', default=False)

    custom_price = models.BooleanField(verbose_name='Custom Price?',
                                       default=False)

    def __unicode__(self):
        return '[{}] {} | {} | {} | {} | {}'.format(
            self.id,
            self.get_status_display(),
            timezone.localtime(self.date).strftime('%b, %d (%H:%M)'),
            timezone.localtime(self.shipping_date).strftime('%b, %d (%H:%M)'),
            self.customer,
            self.coffee,
        )

    def save(self, *args, **kwargs):
        if (self.coffee.is_discovery_pack
                and 'discovery_coffees' not in self.details):
            self.update_discovery_coffees(commit=False)
        super(Order, self).save(*args, **kwargs)

    @property
    def is_editable(self):
        now = CTZ.normalize(timezone.now())
        is_friday = now.isoweekday() == 5
        shipping_date_is_monday = self.shipping_date.isoweekday() == 1
        next_48h = now + timedelta(hours=48)
        next_96h = now + timedelta(hours=96)
        if (self.recurrent and not (is_friday and shipping_date_is_monday
                                    and next_96h > self.shipping_date)
                and (next_48h < self.shipping_date)):
            return True
        return False

    @property
    def is_paused(self):
        return self.status == self.PAUSED

    @property
    def is_first_order(self):
        """Check if this order is the first customer order."""
        is_first = False
        try:
            is_first = self.id == self.customer.orders.earliest('id').id
        except Order.DoesNotExist:
            pass
        return is_first

    def hours_to_change(self):
        """Return hours left to make changes to this order."""
        uneditable_at = self.shipping_date - timedelta(hours=48)
        delta = CTZ.normalize(uneditable_at) - CTZ.normalize(timezone.now())
        delta_hrs = int(delta.total_seconds() / 3600)
        return 1 if delta_hrs == 0 else delta_hrs

    def get_next_shipping_date(self, after=None):
        now = after or CTZ.normalize(timezone.now())
        possible_day = now + timedelta(days=self.interval)
        day = possible_day.isoweekday()
        today = possible_day.replace(hour=12,
                                     minute=0,
                                     second=0,
                                     microsecond=0)
        # noon = now.replace(hour=12, minute=0, second=0, microsecond=0)
        # morning = True if now < noon else False

        # Mon, Tue, Wed, Thu, Fri
        if day in range(1, 6):
            # return today if morning else tomorrow
            return today
        # Saturday
        elif day == 6:
            return today + timedelta(days=2)
        # Sunday
        elif day == 7:
            return today + timedelta(days=1)

    def get_after_next_shipping_date(self):
        return self.get_next_shipping_date(after=self.shipping_date)

    def get_discovery_coffee_ids(self):
        return json.loads(self.details['discovery_coffees'])

    def update_discovery_coffees(self, commit=True):
        self.details['discovery_coffees'] = [
            c.id for c in (CoffeeType.objects.discovery_pack(self.customer))
        ]
        if commit:
            self.save(update_fields=['details'])

    @cached_property
    def discovery_coffees(self):
        coffee_ids = self.get_discovery_coffee_ids()
        coffees = CoffeeType.objects.filter(id__in=coffee_ids)
        reviews = {
            review.coffee.id: review
            for review in self.reviews.filter(coffee_id__in=coffee_ids)
        }
        for coffee in coffees:
            coffee.review = reviews.get(coffee.id, {})
        return coffees
Esempio n. 6
0
class Bio(models.Model):
    """Bio stores physical attributes and contact details for user."""

    person = models.OneToOneField(Person,
                                  related_name='bio',
                                  related_query_name='bio',
                                  on_delete=models.CASCADE)

    # hstore field for storing person's physical attributes.
    # http://djangonauts.github.io/django-hstore/#_python_api
    data = hstore.DictionaryField(schema=[
        {
            'name': 'street_address',
            'class': 'CharField',
            'kwargs': {
                'blank': True,
                'max_length': 255,
                'null': True,
            }
        },
        {
            'name': 'hair_color',
            'class': 'CharField',
            'kwargs': {
                'default':
                'Black',
                'blank':
                True,
                'max_length':
                20,
                'null':
                True,
                'choices': (
                    ("black", "black"),
                    ("dark_brown", "dark_brown"),
                    ("light_brown", "light_brown"),
                    ("blonde", "blonde"),
                    ("red", "red"),
                    ("grey", "grey"),
                    ("white", "white"),
                    ('does_not_matter', ''),
                )
            }
        },
        {
            'name': 'eye_color',
            'class': 'CharField',
            'kwargs': {
                'blank':
                True,
                'max_length':
                20,
                'null':
                True,
                'choices': (
                    ("black", "black"),
                    ("blue", "blue"),
                    ("dark_brown", "dark_brown"),
                    ("light_brown", "light_brown"),
                    ("green", "green"),
                    ("grey", "grey"),
                    ("violet", "violet"),
                    ("hazel", "hazel"),
                    ('does_not_matter', ''),
                )
            },
        },
        {
            'name': 'height',
            'class': 'FloatField',
            'kwargs': {
                'blank': True,
                'null': True,
            }
        },
        {
            'name': 'waist',
            'class': 'IntegerField',
            'kwargs': {
                'blank': True,
                'null': True,
            }
        },
        {
            'name': 'shoulders',
            'class': 'IntegerField',
            'kwargs': {
                'blank': True,
                'null': True,
            }
        },
        {
            'name': 'chest',
            'class': 'IntegerField',
            'kwargs': {
                'blank': True,
                'null': True,
            }
        },
        {
            'name': 'hips',
            'class': 'IntegerField',
            'kwargs': {
                'blank': True,
                'null': True,
            }
        },
        {
            'name': 'shoe_size',
            'class': 'FloatField',
            'kwargs': {
                'blank': True,
                'null': True,
            }
        },
        {
            'name': 'hair_style',
            'class': 'CharField',
            'kwargs': {
                'blank':
                True,
                'max_length':
                50,
                'null':
                True,
                'choices':
                (("army_cut", "army_cut"), ("normal", "normal"),
                 ("slightly_long", "slightly_long"), ("shoulder_length",
                                                      "shoulder_length"),
                 ("partially_bald", "partially_bald"), ("completely_bald",
                                                        "completely_bald"),
                 ("boy_cut", "boy_cut"), ("bust_length", "bust_length"),
                 ("waist_length", "waist_length"),
                 ("knee_length", "knee_length"), ('does_not_matter', ''))
            }
        },
        {
            'name': 'hair_type',
            'class': 'CharField',
            'kwargs': {
                'blank':
                True,
                'max_length':
                50,
                'null':
                True,
                'choices': (('straight',
                             'straight'), ('wavy', 'wavy'), ('curly', 'curly'),
                            ('bald', 'bald'), ('half_bald', 'half_bald'),
                            ('scanty', 'scanty'), ('does_not_matter', ''))
            }
        },
        {
            'name': 'skin_type',
            'class': 'CharField',
            'kwargs': {
                'blank':
                True,
                'max_length':
                50,
                'null':
                True,
                'choices':
                (("very_fair", "very_fair"), ("fair", "fair"),
                 ("wheatish", "wheatish"), ("dusky", "dusky"),
                 ("dark", "dark"), ("very_dark",
                                    "very_dark"), ('does_not_matter', ''))
            }
        },
        {
            'name': 'body_type',
            'class': 'CharField',
            'kwargs': {
                'blank':
                True,
                'max_length':
                50,
                'null':
                True,
                'choices':
                (('skinny', 'skinny'), ('bulky', 'bulky'), ('slim', 'slim'),
                 ('athletic', 'athletic'), ('muscular', 'muscular'),
                 ('curvy', 'curvy'), ('heavy', 'heavy'), ('very_heavy',
                                                          'very_heavy'),
                 ('very_fat', 'very_fat'), ('does_not_matter', ''))
            }
        },
    ],
                                  db_index=True)

    zipcode = models.ForeignKey(PostalCode, null=True, blank=True)

    objects = hstore.HStoreManager()
Esempio n. 7
0
class BasicHStoreData(models.Model):
    hsdata = hstore.DictionaryField()
    objects = hstore.HStoreManager()
Esempio n. 8
0
class Card(models.Model):
    _data = hstore.DictionaryField()
    last_data_update = models.DateTimeField()
    _prices = hstore.DictionaryField()
    last_prices_update = models.DateTimeField()

    objects = hstore.HStoreManager()

    def __unicode__(self):
        card = "Card %s (updated %s)" % (str(
            self._data), self.last_data_update)
        prices = "Prices %s (updated %s)" % (str(
            self._prices), self.last_prices_update)
        return "%s\n%s" % (card, prices)

    def set_data(self, value):
        self._data = self.prepare_hstore(value)
        self.last_data_update = datetime.now()

    def get_data(self):
        if datetime.now() - self.last_data_update > UPDATE_TIMES['data']:
            self._update_data()
        if not self._data.get('link') and 'id' in self._data:
            self._data['link'] = get_link(self._data['id'])
            self.save()
        return self.load_hstore(self._data)

    data = property(get_data, set_data)

    def set_prices(self, value):
        self._prices = self.prepare_hstore(value)
        self.last_prices_update = datetime.now()

    def get_prices(self):
        if datetime.now() - self.last_prices_update > UPDATE_TIMES['prices']:
            self._update_prices()
        return self.load_hstore(self._prices)

    prices = property(get_prices, set_prices)

    def _update_data(self):
        self.last_data_update = datetime.now()
        print 'Update data'

    def _update_prices(self):
        self.last_prices_update = datetime.now()
        print 'Update prices'

    @classmethod
    def freesearch(cls, text):
        splitted = text.split(' ')
        return cls.objects.raw(card_query, (splitted, len(splitted)))

    def load_hstore(self, value):
        for key in value:
            if '&' in value[key] and key != 'link':
                value[key] = value[key].split('&')
                while value[key][-1] == '':
                    value[key] = value[key][:-1]
        return value

    def prepare_hstore(self, value):
        for key in value:
            if isinstance(value[key], list):
                value[key] = '&'.join([smart_str(v) for v in value[key]])
                if '&' not in value[key]:
                    value[key] = value[key] + '&'
            value[key] = smart_str(value[key])
        return value
Esempio n. 9
0
class Experiment(models.Model):

    must_have_attributes = [
        'accession', 'secondaryaccession', 'name', 'releasedate',
        'lastupdatedate', 'samples'
    ]

    must_have_attributes_map = {
        'accession': 'accession',
        'secondaryaccession': 'secondary accession',
        'name': 'name',
        'experimenttype': 'experiment type',
        'releasedate': 'release date',
        'lastupdatedate': 'last update date',
        'samples': 'samples'
    }

    extra_attributes = ['microarrays', 'status']

    data = hstore.DictionaryField(db_index=True)
    objects = hstore.HStoreManager()
    history = HistoricalRecords()
    samples = models.ManyToManyField('Sample')

    microarrays = models.ManyToManyField('Microarray')

    def find(exp):
        return Experiment.objects.filter(data__contains={
            'accession': exp
        }).first()

    def samples(self):
        return Sample.objects.filter(experiment=self)

    def sample_attributes(self):
        """get all attributes for all samples in experiment"""
        return SampleAttribute.objects.filter(sample__experiment=self)

    def __unicode__(self):
        to_print = 'accession'
        if to_print in self.data:
            return self.data[to_print]
        else:
            return 'some experiment'

    def __str__(self):
        to_print = 'accession'
        if to_print in self.data:
            # print("self data",type(self.data))
            return self.data[to_print]
        else:
            return 'some experiment'

    def to_dict(self, pretty_attributes=True):
        """
        Create dict of all meaningful characteristics of the Experiment
        """
        attributes = {}
        for attribute in self.must_have_attributes:
            if attribute in self.data:
                if pretty_attributes:
                    attributes[self.must_have_attributes_map[attribute]] = \
                            self.data[attribute]
                else:
                    attributes[attribute] = self.data[attribute]
        attributes['microarrays'] = self.get_microarrays_lst()
        attributes['status'] = self.cached_status()

        return attributes

    def to_list_of_dicts(pretty_attributes=True):
        exps = Experiment.objects.all()
        list_of_dicts = []
        for exp in exps:
            list_of_dicts.append(exp.to_dict(pretty_attributes))
        return list_of_dicts

    def add_or_replace(data):
        obj, some_bool = Experiment.objects.get_or_create(
            data__contains={'accession': data['accession']})

        obj.data = data
        obj.save()
        return obj

    def get_microarrays_lst(self):
        lst = [m.data['name'] for m in self.microarrays.all()]
        return ', '.join(lst)

    def is_excluded(self):
        return 'excluded' in self.data

    def is_mail_received():
        return 'mail received' in self.data

    def is_unified(self):
        exp_samples = self.samples()
        has_empty_name = SampleAttribute.objects.filter(
            sample__in=exp_samples, unificated_name=None).exists()

        has_empty_value = SampleAttribute.objects.filter(
            sample__in=exp_samples, unificated_value=None).exists()
        if has_empty_name or has_empty_value:
            return False
        else:
            return True

    def set_has_minimal(self):
        if self.has_minimal():
            self.data['has minimal'] = 'true'
        else:
            self.data['has minimal'] = 'false'
        self.save()

    def get_has_minimal(self):
        if 'has minimal' in self.data:
            if self.data['has minimal'] == 'true':
                return True
            else:
                return False
        return False

    def has_minimal(self):
        """
        check whether experiment has minimal sample data,
        needed for sample comparison
        """
        # import time
        # timestart = time.time()
        # print(self, "start")

        bspecimen = StandardName.objects.get(name="Biological Specimen").id
        diagnosis = StandardName.objects.get(name="Diagnosis").id
        age = StandardName.objects.get(name="Gestational Age").id
        age_exp = StandardName.objects.get(
            name="Gestational Age at Time of Sampling").id
        age_avg = StandardName.objects.get(name="Average Gestational Age").id
        age_cat = StandardName.objects.get(name="Gestational Age Category").id

        attributes = SampleAttribute.objects.filter(
            Q(unificated_name=bspecimen) | Q(unificated_name=diagnosis)
            | Q(unificated_name=age) | Q(unificated_name=age_avg)
            | Q(unificated_name=age_exp) | Q(unificated_name=age_cat))

        # timeq1 = time.time()
        # print(timeq1-timestart)

        samples = self.samples()
        # timeq2 = time.time()
        # print(timeq2-timestart)

        for sample in samples:

            sample_attributes = attributes.filter(sample=sample).values_list(
                "unificated_name", flat=True)

            if not (bspecimen in sample_attributes and \
                    diagnosis in sample_attributes and \
                    (age in sample_attributes or
                    age_exp in sample_attributes or
                    age_avg in sample_attributes or
                    age_cat in sample_attributes)):
                for attr in sample_attributes:
                    print(StandardName.objects.get(id=attr))
                # timeq3 = time.time()
                # print(timeq3-timestart)
                # print("end-")
                return False

        # timeq3 = time.time()
        # print(timeq3-timestart)
        # print("end+")

        return True

    def is_cell_line(self):
        if SampleAttribute.objects.filter(
                sample__in=self.samples(),
                unificated_name__name="Cells, Cultured").exists():
            return True
        return False

    def status(self):
        status = []
        # if 'status' in self.data:
        #     status.append(self.data['status'])
        if self.is_unified():
            status.append('Unified')
        if 'mail sent' in self.data:
            status.append('Mail Sent')
        if 'mail received' in self.data:
            status.append('Mail Received')
        if self.is_cell_line():
            status.append('Cell Сulture')

        if self.has_minimal():
            status.append('Has minimal sample data')
        if 'excluded' in self.data:
            status.append('Excluded')
        return ", ".join(status)

    def update_status(self):
        self.data['status'] = self.status()
        self.save()

    def cached_status(self):
        if 'status' not in self.data:
            self.update_status()
        return self.data['status']
Esempio n. 10
0
class Survey(models.Model):
    class Meta:
        db_table = 'survey'

    STATUS_CHOICES = (
        ('approved', 'Approved'),
        ('in_planning', 'In planning'),
        ('not_available', 'Not available'),
    )

    TRANSPORT_PARTS = (
        ('infrastructure', 'Transport infrastructure'),
        ('services', 'Transport services'),
    )

    TRANSPORT_MODES = (
        ('road', 'Road'),
        ('rail', 'Rail'),
        ('aviation', 'Aviation'),
        ('inland_water', 'Inland water shipping'),
        ('maritime', 'Maritime shipping'),
        ('urban_transport', 'Urban transport'),
    )

    IMPACTS = (
        ('temperatures', '(Extreme) Temperatures'),
        ('flooding', 'Flooding'),
        ('sea_level_rise', 'Sea level rise'),
        ('storms', 'Storms'),
        ('ice_snow', 'Ice and snow'),
        ('water_scarcity_droughts', 'Water scarcity and droughts'),
    )

    RELEVANT_CHOICES = (
        ('none', 'None'),
        ('low', 'low'),
        ('medium', 'medium'),
        ('high', 'high'),
        ('don\'t know', 'don\'t know'),
    )

    category = models.ForeignKey(Category)

    country = models.ForeignKey('countries.Country')

    user = models.ForeignKey('tach.User')

    date = models.DateTimeField(auto_now=True)

    status = models.CharField(max_length=50,
                              choices=STATUS_CHOICES,
                              null=True,
                              blank=True)

    title = models.CharField(max_length=256, null=True, blank=True)

    english_title = models.CharField(max_length=256, null=True, blank=True)

    year = models.IntegerField(null=True, blank=True)

    parts_considered = hstore.DictionaryField(null=True, blank=True)

    transport_modes = hstore.DictionaryField(null=True, blank=True)

    climate_change_impacts = hstore.DictionaryField(null=True, blank=True)

    responsible_organisation = models.CharField(max_length=256,
                                                null=True,
                                                blank=True)

    link = models.CharField(max_length=256, null=True, blank=True)

    language = models.ForeignKey(Language, null=True, blank=True)

    contact = models.CharField(max_length=256, null=True, blank=True)

    focus = models.CharField(max_length=256, null=True, blank=True)

    section_a_info = models.TextField(null=True, blank=True)

    section_a_comment = models.TextField(null=True, blank=True)

    section_b_info = models.TextField(null=True, blank=True)

    section_b_comment = models.TextField(null=True, blank=True)

    section_c2 = models.TextField(null=True, blank=True)

    section_d_comment = models.TextField(null=True, blank=True)

    section_c_comment = models.TextField(null=True, blank=True)

    section_e_comment = models.TextField(null=True, blank=True)

    area_of_expertise = models.CharField(max_length=256, null=True, blank=True)

    # section D

    adaptation_strategy = models.CharField(max_length=50,
                                           choices=STATUS_CHOICES,
                                           null=True,
                                           blank=True)

    transport_information = models.CharField(max_length=50,
                                             choices=STATUS_CHOICES,
                                             null=True,
                                             blank=True)

    trans_national_cooperation = models.CharField(max_length=50,
                                                  choices=STATUS_CHOICES,
                                                  null=True,
                                                  blank=True)

    stakeholders_cooperaton = models.CharField(max_length=50,
                                               choices=STATUS_CHOICES,
                                               null=True,
                                               blank=True)

    integration_of_climate_change = models.CharField(max_length=50,
                                                     choices=STATUS_CHOICES,
                                                     null=True,
                                                     blank=True)

    funding = models.CharField(max_length=50,
                               choices=STATUS_CHOICES,
                               null=True,
                               blank=True)

    revision_of_design = models.CharField(max_length=50,
                                          choices=STATUS_CHOICES,
                                          null=True,
                                          blank=True)

    climate_proof = models.CharField(max_length=50,
                                     choices=STATUS_CHOICES,
                                     null=True,
                                     blank=True)

    development_methodologies = models.CharField(max_length=50,
                                                 choices=STATUS_CHOICES,
                                                 null=True,
                                                 blank=True)

    data_collection = models.CharField(max_length=50,
                                       choices=STATUS_CHOICES,
                                       null=True,
                                       blank=True)

    transport_research = models.CharField(max_length=50,
                                          choices=STATUS_CHOICES,
                                          null=True,
                                          blank=True)

    lack_of_awareness = models.CharField(max_length=50,
                                         choices=STATUS_CHOICES,
                                         null=True,
                                         blank=True)

    knowledge_gaps = models.CharField(max_length=50,
                                      choices=STATUS_CHOICES,
                                      null=True,
                                      blank=True)

    data_gaps = models.CharField(max_length=50,
                                 choices=STATUS_CHOICES,
                                 null=True,
                                 blank=True)

    lack_of_training = models.CharField(max_length=50,
                                        choices=STATUS_CHOICES,
                                        null=True,
                                        blank=True)

    lack_of_capacities = models.CharField(max_length=50,
                                          choices=STATUS_CHOICES,
                                          null=True,
                                          blank=True)

    lack_of_resources = models.CharField(max_length=50,
                                         choices=STATUS_CHOICES,
                                         null=True,
                                         blank=True)

    access_to_funding = models.CharField(max_length=50,
                                         choices=STATUS_CHOICES,
                                         null=True,
                                         blank=True)

    lack_of_coordination = models.CharField(max_length=50,
                                            choices=STATUS_CHOICES,
                                            null=True,
                                            blank=True)

    awareness_lack_eu_level = models.CharField(max_length=50,
                                               choices=STATUS_CHOICES,
                                               null=True,
                                               blank=True)

    relevance = models.CharField(max_length=50,
                                 choices=RELEVANT_CHOICES,
                                 null=True,
                                 blank=True)

    d1_comments = models.TextField(null=True, blank=True)

    d2_comments = models.TextField(null=True, blank=True)

    objects = hstore.HStoreManager()