<commit_before>//=============================================================================================================
/**
* @file     main.cpp
* @author   Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     11, 2019
*
* @section  LICENSE
*
* Copyright (C) 2019, Ruben Doerrfel and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief     Example for filtering of data with realtime filtering. This example is combined with
*            ex_read_write_raw for reading and writing fiff files. So the result of the filtering can be seen
*            in MNE-Browse.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <iostream>
#include <vector>
#include <math.h>

#include <fiff/fiff.h>
#include <utils/filterTools/filterdata.h>
#include <rtprocessing/rtfilter.h>

#include <utils/ioutils.h>

//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace RTPROCESSINGLIB;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Command Line Parser
    QCommandLineParser parser;
    parser.setApplicationDescription("Read Write Raw Example");
    parser.addHelpOption();

    QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
    QCommandLineOption outputOption("fileOut", "The output file <out>.", "out", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/test_output.fif");

    parser.addOption(inputOption);
    parser.addOption(outputOption);

    parser.process(a);

    // Init data loading and writing
    QFile t_fileIn(parser.value(inputOption));
    QFile t_fileOut(parser.value(outputOption));

    FiffRawData raw(t_fileIn);

    // Set up pick list: MEG + STI 014 - bad channels
    bool want_meg   = true;
    bool want_eeg   = true;
    bool want_stim  = true;
    QStringList include;
    include << "STI 014";

    MatrixXi picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
    if(picks.cols() == 0) {
        include.clear();
        include << "STI101" << "STI201" << "STI301";
        picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
        if(picks.cols() == 0) {
            printf("channel list may need modification\n");
            return -1;
        }
    }

    RowVectorXd cals;
    FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut, raw.info, cals/*, picks*/);

    // Set up the reading parameters
    fiff_int_t from = raw.first_samp;
    fiff_int_t to = raw.last_samp;

    // To read the whole file at once set quantum = to - from + 1;
    fiff_int_t quantum = to - from + 1;

    // Read and write the data
    bool first_buffer = true;

    fiff_int_t first, last;
    MatrixXd data;
    MatrixXd times;

    // initialize filter settings
    QString filter_name =  "example_cosine";
    FilterData::FilterType type = FilterData::BPF;
    double sFreq = raw.info.sfreq;                                          // get Sample freq from Data
    double centerfreq = 10/(sFreq/2.0);                                     // normed nyquist freq.
    double bandwidth = 10/(sFreq/2.0);
    double parkswidth = 1/(sFreq/2.0);

    RtFilter rtFilter;                                                      // filter object
    MatrixXd dataFiltered;                                                  // filter output

    // channel selection - in this case use every channel
    // size = number of channels; value = index channel number
    QVector<int> channelList(raw.info.nchan);
    for (int i = 0; i < raw.info.nchan; i++){
        channelList[i] = i;
    }

    for(first = from; first < to; first+=quantum) {
        last = first+quantum-1;
        if (last > to) {
            last = to;
        }

        if(!raw.read_raw_segment(data,times,first,last/*,picks*/)) {
            printf("error during read_raw_segment\n");
            return -1;
        }

        //Filtering
        printf("Filtering...");
        dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);
        printf("[done]\n");

        //Writing
        printf("Writing...");
        if(first_buffer) {
           if(first > 0) {
               outfid->write_int(FIFF_FIRST_SAMPLE, &first);
           }
           first_buffer = false;
        }

        outfid->write_raw_buffer(dataFiltered,cals);
        printf("[done]\n");
    }

    outfid->finish_writing_raw();

    printf("Finished\n");

    return 0;
}
<commit_msg>[skip ci] ex_filtering.cpp: remove not used include, whitespace and correct authors name<commit_after>//=============================================================================================================
/**
* @file     main.cpp
* @author   Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     11, 2019
*
* @section  LICENSE
*
* Copyright (C) 2019, Ruben Dörfel and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief     Example for filtering of data with realtime filtering. This example is combined with
*            ex_read_write_raw for reading and writing fiff files. So the result of the filtering can be seen
*            in MNE-Browse.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <iostream>
#include <vector>
#include <math.h>

#include <fiff/fiff.h>
#include <utils/filterTools/filterdata.h>
#include <rtprocessing/rtfilter.h>

//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace RTPROCESSINGLIB;

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Command Line Parser
    QCommandLineParser parser;
    parser.setApplicationDescription("Read Write Raw Example");
    parser.addHelpOption();

    QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw.fif");
    QCommandLineOption outputOption("fileOut", "The output file <out>.", "out", QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/test_output.fif");

    parser.addOption(inputOption);
    parser.addOption(outputOption);

    parser.process(a);

    // Init data loading and writing
    QFile t_fileIn(parser.value(inputOption));
    QFile t_fileOut(parser.value(outputOption));

    FiffRawData raw(t_fileIn);

    // Set up pick list: MEG + STI 014 - bad channels
    bool want_meg   = true;
    bool want_eeg   = true;
    bool want_stim  = true;
    QStringList include;
    include << "STI 014";

    MatrixXi picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
    if(picks.cols() == 0) {
        include.clear();
        include << "STI101" << "STI201" << "STI301";
        picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);
        if(picks.cols() == 0) {
            printf("channel list may need modification\n");
            return -1;
        }
    }

    RowVectorXd cals;
    FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut, raw.info, cals/*, picks*/);

    // Set up the reading parameters
    fiff_int_t from = raw.first_samp;
    fiff_int_t to = raw.last_samp;

    // To read the whole file at once set quantum = to - from + 1;
    fiff_int_t quantum = to - from + 1;

    // Read and write the data
    bool first_buffer = true;

    fiff_int_t first, last;
    MatrixXd data;
    MatrixXd times;

    // initialize filter settings
    QString filter_name =  "example_cosine";
    FilterData::FilterType type = FilterData::BPF;
    double sFreq = raw.info.sfreq;                                          // get Sample freq from Data
    double centerfreq = 10/(sFreq/2.0);                                     // normed nyquist freq.
    double bandwidth = 10/(sFreq/2.0);
    double parkswidth = 1/(sFreq/2.0);

    RtFilter rtFilter;                                                      // filter object
    MatrixXd dataFiltered;                                                  // filter output

    // channel selection - in this case use every channel
    // size = number of channels; value = index channel number
    QVector<int> channelList(raw.info.nchan);
    for (int i = 0; i < raw.info.nchan; i++){
        channelList[i] = i;
    }

    for(first = from; first < to; first+=quantum) {
        last = first+quantum-1;
        if (last > to) {
            last = to;
        }

        if(!raw.read_raw_segment(data,times,first,last/*,picks*/)) {
            printf("error during read_raw_segment\n");
            return -1;
        }

        //Filtering
        printf("Filtering...");
        dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);
        printf("[done]\n");

        //Writing
        printf("Writing...");
        if(first_buffer) {
           if(first > 0) {
               outfid->write_int(FIFF_FIRST_SAMPLE, &first);
           }
           first_buffer = false;
        }

        outfid->write_raw_buffer(dataFiltered,cals);
        printf("[done]\n");
    }

    outfid->finish_writing_raw();

    printf("Finished\n");

    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

