File: bppPopStats.cpp

package info (click to toggle)
bppsuite 2.4.1-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,116 kB
  • sloc: cpp: 3,867; sh: 65; makefile: 5
file content (641 lines) | stat: -rw-r--r-- 30,235 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//
// File: bppPopStats.cpp
// Created by: Julien Dutheil
// Created on: Jun Wed 24 12:04 2015
//

/*
   Copyright or  or Copr. Bio++ Development Team

   This software is a computer program whose purpose is to simulate sequence
   data according to a phylogenetic tree and an evolutionary model.

   This software is governed by the CeCILL  license under French law and
   abiding by the rules of distribution of free software.  You can  use,
   modify and/ or redistribute the software under the terms of the CeCILL
   license as circulated by CEA, CNRS and INRIA at the following URL
   "http://www.cecill.info".

   As a counterpart to the access to the source code and  rights to copy,
   modify and redistribute granted by the license, users are provided only
   with a limited warranty  and the software's author,  the holder of the
   economic rights,  and the successive licensors  have only  limited
   liability.

   In this respect, the user's attention is drawn to the risks associated
   with loading,  using,  modifying and/or developing or reproducing the
   software by the user in light of its specific status of free software,
   that may mean  that it is complicated to manipulate,  and  that  also
   therefore means  that it is reserved for developers  and  experienced
   professionals having in-depth computer knowledge. Users are therefore
   encouraged to load and test the software's suitability as regards their
   requirements in conditions enabling the security of their systems and/or
   data to be ensured and,  more generally, to use and operate it in the
   same conditions as regards security.

   The fact that you are presently reading this means that you have had
   knowledge of the CeCILL license and that you accept its terms.
 */

// From the STL:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <memory>
#include <cmath>

using namespace std;

// From bpp-core:
#include <Bpp/Version.h>
#include <Bpp/App/BppApplication.h>
#include <Bpp/App/ApplicationTools.h>
#include <Bpp/Text/TextTools.h>
#include <Bpp/Text/KeyvalTools.h>

// From bpp-seq:
#include <Bpp/Seq/SiteTools.h>
#include <Bpp/Seq/CodonSiteTools.h>
#include <Bpp/Seq/Alphabet/Alphabet.h>
#include <Bpp/Seq/Alphabet/AlphabetTools.h>
#include <Bpp/Seq/App/SequenceApplicationTools.h>

// From bpp-phyl:
#include <Bpp/Phyl/Tree.h>
#include <Bpp/Phyl/Model/Nucleotide/K80.h>
#include <Bpp/Phyl/Model/Codon/YN98.h>
#include <Bpp/Phyl/Model/RateDistribution/ConstantRateDistribution.h>
#include <Bpp/Phyl/Distance/DistanceEstimation.h>
#include <Bpp/Phyl/Distance/BioNJ.h>
#include <Bpp/Phyl/Likelihood/DRHomogeneousTreeLikelihood.h>
#include <Bpp/Phyl/Likelihood/MarginalAncestralStateReconstruction.h>
#include <Bpp/Phyl/App/PhylogeneticsApplicationTools.h>

// From bpp-popgen
#include <Bpp/PopGen/PolymorphismSequenceContainer.h>
#include <Bpp/PopGen/PolymorphismSequenceContainerTools.h>
#include <Bpp/PopGen/SequenceStatistics.h>

using namespace bpp;

void help()
{
  (*ApplicationTools::message << "__________________________________________________________________________").endLine();
  (*ApplicationTools::message << "bpppopstats parameter1_name=parameter1_value").endLine();
  (*ApplicationTools::message << "      parameter2_name=parameter2_value ... param=option_file").endLine();
  (*ApplicationTools::message).endLine();
  (*ApplicationTools::message << "  Refer to the Bio++ Program Suite Manual for a list of available options.").endLine();
  (*ApplicationTools::message << "__________________________________________________________________________").endLine();
}

