GCsv.cpp 13.3 KB
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
/***************************************************************************
 *             GCsv.cpp - Column separated values table class              *
 * ----------------------------------------------------------------------- *
 *  copyright (C) 2010-2012 by Juergen Knoedlseder                         *
 * ----------------------------------------------------------------------- *
 *                                                                         *
 *  This program 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 3 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.  *
 *                                                                         *
 ***************************************************************************/
/**
 * @file GCsv.cpp
 * @brief Column separated values table class implementation
 * @author Juergen Knoedlseder
 */

/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstdio>            // std::fopen, std::fgets, std::fclose, etc...
#include "GCsv.hpp"
#include "GTools.hpp"
#include "GException.hpp"

/* __ Method name definitions ____________________________________________ */
#define G_ACCESS                              "GCsv::operator() (int&, int&)"
#define G_LOAD                        "GCsv::load(std::string&, std::string)"

/* __ Macros _____________________________________________________________ */

/* __ Coding definitions _________________________________________________ */

/* __ Debug definitions __________________________________________________ */


/*==========================================================================
 =                                                                         =
 =                         Constructors/destructors                        =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Void constructor
 ***************************************************************************/
GCsv::GCsv(void)
{
    // Initialise private members
    init_members();
  
    // Return
    return;
}


/***********************************************************************//**
 * @brief File constructor
 *
 * @param[in] filename Filename.
 * @param[in] sep Column separator (default is whitespace).
 ***************************************************************************/