//===----------------------------------------------------------------------===//
//
// This file implements a pass to emulate 64-bit integer operations with 32-bit
// ones.
//
//===----------------------------------------------------------------------===//

#include "iree/compiler/Codegen/PassDetail.h"
#include "iree/compiler/Codegen/Passes.h"
#include "iree/compiler/Codegen/SPIRV/Utils.h"
#include "iree/compiler/Dialect/HAL/IR/HALDialect.h"
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Arith/Transforms/Passes.h"
#include "mlir/Dialect/Arith/Transforms/WideIntEmulationConverter.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SPIRV/IR/TargetAndABI.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"

#define DEBUG_TYPE "iree-spirv-emulate-i64"

namespace mlir {
namespace iree_compiler {
namespace {

//===----------------------------------------------------------------------===//
// Conversion patterns
//===----------------------------------------------------------------------===//
struct ConvertHalInterfaceBindingSubspan final
    : OpConversionPattern<IREE::HAL::InterfaceBindingSubspanOp> {
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      IREE::HAL::InterfaceBindingSubspanOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    Type newResultTy = getTypeConverter()->convertType(op.getType());
    if (!newResultTy)
      return rewriter.notifyMatchFailure(
          op->getLoc(),
          llvm::formatv("failed to legalize memref type: {0}", op.getType()));

    auto newOp =
        rewriter.replaceOpWithNewOp<IREE::HAL::InterfaceBindingSubspanOp>(
            op, newResultTy, adaptor.getSet(), adaptor.getBinding(),
            adaptor.getDescriptorType(), adaptor.getByteOffset(),
            adaptor.getDynamicDims(), adaptor.getAlignmentAttr());
    LLVM_DEBUG(llvm::dbgs()
               << "WideIntegerEmulation: new op: " << newOp << "\n");
    (void)newOp;
    return success();
  }
};

// TODO(kuhar): Upstream memref conversion patterns.
struct ConvertMemrefLoad final : OpConversionPattern<memref::LoadOp> {
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      memref::LoadOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    Type newResTy = getTypeConverter()->convertType(op.getType());
    if (!newResTy)
      return rewriter.notifyMatchFailure(
          op->getLoc(), llvm::formatv("failed to legalize memref type: {0}",
                                      op.getMemRefType()));

    auto newOp = rewriter.replaceOpWithNewOp<memref::LoadOp>(
        op, newResTy, adaptor.getMemref(), adaptor.getIndices());
    LLVM_DEBUG(llvm::dbgs()
               << "WideIntegerEmulation: new op: " << newOp << "\n");
    (void)newOp;
    return success();
  }
};

// TODO(kuhar): Upstream memref conversion patterns.
struct ConvertMemrefStore final : OpConversionPattern<memref::StoreOp> {
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      memref::StoreOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    Type newTy = getTypeConverter()->convertType(op.getMemRefType());
    if (!newTy)
      return rewriter.notifyMatchFailure(
          op->getLoc(), llvm::formatv("failed to legalize memref type: {0}",
                                      op.getMemRefType()));

    auto newOp = rewriter.replaceOpWithNewOp<memref::StoreOp>(
        op, adaptor.getValue(), adaptor.getMemref(), adaptor.getIndices());
    LLVM_DEBUG(llvm::dbgs()
               << "WideIntegerEmulation: new op: " << newOp << "\n");
    (void)newOp;
    return success();
  }
};

//===----------------------------------------------------------------------===//
// Helper functions
//===----------------------------------------------------------------------===//

// TODO(kuhar): Upstream memref conversion patterns.
static void populateMemrefEmulationPatterns(
    arith::WideIntEmulationConverter &converter, RewritePatternSet &patterns) {
  patterns.add<ConvertMemrefLoad, ConvertMemrefStore>(converter,
                                                      patterns.getContext());
}

// TODO(kuhar): Upstream memref conversion patterns.
static void populateMemrefWideIntegerEmulationConversions(
    arith::WideIntEmulationConverter &typeConverter) {
  typeConverter.addConversion(
      [&typeConverter](MemRefType ty) -> Optional<Type> {
        auto intTy = ty.getElementType().dyn_cast<IntegerType>();
        if (!intTy) return ty;

        if (intTy.getIntOrFloatBitWidth() <=
            typeConverter.getMaxTargetIntBitWidth())
          return ty;

        Type newElemTy = typeConverter.convertType(intTy);
        if (!newElemTy) return None;

        return ty.cloneWith(None, newElemTy);
      });
}

static void populateIreeI64EmulationPatterns(
    arith::WideIntEmulationConverter &converter, RewritePatternSet &patterns) {
  patterns.add<ConvertHalInterfaceBindingSubspan>(converter,
                                                  patterns.getContext());
}

static bool supportsI64(ModuleOp op) {
  spirv::TargetEnvAttr attr = getSPIRVTargetEnvAttr(op);
  assert(attr && "Not a valid spirv module");
  spirv::TargetEnv env(attr);
  return env.allows(spirv::Capability::Int64);
}

