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 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
|
// Copyright (C) 2007-2008 Mark T. Holder
//
// This file is part of NCL (Nexus Class Library).
//
// NCL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// NCL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with NCL; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
/*******************************************************************************
* This file contains code for 4 executables:
* NEXUSnormalizer, NEXUSvalidator, NEXUSinspector, and NEX_us2ml
* with conditional compilation used to determine the behavior.
*
* * NEXUSnormalizer - writes a NEXUS version of the file with consistent
* ordering of blocks and commands. Ideally 2 equivalent files will
* produce the same normalized output. This version of tthe program is
* less ambitious. The goal is to be able to run (for any valid NEXUS
* in.nex file):
* $ NEXUSnormalizer in.nex > outOrig.nex
* $ NEXUSnormalizer outOrig.nex > outSecond.nex
* $ diff outOrig.nex outSecond.nex
* and find no differences.
* * NEXUSvalidator - reports errors and warnings to stderr. Invalid files
* cause exit with a non-zero return code
* * NEXUSinspector - writes a brief report of every block parsed
* * NEXUS_us2ml - writes a nexml version of the input (partially
* implemented, note that the code to write nexml is in us2ml.cpp).
* See the processFilepath() function for an example of how to deal with NCL
* to read a file using the new MultiFormatReader class. When the file
* is correctly read, the processContent() function is called.
*
* All other code has to do with reading command line arguments and other
* user-interface concerns.
*/
#include "ncl/ncl.h"
#include "ncl/nxsblock.h"
#include "ncl/nxspublicblocks.h"
#include "ncl/nxsmultiformat.h"
#include <cassert>
using namespace std;
//#include "ncl/nxscxxdiscretematrix.h"
#if defined(TO_NEXML_CONVERTER) && TO_NEXML_CONVERTER
void writeAsNexml(PublicNexusReader & nexusReader, ostream & os);
#endif
bool gQuietMode = false;
std::ofstream gCommonFileStream;
std::ostream * gCommonOstream = 0L;
#if defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
enum ExportFormatEnum
{
NEXUS_EXPORT_FORMAT,
PHYLIP_EXPORT_FORMAT,
RELAXED_PHYLIP_EXPORT_FORMAT,
FASTA_EXPORT_FORMAT,
NEXML_EXPORT_FORMAT,
UNSUPPORTED_EXPORT_FORMAT
};
ExportFormatEnum gExportFormat = NEXML_EXPORT_FORMAT;
std::string gExportPrefix("out");
ExportFormatEnum readExportFormatName(const std::string &);
void exportData(PublicNexusReader & nexusReader, MultiFormatReader::DataFormatType f, long interleavLen, std::string prefix, std::ostream *);
ExportFormatEnum readExportFormatName(const std::string & s)
{
const char * gExportFormatNames[] = { "nexus",
"phylip",
"relaxedphylip",
"fasta",
"nexml"
};
const unsigned gNumExportFormats = 5;
NxsString l(s.c_str());
NxsString::to_lower(l);
int ind = NxsString::index_in_array(l, gExportFormatNames, gNumExportFormats);
if (ind < 0)
return UNSUPPORTED_EXPORT_FORMAT;
return ExportFormatEnum(ind);
}
std::string gNEXUSSafeNamesToWrite;
std::string gNEXUSSafeNamesToRead;
bool gProduceEvenTrivalTranslation = false;
void reverseTranslateNames(PublicNexusReader & reader, std::string filepath);
void substituteSafeTaxaLabels(PublicNexusReader & reader, std::string filepath, bool evenTrivial);
#endif // if defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
bool gAltNexus = false;
void writeAsNexus(PublicNexusReader & nexusReader, ostream & os);
long gStrictLevel = 2;
bool gUnderscoresToSpaces = false;
bool gValidateInternals = true;
bool gTreesViaInMemoryStruct = true;
long gInterleaveLen = -1;
bool blocksReadInValidation = false;
bool gSuppressingNameTranslationFile = false;
bool gAllowNumericInterpretationOfTaxLabels = true;
enum ProcessActionsEnum
{
REPORT_BLOCKS,
OUTPUT_NORMALIZED_NEXUS,
OUTPUT_ANY_FORMAT,
OUTPUT_NEXML,
VALIDATE_ONLY
};
void processContent(PublicNexusReader & nexusReader, ostream *os, ProcessActionsEnum currentAction);
MultiFormatReader * instantiateReader();
# if defined(MULTIFILE_NEXUS_READER) && MULTIFILE_NEXUS_READER
MultiFormatReader * gNexusReader = NULL;
# endif
void reportNexusStats(const PublicNexusReader & nexusReader, ostream *os)
{
if (!os)
return;
const unsigned nTaxaBlocks = nexusReader.GetNumTaxaBlocks();
*os << nTaxaBlocks << " taxa block(s) read.\n";
for (unsigned t = 0; t < nTaxaBlocks; ++t)
{
NxsTaxaBlock * tb = nexusReader.GetTaxaBlock(t);
*os << "Taxa block #" << t + 1 << ".\n";
tb->Report(*os);
const unsigned nCharBlocks = nexusReader.GetNumCharactersBlocks(tb);
*os << nCharBlocks << " Characters/Data block(s) read that link to this Taxa block.\n";
for (unsigned i = 0; i < nCharBlocks; ++i)
{
NxsCharactersBlock * cb = nexusReader.GetCharactersBlock(tb, i);
//NxsCXXDiscreteMatrix mat(*cb, true);
*os << "Character block #" << i + 1 << " for this Taxa block.\n";
cb->Report(*os);
const unsigned nAssumpBlocks = nexusReader.GetNumAssumptionsBlocks(cb);
*os << nAssumpBlocks << " Assumptions block(s) read that link to this Characters block.\n";
for (unsigned j= 0; j < nAssumpBlocks; ++j)
{
NxsAssumptionsBlock * ab = nexusReader.GetAssumptionsBlock(cb, j);
*os << "Assumptions block #" << j + 1 << " for this Characters block.\n";
ab->Report(*os);
}
}
const unsigned nTreesBlocks = nexusReader.GetNumTreesBlocks(tb);
*os << nTreesBlocks << " Trees/Data block(s) read that link to this Taxa block.\n";
for (unsigned i = 0; i < nTreesBlocks; ++i)
{
NxsTreesBlock * cb = nexusReader.GetTreesBlock(tb, i);
*os << "Trees block #" << i + 1 << " for this Taxa block.\n";
cb->Report(*os);
const unsigned nAssumpBlocks = nexusReader.GetNumAssumptionsBlocks(cb);
*os << nAssumpBlocks << " Assumptions block(s) read that link to this Trees block.\n";
for (unsigned j= 0; j < nAssumpBlocks; ++j)
{
NxsAssumptionsBlock * ab = nexusReader.GetAssumptionsBlock(cb, j);
*os << "Assumptions block #" << j + 1 << " for this Trees block.\n";
ab->Report(*os);
}
}
const unsigned nAssumpBlocks = nexusReader.GetNumAssumptionsBlocks(tb);
*os << nAssumpBlocks << " Assumptions block(s) read that link to this Taxa block.\n";
for (unsigned j= 0; j < nAssumpBlocks; ++j)
{
NxsAssumptionsBlock * ab = nexusReader.GetAssumptionsBlock(tb, j);
*os << "Assumptions block #" << j + 1 << " for this Taxa block.\n";
ab->Report(*os);
}
const unsigned nDistancesBlocks = nexusReader.GetNumDistancesBlocks(tb);
*os << nDistancesBlocks << " Distances block(s) read that link to this Taxa block.\n";
for (unsigned j= 0; j < nDistancesBlocks; ++j)
{
NxsDistancesBlock * ab = nexusReader.GetDistancesBlock(tb, j);
*os << "Distances block #" << j + 1 << " for this Taxa block.\n";
ab->Report(*os);
}
const unsigned nUnalignedBlocks = nexusReader.GetNumUnalignedBlocks(tb);
*os << nUnalignedBlocks << " Unaligned block(s) read that link to this Taxa block.\n";
for (unsigned j= 0; j < nUnalignedBlocks; ++j)
{
NxsUnalignedBlock * ab = nexusReader.GetUnalignedBlock(tb, j);
*os << "Unaligned block #" << j + 1 << " for this Taxa block.\n";
ab->Report(*os);
}
*os << "\n\n";
}
const unsigned nUnknown = nexusReader.GetNumUnknownBlocks();
*os << nUnknown << " private block(s) read.\n";
for (unsigned t = 0; t < nUnknown; ++t)
{
NxsStoreTokensBlockReader * ub = nexusReader.GetUnknownBlock(t);
*os << "Private block #" << t + 1 << " is a " << ub->GetID() << " block.\n";
}
}
void writeAsNexus(PublicNexusReader & nexusReader, ostream & os)
{
BlockReaderList blocks = nexusReader.GetUsedBlocksInOrder();
os << "#NEXUS\n";
for (BlockReaderList::const_iterator bIt = blocks.begin(); bIt != blocks.end(); ++bIt)
{
NxsBlock * b = *bIt;
if (b)
b->WriteAsNexus(os);
}
}
////////////////////////////////////////////////////////////////////////////////
// Takes NxsReader that has successfully read a file, and processes the
// information stored in the reader.
//
// The caller is responsibel for calling DeleteBlocksFromFactories() to clean
// up (if the reader uses the factory API).
////////////////////////////////////////////////////////////////////////////////
void processContent(PublicNexusReader & nexusReader, ostream *os, ProcessActionsEnum currentAction)
{
BlockReaderList blocks = nexusReader.GetUsedBlocksInOrder();
if (currentAction == REPORT_BLOCKS)
reportNexusStats(nexusReader, os);
else if (OUTPUT_NORMALIZED_NEXUS == currentAction && os)
{
writeAsNexus(nexusReader, *os);
}
else if (OUTPUT_NEXML == currentAction && os)
{
# if defined(TO_NEXML_CONVERTER) && TO_NEXML_CONVERTER
writeAsNexml(nexusReader, *os);
# else
cerr << "Error nexml conversion not implemented\n";
exit(1);
# endif
}
else if (OUTPUT_ANY_FORMAT == currentAction && os)
{
# if defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
if (!gNEXUSSafeNamesToRead.empty()) {
reverseTranslateNames(nexusReader, gNEXUSSafeNamesToRead);
}
else if (!gNEXUSSafeNamesToWrite.empty()) {
substituteSafeTaxaLabels(nexusReader, gNEXUSSafeNamesToWrite, gProduceEvenTrivalTranslation);
}
std::string fullExportPrefix;
MultiFormatReader::DataFormatType f = MultiFormatReader::NEXUS_FORMAT;
if (gExportFormat == NEXUS_EXPORT_FORMAT)
exportData(nexusReader, MultiFormatReader::NEXUS_FORMAT, gInterleaveLen, gExportPrefix, gCommonOstream);
else if (gExportFormat == NEXML_EXPORT_FORMAT)
exportData(nexusReader, MultiFormatReader::NEXML_FORMAT, gInterleaveLen, gExportPrefix, gCommonOstream);
else if (gExportFormat == PHYLIP_EXPORT_FORMAT) {
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".dna");
f = (gInterleaveLen < 0 ? MultiFormatReader::PHYLIP_DNA_FORMAT : MultiFormatReader::INTERLEAVED_PHYLIP_DNA_FORMAT);
exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".rna");
f = (gInterleaveLen < 0 ? MultiFormatReader::PHYLIP_RNA_FORMAT : MultiFormatReader::INTERLEAVED_PHYLIP_RNA_FORMAT);
exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".aa");
f = (gInterleaveLen < 0 ? MultiFormatReader::PHYLIP_AA_FORMAT : MultiFormatReader::INTERLEAVED_PHYLIP_AA_FORMAT);
exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
//fullExportPrefix = gExportPrefix;
//fullExportPrefix.append(".discrete");
//f = (gInterleaveLen < 0 ? MultiFormatReader::PHYLIP_DISC_FORMAT : MultiFormatReader::INTERLEAVED_PHYLIP_DISC_FORMAT);
//exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
exportData(nexusReader, MultiFormatReader::PHYLIP_TREE_FORMAT, gInterleaveLen, fullExportPrefix, gCommonOstream);
}
else if (gExportFormat == RELAXED_PHYLIP_EXPORT_FORMAT) {
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".dna");
f = (gInterleaveLen < 0 ? MultiFormatReader::RELAXED_PHYLIP_DNA_FORMAT : MultiFormatReader::INTERLEAVED_RELAXED_PHYLIP_DNA_FORMAT);
exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".rna");
f = (gInterleaveLen < 0 ? MultiFormatReader::RELAXED_PHYLIP_RNA_FORMAT : MultiFormatReader::INTERLEAVED_RELAXED_PHYLIP_RNA_FORMAT);
exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".aa");
f = (gInterleaveLen < 0 ? MultiFormatReader::RELAXED_PHYLIP_AA_FORMAT : MultiFormatReader::INTERLEAVED_RELAXED_PHYLIP_AA_FORMAT);
exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
//fullExportPrefix = gExportPrefix;
//fullExportPrefix.append(".discrete");
//f = (gInterleaveLen < 0 ? MultiFormatReader::RELAXED_PHYLIP_DISC_FORMAT : MultiFormatReader::INTERLEAVED_RELAXED_PHYLIP_DISC_FORMAT);
//exportData(nexusReader, f, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
exportData(nexusReader, MultiFormatReader::RELAXED_PHYLIP_TREE_FORMAT, gInterleaveLen, fullExportPrefix, gCommonOstream);
}
else if (gExportFormat == FASTA_EXPORT_FORMAT) {
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".dna");
exportData(nexusReader, MultiFormatReader::FASTA_DNA_FORMAT, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".rna");
exportData(nexusReader, MultiFormatReader::FASTA_RNA_FORMAT, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
fullExportPrefix.append(".aa");
exportData(nexusReader, MultiFormatReader::FASTA_AA_FORMAT, gInterleaveLen, fullExportPrefix, gCommonOstream);
fullExportPrefix = gExportPrefix;
exportData(nexusReader, MultiFormatReader::RELAXED_PHYLIP_TREE_FORMAT, gInterleaveLen, fullExportPrefix, gCommonOstream);
}
else {
cerr << "Unsupported export format requested.\n";
exit(1);
}
# else
cerr << "Exporting to any format is implemented by this executable.\n";
exit(1);
# endif
}
else if (VALIDATE_ONLY == currentAction)
{
if (!blocks.empty())
blocksReadInValidation = true;
}
}
MultiFormatReader * instantiateReader()
{
MultiFormatReader * nexusReader = new MultiFormatReader(-1, NxsReader::WARNINGS_TO_STDERR);
if (gQuietMode)
nexusReader->SetWarningOutputLevel(NxsReader::SKIPPING_CONTENT_WARNING);
if (gStrictLevel != 2)
nexusReader->SetWarningToErrorThreshold((int)NxsReader::FATAL_WARNING + 1 - (int) gStrictLevel);
if (gUnderscoresToSpaces)
nexusReader->SetCoerceUnderscoresToSpaces(true);
NxsCharactersBlock * charsB = nexusReader->GetCharactersBlockTemplate();
NxsDataBlock * dataB = nexusReader->GetDataBlockTemplate();
charsB->SetAllowAugmentingOfSequenceSymbols(true);
dataB->SetAllowAugmentingOfSequenceSymbols(true);
if (gInterleaveLen > 0)
{
assert(charsB);
charsB->SetWriteInterleaveLen(gInterleaveLen);
dataB->SetWriteInterleaveLen(gInterleaveLen);
}
NxsTreesBlock * treesB = nexusReader->GetTreesBlockTemplate();
assert(treesB);
if (gStrictLevel < 2)
treesB->SetAllowImplicitNames(true);
treesB->SetWriteFromNodeEdgeDataStructure(gTreesViaInMemoryStruct);
treesB->setValidateInternalNodeLabels(gValidateInternals);
treesB->setAllowNumericInterpretationOfTaxLabels(gAllowNumericInterpretationOfTaxLabels);
if (gAltNexus)
treesB->setWriteTranslateTable(false);
if (gStrictLevel < 2)
{
NxsStoreTokensBlockReader *storerB = nexusReader->GetUnknownBlockTemplate();
assert(storerB);
storerB->SetTolerateEOFInBlock(true);
}
nexusReader->conversionOutputRecord.addNumbersToDisambiguateNames = true;
if (gSuppressingNameTranslationFile)
nexusReader->conversionOutputRecord.writeNameTranslationFile = false;
return nexusReader;
}
////////////////////////////////////////////////////////////////////////////////
// Creates a NxsReader, and tries to read the file `filename`. If the
// read succeeds, then processContent will be called.
// \returns 0 on success
////////////////////////////////////////////////////////////////////////////////
#if !defined(MULTIFILE_NEXUS_READER) || !MULTIFILE_NEXUS_READER
int processFilepath(
const char * filename, // name of the file to be read
ostream * os, // output stream to use (NULL for no output). Not that cerr is used to report errors.
MultiFormatReader::DataFormatType fmt, // enum indicating the file format to expect.
ProcessActionsEnum currentAction) // enum that is passed on to processContent to indicate what should be done with the content of the file.
#else
int processFilepath(
const char * filename, // name of the file to be read
ostream * , // output stream to use (NULL for no output). Not that cerr is used to report errors.
MultiFormatReader::DataFormatType fmt, // enum indicating the file format to expect.
ProcessActionsEnum ) // enum that is passed on to processContent to indicate what should be done with the content of the file.
#endif
{
assert(filename);
try
{
MultiFormatReader * nexusReader;
# if defined(MULTIFILE_NEXUS_READER) && MULTIFILE_NEXUS_READER
nexusReader = gNexusReader;
# else
nexusReader = instantiateReader();
# endif
if (!gQuietMode)
cerr << "Executing" << endl;
try {
nexusReader->DemoteBlocks();
nexusReader->ReadFilepath(filename, fmt);
# if !defined(MULTIFILE_NEXUS_READER) || !MULTIFILE_NEXUS_READER
processContent(*nexusReader, os, currentAction);
# endif
}
catch(...)
{
nexusReader->DeleteBlocksFromFactories();
# if ! defined(MULTIFILE_NEXUS_READER) || !MULTIFILE_NEXUS_READER
delete nexusReader;
# endif
throw;
}
# if !defined(MULTIFILE_NEXUS_READER) || !MULTIFILE_NEXUS_READER
nexusReader->DeleteBlocksFromFactories();
delete nexusReader;
# endif
return 0;
}
catch (const NxsException &x)
{
cerr << "Error:\n " << x.msg << endl;
if (x.line > 0 || x.pos > 0)
cerr << "at line " << x.line << ", column (approximately) " << x.col << " (and file position "<< x.pos << ")" << endl;
return 2;
}
}
/*! \returns 0 on success*/
int readFilepathAsNEXUS(const char *filename, MultiFormatReader::DataFormatType fmt, ProcessActionsEnum currentAction)
{
if (!gQuietMode)
cerr << "[Reading " << filename << " ]" << endl;
try {
ostream * outStream = 0L;
if (currentAction != VALIDATE_ONLY)
outStream = &cout;
return processFilepath(filename, outStream, fmt, currentAction);
}
catch (...)
{
cerr << "Normalizing of " << filename << " failed (with an exception)" << endl;
return 1;
}
}
/*! \returns 0 on success*/
int readFilesListedIsFile(const char *masterFilepath, MultiFormatReader::DataFormatType fmt, ProcessActionsEnum currentAction)
{
ifstream masterStream(masterFilepath, ios::binary);
if (masterStream.bad())
{
cerr << "Could not open " << masterFilepath << "." << endl;
exit(3);
}
char filename[1024];
while ((!masterStream.eof()) && masterStream.good())
{
masterStream.getline(filename, 1024);
if (strlen(filename) > 0 && filename[0] != '#')
{
int rc = readFilepathAsNEXUS(filename, fmt, currentAction);
if (rc != 0)
return rc;
}
}
return 0;
}
#if defined(JUST_VALIDATE_NEXUS) && JUST_VALIDATE_NEXUS
const char * gExeName = "NEXUSvalidator";
#elif defined(JUST_REPORT_NEXUS) && JUST_REPORT_NEXUS
const char * gExeName = "NEXUSinspector";
#elif defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
const char * gExeName = "NCLconverter";
#else
# if defined(MULTIFILE_NEXUS_READER) && MULTIFILE_NEXUS_READER
const char * gExeName = "NEXUSunion";
# else
const char * gExeName = "NEXUSnormalizer";
# endif
# endif
void printHelp(ostream & out)
{
# if defined(JUST_VALIDATE_NEXUS) && JUST_VALIDATE_NEXUS
out << "NEXUSvalidator takes reads a file and exits with a success (return code 0) if the file is valid.\n";
# elif defined(JUST_REPORT_NEXUS) && JUST_REPORT_NEXUS
out << "NEXUSinspector takes reads a file and writes a report of the content to standard out.\n";
# elif defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
out << "NCLconverter takes reads a file and writes a report of the content to a file prefix (specified with the -o flag) in the chosen output format (specified with the -e flag).\n";
# else
# if defined(MULTIFILE_NEXUS_READER) && MULTIFILE_NEXUS_READER
out << "NEXUSunion reads a series of NEXUS file and writes the union of all of their content to standard out (using the NEXUSnormalizer conventions of indentation and syntax).\n";
# else
out << "NEXUSnormalizer takes reads a file and rewrites the file to standard out with consistent indentation and syntax.\n";
# endif
# endif
out << "\nThe most common usage is simply:\n " << gExeName << " <path to NEXUS file>\n";
out << "\nCommand-line flags:\n\n";
out << " -h on the command line shows this help message\n\n";
out << " -q suppress NCL status messages while reading files\n\n";
out << " -l<path> reads a file and treats each line of the file as a path to NEXUS file\n\n";
out << " -a output AltNexus (no translation table in trees)\n\n";
out << " -x do NOT validate internal labels in trees as taxa labels\n\n";
out << " -X do NOT treat numbers in trees as taxon numbers, treat them as arbitrary\n labels (should not be used with NEXUS files).\n\n";
out << " -s<non-negative integer> controls the NEXUS strictness level.\n";
out << " the default level is equivalent to -s2 invoking the program with \n";
out << " -s3 or a higher number will convert some warnings into fatal errors.\n";
out << " Running with -s1 will cause the parser to accept dangerous constructs,\n";
out << " and running with -s0 will cause the parser make every attempt to finish\n";
out << " parsing the file (warning about very serious errors).\n\n";
out << " Note that when -s0 strictness level is used, and the parser fails to\n";
out << " finish, it will often be the result of an earlier error than the \n";
out << " error that is reported in the last message.\n";
# if defined(JUST_VALIDATE_NEXUS) && JUST_VALIDATE_NEXUS
//pass
# elif defined(JUST_REPORT_NEXUS) && JUST_REPORT_NEXUS
//pass
# elif defined(TO_NEXML_CONVERTER) && TO_NEXML_CONVERTER
//pass
# else
out << " -i<number> specifies the length of the interleaved pages to create\n";
# endif
out << " -f<format> specifies the input file format expected:\n";
out << " -fnexus NEXUS (this is also the default)\n";
out << " -faafasta Amino acid data in fasta\n";
out << " -fdnafasta DNA data in fasta\n";
out << " -frnafasta RNA data in fasta\n";
out << " The complete list of format names that can follow the -f flag is:\n";
std::vector<std::string> fmtNames = MultiFormatReader::getFormatNames();
for (std::vector<std::string>::const_iterator n = fmtNames.begin(); n != fmtNames.end(); ++n)
{
out << " "<< *n << "\n";
}
# if defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
out << " -e<format> specifies the output file format expected:\n";
out << " -enexus \"normalized\" NEXUS output\n";
out << " -efasta Character data in fasta (could result in multiple output files)\n";
out << " -ephylip Trees and character data in phylip (could result in multiple output files)\n";
out << " -erelaxedphylip Trees and character data in relaxed phylip (could result in multiple output files)\n";
out << " -enexml nexml output (this is also the default)\n";
out << " -o<fn> specifies the output prefix. An appropriate suffix and extension are added\n";
out << " -d<fn> specifies the single output destination. Or you can use -d- to indicate that\n";
out << " output should be directed to standard output.Warning use of this option may result\n";
out << " in an invalid output due to concatenation of separate \"blocks\" of information\n";
out << " into a single file! \n";
out << " -u converts underscores to spaces in formats other than NEXUS.\n";
out << " -y<filename> translate to \"safe\" taxon names and store the new names as a NEXUS.\n";
out << " file called <filename> with a TaxaAssociation block. The first taxa block\n";
out << " in the association block will hold the original names, and the second will\n";
out << " hold the \"safe\" names\n";
out << " -Y<filename> behaves like -y, except with -Y a translation file will be produced even";
out << " if the original names were already \"safe\"\n";
out << " -z<filename> use the NEXUS-formatted file called <filename> with a TaxaAssociation block\n";
out << " to restore original names. Assumes that the first taxa block in the TaxaAssociation\n";
out << " block holds the original name and the second is the current name. This function\n";
out << " is useful for \"undoing\" the effects of the -y option.\n";
out << " -j Suppress the creation of a NameTranslationFile\n";
# endif
}
int do_main(int argc, char *argv[])
{
NxsReader::setNCLCatchesSignals(true);
MultiFormatReader::DataFormatType f(MultiFormatReader::NEXUS_FORMAT);
# if defined(JUST_VALIDATE_NEXUS) && JUST_VALIDATE_NEXUS
ProcessActionsEnum currentAction = VALIDATE_ONLY;
# elif defined(JUST_REPORT_NEXUS) && JUST_REPORT_NEXUS
ProcessActionsEnum currentAction = REPORT_BLOCKS;
# elif defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
ProcessActionsEnum currentAction = OUTPUT_ANY_FORMAT;
# elif defined(TO_NEXML_CONVERTER) && TO_NEXML_CONVERTER
ProcessActionsEnum currentAction = OUTPUT_NEXML;
# else
ProcessActionsEnum currentAction = OUTPUT_NORMALIZED_NEXUS;
# endif
for (int i = 1; i < argc; ++i)
{
const char * filepath = argv[i];
const unsigned slen = strlen(filepath);
if (slen < 2 || filepath[0] != '-')
continue;
if (filepath[1] == 'h')
{
printHelp(cout);
return 1;
}
else if (filepath[1] == 'q')
gQuietMode = true;
else if (filepath[1] == 'x')
gValidateInternals = false;
else if (filepath[1] == 'X')
gAllowNumericInterpretationOfTaxLabels = false;
else if (filepath[1] == 'u')
gUnderscoresToSpaces = true;
else if (filepath[1] == 'j')
gSuppressingNameTranslationFile = true;
else if (filepath[1] == 's')
{
if ((slen == 2) || (!NxsString::to_long(filepath + 2, &gStrictLevel)))
{
cerr << "Expecting an integer after -s\n" << endl;
printHelp(cerr);
return 2;
}
}
# if defined(JUST_VALIDATE_NEXUS) && JUST_VALIDATE_NEXUS
//pass
# elif defined(JUST_REPORT_NEXUS) && JUST_REPORT_NEXUS
//pass
# elif defined(TO_NEXML_CONVERTER) && TO_NEXML_CONVERTER
//pass
# else
else if (filepath[1] == 'i')
{
if ((slen == 2) || (!NxsString::to_long(filepath + 2, &gInterleaveLen)) || gInterleaveLen < 1)
{
cerr << "Expecting a positive integer after -i\n" << endl;
printHelp(cerr);
return 2;
}
}
else if (filepath[1] == 'a')
{
if ((slen != 2))
{
cerr << "Not expecting a value after -a\n" << endl;
printHelp(cerr);
return 2;
}
gAltNexus = true;
}
# endif
# if defined(NCL_CONVERTER_APP) && NCL_CONVERTER_APP
else if (filepath[1] == 'e') {
if (slen > 2)
{
std::string efmtName(filepath + 2, slen - 2);
gExportFormat = readExportFormatName(efmtName);
}
if (f == MultiFormatReader::UNSUPPORTED_FORMAT)
{
cerr << "Expecting a format after -e\n" << endl;
printHelp(cerr);
return 2;
}
}
else if (filepath[1] == 'o') {
if (slen > 2)
{
std::string oname(filepath + 2, slen - 2);
gExportPrefix = oname;
}
if (gExportPrefix.empty())
{
cerr << "Expecting an output file prefix after -o\n" << endl;
printHelp(cerr);
return 2;
}
}
else if (filepath[1] == 'd') {
if (slen > 2)
{
if (gCommonOstream != 0)
{
cerr << "Expecting only one -d flag per invocation.\n" << endl;
return 2;
}
std::string dname(filepath + 2, slen - 2);
if (dname == "-")
gCommonOstream = &std::cout;
else
{
gCommonFileStream.open(dname.c_str());
if (!gCommonFileStream.good())
{
cerr << "Error opening " << dname << ".\n" << flush;
return 2;
}
if (!gQuietMode) {
cerr << "Directing all output to " << dname << ".\n" << flush;
}
gCommonOstream = & gCommonFileStream;
}
}
if (f == MultiFormatReader::UNSUPPORTED_FORMAT)
{
cerr << "Expecting an output file prefix after -o\n" << endl;
printHelp(cerr);
return 2;
}
}
else if (filepath[1] == 'y' || filepath[1] == 'Y') {
if (slen > 2)
{
std::string oname(filepath + 2, slen - 2);
if (!gNEXUSSafeNamesToRead.empty())
{
cerr << "The -y and -z options cannot both be specified!\n" << endl;
printHelp(cerr);
return 2;
}
if (!gNEXUSSafeNamesToWrite.empty())
{
cerr << "The -y only be specified once per invocation!\n" << endl;
printHelp(cerr);
return 2;
}
gNEXUSSafeNamesToWrite = oname;
if (gNEXUSSafeNamesToWrite.empty())
{
cerr << "Expecting an output file prefix after -o\n" << endl;
printHelp(cerr);
return 2;
}
}
if (filepath[1] == 'Y')
gProduceEvenTrivalTranslation = true;
}
else if (filepath[1] == 'z') {
if (slen > 2)
{
std::string oname(filepath + 2, slen - 2);
if (!gNEXUSSafeNamesToWrite.empty())
{
cerr << "The -y and -z options cannot both be specified!\n" << endl;
printHelp(cerr);
return 2;
}
if (!gNEXUSSafeNamesToRead.empty())
{
cerr << "The -z only be specified once per invocation!\n" << endl;
printHelp(cerr);
return 2;
}
gNEXUSSafeNamesToRead = oname;
if (gNEXUSSafeNamesToRead.empty())
{
cerr << "Expecting an output file prefix after -o\n" << endl;
printHelp(cerr);
return 2;
}
}
}
# endif
else if (filepath[1] == 'f')
{
f = MultiFormatReader::UNSUPPORTED_FORMAT;
if (slen > 2)
{
std::string fmtName(filepath + 2, slen - 2);
f = MultiFormatReader::formatNameToCode(fmtName);
if (f == MultiFormatReader::UNSUPPORTED_FORMAT)
{
cerr << "Unknown format \"" << fmtName << "\" after -f\n" << endl;
printHelp(cerr);
return 3;
}
}
if (f == MultiFormatReader::UNSUPPORTED_FORMAT)
{
cerr << "Expecting a format after -f\n" << endl;
printHelp(cerr);
return 2;
}
}
}
# if defined(MULTIFILE_NEXUS_READER) && MULTIFILE_NEXUS_READER
gNexusReader = instantiateReader();
gNexusReader->cullIdenticalTaxaBlocks(true);
# endif
bool readfile = false;
for (int i = 1; i < argc; ++i)
{
const char * filepath = argv[i];
const unsigned slen = strlen(filepath);
if (slen < 1)
continue;
if (strlen(filepath) > 2 && filepath[0] == '-' && filepath[1] == 'l')
{
readfile = true;
int rc = readFilesListedIsFile(filepath+2, f, currentAction);
if (rc != 0)
return rc;
}
else if (filepath[0] != '-')
{
readfile = true;
int rc = readFilepathAsNEXUS(filepath, f, currentAction);
if (rc != 0)
return rc;
}
}
# if defined(MULTIFILE_NEXUS_READER) && MULTIFILE_NEXUS_READER
if (gNexusReader)
{
processContent(*gNexusReader, &std::cout, OUTPUT_NORMALIZED_NEXUS);
gNexusReader->DeleteBlocksFromFactories();
delete gNexusReader;
}
# endif
if (!readfile)
{
cerr << "Expecting the path to NEXUS file as the only command line argument!\n" << endl;
printHelp(cerr);
return 1;
}
# if defined(JUST_VALIDATE_NEXUS) && JUST_VALIDATE_NEXUS
if (blocksReadInValidation)
return 0;
std::cerr << "No blocks read\n";
return 1;
# else
return 0;
# endif
}
int main(int argc, char *argv[])
{
int rc = do_main(argc, argv);
if (gCommonOstream != 0L && gCommonOstream == &gCommonFileStream)
gCommonFileStream.close();
return rc;
}
|