def execute_query(self, author, course, request):
     return [p for p in Project.get_user_projects(author, course).filter(submitted=True)
             if p.visible(request)]
Exemple #2
0
 def execute_query(self, author, course, request):
     return [
         p for p in Project.get_user_projects(author, course).filter(
             submitted=True) if p.visible(request)
     ]
Exemple #3
0
def cohort_detail(request, cohort_id=0, workbook_id=0, worksheet_id=0, create_workbook=False):
    if debug: print >> sys.stderr,'Called '+sys._getframe().f_code.co_name
    users = User.objects.filter(is_superuser=0).exclude(id=request.user.id)
    cohort = None
    shared_with_users = []

    # service = build('meta', 'v1', discoveryServiceUrl=META_DISCOVERY_URL)
    clin_attr = [
        'Project',
        'Study',
        'vital_status',
        # 'survival_time',
        'gender',
        'age_at_initial_pathologic_diagnosis',
        'SampleTypeCode',
        'tumor_tissue_site',
        'histological_type',
        'prior_dx',
        'pathologic_stage',
        'person_neoplasm_cancer_status',
        'new_tumor_event_after_initial_treatment',
        'neoplasm_histologic_grade',
        # 'bmi',
        'residual_tumor',
        # 'targeted_molecular_therapy', TODO: Add to metadata_samples
        'tobacco_smoking_history',
        'icd_10',
        'icd_o_3_site',
        'icd_o_3_histology'
    ]

    # data_attr = [
    #     'has_Illumina_DNASeq',
    #     'has_BCGSC_HiSeq_RNASeq',
    #     'has_UNC_HiSeq_RNASeq',
    #     'has_BCGSC_GA_RNASeq',
    #     'has_UNC_GA_RNASeq',
    #     'has_HiSeq_miRnaSeq',
    #     'has_GA_miRNASeq',
    #     'has_RPPA',
    #     'has_SNP6',
    #     'has_27k',
    #     'has_450k'
    # ]

    data_attr = [
        'DNA_sequencing',
        'RNA_sequencing',
        'miRNA_sequencing',
        'Protein',
        'SNP_CN',
        'DNA_methylation'
    ]

    molec_attr = [
        'somatic_mutation_status',
        'mRNA_expression',
        'miRNA_expression',
        'DNA_methylation',
        'gene_copy_number',
        'protein_quantification'
    ]

    clin_attr_dsp = []
    clin_attr_dsp += clin_attr

    token = SocialToken.objects.filter(account__user=request.user, account__provider='Google')[0].token
    data_url = METADATA_API + 'v2/metadata_counts'
    payload = {
        'token': token
    }
    results = urlfetch.fetch(data_url, method=urlfetch.POST, payload=json.dumps(payload), deadline=60, headers={'Content-Type': 'application/json'})
    results = json.loads(results.content)
    totals = results['total']

    if USER_DATA_ON:
        # Add in user data
        user_attr = ['user_project','user_study']
        projects = Project.get_user_projects(request.user, True)
        studies = Study.get_user_studies(request.user, True)
        features = User_Feature_Definitions.objects.filter(study__in=studies)
        study_counts = {}
        project_counts = {}

        for count in results['count']:
            if 'id' in count and count['id'].startswith('study:'):
                split = count['id'].split(':')
                study_id = split[1]
                feature_name = split[2]
                study_counts[study_id] = count['total']

        user_studies = []
        for study in studies:
            count = study_counts[study.id] if study.id in study_counts else 0

            if not study.project_id in project_counts:
                project_counts[study.project_id] = 0
            project_counts[study.project_id] += count

            user_studies += ({
                            'count': str(count),
                            'value': study.name,
                            'id'   : study.id
                          },)

        user_projects = []
        for project in projects:
            user_projects += ({
                                'count': str(project_counts[project.id]) if project.id in project_counts else 0,
                                'value': project.name,
                                'id'   : project.id
                                },)

        results['count'].append({
            'name': 'user_projects',
            'values': user_projects
        })
        results['count'].append({
            'name': 'user_studies',
            'values': user_studies
        })

    # Get and sort counts
    attr_details = {
        'RNA_sequencing': [],
        'miRNA_sequencing': [],
        'DNA_methylation': []
    }
    keys = []
    for item in results['count']:
        #print item
        key = item['name']
        values = item['values']

        if key.startswith('has_'):
            data_availability_sort(key, values, data_attr, attr_details)
        else:
            keys.append(item['name'])
            item['values'] = sorted(values, key=lambda k: int(k['count']), reverse=True)

            if item['name'].startswith('user_'):
                clin_attr_dsp += (item['name'],)

    for key, value in attr_details.items():
        results['count'].append({
                                    'name': key,
                                    'values': value,
                                    'id': None
                                 })

    template_values = {
        'request': request,
        'users': users,
        'attr_list': keys,
        'attr_list_count': results['count'],
        'total_samples': int(totals),
        'clin_attr': clin_attr_dsp,
        'data_attr': data_attr,
        'molec_attr': molec_attr,
        'base_url': settings.BASE_URL,
        'base_api_url': settings.BASE_API_URL,
        'token': token
    }

    if USER_DATA_ON:
        template_values['user_attr'] = user_attr

    if workbook_id and worksheet_id :
        template_values['workbook']  = Workbook.objects.get(id=workbook_id)
        template_values['worksheet'] = Worksheet.objects.get(id=worksheet_id)
    elif create_workbook:
        template_values['create_workbook'] = True

    template = 'cohorts/new_cohort.html'

    if cohort_id != 0:
        try:
            cohort = Cohort.objects.get(id=cohort_id, active=True)
            cohort.perm = cohort.get_perm(request)
            cohort.owner = cohort.get_owner()

            if not cohort.perm:
                messages.error(request, 'You do not have permission to view that cohort.')
                return redirect('cohort_list')

            cohort.mark_viewed(request)

            shared_with_ids = Cohort_Perms.objects.filter(cohort=cohort, perm=Cohort_Perms.READER).values_list('user', flat=True)
            shared_with_users = User.objects.filter(id__in=shared_with_ids)
            template = 'cohorts/cohort_details.html'
            template_values['cohort'] = cohort
            template_values['total_samples'] = len(cohort.samples_set.all())
            template_values['total_patients'] = len(cohort.patients_set.all())
            template_values['shared_with_users'] = shared_with_users
        except ObjectDoesNotExist:
            # Cohort doesn't exist, return to user landing with error.
            messages.error(request, 'The cohort you were looking for does not exist.')
            return redirect('cohort_list')

    return render(request, template, template_values)