//===----------------------------------------------------------------------===//
// Main pass
//===----------------------------------------------------------------------===//

struct SPIRVEmulateI64Pass final
    : public SPIRVEmulateI64Base<SPIRVEmulateI64Pass> {
  void getDependentDialects(DialectRegistry &registry) const override {
    registry.insert<vector::VectorDialect>();
  }

  void runOnOperation() override {
    ModuleOp op = getOperation();
    if (supportsI64(op)) return;

    arith::WideIntEmulationConverter typeConverter(32);
    populateMemrefWideIntegerEmulationConversions(typeConverter);

    MLIRContext *ctx = &getContext();
    ConversionTarget target(*ctx);
    target.addDynamicallyLegalOp<func::FuncOp>([&typeConverter](Operation *op) {
      return typeConverter.isLegal(cast<func::FuncOp>(op).getFunctionType());
    });
    target.addDynamicallyLegalDialect<
        arith::ArithDialect, func::FuncDialect, IREE::HAL::HALDialect,
        memref::MemRefDialect, vector::VectorDialect>(
        [&typeConverter](Operation *op) {
          bool legal = typeConverter.isLegal(op);
          LLVM_DEBUG(if (!legal) llvm::dbgs()
                     << "WideIntegerEmulation: illegal op: " << *op << "\n");
          return legal;
        });

    RewritePatternSet patterns(ctx);
    arith::populateArithWideIntEmulationPatterns(typeConverter, patterns);
    populateMemrefEmulationPatterns(typeConverter, patterns);
    populateIreeI64EmulationPatterns(typeConverter, patterns);

    if (failed(applyPartialConversion(op, target, std::move(patterns))))
      signalPassFailure();
  }
};

}  // namespace

//===----------------------------------------------------------------------===//
// Public interface
//===----------------------------------------------------------------------===//

std::unique_ptr<OperationPass<ModuleOp>> createSPIRVEmulateI64Pass() {
  return std::make_unique<SPIRVEmulateI64Pass>();
}

}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>[spirv] Use upstream memfref emulation patterns for WIE. NFC. (#11193)<commit_after>// Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

//===----------------------------------------------------------------------===//
//
// This file implements a pass to emulate 64-bit integer operations with 32-bit
// ones.
//
//===----------------------------------------------------------------------===//

#include "iree/compiler/Codegen/PassDetail.h"
#include "iree/compiler/Codegen/Passes.h"
#include "iree/compiler/Codegen/SPIRV/Utils.h"
#include "iree/compiler/Dialect/HAL/IR/HALDialect.h"
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Arith/Transforms/Passes.h"
#include "mlir/Dialect/Arith/Transforms/WideIntEmulationConverter.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/Transforms/Passes.h"
#include "mlir/Dialect/SPIRV/IR/TargetAndABI.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"

#define DEBUG_TYPE "iree-spirv-emulate-i64"

namespace mlir {
namespace iree_compiler {
namespace {

//===----------------------------------------------------------------------===//
// Conversion patterns
//===----------------------------------------------------------------------===//
struct ConvertHalInterfaceBindingSubspan final
    : OpConversionPattern<IREE::HAL::InterfaceBindingSubspanOp> {
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      IREE::HAL::InterfaceBindingSubspanOp op, OpAdaptor adaptor,
      ConversionPatternRewriter &rewriter) const override {
    Type newResultTy = getTypeConverter()->convertType(op.getType());
    if (!newResultTy)
      return rewriter.notifyMatchFailure(
          op->getLoc(),
          llvm::formatv("failed to legalize memref type: {0}", op.getType()));

    auto newOp =
        rewriter.replaceOpWithNewOp<IREE::HAL::InterfaceBindingSubspanOp>(
            op, newResultTy, adaptor.getSet(), adaptor.getBinding(),
            adaptor.getDescriptorType(), adaptor.getByteOffset(),
            adaptor.getDynamicDims(), adaptor.getAlignmentAttr());
    LLVM_DEBUG(llvm::dbgs()
               << "WideIntegerEmulation: new op: " << newOp << "\n");
    (void)newOp;
    return success();
  }
};

//===----------------------------------------------------------------------===//
// Helper functions
//===----------------------------------------------------------------------===//

static void populateIreeI64EmulationPatterns(
    arith::WideIntEmulationConverter &converter, RewritePatternSet &patterns) {
  patterns.add<ConvertHalInterfaceBindingSubspan>(converter,
                                                  patterns.getContext());
}

static bool supportsI64(ModuleOp op) {
  spirv::TargetEnvAttr attr = getSPIRVTargetEnvAttr(op);
  assert(attr && "Not a valid spirv module");
  spirv::TargetEnv env(attr);
  return env.allows(spirv::Capability::Int64);
}

//===----------------------------------------------------------------------===//
// Main pass
//===----------------------------------------------------------------------===//

struct SPIRVEmulateI64Pass final
    : public SPIRVEmulateI64Base<SPIRVEmulateI64Pass> {
  void getDependentDialects(DialectRegistry &registry) const override {
    registry.insert<vector::VectorDialect>();
  }

  void runOnOperation() override {
    ModuleOp op = getOperation();
    if (supportsI64(op)) return;

    arith::WideIntEmulationConverter typeConverter(32);
    memref::populateMemRefWideIntEmulationConversions(typeConverter);

    MLIRContext *ctx = &getContext();
    ConversionTarget target(*ctx);
    target.addDynamicallyLegalOp<func::FuncOp>([&typeConverter](Operation *op) {
      return typeConverter.isLegal(cast<func::FuncOp>(op).getFunctionType());
    });
    target.addDynamicallyLegalDialect<
        arith::ArithDialect, func::FuncDialect, IREE::HAL::HALDialect,
        memref::MemRefDialect, vector::VectorDialect>(
        [&typeConverter](Operation *op) {
          bool legal = typeConverter.isLegal(op);
          LLVM_DEBUG(if (!legal) llvm::dbgs()
                     << "WideIntegerEmulation: illegal op: " << *op << "\n");
          return legal;
        });

    RewritePatternSet patterns(ctx);
    arith::populateArithWideIntEmulationPatterns(typeConverter, patterns);
    memref::populateMemRefWideIntEmulationPatterns(typeConverter, patterns);
    populateIreeI64EmulationPatterns(typeConverter, patterns);

    if (failed(applyPartialConversion(op, target, std::move(patterns))))
      signalPassFailure();
  }
};

}  // namespace

//===----------------------------------------------------------------------===//
// Public interface
//===----------------------------------------------------------------------===//

std::unique_ptr<OperationPass<ModuleOp>> createSPIRVEmulateI64Pass() {
  return std::make_unique<SPIRVEmulateI64Pass>();
}

}  // namespace iree_compiler
}  // namespace mlir
<|endoftext|>


