Passed
Push — master ( 9fd6b6...ce1e09 )
by Jonathan
05:22
created

SosaStatsController::getTop10Ancestors()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 10
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 15
rs 8.8333
1
<?php
2
/**
3
 * webtrees-lib: MyArtJaub library for webtrees
4
 *
5
 * @package MyArtJaub\Webtrees
6
 * @subpackage Sosa
7
 * @author Jonathan Jaubart <[email protected]>
8
 * @copyright Copyright (c) 2009-2016, Jonathan Jaubart
9
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3
10
 */
11
namespace MyArtJaub\Webtrees\Module\Sosa;
12
13
use Fisharebest\Webtrees\Auth;
14
use Fisharebest\Webtrees\Controller\PageController;
15
use Fisharebest\Webtrees\Filter;
16
use Fisharebest\Webtrees\I18N;
17
use Fisharebest\Webtrees\Individual;
18
use Fisharebest\Webtrees\Module\AbstractModule;
19
use MyArtJaub\Webtrees\Functions\Functions;
20
use MyArtJaub\Webtrees\Globals;
21
use MyArtJaub\Webtrees\Module\Sosa\Model\SosaProvider;
22
use MyArtJaub\Webtrees\Mvc\Controller\MvcController;
23
use MyArtJaub\Webtrees\Mvc\View\ViewBag;
24
use MyArtJaub\Webtrees\Mvc\View\ViewFactory;
25
26
/**
27
 * Controller for SosaStats
28
 */
