/* $Id: DistanceMatrix.cpp 498903 2016-04-20 15:50:10Z ivanov $
 * ===========================================================================
 *
 *                            PUBLIC DOMAIN NOTICE
 *               National Center for Biotechnology Information
 *
 *  This software/database is a "United States Government Work" under the
 *  terms of the United States Copyright Act.  It was written as part of
 *  the author's official duties as a United States Government employee and
 *  thus cannot be copyrighted.  This software/database is freely available
 *  to the public for use. The National Library of Medicine and the U.S.
 *  Government have not placed any restriction on its use or reproduction.
 *
 *  Although all reasonable efforts have been taken to ensure the accuracy
 *  and reliability of the software and data, the NLM and the U.S.
 *  Government do not and cannot warrant the performance or results that
 *  may be obtained by using this software or data. The NLM and the U.S.
 *  Government disclaim all warranties, express or implied, including
 *  warranties of performance, merchantability or fitness for any particular
 *  purpose.
 *
 *  Please cite the author in any work or product based on this material.
 *
 * ===========================================================================
 *
 * Author:  Josh Cherry
 *
 * File Description:
 *   .......
 *
 * Remark:
 *   This code was originally generated by application DATATOOL
 *   using the following specifications:
 *   'biotree.asn'.
 */

// standard includes
#include <ncbi_pch.hpp>

// generated includes
#include <objects/biotree/DistanceMatrix.hpp>

// generated classes

BEGIN_NCBI_SCOPE

BEGIN_objects_SCOPE // namespace ncbi::objects::

// destructor
CDistanceMatrix::~CDistanceMatrix(void)
{
}


void CDistanceMatrix::AsMatrix(CNcbiMatrix<double>& mat) const
{
    size_t sz = GetLabels().size();
    if (GetDistances().size() != sz * (sz - 1) / 2) {
        throw runtime_error("mismatch between number of labels "
                            "and number of distances");
    }
    mat.Resize(sz, sz);
    mat.Set(0);
    size_t idx = 0;
    for (size_t j = 0; j < sz; ++j) {
        for (size_t i = j + 1; i < sz; ++i) {
            mat(i, j) = mat(j, i) = GetDistances()[idx];
            ++idx;
        }
    }
}


void CDistanceMatrix::FromMatrix(const CNcbiMatrix<double>& mat)
{
    // Check that the matrix passed in is appropriate
    if (mat.GetRows() != mat.GetCols()) {
        throw runtime_error("matrix is not square");
    }
    size_t sz = mat.GetCols();
    for (size_t i = 0; i < sz; ++i) {
        if (mat(i, i) != 0) {
            throw runtime_error("element on main diagonal is nonzero");
        }
        for (size_t j = 0; j < sz; ++j) {
            if (mat(i, j) != mat(j, i)) {
                throw runtime_error("matrix is not symmetric");
            }
        }
    }

    // Set distances accordingly
    ResetDistances();
    for (size_t j = 0; j < sz; ++j) {
        for (size_t i = j + 1; i < sz; ++i) {
            // should check that mat(i, j) == mat(j, i);
            SetDistances().push_back(mat(i, j));
        }
    }
}


void CDistanceMatrix::Read(istream &istr, EFormat format) {
    if (format == eGuess) {
        CT_POS_TYPE init_pos = istr.tellg();
        try {
            Read(istr, eSquare);
            return;
        }
        catch (std::exception&) {
            istr.seekg(init_pos);
        }
        try {
            Read(istr, eUpper);
            return;
        }
        catch (std::exception&) {
            istr.seekg(init_pos);
        }
        Read(istr, eLower);
        return;
    }

    string line;
    NcbiGetlineEOL(istr, line);

    unsigned int dim = NStr::StringToUInt(NStr::TruncateSpaces(line));

    vector<string> names;
    vector<vector<double> > values;

    for (unsigned int i = 0; i < dim; ++i) {
        unsigned int count = 0;
        vector<double> line_values;
        unsigned int min_expected_cols, max_expected_cols;
        if (format == eSquare) {
            min_expected_cols = dim;
            max_expected_cols = dim;
        } else if (format == eLower) {
            min_expected_cols = i;
            max_expected_cols = i + 1;  // main diagonal is optional
        } else if (format == eUpper) {
            min_expected_cols = dim - i;
            max_expected_cols = dim - i;
        } else {
            throw runtime_error("invald matrix format specified");
        }
        while (true) {
            NcbiGetlineEOL(istr, line);
            if (istr.eof()) {
                throw runtime_error("unexpected EOF");
            }
            if (!istr.good()) {
                throw runtime_error("problem reading file");
            }
            if (count == 0) {
                string name = NStr::TruncateSpaces(line.substr(0, 10));
                names.push_back(name);
                line = line.substr(10);
            }
            list<string> fields;
            NStr::Split(line, " \t\n\r", fields, NStr::fSplit_Tokenize);
            ITERATE (list<string>, field, fields) {
                line_values.push_back(NStr::StringToDouble(*field));
            }
            if (line_values.size() > max_expected_cols) {
                throw runtime_error("too many columns in row");
            }
            if (line_values.size() >= min_expected_cols) {
                break;
            }
            ++count;
        }
        values.push_back(line_values);
    }
    CNcbiMatrix<double> mat(dim, dim);
    for (unsigned int i = 0; i < dim; ++i) {
        for (unsigned int j = 0; j < dim; ++j) {
            if (format == eSquare) {
                mat(i, j) = values[i][j];
            } else if (format == eUpper) {
                if (i > j) {
                    mat(i, j) = values[j][i];
                } else {
                    mat(i, j) = values[i][j];
                }
            } else {  // eLower
                if (i == j) {
                    if (values[i].size() == i + 1) {
                        // diagonal value was provided in file
                        mat(i, j) = values[i][j];
                    } else {
                        mat(i, j) = 0;
                    }
                } else if (i > j) {
                    mat(i, j) = values[i][j];
                } else {
                    mat(i, j) = values[j][i];
                }
            }
        }
    }
    FromMatrix(mat);
    ResetLabels();
    ITERATE (vector<string>, name, names) {
        SetLabels().push_back(*name);
    }
}

END_objects_SCOPE // namespace ncbi::objects::

END_NCBI_SCOPE

/* Original file checksum: lines: 65, chars: 1906, CRC32: af87b363 */