<commit_before>// -*- mode: c++, encoding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * 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/>.
 */
#include <stdlib.h>
#include <iostream>
#include <vector>

#include "cleaner.hpp"
#include "prompter.hpp"
#include "Senario.hpp"

#include "BasicSenario.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * This the main entry point of the program
   *
   * @param   argc  The number of elements in `argv`
   * @param   argv  Command line arguments, including the execute file
   * @return        Exit value, 0 if successful
   */
  int __main__(int argc, char** argv)
  {
    (void) argc;
    (void) argv;

    /** Initialise random **/
    unsigned a, d;
    asm("cpuid");
    asm volatile("rdtsc" : "=a" (a), "=d" (d));
    srand(((long long)a) | (((long long)d) << 32LL));

    std::vector<std::string> senarioTitles = {BasicSenario::getTitle()};

    long senarioIndex = promptDialogue(4,
		 "Welcome to tbrpg!",
		 "Select a game senario.\n"
		 "\n"
		 "Use the up and down arrow keys to nagivate,\n"
		 "and press enter, spacebar or the right arrow\n"
		 "key to start the select senario. You can\n"
		 "also use the letter in front of the senario.\n"
		 "\n"
		 "If you want to exit, press <control>g.",
		 senarioTitles, 0);

    std::flush(std::cout << "You have selected game senario #" << senarioIndex << std::endl);

    cleaner::clean();
    return 0;
  }
}

int main(int argc, char** argv)
{
  return tbrpg::__main__(argc, argv);
}

<commit_msg>exit game when not selecting a senario<commit_after>// -*- mode: c++, encoding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * 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/>.
 */
#include <stdlib.h>
#include <iostream>
#include <vector>

#include "cleaner.hpp"
#include "prompter.hpp"
#include "Senario.hpp"

#include "BasicSenario.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * This the main entry point of the program
   *
   * @param   argc  The number of elements in `argv`
   * @param   argv  Command line arguments, including the execute file
   * @return        Exit value, 0 if successful
   */
  int __main__(int argc, char** argv)
  {
    (void) argc;
    (void) argv;

    /** Initialise random **/
    unsigned a, d;
    asm("cpuid");
    asm volatile("rdtsc" : "=a" (a), "=d" (d));
    srand(((long long)a) | (((long long)d) << 32LL));

    std::vector<std::string> senarioTitles = {BasicSenario::getTitle()};

    long senarioIndex = promptDialogue(4,
		 "Welcome to tbrpg!",
		 "Select a game senario.\n"
		 "\n"
		 "Use the up and down arrow keys to nagivate,\n"
		 "and press enter, spacebar or the right arrow\n"
		 "key to start the select senario. You can\n"
		 "also use the letter in front of the senario.\n"
		 "\n"
		 "If you want to exit, press <control>g.",
		 senarioTitles, 0);

    if (senarioIndex < 0)
      {
	cleaner::clean();
	return 0;
      }

    std::flush(std::cout << "You have selected game senario #" << senarioIndex << std::endl);

    cleaner::clean();
    return 0;
  }
}

int main(int argc, char** argv)
{
  return tbrpg::__main__(argc, argv);
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9c_mi_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9c_mi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_7 = 7;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x19 = 0x19;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;

fapi2::ReturnCode p9c_mi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        uint64_t l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC = literal_1;
        uint64_t l_def_ENABLE_DYNAMIC_64_128B_READS = literal_1;
        uint64_t l_def_ENABLE_ECRESP = literal_1;
        uint64_t l_def_ENABLE_AMO_CACHING = literal_1;
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_7 );

            if (l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC)
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
            }

            if (l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC)
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_0x19 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_ON = 0x1;
            l_scom_buffer.insert<48, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON = 0x1;
            l_scom_buffer.insert<21, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<23, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON );

            if (l_def_ENABLE_DYNAMIC_64_128B_READS)
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
            }

            if (l_def_ENABLE_ECRESP)
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON = 0x1;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (l_def_ENABLE_AMO_CACHING)
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>dis spec ops dcbf HW414958<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9c_mi_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9c_mi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_7 = 7;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_0x19 = 0x19;
constexpr uint64_t literal_0b0000000000001000000 = 0b0000000000001000000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;