29
class SosaStatsController extends MvcController
30
{
31
    /**
32
     * Sosa Provider for the controller
33
     * @var SosaProvider $sosa_provider
34
     */
35
    protected $sosa_provider;
36
    
37
    /**
38
     * Constructor for SosaStatsController
39
     * @param AbstractModule $module
40
     */
41
    public function __construct(AbstractModule $module) {
42
        parent::__construct($module);
43
        
44
        $this->sosa_provider = new SosaProvider(Globals::getTree(), Auth::user());
45
    }
46
    
47
    /**
48
     * Pages
49
     */
50
    
51
    /**
52
     * SosaStats@index
53
     */
54
    public function index() {
55
        $wt_tree = Globals::getTree();
56
        $controller = new PageController();
57
        $controller
58
            ->setPageTitle(I18N::translate('Sosa Statistics'))
59
            ->addInlineJavascript('$(".help_tooltip").tooltip();')
60
        ;
61
62
        $view_bag = new ViewBag();
63
        $view_bag->set('title', $controller->getPageTitle());
64
        $view_bag->set('is_setup', false);
65
        
66
        if($this->sosa_provider->isSetup()) {
67
            $view_bag->set('is_setup', true);
68
            
69
            $view_bag->set('root_indi', $this->sosa_provider->getRootIndi());
70
            
71
            $sosaCount = $this->sosa_provider->getSosaCount();
72
            $diffSosaCount = $this->sosa_provider->getDifferentSosaCount();
73
            
74
            $general_stats = array(
75
                'sosa_count' => $sosaCount,
76
                'distinct_count' => $diffSosaCount,
77
                'sosa_rate' => Functions::safeDivision($diffSosaCount, $this->sosa_provider->getTotalIndividuals()),
78
                'pedi_collapse' => 1 - Functions::safeDivision($diffSosaCount, $sosaCount),
79
                'mean_gen_time' => $this->sosa_provider->getMeanGenerationTime()
80
            );
81
            $view_bag->set('general_stats', $general_stats);
82
            
83
            $stats_gen = $this->sosa_provider->getStatisticsByGeneration();
84
            $view_bag->set('missinganc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList@missing&ged='.$wt_tree->getNameUrl().'&gen=');
85
            $view_bag->set('sosaanc_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaList&ged='.$wt_tree->getNameUrl().'&gen=');
86
            
87
            $gen_theoretical=1;
88
            $total_theoretical=0;
89
            $prev_diff=0;
90
            $prev_known=0.5;
91
            $generation_stats = array();
92
            
93
            foreach($stats_gen as $gen => $tab){
94
                $genY1= I18N::translate('-');
95
                $genY2= I18N::translate('-');
96
                if($tab['firstBirth']>0) $genY1=$tab['firstEstimatedBirth'];
97
                if($tab['lastBirth']>0) $genY2=$tab['lastEstimatedBirth'];
98
                $total_theoretical += $gen_theoretical;
99
                $perc_sosa_count_theor = Functions::safeDivision($tab['sosaCount'], $gen_theoretical);
100
                $missing=2*$prev_known - $tab['sosaCount'];
101
                $gen_diff=$tab['diffSosaTotalCount']-$prev_diff;
102
                
103
                $generation_stats[$gen] = array(
104
                    'gen_min_birth' => $genY1,
105
                    'gen_max_birth' => $genY2,
106
                    'theoretical' => $gen_theoretical,
107
                    'known' => $tab['sosaCount'],
108
                    'perc_known' => $perc_sosa_count_theor,
109
                    'missing' => $missing,
110
                    'perc_missing' => 1-Functions::safeDivision($tab['sosaCount'], 2*$prev_known),
111
                    'total_known' => $tab['sosaTotalCount'],
112
                    'perc_total_known' => Functions::safeDivision($tab['sosaTotalCount'], $total_theoretical),
113
                    'different' => $gen_diff,
114
                    'perc_different' => Functions::safeDivision($gen_diff, $tab['sosaCount']),
115
                    'total_different' => $tab['diffSosaTotalCount'],
116
                    'pedi_collapse' => 1 - Functions::safeDivision($tab['diffSosaTotalCount'], $tab['sosaTotalCount'])
117
                );
118
                
119
                $gen_theoretical = $gen_theoretical * 2;
120
                $prev_known=$tab['sosaCount'];
121
                $prev_diff=$tab['diffSosaTotalCount'];
122
            }
123
            
124
            $view_bag->set('generation_stats', $generation_stats);
125
            
126
            $gen_depth_stats = $this->sosa_provider->getGenerationDepthStatsAtGen(1);
127
            $view_bag->set('mean_gen_depth', count($gen_depth_stats) > 0 ? $gen_depth_stats[1]['mean_gen_depth'] : 0);
128
            $view_bag->set('stddev_gen_depth', count($gen_depth_stats) > 0 ? $gen_depth_stats[1]['stddev_gen_depth'] : 0);
129
            
130
            $view_bag->set('top10multiancestors', $this->getTop10Ancestors());
131
            
132
            $view_bag->set('chart_img_g2', $this->htmlAncestorDispersionG2());
133
            $view_bag->set('chart_img_g3', $this->htmlAncestorDispersionG3());
134
            
135
            $view_bag->set('chart_img_gendepth3', $this->htmlAncestorGenDepthG3());
136
            //$view_bag->set('mean_gen_depth_gen3_stats', $this->sosa_provider->getMeanGeneratuonDepthAndDeviationAtGen(3));
137
        }
138
        
139
        ViewFactory::make('SosaStats', $this, $controller, $view_bag)->render();   
140
    }
141
    
142
    /**
143
     * Return an array of the top 10 of ancestor appearing multiple times, grouped by the number of occurrences.
144
     * The key is the number of appearance, and the value contains the list of Inidvidual
145
     * 
146
     * @return array Top 10 ancestors with count
147
     */
148
    private function getTop10Ancestors()
149
    {
150
        $top10multiancestors = $this->sosa_provider->getTopMultiSosaAncestorsNoTies(10);
151
        $top10ancestors = array();
152
        if($top10multiancestors !== null && count($top10multiancestors)) {
153
            foreach($top10multiancestors as $pid => $count) {
154
                $indi = Individual::getInstance($pid, $this->sosa_provider->getTree());
155
                if($indi !== null && $indi->canShowName()) {
156
                    array_key_exists($count, $top10ancestors) ?
157
                        $top10ancestors[$count][] = $indi:
158
                        $top10ancestors[$count] = array($count => $indi);
159
                }
160
            }
161
        }
162
        return $top10ancestors;
163
    }
164
        
165
    /**
166
     * Returns HTML code for a graph showing the dispersion of ancestors across father & mother
167
     * @return string HTML code
168
     */
169
     private function htmlAncestorDispersionG2()
170
    {
171
        $ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(2);
172
        if(count($ancestorsDispGen2) == 0) return;
173
        
174
        $size = '600x300';
175
        
176
        $total = array_sum($ancestorsDispGen2);
177
        $father_count = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
178
        $father = array (
179
            'color' => '84beff', 
180
            'count' => $father_count, 
181
            'perc' => Functions::safeDivision($father_count, $total), 
182
            'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fat')            
183
        );
184
        $mother_count = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
185
        $mother = array (
186
            'color' => 'ffd1dc', 
187
            'count' => $mother_count, 
188
            'perc' => Functions::safeDivision($mother_count, $total),
189
            'name' => \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('mot')
190
        );
191
        $shared_count = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
192
        $shared = array (
193
            'color' => '777777', 
194
            'count' => $shared_count, 
195
            'perc' => Functions::safeDivision($shared_count, $total),
196
            'name' => I18N::translate('Shared')
197
        );
198
        
199
        $chd = $this->arrayToExtendedEncoding(array(4095 * $father['perc'], 4095 * $shared['perc'], 4095 * $mother['perc']));
200
        $chart_title = I18N::translate('Known Sosa ancestors\' dispersion');
201
        $chl = 
202
             $father['name'] . ' - ' . I18N::percentage($father['perc'], 1) . '|' .
203
             $shared['name'] . ' - ' . I18N::percentage($shared['perc'], 1) . '|' .
204
             $mother['name'] . ' - ' . I18N::percentage($mother['perc'], 1);
205
        return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$father['color']},{$shared['color']},{$mother['color']}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