int main(int args, char** argv)
{
  cout << "******************************************************************" << endl;
  cout << "*              Bio++ Population Statistics, version " << BPP_VERSION << "        *" << endl;
  cout << "* Author: J. Dutheil                        Last Modif. " << BPP_REL_DATE << " *" << endl;
  cout << "******************************************************************" << endl;
  cout << endl;

  if (args == 1)
  {
    help();
    return 0;
  }

  BppApplication bpppopstats(args, argv, "BppPopStats");
  bpppopstats.startTimer();

  string logFile = ApplicationTools::getAFilePath("logfile", bpppopstats.getParams(), false, false);
  unique_ptr<ofstream> cLog;
  if (logFile != "none")
    cLog.reset(new ofstream(logFile.c_str(), ios::out));

  //This counts instances of each tool, in case one is used several times, for instance with different options:
  map<string, unsigned int> toolCounter;

  try
  {
    // Get alphabet
    Alphabet* alphabet = SequenceApplicationTools::getAlphabet(bpppopstats.getParams(), "", false, true, true);

    // Get the genetic code, if codon alphabet
    unique_ptr<GeneticCode> gCode;
    CodonAlphabet* codonAlphabet = dynamic_cast<CodonAlphabet*>(alphabet);
    if (codonAlphabet) {
      string codeDesc = ApplicationTools::getStringParameter("genetic_code", bpppopstats.getParams(), "Standard", "", true, true);
      ApplicationTools::displayResult("Genetic Code", codeDesc);
      gCode.reset(SequenceApplicationTools::getGeneticCode(codonAlphabet->getNucleicAlphabet(), codeDesc));
    }

    unique_ptr<PolymorphismSequenceContainer> psc;
    if (ApplicationTools::parameterExists("input.sequence.file.ingroup", bpppopstats.getParams())) {
      // Get the ingroup alignment:
      unique_ptr<SiteContainer> sitesIn(SequenceApplicationTools::getSiteContainer(alphabet, bpppopstats.getParams(), ".ingroup", false, true));
      psc.reset(new PolymorphismSequenceContainer(*sitesIn));
      if (ApplicationTools::parameterExists("input.sequence.file.outgroup", bpppopstats.getParams())) {
        // Get the outgroup alignment:
        unique_ptr<SiteContainer> sitesOut(SequenceApplicationTools::getSiteContainer(alphabet, bpppopstats.getParams(), ".outgroup", false, true));
        SequenceContainerTools::append(*psc, *sitesOut);
        for (size_t i = sitesIn->getNumberOfSequences(); i < psc->getNumberOfSequences(); ++i) {
          psc->setAsOutgroupMember(i);
        }
      }
    } else {
      //Everything in one file
      unique_ptr<SiteContainer> sites(SequenceApplicationTools::getSiteContainer(alphabet, bpppopstats.getParams(), "", false, true));
      psc.reset(new PolymorphismSequenceContainer(*sites));
      if (ApplicationTools::parameterExists("input.sequence.outgroup.index", bpppopstats.getParams())) {
        vector<size_t> outgroups = ApplicationTools::getVectorParameter<size_t>("input.sequence.outgroup.index", bpppopstats.getParams(), ',', "");
        for (auto g : outgroups) {
          psc->setAsOutgroupMember(g-1);
        }
      }
      if (ApplicationTools::parameterExists("input.sequence.outgroup.name", bpppopstats.getParams())) {
        vector<string> outgroups = ApplicationTools::getVectorParameter<string>("input.sequence.outgroup.name", bpppopstats.getParams(), ',', "");
        for (auto g : outgroups) {
          ApplicationTools::displayResult("Sequence from outgroup", g);
          psc->setAsOutgroupMember(g);
        }
      }
    }

    // Take care of stop codons:
    string stopCodonOpt = ApplicationTools::getStringParameter("input.sequence.stop_codons_policy", bpppopstats.getParams(), "Keep", "", true, true);
    ApplicationTools::displayResult("Stop codons policy", stopCodonOpt);

    if (stopCodonOpt == "Keep") {
      //do nothing
    } else if (stopCodonOpt == "RemoveIfLast") {
      if (CodonSiteTools::hasStop(psc->getSite(psc->getNumberOfSites() - 1), *gCode)) {
        psc->deleteSite(psc->getNumberOfSites() - 1);
        ApplicationTools::displayMessage("Info: last site contained a stop codon and was discarded.");
        if (logFile != "none")
          *cLog << "# Info: last site contained a stop codon and was discarded." << endl;
      }
    } else if (stopCodonOpt == "RemoveAll") {
      size_t l1 = psc->getNumberOfSites();
      SiteContainerTools::removeStopCodonSites(*psc, *gCode);
      size_t l2 = psc->getNumberOfSites();
      if (l2 != l1) {
        ApplicationTools::displayMessage("Info: discarded " + TextTools::toString(l1 - l2) + " sites with stop codons.");
        if (logFile != "none")
          *cLog << "# Info: discarded " << (l1 - l2) << " sites with stop codons." << endl;
      }
    } else {
      throw Exception("Unrecognized option for input.sequence.stop_codons_policy: " + stopCodonOpt);
    }

    shared_ptr<PolymorphismSequenceContainer> pscIn;
    shared_ptr<PolymorphismSequenceContainer> pscOut;

    if (psc->hasOutgroup()) {
      pscIn.reset(PolymorphismSequenceContainerTools::extractIngroup(*psc));
      pscOut.reset(PolymorphismSequenceContainerTools::extractOutgroup(*psc));
    } else {
      pscIn = std::move(psc);
    }
    ApplicationTools::displayResult("Number of sequences in ingroup", pscIn->getNumberOfSequences());
    ApplicationTools::displayResult("Number of sequences in outgroup", pscOut.get() ? pscOut->getNumberOfSequences() : 0);
   
    // Shall we estimate some parameters first?
    
    bool estimateTsTv = ApplicationTools::getBooleanParameter("estimate.kappa", bpppopstats.getParams(), false, "", false, 1);
    double kappa = 1;
    double omega = -1;
    
    bool estimateAncestor = ApplicationTools::getBooleanParameter("estimate.ancestor", bpppopstats.getParams(), false, "", false, 1);
    if (estimateAncestor & ! pscOut)
      throw Exception("Error: an outgroup sequence is needed for estimating ancestral states.");

    bool fitModel = estimateTsTv || estimateAncestor;

    // Fit a model for later use:
    unique_ptr<Tree> tree;
    unique_ptr<SubstitutionModel> model;
    unique_ptr<DiscreteDistribution> rDist;
    DRTreeLikelihood* treeLik = nullptr;
    unique_ptr<Sequence> ancestralSequence;
    if (fitModel) {
      // Get the alignment:
      bool sampleIngroup = ApplicationTools::getBooleanParameter("estimate.sample_ingroup", bpppopstats.getParams(), true);
      size_t sampleIngroupSize = 0;
      if (sampleIngroup) {
        sampleIngroupSize = ApplicationTools::getParameter<size_t>("estimate.sample_ingroup.size", bpppopstats.getParams(), 10);
        if (sampleIngroupSize > pscIn->getNumberOfSequences()) {
          ApplicationTools::displayWarning("Sample size higher than number of sequence. No sampling performed.");
          sampleIngroup = false;
        }
      }
      unique_ptr<AlignedSequenceContainer> aln;
      if (sampleIngroup) {
        ApplicationTools::displayResult("Nb of ingroup sequences for model fitting", sampleIngroupSize);
        aln.reset(new AlignedSequenceContainer(pscIn->getAlphabet()));
        vector<string> selection(sampleIngroupSize);
        RandomTools::getSample(pscIn->getSequencesNames(), selection, false); 
        SequenceContainerTools::getSelectedSequences(*pscIn, selection ,*aln);
      } else {
        aln.reset(new AlignedSequenceContainer(*pscIn));
      }
      if (pscOut) {
        aln->addSequence(pscOut->getSequence(0)); //As for now, we only consider one sequence as outgroup, the first one.
      }

      // Get a tree:
      string treeOpt = ApplicationTools::getStringParameter("input.tree.method", bpppopstats.getParams(), "bionj", "");
      if (codonAlphabet) {
        unique_ptr<FrequenciesSet> freqSet(new FixedCodonFrequenciesSet(gCode.get()));
        model.reset(new YN98(gCode.get(), freqSet.release()));
      } else {
        model.reset(new K80(&AlphabetTools::DNA_ALPHABET));
      } //Note: proteins not supported!
      rDist.reset(new ConstantRateDistribution()); 
      if (treeOpt == "user") {
        tree.reset(PhylogeneticsApplicationTools::getTree(bpppopstats.getParams()));
      } else if (treeOpt == "bionj") {
        ApplicationTools::displayTask("Estimating distance matrix", true);
        //DistanceEstimation distEstimation(model->clone(), rDist->clone(), aln.get(), 1, false);
        //distEstimation.computeMatrix();
        //unique_ptr<DistanceMatrix> matrix(distEstimation.getMatrix());
        unique_ptr<DistanceMatrix> matrix(SiteContainerTools::computeSimilarityMatrix(*aln, true, SiteContainerTools::SIMILARITY_NOGAP, true));
        
        ApplicationTools::displayTaskDone();
        ApplicationTools::displayTask("Computing BioNJ tree", true);
        BioNJ bionj(false, true);
        bionj.setDistanceMatrix(*matrix);
        bionj.computeTree();
        ApplicationTools::displayTaskDone();
        tree.reset(bionj.getTree());
      } else {
        throw Exception("Invalid input.tree.method. Should be either 'user' or 'bionj'.");
      }

      // Create a likelihood object:
      treeLik = new DRHomogeneousTreeLikelihood(*tree, *aln, model.get(), rDist.get());
      treeLik->initialize();
      if (std::isinf(treeLik->getValue()))
        throw Exception("Error: null likelihood. Possible cause: stop codon or numerical underflow (too many sequences).");
      // Optimize parameters:
      treeLik = dynamic_cast<DRTreeLikelihood*>(PhylogeneticsApplicationTools::optimizeParameters(treeLik, treeLik->getParameters(), bpppopstats.getParams(), "", true, true, 2));

      // Get kappa:              
      if (estimateTsTv) {
        kappa = model->getParameter("kappa").getValue();
        ApplicationTools::displayResult("Transition / transversions ratio", kappa);
      }
      if (estimateAncestor) {
        MarginalAncestralStateReconstruction asr(treeLik);
        int outgroupId = tree->getLeafId(pscOut->getSequence(0).getName());
        ancestralSequence.reset(asr.getAncestralSequenceForNode(tree->getFatherId(outgroupId)));
      }
      if (codonAlphabet) {
        omega = model->getParameter("omega").getValue();
      }
    }
    if (treeLik)
      delete treeLik; //Not needed anymore.

    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    
    // Compute statistics
    vector<string> actions = ApplicationTools::getVectorParameter<string>("pop.stats", bpppopstats.getParams(), ',', "", "", false, 1);

    for (size_t a = 0; a < actions.size(); a++)
    {
      string cmdName;
      map<string, string> cmdArgs;
      KeyvalTools::parseProcedure(actions[a], cmdName, cmdArgs);
      toolCounter[cmdName]++;

      // +-------------------+
      // | Frequencies       |
      // +-------------------+
      if (cmdName == "SiteFrequencies")
      {
        unsigned int s = SequenceStatistics::numberOfPolymorphicSites(*pscIn);
        ApplicationTools::displayResult("Number of segregating sites:", s);
        unsigned int nsg = SequenceStatistics::numberOfSingletons(*pscIn);
        ApplicationTools::displayResult("Number of singletons:", nsg);
        //Print to logfile:
        if (logFile != "none") {
          *cLog << "# Site frequencies" << endl;
          *cLog << "NbSegSites" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << s << endl;
          *cLog << "NbSingl" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << nsg << endl;
        }
      }

      // +-------------------+
      // | Watterson's theta |
      // +-------------------+
      else if (cmdName == "Watterson75")
      {
        double thetaW75 = SequenceStatistics::watterson75(*pscIn, true, true, true);
        ApplicationTools::displayResult("Watterson's (1975) theta:", thetaW75);
        //Print to logfile:
        if (logFile != "none") {
          *cLog << "# Watterson's (1975) theta" << endl;
          *cLog << "thetaW75" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << thetaW75 << endl;
        }
      }

      // +-------------+
      // | Tajima's pi |
      // +-------------+
      else if (cmdName == "Tajima83")
      {
        double piT83 = SequenceStatistics::tajima83(*pscIn, true, true, true);
        ApplicationTools::displayResult("Tajima's (1983) pi:", piT83);
        //Print to logfile:
        if (logFile != "none") {
          *cLog << "# Tajima's (1983) pi" << endl;
          *cLog << "piT83" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << piT83 << endl;
        }
      }

      // +------------+
      // | Tajima's D |
      // +------------+
      else if (cmdName == "TajimaD")
      {
        string positions = ApplicationTools::getStringParameter("positions", cmdArgs, "all", "", false, 1);
        shared_ptr<PolymorphismSequenceContainer> pscTmp;
        if ((positions == "synonymous" || positions == "non-synonymous") && !codonAlphabet)
          throw Exception("Error: synonymous and non-synonymous positions can only be defined with a codon alphabet.");
        if (positions == "synonymous") {
          pscTmp.reset(PolymorphismSequenceContainerTools::getSynonymousSites(*pscIn, *gCode));
        } else if (positions == "non-synonymous") {
          pscTmp.reset(PolymorphismSequenceContainerTools::getNonSynonymousSites(*pscIn, *gCode));
        } else if (positions == "all") {
          pscTmp = pscIn;
        } else throw Exception("Unrecognized option for argument 'positions': " + positions);

        if (SequenceStatistics::numberOfPolymorphicSites(*pscTmp) > 0) {
          double tajimaD = SequenceStatistics::tajimaDss(*pscTmp, true, true);
          ApplicationTools::displayResult("Tajima's (1989) D:", tajimaD);
          //Print to logfile:
          if (logFile != "none") {
            *cLog << "# Tajima's (1989) D (" << positions << " sites)" << endl;
            *cLog << "tajD" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << tajimaD << endl;
          }
        } else {
          ApplicationTools::displayResult<string>("Tajima's (1989) D:", "NA (0 polymorphic sites)");
          if (logFile != "none") {
            *cLog << "# Tajima's (1989) D (" << positions << " sites)" << endl;
            *cLog << "tajD" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = NA" << endl;
          }
          
        }
      }

      // +-----------+
      // | FuAndLiD* |
      // +-----------+
      else if (cmdName == "FuAndLiDStar")
      {
        bool useTotMut = ApplicationTools::getBooleanParameter("tot_mut", cmdArgs, true, "", false, 1);
        double flDstar = SequenceStatistics::fuLiDStar(*pscIn, !useTotMut);
        ApplicationTools::displayResult("Fu and Li's (1993) D*:", flDstar);
        ApplicationTools::displayResult("  computed using", (useTotMut ? "total number of mutations" : "number of segregating sites"));
        //Print to logfile:
        if (logFile != "none") {
          *cLog << "# Fu and Li's (1993) D*" << endl;
          if (useTotMut)
            *cLog << "fuLiDstarTotMut" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << flDstar << endl;
          else
            *cLog << "fuLiDstarSegSit" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << flDstar << endl;
        }
      }

      // +-----------+
      // | FuAndLiF* |
      // +-----------+
      else if (cmdName == "FuAndLiFStar")
      {
        bool useTotMut = ApplicationTools::getBooleanParameter("tot_mut", cmdArgs, true, "", false, 1);
        double flFstar = SequenceStatistics::fuLiFStar(*pscIn, !useTotMut);
        ApplicationTools::displayResult("Fu and Li (1993)'s F*:", flFstar);
        ApplicationTools::displayResult("  computed using", (useTotMut ? "total number of mutations" : "number of segregating sites"));
        //Print to logfile:
        if (logFile != "none") {
          *cLog << "# Fu and Li's (1993) F*" << endl;
          if (useTotMut)
            *cLog << "fuLiFstarTotMut" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << flFstar << endl;
          else
            *cLog << "fuLiFstarSegSit" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << flFstar << endl;
        }
      }
      // +-----------+
      // | PiN / PiS |
      // +-----------+
      else if (cmdName == "PiN_PiS")
      {
        if (!codonAlphabet) {
          throw Exception("PiN_PiS can only be used with a codon alignment. Check the input alphabet!");
        }
        double piS = SequenceStatistics::piSynonymous(*pscIn, *gCode);
        double piN = SequenceStatistics::piNonSynonymous(*pscIn, *gCode);
        double nbS = SequenceStatistics::meanNumberOfSynonymousSites(*pscIn, *gCode, kappa);
        double nbN = SequenceStatistics::meanNumberOfNonSynonymousSites(*pscIn, *gCode, kappa);
        double r = (piN / nbN) / (piS / nbS);
        ApplicationTools::displayResult("PiN:", piN);
        ApplicationTools::displayResult("PiS:", piS);
        ApplicationTools::displayResult("#N:", nbN);
        ApplicationTools::displayResult("#S:", nbS);
        ApplicationTools::displayResult("PiN / PiS (corrected for #N and #S):", r);
        if (fitModel) {
          ApplicationTools::displayResult("Omega (YN98 model):", omega);
        }

        if (logFile != "none") {
          *cLog << "# PiN and PiS" << endl;
          *cLog << "PiN" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << piN << endl;
          *cLog << "PiS" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << piS << endl;
          *cLog << "NbN" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << nbN << endl;
          *cLog << "NbS" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << nbS << endl;
          if (fitModel) {
            *cLog << "Omega" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << omega << endl;
          }
        }
      }

      // +---------+
      // | dN / dS |
      // +---------+
      else if (cmdName == "dN_dS")
      {
        if (!codonAlphabet) {
          throw Exception("dN_dS can only be used with a codon alignment. Check the input alphabet!");
        }
        //Get consensus sequences:
        unique_ptr<SiteContainer> alnIn(pscIn->toSiteContainer());
        unique_ptr<SiteContainer> alnOut(pscOut->toSiteContainer());
        unique_ptr<Sequence> consensusIn(SiteContainerTools::getConsensus(*alnIn, "consIn", true, false));
        unique_ptr<Sequence> consensusOut(SiteContainerTools::getConsensus(*alnOut, "consOut", true, false));
        unique_ptr<AlignedSequenceContainer> alnCons(new AlignedSequenceContainer(codonAlphabet));
        alnCons->addSequence(*consensusIn);
        alnCons->addSequence(*consensusOut);
        unique_ptr<FrequenciesSet> freqSetDiv(new FixedCodonFrequenciesSet(gCode.get()));
        YN98* modelDiv = new YN98(gCode.get(), freqSetDiv.release());
        DiscreteDistribution* rDistDiv = new ConstantRateDistribution(); 
        DistanceEstimation distEstimation(modelDiv, rDistDiv, alnCons.get(), 0, false);
        distEstimation.setAdditionalParameters(modelDiv->getIndependentParameters());
        distEstimation.computeMatrix();
        unique_ptr<DistanceMatrix> matrix(distEstimation.getMatrix());
        ApplicationTools::displayResult("Yang and Nielsen's Omega (dN/dS):", modelDiv->getParameter("omega").getValue());
        ApplicationTools::displayResult("Yang and Nielsen's Kappa:", modelDiv->getParameter("kappa").getValue());
        ApplicationTools::displayResult("Yang and Nielsen's Distance:", (*matrix)(1,0));
        if (logFile != "none") {
          *cLog << "# dN and dS (Yang and Nielsen's 1998 substitution model)" << endl;
          *cLog << "OmegaDiv" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << modelDiv->getParameter("omega").getValue() << endl;
          *cLog << "KappaDiv" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << modelDiv->getParameter("kappa").getValue() << endl;
          *cLog << "DistanceDiv" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << (*matrix)(1,0) << endl;
        }
      }

      // +---------+
      // | MK test |
      // +---------+
      else if (cmdName == "MKT")
      {
        if (!codonAlphabet) {
          throw Exception("MacDonald-Kreitman test can only be performed on a codon alignment. Check the input alphabet!");
        }
        if (!pscOut) {
          throw Exception("MacDonald-Kreitman test requires at least one outgroup sequence.");
        }
        vector<unsigned int> mktable = SequenceStatistics::mkTable(*pscIn, *pscOut, *gCode);
        ApplicationTools::displayResult("MK table, Pa:", mktable[0]);
        ApplicationTools::displayResult("MK table, Ps:", mktable[1]);
        ApplicationTools::displayResult("MK table, Da:", mktable[2]);
        ApplicationTools::displayResult("MK table, Ds:", mktable[3]);
        if (logFile != "none") {
          *cLog << "# MK table" << endl;
          *cLog << "# Pa Ps Da Ds" << endl;
          *cLog << "MKtable" << (toolCounter[cmdName] > 1 ? TextTools::toString(toolCounter[cmdName]) : "") << " = " << mktable[0] << " " << mktable[1] << " " << mktable[2] << " " << mktable[3] << endl;
        }
      }

      // +-----------------------+
      // | Codon site statistics |
      // +-----------------------+
      else if (cmdName == "CodonSiteStatistics")
      {
        if (!codonAlphabet) {
          throw Exception("CodonSiteStatstics can only be used with a codon alignment. Check the input alphabet!");
        }
        string path = ApplicationTools::getAFilePath("output.file", cmdArgs, true, false);
        if (path == "none") throw Exception("You must specify an output file for CodonSiteStatistics"); 
        ApplicationTools::displayResult("Site statistics output to:", path);
        ofstream out(path.c_str(), ios::out);
        out << "Site\tMissingDataFrequency\tNbAlleles\tMinorAlleleFrequency\tMajorAlleleFrequency\tMinorAllele\tMajorAllele";
        out << "\tMeanNumberSynPos\tIsSynPoly\tIs4Degenerated\tPiN\tPiS";
        bool outgroup = (pscOut && pscOut->getNumberOfSequences() == 1);
        if (outgroup) {
          out << "\tOutgroupAllele";
        }
        if (estimateAncestor) {
          out << "\tAncestralAllele";
        }
        if (outgroup) {
          out << "\tMeanNumberSynPosDiv\tdN\tdS";
        }
        out << endl;

        unique_ptr<SiteContainer> sites(pscIn->toSiteContainer());
        for (size_t i = 0; i < sites->getNumberOfSites(); ++i) {
          const Site& site = sites->getSite(i);
          map<int, size_t> counts;
          SymbolListTools::getCounts(site, counts);
          size_t minFreq = site.size() + 1;
          size_t maxFreq = 0;
          int minState = -1;
          int maxState = -1;
          size_t nbAlleles = 0;
          size_t nbMissing = 0;
          for (map<int, size_t>::iterator it = counts.begin(); it != counts.end(); it++)
          {
            if (!alphabet->isUnresolved(it->first)
              && !alphabet->isGap(it->first)) {
              nbAlleles++; 
              if (it->second != 0) {
                if (it->second < minFreq) {
                  minFreq = it->second;
                  minState = it->first;        
                }
                if (it->second > maxFreq) {
                  maxFreq = it->second;
                  maxState = it->first;
                }
              }
            } else {
              nbMissing += it->second;            
            }
          }
          
          out << site.getPosition() << "\t";
          out << nbMissing << "\t";
          out << nbAlleles << "\t";
          out << minFreq << "\t";
          out << maxFreq << "\t";
          out << alphabet->intToChar(minState) << "\t";
          out << alphabet->intToChar(maxState) << "\t";
          if (estimateAncestor) {
            out << CodonSiteTools::numberOfSynonymousPositions(ancestralSequence->getValue(i), *gCode, kappa) << "\t";
          } else {
            out << CodonSiteTools::meanNumberOfSynonymousPositions(site, *gCode, kappa) << "\t";
          }
          out << CodonSiteTools::isSynonymousPolymorphic(site, *gCode) << "\t";
          out << CodonSiteTools::isFourFoldDegenerated(site, *gCode) << "\t";
          out << CodonSiteTools::piNonSynonymous(site, *gCode) << "\t";
          out << CodonSiteTools::piSynonymous(site, *gCode);
          if (outgroup) {
           out << "\t" << pscOut->getSequence(0).getChar(i); 
          }
          if (estimateAncestor) {
           out << "\t" << ancestralSequence->getChar(i); 
          }
          if (outgroup) {
            //Add divergence
            int outgroupState = pscOut->getSequence(0)[i];
            if (codonAlphabet->isUnresolved(outgroupState) || codonAlphabet->isGap(outgroupState)) {
              out << "\tNA\tNA\tNA";
            } else {
              //Average over outgroup (Note: minState and maxState are identical in this case)
              out << "\t" << (CodonSiteTools::numberOfSynonymousPositions(outgroupState, *gCode, kappa) +
                                     CodonSiteTools::numberOfSynonymousPositions(minState, *gCode, kappa)) / 2.;
              if (nbAlleles == 1) {
                //Compare with outgroup:
                if (site[0] == outgroupState) {
                  out << "\t0\t0";
                } else {
                  //This is a real substitution:
                  double nt = static_cast<double>(CodonSiteTools::numberOfDifferences(outgroupState, minState, *codonAlphabet));
                  double ns = CodonSiteTools::numberOfSynonymousDifferences(outgroupState, minState, *gCode); 
                  out << "\t" << (nt - ns) << "\t" << ns;
                }
              } else {
                //Site is polymorphic, this is not a substitution    
                out << "\t0\t0";
              }
            }
          }
          out << endl;
        }
      }
      
      else throw Exception("Unknown operation " + cmdName + ".");
    }
 
    // We're done!
    bpppopstats.done();
  }
  catch (exception& e)
  {
    if (logFile != "none")
      *cLog << "# Error: " << e.what() << endl;
    cout << e.what() << endl;
    return 1;
  }

  return 0;
}