fapi2::ReturnCode p9c_mi_scom(const fapi2::Target<fapi2::TARGET_TYPE_MI>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        uint64_t l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC = literal_1;
        uint64_t l_def_ENABLE_DYNAMIC_64_128B_READS = literal_1;
        uint64_t l_def_ENABLE_ECRESP = literal_1;
        uint64_t l_def_ENABLE_AMO_CACHING = literal_1;
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_7 );

            if (l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC)
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );
            }

            if (l_def_ENABLE_PREFETCH_DROP_PROMOTE_BASIC)
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_0x19 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_ON = 0x1;
            l_scom_buffer.insert<48, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_PERFMON_COMMAND_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON = 0x1;
            l_scom_buffer.insert<21, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_EMERGENCY_THROTTLE_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<22, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_CHECKSTOP_COMMAND_ON );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON = 0x1;
            l_scom_buffer.insert<23, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_TRACESTOP_COMMAND_ON );

            if (l_def_ENABLE_DYNAMIC_64_128B_READS)
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
            }

            if (l_def_ENABLE_ECRESP)
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON = 0x1;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            l_scom_buffer.insert<33, 19, 45, uint64_t>(literal_0b0000000000001000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (l_def_ENABLE_AMO_CACHING)
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "exception.hpp"

#include <string>
#include <vector>

using std::string;
using pfi::text::json::json;

namespace jubatus {
namespace jsonconfig {

config_error::config_error(const std::string& path, const std::string& message)
    : path_(path),
      message_(message + " (" + path_ + ")") {
}

config_error::~config_error() throw () {
}

namespace {

const char* TypeToName(json::json_type_t t) {
  switch (t) {
    case json::Null:
      return "Null";
    case json::Integer:
      return "Integer";
    case json::Float:
      return "Float";
    case json::Bool:
      return "Bool";
    case json::String:
      return "String";
    case json::Array:
      return "Array";
    case json::Object:
      return "Object";
    default:
      return "Unknown Type";
  }
}

std::string MakeTypeErrorMessage(json::json_type_t expect,
                                 json::json_type_t actual) {
  return string(TypeToName(expect)) + " is expected, but " + TypeToName(actual)
      + " is given.";
}

std::string MakeOutOfRangeMessage(size_t size, size_t index) {
  std::ostringstream os;
  os << "Out of range 0.." << size << ": " << index;
  return os.str();
}

std::string MakeNotFoundMessage(const std::string& key) {
  return "\"" + key + "\" is not found";
}

}  // namespace

type_error::type_error(const std::string& path, json::json_type_t expect,
                       json::json_type_t actual)
    : config_error(path, MakeTypeErrorMessage(expect, actual)),
      expect_(expect),
      actual_(actual) {
}

type_error::~type_error() throw () {
}

out_of_range::out_of_range(const std::string& path, size_t size, size_t index)
    : config_error(path, MakeOutOfRangeMessage(size, index)),
      size_(size),
      index_(index) {
}

out_of_range::~out_of_range() throw () {
}

not_found::not_found(const std::string& path, const std::string& key)
    : config_error(path, MakeNotFoundMessage(key)),
      key_(key) {
}

not_found::~not_found() throw () {
}

cast_check_error::cast_check_error(
    const std::vector<pfi::lang::shared_ptr<config_error> >& errors)
    : errors_(errors.begin(), errors.end()) {
}

cast_check_error::~cast_check_error() throw () {
}

}  // jsonconfig
}  // jubatus
<commit_msg>fix common/jsonconfig style for cpplint<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "exception.hpp"

#include <string>
#include <vector>

using std::string;
using pfi::text::json::json;

namespace jubatus {
namespace jsonconfig {

config_error::config_error(const std::string& path, const std::string& message)
    : path_(path),
      message_(message + " (" + path_ + ")") {
}

config_error::~config_error() throw () {
}

namespace {

const char* TypeToName(json::json_type_t t) {
  switch (t) {
    case json::Null:
      return "Null";
    case json::Integer:
      return "Integer";
    case json::Float:
      return "Float";
    case json::Bool:
      return "Bool";
    case json::String:
      return "String";
    case json::Array:
      return "Array";
    case json::Object:
      return "Object";
    default:
      return "Unknown Type";
  }
}

std::string MakeTypeErrorMessage(json::json_type_t expect,
                                 json::json_type_t actual) {
  return string(TypeToName(expect)) + " is expected, but " + TypeToName(actual)
      + " is given.";
}

std::string MakeOutOfRangeMessage(size_t size, size_t index) {
  std::ostringstream os;
  os << "Out of range 0.." << size << ": " << index;
  return os.str();
}

std::string MakeNotFoundMessage(const std::string& key) {
  return "\"" + key + "\" is not found";
}

}  // namespace

type_error::type_error(const std::string& path, json::json_type_t expect,
                       json::json_type_t actual)
    : config_error(path, MakeTypeErrorMessage(expect, actual)),
      expect_(expect),
      actual_(actual) {
}

type_error::~type_error() throw () {
}

out_of_range::out_of_range(const std::string& path, size_t size, size_t index)
    : config_error(path, MakeOutOfRangeMessage(size, index)),
      size_(size),
      index_(index) {
}

out_of_range::~out_of_range() throw () {
}

not_found::not_found(const std::string& path, const std::string& key)
    : config_error(path, MakeNotFoundMessage(key)),
      key_(key) {
}

not_found::~not_found() throw () {
}

cast_check_error::cast_check_error(
    const std::vector<pfi::lang::shared_ptr<config_error> >& errors)
    : errors_(errors.begin(), errors.end()) {
}

cast_check_error::~cast_check_error() throw () {
}

}  // namespace jsonconfig
}  // namespace jubatus
<|endoftext|>


<commit_before>
/* COptMethodSA code */

/***************************************************************************************
 * This is the implementation of the Simulated Annealing for Optimization.  The
 * class is inherited from the COptAlgorithm class
 *
 *       Implemented by Dingjun Chen
 *  Starting Date: 09/22/03
 *
 ***************************************************************************************/

#define BESTFOUNDSOFAR 2
#define NumDirection 10
#define TRUE 1
#define FALSE 0
#define PI 3.1415926

#include <vector>

#include "copasi.h"
#include "COptMethod.h"
#include "COptMethodSA.h"
#include "CRealProblem.h"
#include "randomGenerator/CRandom.h"

COptMethodSA::COptMethodSA():
    COptMethod()
{
  setName("SimulatedAnnealing");
  mTypeEnum = COptMethod::SimulatedAnnealing;
  setType(COptMethod::TypeName[mTypeEnum]);

  add("SimulatedAnnealing.Iterations", 10000, CParameter::UINT);
  add("SimulatedAnnealing.RandomGenerator.Type", CRandom::mt19937, CParameter::INT);
  add("SimulatedAnnealing.RandomGenerator.Seed", 0, CParameter::INT);
}

COptMethodSA::COptMethodSA(const COptMethodSA & src):
    COptMethod(src)
{}

/**
 * Destructor
 */
COptMethodSA::~COptMethodSA(){}

/**
 * Optimizer Function
 * Returns: nothing
 */

C_INT32 COptMethodSA::optimise()
{
  C_FLOAT64 la;
  C_INT32 NumSignificantPoint, NumTempChange, NumIteration = (C_INT32) getValue("SimulatedAnnealing.Iterations");
  C_INT32 j, NumParameter = mParameters->size();

  //variable settings neccessary for SA
  CVector<double> candparameter(NumParameter);  //one-dimentional array of candidate value for parameters
  double candFuncValue;                // candidate value of objective function

  CVector<double> thisparameter(NumParameter);  //current parameters
  double thisFuncValue;                //current value of the objective function

  CVector <double> newparameter(NumParameter);   //new parameter value
  double newFuncValue;     //function value of new point

  CVector <double> step(NumParameter);   //array of maximum steps for each parameter
  CVector <int> NumStepAccep(NumParameter);       //number of steps accepted

  double TempDecreaseRate = 0.85; //temperature decrease rate
  double BoltzmannConstant = 1.0; //Boltzmann constant

  double InitialTemp = 1.0; //initial temperature
  double t;  //current temperature

  double ConvgCriterion = 0.00001; // convergence criterion or program termination criterion
  double ChangeValue, EnergyDifference;

  CVector <double> fk(BESTFOUNDSOFAR);
  bool ready, linear;

  /* Create a random number generator */
  CRandom::Type Type;
  Type = (CRandom::Type) (C_INT32) getValue("SimulatedAnnealing.RandomGenerator.Type");
  unsigned C_INT32 Seed;
  Seed = (unsigned C_INT32) getValue("SimulatedAnnealing.RandomGenerator.Seed");
  CRandom * pRand = CRandom::createGenerator(Type, Seed);

  assert(pRand);

  double * Minimum = mParameterMin->array();
  double * Maximum = mParameterMax->array();
  double * Parameter = mParameters->array();

  //dump_datafile_init()

  //inital temperature
  t = InitialTemp;

  //inital point
  NumSignificantPoint = 0;

  //generate initial parameters randomly
  for (j = 0; j < NumParameter; j++)
    {
      linear = false;
      la = 1.0;

      if (Minimum[j] == 0.0) Minimum[j] = DBL_EPSILON;

      if ((Maximum[j] <= 0.0) || (Minimum[j] <= 0.0)) linear = true;

      else
        {
          la = log10(Maximum[j]) - log10(Minimum[j]);
          if (la < 1.8) linear = true;
        }

      if (linear)
        Parameter[j] =
          Minimum[j] + pRand->getRandomCC() * (Maximum[j] - Minimum[j]);
      else
        Parameter[j] = Minimum[j] * pow(10, la * pRand->getRandomCC());
    } //  Initialization ends

  for (int kk = 0; kk < NumParameter; kk++)
    candparameter[kk] = thisparameter[kk] = newparameter[kk] = Parameter[kk];

  // calculate the function fitness value
  double FitnessValue = mOptProblem->calculate();
  thisFuncValue = candFuncValue = FitnessValue;

  //Remember them
  for (int mm = 0; mm < BESTFOUNDSOFAR; mm++) fk[mm] = thisFuncValue;

  //initial step sizes
  for (int jj = 0; jj < NumParameter; jj++)
    {
      NumStepAccep[jj] = 0;
      step[jj] = fabs(candparameter[jj]);
    }

  //no temperature reductions yet
  NumTempChange = 0;

  do
    {
      for (int ff = 0; ff < NumIteration; ff++) //step adjustments
        {
          std::cout << "New iteration begins ......" << std::endl;
          std::cout << "Current Temperature: " << t << std::endl;
          std::cout << "Number of Temperature Change: " << NumTempChange << std::endl;

          for (j = 0; j < NumDirection; j++) // adjustment in all directions
            {
              for (int hh = 0; hh < NumParameter; hh++)
                {
                  // ChangeValue=tan(2*PI*rand()/RAND_MAX)*(t/pow(pow(2,2.0)+t*t,(NumParameter+1)/2.0));
                  ChangeValue = tan(2 * PI * pRand->getRandomCC()) * (t / pow(pow(2, 2.0) + t * t, (NumParameter + 1) / 2.0));
                  newparameter[hh] = thisparameter[hh] + step[hh] * ChangeValue;

                  if (newparameter[hh] < Minimum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);
                  if (newparameter[hh] > Maximum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);
                  for (int exchange = 0; exchange < NumParameter; exchange++)
                    {
                      Parameter[exchange] = newparameter[exchange];
                    }

                  // calculate the function value
                  double FitnessValue = mOptProblem->calculate();
                  newFuncValue = FitnessValue;

                  //Calculate the energy difference
                  EnergyDifference = newFuncValue - thisFuncValue;

                  //keep newparameter if energy is reduced
                  if (newFuncValue <= thisFuncValue)
                    {
                      for (int exchange = 0; exchange < NumParameter; exchange++)
                        {
                          thisparameter[exchange] = newparameter[exchange];
                        }
                      thisFuncValue = newFuncValue;

                      NumSignificantPoint++; // a new point counted
                      NumStepAccep[hh]++; //a new point in this coordinate counted

                      if (thisFuncValue < candFuncValue)
                        {
                          for (int aa = 0; aa < NumParameter; aa++)
                            Parameter[aa] = candparameter[aa] = thisparameter[aa];
                          candFuncValue = thisFuncValue;

                          if (!mOptProblem->checkFunctionalConstraints())
                            continue;

                          //set the  best function value
                          mOptProblem->setBestValue(candFuncValue);
                          std::cout << "the Best value (" << NumSignificantPoint << "): " << candFuncValue << std::endl;

                          //store the combination of the best parameter values found so far at current temperature
                          mOptProblem->getBestParameter() = *mParameters;

                          std::cout << "the Best Parameters: (";
                          for (int kk = 0; kk < mOptProblem->getParameterNum(); kk++)
                            std::cout << mOptProblem->getParameter(kk) << ", ";

                          std::cout << ")" << std::endl;
                        }
                    }
                  else
                    {
                      //keep newparameter with probability, if newFuncValue is increased
                      double Probability = exp(-(newFuncValue - thisFuncValue) / (BoltzmannConstant * t));
                      if (Probability > pRand->getRandomCC())
                        {
                          //Keep the new point
                          for (int exchange = 0; exchange < NumParameter; exchange++)
                            {
                              thisparameter[exchange] = newparameter[exchange];
                            }
                          thisFuncValue = newFuncValue;
                          NumSignificantPoint++; // a new point counted
                          NumStepAccep[hh]++; //a new point in this coordinate counted
                        }
                    }
                }
            }

          //update the step sizes
          for (int nn = 0; nn < NumParameter; nn++)
            {
              double StepAdjustment = (double) NumStepAccep[nn] / (double)NumDirection;
              if (StepAdjustment > 0.6) step[nn] *= 1 + 5 * (StepAdjustment - 0.6);
              if (StepAdjustment < 0.4) step[nn] /= 1 + 5 * (0.4 - StepAdjustment);
              NumStepAccep[nn] = 0;
            }
        }

      //update the temperature
      t *= TempDecreaseRate;
      NumTempChange++;

      // if this is the first cycle then ignore the convergence test
      if (NumTempChange == 1) ready = FALSE;
      else
        {
          ready = TRUE;
          //check if there is not much change for termination criterion since last BESTFOUNDSOFAR times
          for (int ii = 0; ii < BESTFOUNDSOFAR; ii++)
            if (fabs(fk[ii] - thisFuncValue) > ConvgCriterion)
              {
                ready = FALSE;
                break;
              }
          if (!ready)
            {
              for (int aa = 0; aa < BESTFOUNDSOFAR - 1; aa++)
                fk[aa] = fk[aa + 1];
              fk[BESTFOUNDSOFAR - 1] = thisFuncValue;
            }
          else
            //check the termination criterion of not much larger than last optimal
            if (fabs(thisFuncValue - candFuncValue) > ConvgCriterion)ready = FALSE;
        }

      if (!ready)
        {
          NumSignificantPoint++;
          for (int kk = 0; kk < NumParameter; kk++)
            thisparameter[kk] = candparameter[kk];
          thisFuncValue = candFuncValue;
        }
    }
  while (!ready); // do-while loop ends

  pdelete(pRand);
  return 0;
}
<commit_msg>Fixed definition of PI.<commit_after>
/* COptMethodSA code */

/***************************************************************************************
 * This is the implementation of the Simulated Annealing for Optimization.  The
 * class is inherited from the COptAlgorithm class
 *
 *       Implemented by Dingjun Chen
 *  Starting Date: 09/22/03
 *
 ***************************************************************************************/

#define BESTFOUNDSOFAR 2
#define NumDirection 10
#define TRUE 1
#define FALSE 0
// #define PI 3.1415926

#include <vector>
#include <math.h>

#include "copasi.h"
#include "COptMethod.h"
#include "COptMethodSA.h"
#include "CRealProblem.h"
#include "randomGenerator/CRandom.h"

static double PI = 4.0 * atan(1.0);

COptMethodSA::COptMethodSA():
    COptMethod()
{
  setName("SimulatedAnnealing");
  mTypeEnum = COptMethod::SimulatedAnnealing;
  setType(COptMethod::TypeName[mTypeEnum]);

  add("SimulatedAnnealing.Iterations", 10000, CParameter::UINT);
  add("SimulatedAnnealing.RandomGenerator.Type", CRandom::mt19937, CParameter::INT);
  add("SimulatedAnnealing.RandomGenerator.Seed", 0, CParameter::INT);
}

COptMethodSA::COptMethodSA(const COptMethodSA & src):
    COptMethod(src)
{}

/**
 * Destructor
 */
COptMethodSA::~COptMethodSA(){}

/**
 * Optimizer Function
 * Returns: nothing
 */

C_INT32 COptMethodSA::optimise()
{
  C_FLOAT64 la;
  C_INT32 NumSignificantPoint, NumTempChange, NumIteration = (C_INT32) getValue("SimulatedAnnealing.Iterations");
  C_INT32 j, NumParameter = mParameters->size();

  //variable settings neccessary for SA
  CVector<double> candparameter(NumParameter);  //one-dimentional array of candidate value for parameters
  double candFuncValue;                // candidate value of objective function

  CVector<double> thisparameter(NumParameter);  //current parameters
  double thisFuncValue;                //current value of the objective function

  CVector <double> newparameter(NumParameter);   //new parameter value
  double newFuncValue;     //function value of new point

  CVector <double> step(NumParameter);   //array of maximum steps for each parameter
  CVector <int> NumStepAccep(NumParameter);       //number of steps accepted

  double TempDecreaseRate = 0.85; //temperature decrease rate
  double BoltzmannConstant = 1.0; //Boltzmann constant

  double InitialTemp = 1.0; //initial temperature
  double t;  //current temperature

  double ConvgCriterion = 0.00001; // convergence criterion or program termination criterion
  double ChangeValue, EnergyDifference;

  CVector <double> fk(BESTFOUNDSOFAR);
  bool ready, linear;

  /* Create a random number generator */
  CRandom::Type Type;
  Type = (CRandom::Type) (C_INT32) getValue("SimulatedAnnealing.RandomGenerator.Type");
  unsigned C_INT32 Seed;
  Seed = (unsigned C_INT32) getValue("SimulatedAnnealing.RandomGenerator.Seed");
  CRandom * pRand = CRandom::createGenerator(Type, Seed);

  assert(pRand);

  double * Minimum = mParameterMin->array();
  double * Maximum = mParameterMax->array();
  double * Parameter = mParameters->array();

  //dump_datafile_init()

  //inital temperature
  t = InitialTemp;

  //inital point
  NumSignificantPoint = 0;

  //generate initial parameters randomly
  for (j = 0; j < NumParameter; j++)
    {
      linear = false;
      la = 1.0;

      if (Minimum[j] == 0.0) Minimum[j] = DBL_EPSILON;

      if ((Maximum[j] <= 0.0) || (Minimum[j] <= 0.0)) linear = true;

      else
        {
          la = log10(Maximum[j]) - log10(Minimum[j]);
          if (la < 1.8) linear = true;
        }

      if (linear)
        Parameter[j] =
          Minimum[j] + pRand->getRandomCC() * (Maximum[j] - Minimum[j]);
      else
        Parameter[j] = Minimum[j] * pow(10, la * pRand->getRandomCC());
    } //  Initialization ends

  for (int kk = 0; kk < NumParameter; kk++)
    candparameter[kk] = thisparameter[kk] = newparameter[kk] = Parameter[kk];

  // calculate the function fitness value
  double FitnessValue = mOptProblem->calculate();
  thisFuncValue = candFuncValue = FitnessValue;

  //Remember them
  for (int mm = 0; mm < BESTFOUNDSOFAR; mm++) fk[mm] = thisFuncValue;

  //initial step sizes
  for (int jj = 0; jj < NumParameter; jj++)
    {
      NumStepAccep[jj] = 0;
      step[jj] = fabs(candparameter[jj]);
    }

  //no temperature reductions yet
  NumTempChange = 0;

  do
    {
      for (int ff = 0; ff < NumIteration; ff++) //step adjustments
        {
          std::cout << "New iteration begins ......" << std::endl;
          std::cout << "Current Temperature: " << t << std::endl;
          std::cout << "Number of Temperature Change: " << NumTempChange << std::endl;

          for (j = 0; j < NumDirection; j++) // adjustment in all directions
            {
              for (int hh = 0; hh < NumParameter; hh++)
                {
                  // ChangeValue=tan(2*PI*rand()/RAND_MAX)*(t/pow(pow(2,2.0)+t*t,(NumParameter+1)/2.0));
                  ChangeValue = tan(2 * PI * pRand->getRandomCC()) * (t / pow(pow(2, 2.0) + t * t, (NumParameter + 1) / 2.0));
                  newparameter[hh] = thisparameter[hh] + step[hh] * ChangeValue;

                  if (newparameter[hh] < Minimum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);
                  if (newparameter[hh] > Maximum[hh]) newparameter[hh] = Minimum[hh] + pRand->getRandomCC() * (Maximum[hh] - Minimum[hh]);
                  for (int exchange = 0; exchange < NumParameter; exchange++)
                    {
                      Parameter[exchange] = newparameter[exchange];
                    }

                  // calculate the function value
                  double FitnessValue = mOptProblem->calculate();
                  newFuncValue = FitnessValue;

                  //Calculate the energy difference
                  EnergyDifference = newFuncValue - thisFuncValue;

                  //keep newparameter if energy is reduced
                  if (newFuncValue <= thisFuncValue)
                    {
                      for (int exchange = 0; exchange < NumParameter; exchange++)
                        {
                          thisparameter[exchange] = newparameter[exchange];
                        }
                      thisFuncValue = newFuncValue;

                      NumSignificantPoint++; // a new point counted
                      NumStepAccep[hh]++; //a new point in this coordinate counted

                      if (thisFuncValue < candFuncValue)
                        {
                          for (int aa = 0; aa < NumParameter; aa++)
                            Parameter[aa] = candparameter[aa] = thisparameter[aa];
                          candFuncValue = thisFuncValue;

                          if (!mOptProblem->checkFunctionalConstraints())
                            continue;

                          //set the  best function value
                          mOptProblem->setBestValue(candFuncValue);
                          std::cout << "the Best value (" << NumSignificantPoint << "): " << candFuncValue << std::endl;

                          //store the combination of the best parameter values found so far at current temperature
                          mOptProblem->getBestParameter() = *mParameters;

                          std::cout << "the Best Parameters: (";
                          for (int kk = 0; kk < mOptProblem->getParameterNum(); kk++)
                            std::cout << mOptProblem->getParameter(kk) << ", ";

                          std::cout << ")" << std::endl;
                        }
                    }
                  else
                    {
                      //keep newparameter with probability, if newFuncValue is increased
                      double Probability = exp(-(newFuncValue - thisFuncValue) / (BoltzmannConstant * t));
                      if (Probability > pRand->getRandomCC())
                        {
                          //Keep the new point
                          for (int exchange = 0; exchange < NumParameter; exchange++)
                            {
                              thisparameter[exchange] = newparameter[exchange];
                            }
                          thisFuncValue = newFuncValue;
                          NumSignificantPoint++; // a new point counted
                          NumStepAccep[hh]++; //a new point in this coordinate counted
                        }
                    }
                }
            }

          //update the step sizes
          for (int nn = 0; nn < NumParameter; nn++)
            {
              double StepAdjustment = (double) NumStepAccep[nn] / (double)NumDirection;
              if (StepAdjustment > 0.6) step[nn] *= 1 + 5 * (StepAdjustment - 0.6);
              if (StepAdjustment < 0.4) step[nn] /= 1 + 5 * (0.4 - StepAdjustment);
              NumStepAccep[nn] = 0;
            }
        }

      //update the temperature
      t *= TempDecreaseRate;
      NumTempChange++;

      // if this is the first cycle then ignore the convergence test
      if (NumTempChange == 1) ready = FALSE;
      else
        {
          ready = TRUE;
          //check if there is not much change for termination criterion since last BESTFOUNDSOFAR times
          for (int ii = 0; ii < BESTFOUNDSOFAR; ii++)
            if (fabs(fk[ii] - thisFuncValue) > ConvgCriterion)
              {
                ready = FALSE;
                break;
              }
          if (!ready)
            {
              for (int aa = 0; aa < BESTFOUNDSOFAR - 1; aa++)
                fk[aa] = fk[aa + 1];
              fk[BESTFOUNDSOFAR - 1] = thisFuncValue;
            }
          else
            //check the termination criterion of not much larger than last optimal
            if (fabs(thisFuncValue - candFuncValue) > ConvgCriterion)ready = FALSE;
        }

      if (!ready)
        {
          NumSignificantPoint++;
          for (int kk = 0; kk < NumParameter; kk++)
            thisparameter[kk] = candparameter[kk];
          thisFuncValue = candFuncValue;
        }
    }
  while (!ready); // do-while loop ends

  pdelete(pRand);
  return 0;
}
<|endoftext|>