Skip to content
Snippets Groups Projects
APIController.php 57.5 KiB
Newer Older
  • Learn to ignore specific revisions
  •         $metadata = new \stdClass();
    
            try {
                $attributes = $request->validate([
                    'election_type' => 'required|string|in:d2,d3'
                ]);
            } catch (ValidationException $e) {
                return response()->json([
                    'message' => 'Incorrect payload',
                    'val_errors' => $e->errors()
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }
            $type = $attributes['election_type'];
    
            $metadata->election_type = $type;
    
            $templatePopulation = Population::where('id', '=', $template)
    
                //->whereNull('parent_id')
    
                ->with(['childPopulations' => function ($q) use ($type) {
                    $q->where('election_type', '=', $type)
                        ->with('elections.extension');
                }])
                ->firstOrFail()
                ->makeHidden('childPopulations');
    
            $templatePopulation->report_metadata = $metadata;
    
            $countA = $templatePopulation->voters()->where('group', '=', 'A')->count();
            $countB = $templatePopulation->voters()->where('group', '=', 'B')->count();
    
            $templatePopulation->no_of_voters = $countA + $countB;
    
            if ($templatePopulation->no_of_voters < 1) {
                return response()->json(['error' => 'No voters in population'], Response::HTTP_NOT_FOUND);
            }
    
            $templatePopulation->no_of_voters_a = $countA;
            $templatePopulation->no_of_voters_b = $countB;
            $templatePopulation->no_of_child_populations = $templatePopulation->childPopulations->count();
    
            $first = true;
            $minElectionCount = 0;
            $maxElectionCount = 0;
            $childPopulationCount = 0;
    
            foreach ($templatePopulation->childPopulations as $childPopulation) {
                $childPopulationCount++;
                $electionCount = $childPopulation->elections()->count();
                if ($first) {
                    $minElectionCount = $electionCount;
                    $maxElectionCount = $electionCount;
                    $first = false;
                } else {
                    if ($electionCount > $maxElectionCount) {
                        $maxElectionCount = $electionCount;
                    }
                    if ($electionCount < $minElectionCount) {
                        $minElectionCount = $electionCount;
                    }
                }
                $childPopulation->elections_count = $electionCount;
                $childPopulation->makeHidden('elections');
            }
            $templatePopulation->min_election_count = $minElectionCount;
            $templatePopulation->max_election_count = $maxElectionCount;
    
            // init weight counters
            $weightsSequencesA = array();
            $weightsSequencesB = array();
            $weightShareSequenceB = array();
            $minWeightShareSequenceB = array();
            $maxWeightShareSequenceB = array();
    
            $minWeightsSequencesA = array();
            $minWeightsSequencesB = array();
            $maxWeightsSequencesA = array();
            $maxWeightsSequencesB = array();
    
            for ($i = 0; $i < $minElectionCount; $i++) {
                $weightsSequencesA[$i] = 0;
                $weightsSequencesB[$i] = 0;
            }
    
            $first = true;
            foreach ($templatePopulation->childPopulations as $childPopulation) {
                $childPopulation->exceeding_elections = $childPopulation->elections_count - $minElectionCount;
    
                if ($first) {
                    for ($i = 0; $i < $minElectionCount; $i++) {
                        $weightA = $childPopulation->elections[$i]->extension->weight_a;
                        $weightB = $childPopulation->elections[$i]->extension->weight_b;
                        $weightShareB = $weightB / ($weightA + $weightB);
                        $weightsSequencesA[$i] = $weightA;
                        $weightsSequencesB[$i] = $weightB;
                        $minWeightsSequencesA[$i] = $weightA;
                        $minWeightsSequencesB[$i] = $weightB;
                        $maxWeightsSequencesA[$i] = $weightA;
                        $maxWeightsSequencesB[$i] = $weightB;
                        $weightShareSequenceB[$i] = $weightShareB;
                        $minWeightShareSequenceB[$i] = $weightShareB;
                        $maxWeightShareSequenceB[$i] = $weightShareB;
                    }
                    $first = false;
                    continue;
                }
                for ($i = 0; $i < $minElectionCount; $i++) {
                    $weightA = $childPopulation->elections[$i]->extension->weight_a;
                    $weightB = $childPopulation->elections[$i]->extension->weight_b;
                    $weightShareB = $weightB / ($weightA + $weightB);
                    $weightsSequencesA[$i] += $weightA;
                    $weightsSequencesB[$i] += $weightB;
    
                    $weightShareSequenceB[$i] += $weightShareB;
    
                    if ($minWeightsSequencesA[$i] > $weightA) {
                        $minWeightsSequencesA[$i] = $weightA;
                    }
                    if ($minWeightsSequencesB[$i] > $weightB) {
                        $minWeightsSequencesB[$i] = $weightB;
                    }
                    if ($weightA > $maxWeightsSequencesA[$i]) {
                        $maxWeightsSequencesA[$i] = $weightA;
                    }
                    if ($weightB > $maxWeightsSequencesB[$i]) {
                        $maxWeightsSequencesB[$i] = $weightB;
                    }
                    if ($weightShareB > $maxWeightShareSequenceB[$i]) {
                        $maxWeightShareSequenceB[$i] = $weightShareB;
                    }
                    if ($minWeightShareSequenceB[$i] > $weightShareB) {
                        $minWeightShareSequenceB[$i] = $weightShareB;
                    }
                }
            }
    
            $weightsAvgTimeline = array();
            //$votersFactorA = $templatePopulation->no_of_child_populations * $countA;
            //$votersFactorB = $templatePopulation->no_of_child_populations * $countB;
    
    
            $previousWeightShareB = 0;
    
    
            for ($i = 0; $i < $minElectionCount; $i++) {
                $newWeight = new \stdClass();
    
                $newWeight->min_sum_weight_a = $minWeightsSequencesA[$i];
                $newWeight->max_sum_weight_a = $maxWeightsSequencesA[$i];
                $newWeight->min_sum_weight_b = $minWeightsSequencesB[$i];
                $newWeight->max_sum_weight_b = $maxWeightsSequencesB[$i];
    
                //$newWeight->avg_voter_weight_a = $weightsSequencesA[$i] / $votersFactorA;
                //$newWeight->avg_voter_weight_b = $weightsSequencesB[$i] / $votersFactorB;
    
                $newWeight->avg_sum_weight_a = $weightsSequencesA[$i] / $templatePopulation->no_of_child_populations;
                $newWeight->avg_sum_weight_b = $weightsSequencesB[$i] / $templatePopulation->no_of_child_populations;
                $newWeight->share_sum_weight_b = $weightShareSequenceB[$i] / $templatePopulation->no_of_child_populations;
                $newWeight->min_share_sum_weight_b = $minWeightShareSequenceB[$i];
                $newWeight->max_share_sum_weight_b = $maxWeightShareSequenceB[$i];
    
                $shareDiff = $newWeight->share_sum_weight_b - $previousWeightShareB;
                $newWeight->diff_share_sum_weight_b = $shareDiff > 0 ? $shareDiff : -$shareDiff;
                $previousWeightShareB = $newWeight->share_sum_weight_b;
    
    
                array_push($weightsAvgTimeline, $newWeight);
            }
    
            $templatePopulation->weights = $weightsAvgTimeline;
    
            $endTime = microtime(true);
            $metadata->process_time = round($endTime - $startTime, 5);
    
            return response()->json($templatePopulation, Response::HTTP_OK);
        }
    
    
        public function fetchAllPerformanceModeElections(int $template, Request $request) {
            $startTime = microtime(true);
            $metadata = new \stdClass();
    
            $templatePopulation = Population::where('id', '=', $template)
                //->whereNull('parent_id')
                ->with(['childPopulations' => function ($q){
                    $q->where('stage', '=', 'p')
                        ->with(['elections' => function ($q1) {
                            $q1->where('type', '=', 'd1')
                                ->with('extension');
                        }]);
                }])
                ->firstOrFail()
                ->makeHidden('childPopulations');
    
            $d2TypesCount = 0;
            $d2Correct = 0;
            $d2Incorrect = 0;
            $d3TypesCount = 0;
            $d3Correct = 0;
            $d3Incorrect = 0;
    
            foreach ($templatePopulation->childPopulations as $childPopulation) {
                $electionCount = $childPopulation->elections->count();
                $totalCorrect = $childPopulation->elections->sum('total_correct');
                $totalIncorrect = $childPopulation->elections->sum('total_incorrect');
                if ($childPopulation->election_type == 'd2') {
                    $d2TypesCount += $electionCount;
                    $d2Correct += $totalCorrect;
                    $d2Incorrect += $totalIncorrect;
                } elseif($childPopulation->election_type == 'd2') {
                    $d3TypesCount += $electionCount;
                    $d3Correct += $totalCorrect;
                    $d3Incorrect += $totalIncorrect;
                }
            }
    
            $response = new \stdClass();
            $response->report_metadata = $metadata;
    
            $response->results = array();
    
            $d2Votes = $d2Correct + $d2Incorrect;
    
            if ($d2Votes > 0) {
                $d2Stats = new \stdClass();
                $d2Stats->election_type = 'd2';
                $d2Stats->election_count = $d2TypesCount;
                $d2Stats->correct = $d2Correct;
                $d2Stats->incorrect = $d2Incorrect;
                $d2Stats->percent_correct = 100 * $d2Correct / $d2Votes;
                $response->results['d2'] = $d2Stats;
            } else {
                $response->results['d2'] = null;
            }
    
            $d3Votes = $d3Correct + $d3Incorrect;
    
            if ($d3Votes > 0) {
                $d3Stats = new \stdClass();
                $d3Stats->election_type = 'd3';
                $d3Stats->election_count = $d3TypesCount;
                $d3Stats->correct = $d3Correct;
                $d3Stats->incorrect = $d3Incorrect;
                $d3Stats->percent_correct = 100 * $d2Correct / $d3Votes;
                $response->results['d3'] = $d3Stats;
            } else {
                $response->results['d3'] = null;
            }
    
            $endTime = microtime(true);
            $metadata->process_time = round($endTime - $startTime, 5);
    
            return response()->json($response, Response::HTTP_OK);
        }
    
        /**
         * Gets all performance mode results for d1,d2,d3
         *
         * @param int $template
         * @param Request $request
         * @return \Illuminate\Http\JsonResponse
         */
        public function getTemplateElectionResultStats(int $template, Request $request) {
            $startTime = microtime(true);
            $metadata = new \stdClass();
    
            try {
                $attributes = $request->validate([
                    'election_type' => 'required|string|in:d1,d2,d3'
                ]);
            } catch (ValidationException $e) {
                return response()->json([
                    'message' => 'Incorrect payload',
                    'val_errors' => $e->errors()
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }
            $type = $attributes['election_type'];
            $metadata->election_type = $type;
    
            $templatePopulation = Population::where('id', '=', $template)
                //->whereNull('parent_id')
                ->with(['childPopulations' => function ($q) use ($type) {
                    $q->where('election_type', '=', $type)
                        ->where('stage', '=', 'p')
                        ->with(['elections' => function ($q1) {
                            $q1->where('type', '=', 'd1')
                                ->with('extension');
                        }]);
                }])
                ->firstOrFail()
                ->makeHidden('childPopulations');
    
            $templatePopulation->report_metadata = $metadata;
    
            $countA = $templatePopulation->voters()->where('group', '=', 'A')->count();
            $countB = $templatePopulation->voters()->where('group', '=', 'B')->count();
    
            $templatePopulation->no_of_voters = $countA + $countB;
    
            $templatePopulation->avg_expertise = $templatePopulation->voters()->average('expertise');
            $templatePopulation->max_expertise = $templatePopulation->voters()->max('expertise');
    
            if ($templatePopulation->no_of_voters < 1) {
                return response()->json(['error' => 'No voters in population'], Response::HTTP_NOT_FOUND);
            }
    
            $templatePopulation->no_of_voters_a = $countA;
            $templatePopulation->no_of_voters_b = $countB;
            $templatePopulation->no_of_child_populations = $templatePopulation->childPopulations->count();
    
            $first = true;
            $minElectionCount = 0;
            $maxElectionCount = 0;
            $childPopulationCount = 0;
    
            $noumberOfVoters = $templatePopulation->no_of_voters;
            $electionResultsGathered = array();
    
            foreach ($templatePopulation->childPopulations as $childPopulation) {
                $childPopulationCount++;
                $electionCount = $childPopulation->elections->count();
    
                if ($first) {
                    $minElectionCount = $electionCount;
                    $maxElectionCount = $electionCount;
                    $first = false;
                } else {
                    if ($electionCount > $maxElectionCount) {
                        $maxElectionCount = $electionCount;
                    }
                    if ($electionCount < $minElectionCount) {
                        $minElectionCount = $electionCount;
                    }
                }
                $childPopulation->elections_count = $electionCount;
                $childPopulation->makeHidden('elections');
    
                foreach ($childPopulation->elections as $election) {
                    $correct = $election->total_correct;
                    $correctShare = $correct / $noumberOfVoters;
                    $correctPercent = 100 * $correctShare;
                    array_push($electionResultsGathered, $correctPercent);
                }
    
            }
            $templatePopulation->min_election_count = $minElectionCount;
            $templatePopulation->max_election_count = $maxElectionCount;
    
            sort($electionResultsGathered);
            $templatePopulation->all_elections_gathered = $electionResultsGathered;
    
            $logPath = 'election_logs/' . $templatePopulation->id  . '_' . time() . '.json';
    
            Storage::disk('local')->put($logPath, json_encode($electionResultsGathered));
    
            $endTime = microtime(true);
            $metadata->process_time = round($endTime - $startTime, 5);
    
            return response()->json($templatePopulation, Response::HTTP_OK);
    
    
            $electionResults = array();
            $electionResultsDetails = array();
            $electionResultsGathered = array();
    
            for ($i = 0; $i < $minElectionCount; $i++) {
                $electionResults[$i] = 0;
            }
    
            $distributionGathered = array();
            $distributionGatheredRounded5 = array();
            $distributionGatheredRounded10 = array();
    
            for($i=0;$i<101;$i++){
                $distributionGathered[$i] = 0;
            }
            for($i=0;$i<21;$i++){
                $distributionGatheredRounded5[$i] = 0;
            }
            for($i=0;$i<11;$i++){
                $distributionGatheredRounded10[$i] = 0;
            }
    
            foreach ($templatePopulation->childPopulations as $childPopulation) {
                $childPopulation->exceeding_elections = $childPopulation->elections_count - $minElectionCount;
                $childResults = array();
    
                for ($i = 0; $i < $minElectionCount; $i++) {
                    $correct = $childPopulation->elections[$i]->total_correct;
                    $correctShare = $correct / $templatePopulation->no_of_voters;
                    $correctPercent = 100 * $correctShare;
                    $electionResults[$i] += $correctPercent;
                    array_push($childResults, $correctPercent);
                    array_push($electionResultsGathered, $correctPercent);
                    $distributionGathered[floor($correctPercent)]++;
                    $distributionGatheredRounded5[floor(20 * $correctShare)]++;
                    $distributionGatheredRounded10[floor(10 * $correctShare)]++;
                }
                array_push($electionResultsDetails, $childResults);
            }
    /*
            $electionsAvgTimeline = array();
            for ($i = 0; $i < $minElectionCount; $i++) {
                $newResult = $electionResults[$i] / $templatePopulation->no_of_child_populations;
                array_push($electionsAvgTimeline, $newResult);
            }
    */
            //sort($electionsAvgTimeline);
            //$templatePopulation->elections_avg = $electionsAvgTimeline;
            //$templatePopulation->elections_detailed = $electionResultsDetails;
            sort($electionResultsGathered);
            $templatePopulation->all_elections_gathered = $electionResultsGathered;
            //$templatePopulation->elections_gathered_distribution = $distributionGathered;
            //$templatePopulation->elections_gathered_distribution_5 = $distributionGatheredRounded5;
            //$templatePopulation->elections_gathered_distribution_10 = $distributionGatheredRounded10;
    
    
    
    
    
    
            $endTime = microtime(true);
            $metadata->process_time = round($endTime - $startTime, 5);
    
            return response()->json($templatePopulation, Response::HTTP_OK);
        }