GCsv::GCsv(const std::string& filename, std::string sep)
{ 
    // Initialise private
    init_members();

    // Load CSV table
    load(filename, sep);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy constructor
 *
 * @param[in] csv Column separated values table.
 ***************************************************************************/
GCsv::GCsv(const GCsv& csv)
{ 
    // Initialise private
    init_members();

    // Copy members
    copy_members(csv);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Destructor
 ***************************************************************************/
GCsv::~GCsv(void)
{
    // Free members
    free_members();

    // Return
    return;
}


/*==========================================================================
 =                                                                         =
 =                                Operators                                =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Assignment operator
 *
 * @param[in] csv Column separated values table.
 ***************************************************************************/
GCsv& GCsv::operator= (const GCsv& csv)
{ 
    // Execute only if object is not identical
    if (this != &csv) {

        // Free members
        free_members();

        // Initialise private members for clean destruction
        init_members();

        // Copy members
        copy_members(csv);

    } // endif: object was not identical
  
    // Return
    return *this;
}


/***********************************************************************//**
 * @brief Table element access operator
 *
 * @param[in] row Table row.
 * @param[in] col Table column.
 ***************************************************************************/
std::string& GCsv::operator() (const int& row, const int& col)
{
    // Perform range check
    #if defined(G_RANGE_CHECK)
    if (row < 0 || row >= m_rows || col < 0 || col >= m_cols) {
        throw GException::out_of_range(G_ACCESS, row, col, m_rows-1, m_cols-1);
    }
    #endif

    // Return element
    return m_data[row][col];
}


/***********************************************************************//**
 * @brief Table element access operator (const version)
 *
 * @param[in] row Table row.
 * @param[in] col Table column.
 ***************************************************************************/
const std::string& GCsv::operator() (const int& row, const int& col) const
{
    // Perform range check
    #if defined(G_RANGE_CHECK)
    if (row < 0 || row >= m_rows || col < 0 || col >= m_cols) {
        throw GException::out_of_range(G_ACCESS, row, col, m_rows, m_cols);
    }
    #endif

    // Return element
    return m_data[row][col];
}


/*==========================================================================
 =                                                                         =
 =                             Public methods                              =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Clear instance
 *
 * This method properly resets the object to an initial state.
 ***************************************************************************/
void GCsv::clear(void)
{
    // Free class members
    free_members();

    // Initialise members
    init_members();

    // Return
    return;
}


/***********************************************************************//**
 * @brief Clone instance
 **************************************************************************/
GCsv* GCsv::clone(void) const
{
    return new GCsv(*this);
}


/***********************************************************************//**
 * @brief Get string value
 *
 * @param[in] row Table row.
 * @param[in] col Table column.
 *
 * Returns value of specified row and column as string.
 ***************************************************************************/
std::string GCsv::string(const int& row, const int& col) const
{
    // Return value
    return (*this)(row, col);
}


/***********************************************************************//**
 * @brief Get double precision value
 *
 * @param[in] row Table row.
 * @param[in] col Table column.
 *
 * Returns value of specified row and column as double precision.
 ***************************************************************************/
double GCsv::real(const int& row, const int& col) const
{
    // Convert element into double
    double value = todouble((*this)(row, col));

    // Return value
    return value;
}


/***********************************************************************//**
 * @brief Get integer value
 *
 * @param[in] row Table row.
 * @param[in] col Table column.
 *
 * Returns value of specified row and column as integer.
 ***************************************************************************/
int GCsv::integer(const int& row, const int& col) const
{
    // Convert element into int
    int value = toint((*this)(row, col));

    // Return value
    return value;
}


/***********************************************************************//**
 * @brief Load CSV table
 *
 * @param[in] filename Filename.
 * @param[in] sep Column separator (default is whitespace).
 *
 * @exception GException::file_not_found
 *            CSV table file not found.
 * @exception GException::csv_bad_columns
 *            Inconsistent columns encountered in CSV table file.
 *
 * Load CSV table from ASCII file.
 * Any environment variable present in the filename will be expanded.
 **************************************************************************/
void GCsv::load(const std::string& filename, std::string sep)
{
    // Clear instance
    clear();

    // If no seperator is given then assume a whitespace
    if (sep.length() == 0) {
        sep = " ";
    }

    // Allocate line buffer
    const int n = 10000; 
    char  line[n];

    // Expand environment variables
    std::string fname = expand_env(filename);

    // Open CSV table (read-only
    FILE* fptr = std::fopen(fname.c_str(), "r");
    if (fptr == NULL) {
        throw GException::file_not_found(G_LOAD, fname);
    }

    // Read lines
    int iline = 0;
    while (std::fgets(line, n, fptr) != NULL) {

        // Increment line counter
        iline++;

        // Get line with leading and trailing whitespace removed
        std::string sline = strip_chars(strip_whitespace(std::string(line)),"\n");

        // Skip line if empty
        if (sline.length() == 0)
            continue;

        // Split line in elements
        std::vector<std::string> elements = split(sline, sep);
        for (int i = 0; i < elements.size(); ++i) {
            elements[i] = strip_whitespace(elements[i]);
        }

        // If this is the first valid line then simply store the elements
        if (m_data.empty()) {
            m_data.push_back(elements);
            m_cols = elements.size();
        }

        // ... otherwise check table consistency and add elements
        else {
            // Check table consistency
            if (m_cols != elements.size()) {
                throw GException::csv_bad_columns(G_LOAD, fname,
                                  iline, m_cols, elements.size());
            }

            // Append elements
            m_data.push_back(elements);
        }

        // Increment number of rows
        m_rows++;

    } // endwhile: looped over lines

    // Close file
    std::fclose(fptr);

    // Return
    return;
}


/***********************************************************************//**
 * @brief Print class information
 ***************************************************************************/
std::string GCsv::print(void) const
{
    // Initialise result string
    std::string result;

    // Append header
    result.append("=== GCsv ===");
    result.append("\n"+parformat("Number of columns")+str(m_cols));
    result.append("\n"+parformat("Number of rows")+str(m_rows));

    // Return result
    return result;
}


/*==========================================================================
 =                                                                         =
 =                             Private methods                             =
 =                                                                         =
 ==========================================================================*/

/***********************************************************************//**
 * @brief Initialise class members
 ***************************************************************************/
void GCsv::init_members(void)
{
    // Initialise members
    m_cols = 0;
    m_rows = 0;
    m_data.clear();
  
    // Return
    return;
}


/***********************************************************************//**
 * @brief Copy class members
 *
 * @param[in] csv Column separated values table.
 ***************************************************************************/
void GCsv::copy_members(const GCsv& csv)
{
    // Copy members
    m_cols = csv.m_cols;
    m_rows = csv.m_rows;
    m_data = csv.m_data;
    
    // Return
    return;
}


/***********************************************************************//**
 * @brief Delete class members
 ***************************************************************************/
void GCsv::free_members(void)
{
    // Return
    return;
}


/*==========================================================================
 =                                                                         =
 =                                 Friends                                 =
 =                                                                         =
 ==========================================================================*/