206
    }
207
    
208
    /**
209
     * Returns HTML code for a graph showing the dispersion of ancestors across grand-parents
210
     * @return string HTML code
211
     */
212
    private function htmlAncestorDispersionG3()
213
    {
214
        $ancestorsDispGen2 = $this->sosa_provider->getAncestorDispersionForGen(3);
215
        
216
        $size = '700x300';
217
        
218
        $color_motmot = 'ffd1dc';
219
        $color_motfat = 'b998a0';
220
        $color_fatfat = '577292';
221
        $color_fatmot = '84beff';
222
        $color_shared = '777777';
223
    
224
        $total_fatfat = array_key_exists(1, $ancestorsDispGen2) ? $ancestorsDispGen2[1] : 0;
225
        $total_fatmot = array_key_exists(2, $ancestorsDispGen2) ? $ancestorsDispGen2[2] : 0;
226
        $total_motfat = array_key_exists(4, $ancestorsDispGen2) ? $ancestorsDispGen2[4] : 0;
227
        $total_motmot = array_key_exists(8, $ancestorsDispGen2) ? $ancestorsDispGen2[8] : 0;
228
        $total_sha = array_key_exists(-1, $ancestorsDispGen2) ? $ancestorsDispGen2[-1] : 0;
229
        $total = $total_fatfat + $total_fatmot + $total_motfat+ $total_motmot + $total_sha;
230
    
231
        $chd = $this->arrayToExtendedEncoding(array(
232
	    4095 * Functions::safeDivision($total_fatfat, $total), 
233
            4095 * Functions::safeDivision($total_fatmot, $total),
234
            4095 * Functions::safeDivision($total_sha, $total), 
235
            4095 * Functions::safeDivision($total_motfat, $total),
236
            4095 * Functions::safeDivision($total_motmot, $total)          
237
        ));
238
        $chart_title = I18N::translate('Known Sosa ancestors\' dispersion - G3');
239
        $chl =
240
            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatfat, $total), 1) . '|' .
