Beispiel #1
0
    def test_niceness(self):
        """ Test niceness level for pedigree with sibling and large pedigree. """
        pedigree = deepcopy(self.pedigree)
        self.assertEqual(Predictions._get_niceness(pedigree, factor=1), len(pedigree.people))
        self.assertEqual(Predictions._get_niceness(pedigree, factor=0.01), 19)

        # sister
        target = pedigree.get_target()
        sister = Female("FAM1", "F01", "0011", target.fathid, target.mothid, age="22",
                        yob=str(self.year-23), cancers=Cancers(bc1=Cancer("20")))
        pedigree.people.append(sister)
        self.assertEqual(Predictions._get_niceness(pedigree), 1)
Beispiel #2
0
    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid(raise_exception=True):
            validated_data = serializer.validated_data
            pf = PedigreeFile(validated_data.get('pedigree_data'))
            model_settings = settings.BC_MODEL
            params = ModelParams.factory(validated_data, model_settings)

            tenyr_ages = re.sub("[\[\]]", "", validated_data.get('tenyr_ages'))
            tenyr_ages = [int(item.strip()) for item in tenyr_ages.split(',')]
            logger.debug(tenyr_ages)

            output = {
                "timestamp": datetime.datetime.now(),
                "mutation_frequency": {
                    params.population: params.mutation_frequency
                },
                "mutation_sensitivity": params.mutation_sensitivity,
                "cancer_incidence_rates": params.cancer_rates,
                "pedigree_result": []
            }

            risk_factor_code = validated_data.get('risk_factor_code', 0)
            prs = validated_data.get('prs', None)
            if prs is not None:
                prs = Prs(prs.get('alpha'), prs.get('zscore'))

            try:
                warnings = PedigreeFile.validate(pf.pedigrees)
                if len(warnings) > 0:
                    output['warnings'] = warnings
            except ValidationError as e:
                logger.error(e)
                return JsonResponse(e.detail,
                                    content_type="application/json",
                                    status=status.HTTP_400_BAD_REQUEST)

            # note limit username string length used here to avoid paths too long for model code
            cwd = tempfile.mkdtemp(prefix=str(request.user)[:20] + "_",
                                   dir=settings.CWD_DIR)
            try:
                for pedi in pf.pedigrees:
                    this_params = deepcopy(params)
                    # check if Ashkenazi Jewish status set & correct mutation frequencies
                    if pedi.is_ashkn() and not REGEX_ASHKN.match(
                            params.population):
                        msg = 'mutation frequencies set to Ashkenazi Jewish population values ' \
                              'for family ('+pedi.famid+') as a family member has Ashkenazi Jewish status.'
                        logger.debug(
                            'mutation frequencies set to Ashkenazi Jewish population values'
                        )
                        if 'warnings' in output:
                            output['warnings'].append(msg)
                        else:
                            output['warnings'] = [msg]
                        this_params.population = 'Ashkenazi'
                        this_params.mutation_frequency = model_settings[
                            'MUTATION_FREQUENCIES']['Ashkenazi']

                    if isinstance(pedi, CanRiskPedigree):
                        # for canrisk format files check if risk factors and/or prs set in the header
                        mname = model_settings['NAME']
                        if 'risk_factor_code' not in request.data.keys():
                            risk_factor_code = pedi.get_rfcode(mname)

                        if prs is None or len(pf.pedigrees) > 1:
                            prs = pedi.get_prs(mname)

                    calcs = Predictions(pedi,
                                        model_params=this_params,
                                        risk_factor_code=risk_factor_code,
                                        prs=prs,
                                        run_risks=False,
                                        cwd=cwd,
                                        request=request,
                                        model_settings=model_settings)
                    calcs.niceness = Predictions._get_niceness(calcs.pedi)

                    calcs.ten_yr_cancer_risk = []
                    for tenyr in tenyr_ages:
                        ten_yr_risk, _v = RangeRisk(calcs, int(tenyr),
                                                    int(tenyr + 10),
                                                    "10 YR RANGE").get_risk()
                        if ten_yr_risk is not None:
                            calcs.ten_yr_cancer_risk.append(ten_yr_risk[0])

                    # Add input parameters and calculated results as attributes to 'this_pedigree'
                    this_pedigree = {}
                    this_pedigree["family_id"] = pedi.famid
                    this_pedigree["proband_id"] = pedi.get_target().pid
                    this_pedigree["risk_factors"] = self.get_risk_factors(
                        model_settings, risk_factor_code)
                    if prs is not None:
                        this_pedigree["prs"] = {
                            'alpha': prs.alpha,
                            'zscore': prs.zscore
                        }
                    this_pedigree["mutation_frequency"] = {
                        this_params.population: this_params.mutation_frequency
                    }
                    self.add_attr("version", output, calcs, output)
                    self.add_attr("ten_yr_cancer_risk", this_pedigree, calcs,
                                  output)

                    output["pedigree_result"].append(this_pedigree)
            except ValidationError as e:
                logger.error(e)
                return JsonResponse(e.detail,
                                    content_type="application/json",
                                    status=status.HTTP_400_BAD_REQUEST,
                                    safe=False)
            finally:
                shutil.rmtree(cwd)
            output_serialiser = OutputSerializer(output)
            return Response(output_serialiser.data,
                            template_name='result_tab_gp.html')

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)