Skip to content
Snippets Groups Projects
ADIOS1CommonRead.cpp 14.1 KiB
Newer Older
pnorbert's avatar
pnorbert committed
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
/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * ADIOS1CommonRead.cpp
 *
 *  Created on: Oct 26, 2017
 *      Author: Norbert Podhorszki pnorbert@ornl.gov
 *              William F Godoy godoywf@ornl.gov
 */

#include "ADIOS1CommonRead.h"
#include "ADIOS1CommonRead.tcc"

#include "adios2/ADIOSMPI.h"
#include "adios2/helper/adiosFunctions.h" //OpenModeToString, GetType

extern int adios_verbose_level;
extern int adios_errno;

namespace adios2
{
namespace interop
{

ADIOS1CommonRead::ADIOS1CommonRead(const std::string &fileName,
                                   MPI_Comm mpiComm, const bool debugMode)
: ADIOS1Common(fileName, mpiComm, debugMode)
{
    Init();
    adios_read_init_method(m_ReadMethod, m_MPIComm, "");
}

ADIOS1CommonRead::~ADIOS1CommonRead()
{
    Close();
    adios_read_finalize_method(m_ReadMethod);
}

bool ADIOS1CommonRead::Open()
{
    if (m_OpenAsFile)
    {
        m_fh =
            adios_read_open_file(m_FileName.c_str(), m_ReadMethod, m_MPIComm);
    }
    else
    {
        m_fh = adios_read_open(m_FileName.c_str(), m_ReadMethod, m_MPIComm,
                               ADIOS_LOCKMODE_CURRENT, 0.0);
    }
    return (m_fh != NULL);
}

void ADIOS1CommonRead::DefineADIOS2Variable(IO &io, const char *name,
                                            const ADIOS_VARINFO *vi, Dims gdims,
                                            bool isJoined, bool isGlobal)
{
    switch (vi->type)
    {
    case adios_unsigned_byte:
        DefineADIOS2Variable<unsigned char>(io, name, vi, gdims, isJoined,
                                            isGlobal);
        break;
    case adios_unsigned_short:
        DefineADIOS2Variable<unsigned short>(io, name, vi, gdims, isJoined,
                                             isGlobal);
        break;
    case adios_unsigned_integer:
        DefineADIOS2Variable<unsigned int>(io, name, vi, gdims, isJoined,
                                           isGlobal);
        break;
    case adios_unsigned_long:
        DefineADIOS2Variable<unsigned long long int>(io, name, vi, gdims,
                                                     isJoined, isGlobal);
        break;

    case adios_byte:
        DefineADIOS2Variable<char>(io, name, vi, gdims, isJoined, isGlobal);
        break;
    case adios_short:
        DefineADIOS2Variable<short>(io, name, vi, gdims, isJoined, isGlobal);
        break;
    case adios_integer:
        DefineADIOS2Variable<int>(io, name, vi, gdims, isJoined, isGlobal);
        break;
    case adios_long:
        DefineADIOS2Variable<long long int>(io, name, vi, gdims, isJoined,
                                            isGlobal);
        break;

    case adios_real:
        DefineADIOS2Variable<float>(io, name, vi, gdims, isJoined, isGlobal);
        break;
    case adios_double:
        DefineADIOS2Variable<double>(io, name, vi, gdims, isJoined, isGlobal);
        break;
    case adios_long_double:
        DefineADIOS2Variable<long double>(io, name, vi, gdims, isJoined,
                                          isGlobal);
        break;

    case adios_string:
        /*FIXME: DefineADIOS2Variable<std::string>(io, name, vi, gdims,
           isJoined,
                                          isGlobal);*/
        break;
    case adios_complex:
        DefineADIOS2Variable<std::complex<float>>(io, name, vi, gdims, isJoined,
                                                  isGlobal);
        break;
    case adios_double_complex:
        DefineADIOS2Variable<std::complex<double>>(io, name, vi, gdims,
                                                   isJoined, isGlobal);
        break;
    default:
        break;
    }
}

void ADIOS1CommonRead::GenerateVariables(IO &io)
{
    /* Create a Variable for each variable in the file */
    for (int varid = 0; varid < m_fh->nvars; varid++)
    {
        // here read variable metadata (dimensions, type, etc.)...then create a
        // Variable like below:
        // Variable<T>& variable = io.DefineVariable<T>( m_Name + "/" +
        // name, )
        // return &variable; //return address if success
        ADIOS_VARINFO *vi = adios_inq_var(m_fh, m_fh->var_namelist[varid]);
        if (vi != nullptr)
        {
            if (vi->ndim > 0)
            {
                Dims gdims = Uint64ArrayToSizetVector(vi->ndim, vi->dims);

                bool joinedread = false;
                if (gdims[0] == JoinedDim)
                {
                    /* Joined Array */
                    InqVarBlockInfo(vi);
                    size_t joined_size = 0;
                    for (int i = 0; i < *vi->nblocks; i++)
                    {
                        joined_size += vi->blockinfo[i].count[0];
                    }
                    gdims[0] = joined_size;
                    joinedread = true;
                }

                if (!vi->global)
                {
                    /* Local array */
                    for (int j = 0; j < vi->ndim; ++j)
                    {
                        gdims[j] = IrregularDim;
                    }
                }
                else
                {
                    /* Check if dimensions change in time */
                    for (int step = 1; step < vi->nsteps; ++step)
                    {
                        Dims dims =
                            gdims; // GetGlobalDimsAtStep(vi, step, joinedread);
                        for (int j = 0; j < vi->ndim; ++j)
                        {
                            if (dims[j] != gdims[j])
                                gdims[j] = IrregularDim;
                        }
                    }
                }
                DefineADIOS2Variable(io, m_fh->var_namelist[vi->varid], vi,
                                     gdims, joinedread, (vi->global > 0));
            }
            else /* Scalars */
            {
                /* scalar variable but global value or local value*/
                bool isChangingDim = false;
                bool isLocalValue = IsVarLocalValue(vi);
                if (isLocalValue)
                {
                    /* Local Value */
                    for (int step = 1; step < vi->nsteps; ++step)
                    {
                        if (vi->nblocks[step] != vi->nblocks[0])
                            isChangingDim = true;
                    }
                    if (isChangingDim)
                    {
                        DefineADIOS2Variable(io, m_fh->var_namelist[vi->varid],
                                             vi, {IrregularDim}, false, false);
                    }
                    else
                    {
                        DefineADIOS2Variable(io, m_fh->var_namelist[vi->varid],
                                             vi, {(unsigned int)vi->nblocks[0]},
                                             false, false);
                    }
                }
                else
                {
                    DefineADIOS2Variable(io, m_fh->var_namelist[vi->varid], vi,
                                         {}, false, true);
                }
            }
            adios_free_varinfo(vi);
        }
    }
}

void ADIOS1CommonRead::ScheduleReadCommon(const std::string &name,
                                          const Dims &offs, const Dims &ldims,
                                          const int fromStep, const int nSteps,
                                          const bool readAsLocalValue,
                                          const bool readAsJoinedArray,
                                          void *data)
{
    if (readAsLocalValue)
    {
        /* Get all the requested values from metadata now */
        ADIOS_VARINFO *vi = adios_inq_var(m_fh, name.c_str());
        if (vi)
        {
            adios_inq_var_stat(m_fh, vi, 0, 1);
            int elemsize = adios_type_size(vi->type, nullptr);
            long long blockidx = 0;
            for (int i = 0; i < fromStep; i++)
            {
                blockidx += vi->nblocks[i];
            }
            char *dest = (char *)data;
            for (int i = fromStep; i < fromStep + nSteps; i++)
            {
                for (int j = 0; j < vi->nblocks[i]; j++)
                {
                    memcpy(dest, vi->statistics->blocks->mins[blockidx],
                           elemsize);
                    ++blockidx;
                    dest += elemsize;
                }
            }
            adios_free_varinfo(vi);
        }
    }
    else
    {
        uint64_t start[32], count[32];
        for (int i = 0; i < ldims.size(); i++)
        {
            start[i] = (uint64_t)offs[i];
            count[i] = (uint64_t)ldims[i];
        }
        ADIOS_SELECTION *sel = nullptr;
        if (ldims.size() > 0)
        {
            sel = adios_selection_boundingbox(ldims.size(), start, count);
        }
        adios_schedule_read(m_fh, sel, name.c_str(), (int)fromStep, (int)nSteps,
                            data);
        adios_selection_delete(sel);
    }
}

void ADIOS1CommonRead::PerformReads()
{
    adios_perform_reads(m_fh, static_cast<int>(ReadMode::Blocking));
}

AdvanceStatus ADIOS1CommonRead::AdvanceStep(AdvanceMode mode,
                                            const float timeout_sec)
{
    if (m_OpenAsFile)
    {
        throw std::invalid_argument("ERROR: ADIOS1Reader does not allow "
                                    "Advance() on a file which was opened for "
                                    "read as File\n");
    }
    if (mode != AdvanceMode::NextAvailable &&
        mode != AdvanceMode::LatestAvailable)
    {
        throw std::invalid_argument(
            "ERROR: ADIOS1Reader.Advance() only allows "
            "for NextAvailable or LatestAvailable modes.\n");
    }
    int last = (mode == AdvanceMode::NextAvailable ? 0 : 1);
    float *to = const_cast<float *>(&timeout_sec);
    adios_advance_step(m_fh, last, *to);

    AdvanceStatus status;
    switch (adios_errno)
    {
    case err_no_error:
        status = AdvanceStatus::OK;
        break;
    case err_end_of_stream:
        status = AdvanceStatus::EndOfStream;
        break;
    case err_step_notready:
        status = AdvanceStatus::StepNotReady;
        break;
    default:
        status = AdvanceStatus::OtherError;
        break;
    }
    return status;
}

void ADIOS1CommonRead::ReleaseStep() { adios_release_step(m_fh); }

ADIOS_VARINFO *ADIOS1CommonRead::InqVar(const std::string &varName)
{
    return adios_inq_var(m_fh, varName.c_str());
}

void ADIOS1CommonRead::InqVarBlockInfo(ADIOS_VARINFO *vi)
{
    adios_inq_var_blockinfo(m_fh, vi);
}

void ADIOS1CommonRead::FreeVarInfo(ADIOS_VARINFO *vi) {}

bool ADIOS1CommonRead::IsVarLocalValue(ADIOS_VARINFO *vi)
{
    bool isLocalValue = false;
    std::string aname(m_fh->var_namelist[vi->varid]);
    aname = aname + "/ReadAsArray";
    for (int i = 0; i < vi->nattrs; ++i)
    {
        if (!strcmp(m_fh->attr_namelist[vi->attr_ids[i]], aname.c_str()))
        {
            isLocalValue = true;
            break;
        }
    }
    return isLocalValue;
}

void ADIOS1CommonRead::Close()
{
    if (m_IsFileOpen)
    {
        adios_read_close(m_fh);
        m_IsFileOpen = false;
    }
}

// PRIVATE
void ADIOS1CommonRead::Init()
{
    if (!m_IsInitialized)
    {
        m_IsInitialized = true;
    }
}

void ADIOS1CommonRead::InitParameters(const Params &parameters)
{
    auto itOpenAsFile = parameters.find("OpenAsFile");
    if (itOpenAsFile == parameters.end())
    {
        m_OpenAsFile = false;
    }
    else if (itOpenAsFile->second == "true")
    {
        m_OpenAsFile = true;
    }

    auto itVerbosity = parameters.find("verbose");
    if (itVerbosity != parameters.end())
    {
        int verbosity = std::stoi(itVerbosity->second);
        if (m_DebugMode)
        {
            if (verbosity < 0 || verbosity > 5)
                throw std::invalid_argument(
                    "ERROR: Method verbose argument must be an "
                    "integer in the range [0,5], in call to "
                    "Open or Engine constructor\n");
        }
        adios_verbose_level = verbosity;
    }
}

void ADIOS1CommonRead::InitTransports(
    const std::vector<Params> &transportsParameters)
{
    for (const auto &parameters : transportsParameters)
    {
        auto itTransport = parameters.find("transport");
        if (itTransport->second == "file" || itTransport->second == "File" ||
            itTransport->second == "bp" || itTransport->second == "BP")
        {
            m_ReadMethod = ADIOS_READ_METHOD_BP;
        }
        else
        {
            if (m_DebugMode)
            {
                throw std::invalid_argument(
                    "ERROR: transport " + itTransport->second +
                    " (you mean File?) not supported, in " + m_FileName + "\n");
            }
        }
    }
}

/*
void ADIOS1CommonRead::DefineVariable(const std::string &name,
                                      const ShapeID shapeID,
                                      enum ADIOS_DATATYPES vartype,
                                      const std::string ldims,
                                      const std::string gdims,
                                      const std::string offsets)
{
    switch (shapeID)
    {
    case ShapeID::GlobalValue:
        adios_define_var(m_ADIOSGroup, name.c_str(), "", vartype, "", "",
"");
        break;
    case ShapeID::LocalValue:
        adios_define_var(m_ADIOSGroup, name.c_str(), "", vartype, "", "",
"");
        adios_define_attribute(m_ADIOSGroup, "ReadAsArray", name.c_str(),
                               adios_byte, "1", nullptr);
        break;
    case ShapeID::GlobalArray:
    case ShapeID::LocalArray:
    case ShapeID::JoinedArray:
        adios_define_var(m_ADIOSGroup, name.c_str(), "", vartype,
ldims.c_str(),
                         gdims.c_str(), offsets.c_str());
        break;
    }
}*/

/*
// Explicit declaration of the public template methods
#define declare_template_instantiation(T) \
    template void ADIOS1CommonRead::ReadVariable<T>( \
        const std::string &name, const ShapeID shapeID, const Dims ldims, \
        const Dims gdims, const Dims offsets, const T *values);
ADIOS2_FOREACH_TYPE_1ARG(declare_template_instantiation)
#undef declare_template_instantiation
*/

} // end namespace interop
} // end namespace adios