241
            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('fatmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_fatmot, $total), 1) . '|' .
242
            I18N::translate('Shared') . ' - ' . I18N::percentage(Functions::safeDivision($total_sha, $total), 1) . '|' .
243
            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motfat') . ' - ' . I18N::percentage(Functions::safeDivision($total_motfat, $total), 1) . '|' .
244
            \Fisharebest\Webtrees\Functions\Functions::getRelationshipNameFromPath('motmot') . ' - ' . I18N::percentage(Functions::safeDivision($total_motmot, $total), 1);
245
         return "<img src=\"https://chart.googleapis.com/chart?cht=p&chp=1.5708&amp;chd=e:{$chd}&amp;chs={$size}&amp;chco={$color_fatfat},{$color_fatmot},{$color_shared},{$color_motfat},{$color_motmot}&amp;chf=bg,s,ffffff00&amp;chl={$chl}\" alt=\"" . $chart_title . "\" title=\"" . $chart_title . "\" />";
246
    }    
247
    
248
    /**
249
     * Returns HTML code for a graph showing the grand-parents' mean generation depth and standard deviation
250
     * @return string HTML code
251
     */
252
    private function htmlAncestorGenDepthG3() {
253
        $ancestorsGenDepth3 = $this->sosa_provider->getGenerationDepthStatsAtGen(3);
254
        if(count($ancestorsGenDepth3) == 0) return;
255
        
256
        $ancestors = array();
257
        $chd_mean = array();
258
        $chd_error_low = array();
259
        $chd_error_high = array();
260
        foreach($ancestorsGenDepth3 as $sosa => $genDepthStat) {
261
            $ancestor = Individual::getInstance($genDepthStat['root_ancestor_id'], $this->sosa_provider->getTree());
262
            if($ancestor !== null && $ancestor->canShowName()) {
263
                $tmp = $ancestor->getAllNames();
264
                $ancestors[] = Filter::escapeUrl($tmp[$ancestor->getPrimaryName()]['fullNN']);
265
            }
266
            else {
267
                $ancestors[] = I18N::translate('Sosa %s', I18N::number($sosa));
268
            }
269
            $chd_mean[] = $genDepthStat['mean_gen_depth'];
270
            $chd_error_low[] = $genDepthStat['mean_gen_depth'] - $genDepthStat['stddev_gen_depth'];
271
            $chd_error_high[] = $genDepthStat['mean_gen_depth'] + $genDepthStat['stddev_gen_depth'];
272
        }
273
        
274
        $maxChd = ceil(max($chd_error_high));
275
        $chd = implode(',', $chd_mean) . '|' . implode(',', $chd_error_low) . '|' . implode(',', $chd_error_high);
276
        $chxl = implode('|', array_reverse($ancestors));
277
        $chbh = 30;
278
        $chs = 4 * $chbh + 50;
279
        $chxl_title = I18N::translate('Mean generation depth and standard deviation');
280
        
281
        return "<img src=\"https://chart.googleapis.com/chart?cht=bhs&chco=84beff&chs=600x{$chs}&chbh={$chbh}&chd=t1:{$chd}&chds=0,{$maxChd}&chxt=x,x,y&chxl=1:|{$chxl_title}|2:|{$chxl}&chxp=1,50&chxr=0,0,{$maxChd},1&chm=E,577292,1:2,,2\" />";
282
    }
283
284
    /**
285
     * Convert an array to Google Chart encoding
286
     * @param arrat $a Array to encode
287
     * @return string
288
     */
289
    private function arrayToExtendedEncoding($a) {
290
        $xencoding = WT_GOOGLE_CHART_ENCODING;
291
    
292
        $encoding = '';
293
        foreach ($a as $value) {
294
            if ($value < 0) {
295
                $value = 0;
296
            }
297
            $first  = (int) ($value / 64);
298
            $second = $value % 64;
299
            $encoding .= $xencoding[(int) $first] . $xencoding[(int) $second];
300
        }
301
    
302
        return $encoding;
303
    }
304
    
305
    
306
}