<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2007-2008 The Florida State University
 * 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 the copyright holders 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.
 *
 * Authors: Stephen Hines
 */

#include "arch/arm/insts/macromem.hh"
#include "arch/arm/decoder.hh"

using namespace ArmISAInst;

namespace ArmISA
{

MacroMemOp::MacroMemOp(const char *mnem, ExtMachInst machInst,
                       OpClass __opClass, IntRegIndex rn,
                       bool index, bool up, bool user, bool writeback,
                       bool load, uint32_t reglist) :
    PredMacroOp(mnem, machInst, __opClass)
{
    uint32_t regs = reglist;
    uint32_t ones = number_of_ones(reglist);
    // Remember that writeback adds a uop
    numMicroops = ones + (writeback ? 1 : 0) + 1;
    microOps = new StaticInstPtr[numMicroops];
    uint32_t addr = 0;

    if (!up)
        addr = (ones << 2) - 4;

    if (!index)
        addr += 4;

    StaticInstPtr *uop = microOps;
    StaticInstPtr wbUop;
    if (writeback) {
        if (up) {
            wbUop = new MicroAddiUop(machInst, rn, rn, ones * 4);
        } else {
            wbUop = new MicroSubiUop(machInst, rn, rn, ones * 4);
        }
    }

    // Add 0 to Rn and stick it in ureg0.
    // This is equivalent to a move.
    *uop = new MicroAddiUop(machInst, INTREG_UREG0, rn, 0);

    // Write back at the start for loads. This covers the ldm exception return
    // case where the base needs to be written in the old mode. Stores may need
    // the original value of the base, but they don't change mode and can
    // write back at the end like before.
    if (load && writeback) {
        *++uop = wbUop;
    }

    unsigned reg = 0;
    bool force_user = user & !bits(reglist, 15);
    bool exception_ret = user & bits(reglist, 15);

    for (int i = 0; i < ones; i++) {
        // Find the next register.
        while (!bits(regs, reg))
            reg++;
        replaceBits(regs, reg, 0);

        unsigned regIdx = reg;
        if (force_user) {
            regIdx = intRegInMode(MODE_USER, regIdx);
        }

        if (load) {
            if (reg == INTREG_PC && exception_ret) {
                // This must be the exception return form of ldm.
                *++uop = new MicroLdrRetUop(machInst, regIdx,
                                           INTREG_UREG0, up, addr);
            } else {
                *++uop = new MicroLdrUop(machInst, regIdx,
                                        INTREG_UREG0, up, addr);
            }
        } else {
            *++uop = new MicroStrUop(machInst, regIdx, INTREG_UREG0, up, addr);
        }

        if (up)
            addr += 4;
        else
            addr -= 4;
    }

    if (!load && writeback) {
        *++uop = wbUop;
    }

    (*uop)->setLastMicroop();

    for (StaticInstPtr *curUop = microOps;
            !(*curUop)->isLastMicroop(); curUop++) {
        MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
        assert(uopPtr);
        uopPtr->setDelayedCommit();
    }
}

MacroVFPMemOp::MacroVFPMemOp(const char *mnem, ExtMachInst machInst,
                             OpClass __opClass, IntRegIndex rn,
                             RegIndex vd, bool single, bool up,
                             bool writeback, bool load, uint32_t offset) :
    PredMacroOp(mnem, machInst, __opClass)
{
    int i = 0;

    // The lowest order bit selects fldmx (set) or fldmd (clear). These seem
    // to be functionally identical except that fldmx is deprecated. For now
    // we'll assume they're otherwise interchangable.
    int count = (single ? offset : (offset / 2));
    if (count == 0 || count > NumFloatArchRegs)
        warn_once("Bad offset field for VFP load/store multiple.\n");
    if (count == 0) {
        // Force there to be at least one microop so the macroop makes sense.
        writeback = true;
    }
    if (count > NumFloatArchRegs)
        count = NumFloatArchRegs;

    numMicroops = count * (single ? 1 : 2) + (writeback ? 1 : 0);
    microOps = new StaticInstPtr[numMicroops];

    uint32_t addr = 0;

    if (!up)
        addr = 4 * offset;

    bool tempUp = up;
    for (int j = 0; j < count; j++) {
        if (load) {
            microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn,
                                              tempUp, addr);
            if (!single)
                microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn,
                                                  tempUp, addr + 4);
        } else {
            microOps[i++] = new MicroStrFpUop(machInst, vd++, rn,
                                              tempUp, addr);
            if (!single)
                microOps[i++] = new MicroStrFpUop(machInst, vd++, rn,
                                                  tempUp, addr + 4);
        }
        if (!tempUp) {
            addr -= (single ? 4 : 8);
            // The microops don't handle negative displacement, so turn if we
            // hit zero, flip polarity and start adding.
            if (addr == 0) {
                tempUp = true;
            }
        } else {
            addr += (single ? 4 : 8);
        }
    }

    if (writeback) {
        if (up) {
            microOps[i++] =
                new MicroAddiUop(machInst, rn, rn, 4 * offset);
        } else {
            microOps[i++] =
                new MicroSubiUop(machInst, rn, rn, 4 * offset);
        }
    }

    assert(numMicroops == i);
    microOps[numMicroops - 1]->setLastMicroop();

    for (StaticInstPtr *curUop = microOps;
            !(*curUop)->isLastMicroop(); curUop++) {
        MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
        assert(uopPtr);
        uopPtr->setDelayedCommit();
    }
}

}
<commit_msg>ARM: Fix double precision load/store multiple decrement.<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2007-2008 The Florida State University
 * 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 the copyright holders 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.
 *
 * Authors: Stephen Hines
 */

#include "arch/arm/insts/macromem.hh"
#include "arch/arm/decoder.hh"

using namespace ArmISAInst;

namespace ArmISA
{

MacroMemOp::MacroMemOp(const char *mnem, ExtMachInst machInst,
                       OpClass __opClass, IntRegIndex rn,
                       bool index, bool up, bool user, bool writeback,
                       bool load, uint32_t reglist) :
    PredMacroOp(mnem, machInst, __opClass)
{
    uint32_t regs = reglist;
    uint32_t ones = number_of_ones(reglist);
    // Remember that writeback adds a uop
    numMicroops = ones + (writeback ? 1 : 0) + 1;
    microOps = new StaticInstPtr[numMicroops];
    uint32_t addr = 0;

    if (!up)
        addr = (ones << 2) - 4;

    if (!index)
        addr += 4;

    StaticInstPtr *uop = microOps;
    StaticInstPtr wbUop;
    if (writeback) {
        if (up) {
            wbUop = new MicroAddiUop(machInst, rn, rn, ones * 4);
        } else {
            wbUop = new MicroSubiUop(machInst, rn, rn, ones * 4);
        }
    }

    // Add 0 to Rn and stick it in ureg0.
    // This is equivalent to a move.
    *uop = new MicroAddiUop(machInst, INTREG_UREG0, rn, 0);

    // Write back at the start for loads. This covers the ldm exception return
    // case where the base needs to be written in the old mode. Stores may need
    // the original value of the base, but they don't change mode and can
    // write back at the end like before.
    if (load && writeback) {
        *++uop = wbUop;
    }

    unsigned reg = 0;
    bool force_user = user & !bits(reglist, 15);
    bool exception_ret = user & bits(reglist, 15);

    for (int i = 0; i < ones; i++) {
        // Find the next register.
        while (!bits(regs, reg))
            reg++;
        replaceBits(regs, reg, 0);

        unsigned regIdx = reg;
        if (force_user) {
            regIdx = intRegInMode(MODE_USER, regIdx);
        }

        if (load) {
            if (reg == INTREG_PC && exception_ret) {
                // This must be the exception return form of ldm.
                *++uop = new MicroLdrRetUop(machInst, regIdx,
                                           INTREG_UREG0, up, addr);
            } else {
                *++uop = new MicroLdrUop(machInst, regIdx,
                                        INTREG_UREG0, up, addr);
            }
        } else {
            *++uop = new MicroStrUop(machInst, regIdx, INTREG_UREG0, up, addr);
        }

        if (up)
            addr += 4;
        else
            addr -= 4;
    }

    if (!load && writeback) {
        *++uop = wbUop;
    }

    (*uop)->setLastMicroop();

    for (StaticInstPtr *curUop = microOps;
            !(*curUop)->isLastMicroop(); curUop++) {
        MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
        assert(uopPtr);
        uopPtr->setDelayedCommit();
    }
}

MacroVFPMemOp::MacroVFPMemOp(const char *mnem, ExtMachInst machInst,
                             OpClass __opClass, IntRegIndex rn,
                             RegIndex vd, bool single, bool up,
                             bool writeback, bool load, uint32_t offset) :
    PredMacroOp(mnem, machInst, __opClass)
{
    int i = 0;

    // The lowest order bit selects fldmx (set) or fldmd (clear). These seem
    // to be functionally identical except that fldmx is deprecated. For now
    // we'll assume they're otherwise interchangable.
    int count = (single ? offset : (offset / 2));
    if (count == 0 || count > NumFloatArchRegs)
        warn_once("Bad offset field for VFP load/store multiple.\n");
    if (count == 0) {
        // Force there to be at least one microop so the macroop makes sense.
        writeback = true;
    }
    if (count > NumFloatArchRegs)
        count = NumFloatArchRegs;

    numMicroops = count * (single ? 1 : 2) + (writeback ? 1 : 0);
    microOps = new StaticInstPtr[numMicroops];

    int64_t addr = 0;

    if (!up)
        addr = 4 * offset;

    bool tempUp = up;
    for (int j = 0; j < count; j++) {
        if (load) {
            microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn,
                                              tempUp, addr);
            if (!single)
                microOps[i++] = new MicroLdrFpUop(machInst, vd++, rn, tempUp,
                                                  addr + (up ? 4 : -4));
        } else {
            microOps[i++] = new MicroStrFpUop(machInst, vd++, rn,
                                              tempUp, addr);
            if (!single)
                microOps[i++] = new MicroStrFpUop(machInst, vd++, rn, tempUp,
                                                  addr + (up ? 4 : -4));
        }
        if (!tempUp) {
            addr -= (single ? 4 : 8);
            // The microops don't handle negative displacement, so turn if we
            // hit zero, flip polarity and start adding.
            if (addr <= 0) {
                tempUp = true;
                addr = -addr;
            }
        } else {
            addr += (single ? 4 : 8);
        }
    }

    if (writeback) {
        if (up) {
            microOps[i++] =
                new MicroAddiUop(machInst, rn, rn, 4 * offset);
        } else {
            microOps[i++] =
                new MicroSubiUop(machInst, rn, rn, 4 * offset);
        }
    }

    assert(numMicroops == i);
    microOps[numMicroops - 1]->setLastMicroop();

    for (StaticInstPtr *curUop = microOps;
            !(*curUop)->isLastMicroop(); curUop++) {
        MicroOp * uopPtr = dynamic_cast<MicroOp *>(curUop->get());
        assert(uopPtr);
        uopPtr->setDelayedCommit();
    }
}

}
<|endoftext|>


<commit_before>#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "../com_intel_vmf_MetadataDesc.h"

using namespace vmf;

static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method)
{
    std::string what = "unknown exception";
    jclass je = 0;

    if (e)
    {
        std::string exception_type = "std::exception";

        if (dynamic_cast<const Exception*>(e))
        {
            exception_type = "vmf::Exception";
            je = env->FindClass("com/intel/vmf/VmfException");
        }

        what = exception_type + ": " + e->what();
    }

    if (!je)
        je = env->FindClass("java/lang/Exception");

    env->ThrowNew(je, what.c_str());

    VMF_LOG_ERROR(what.c_str());
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__ (JNIEnv *, jclass)
{
    return (jlong) new MetadataDesc ();
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: (Ljava/lang/String;J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2J (JNIEnv *env, jclass, jstring mdName, jlong type)
{
    std::string sName (env->GetStringUTFChars (mdName, NULL));
    Variant::Type Type = (Variant::Type) type;
    return (jlong) new MetadataDesc (sName, Type);
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: (Ljava/lang/String;[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs)
{
    std::string sName (env->GetStringUTFChars (mdName, NULL));
    std::vector <FieldDesc> descs;
    jlong* cArray = env->GetLongArrayElements (fieldDescs, 0);
    jsize len = env->GetArrayLength (fieldDescs);

    for (int i = 0; i < len; i++)
    {
        FieldDesc* pFieldDesc = (FieldDesc*) cArray[i];
        descs.push_back (*pFieldDesc);
    }

    env->ReleaseLongArrayElements (fieldDescs, cArray, 0);
    return (jlong) new MetadataDesc (sName, descs);
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: (Ljava/lang/String;[J[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs, jlongArray refDescs)
{
    std::string sName (env->GetStringUTFChars (mdName, NULL));
    std::vector <FieldDesc> fdVec;
    std::vector<std::shared_ptr<ReferenceDesc>> rdVec;
    jlong* descArray = env->GetLongArrayElements (fieldDescs, 0);
    jlong* refArray = env->GetLongArrayElements (refDescs, 0);
    jsize lenDescs = env->GetArrayLength (fieldDescs);
    jsize lenRefs = env->GetArrayLength (refDescs);

    for (int i = 0; i < lenDescs; i++)
    {
        FieldDesc* pFieldDesc = (FieldDesc*) descArray[i];
        fdVec.push_back (*pFieldDesc);
    }

    for (int i = 0; i < lenRefs; i++)
    {
       ReferenceDesc* pRefDesc = (ReferenceDesc*) refArray[i];
       std::shared_ptr<ReferenceDesc> spRefDesc(pRefDesc);
       rdVec.push_back (spRefDesc);
    }

    env->ReleaseLongArrayElements (fieldDescs, descArray, 0);
    env->ReleaseLongArrayElements (refDescs, refArray, 0);
    return (jlong) new MetadataDesc (sName, fdVec, rdVec);
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getMetadataName
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getMetadataName (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getMetadataName";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        std::string str = obj->getMetadataName ();
        return env->NewStringUTF (str.c_str());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;

}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getSchemaName
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getSchemaName (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getSchemaName";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        std::string str = obj->getSchemaName ();
        return env->NewStringUTF (str.c_str());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getFields
 * Signature: (J)[Lcom/intel/vmf/FieldDesc;
 */
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFields (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getFields";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        std::vector<FieldDesc> vec = obj->getFields ();
        jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
        jlong* body = env->GetLongArrayElements (nObjs, 0);

        for (std::size_t i = 0; i < vec.size(); i++)
        {
            body[i] = (jlong) new FieldDesc (vec[i].name, vec[i].type, vec[i].optional);
        }

        env->ReleaseLongArrayElements (nObjs, body, 0);
        return nObjs;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getAllReferenceDescs
 * Signature: (J)[Lcom/intel/vmf/ReferenceDesc;
 */
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getAllReferenceDescs (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getAllReferenceDescs";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        std::vector<std::shared_ptr<ReferenceDesc>> vec = obj->getAllReferenceDescs ();
        jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
        jlong* body = env->GetLongArrayElements (nObjs, 0);

        for (std::size_t i = 0; i < vec.size(); i++)
        {
            body[i] = (jlong) vec[i].get();
        }

        env->ReleaseLongArrayElements (nObjs, body, 0);
        return nObjs;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_declareCustomReference
 * Signature: (JLjava/lang/String;Z)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1declareCustomReference (JNIEnv *env, jclass, jlong self, jstring refName, jboolean isUnique)
{
    static const char method_name[] = "MetadataDesc::n_1declareCustomReference";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        obj->declareCustomReference (sName, (isUnique == 1) ? true : false);
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getReferenceDesc
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1getReferenceDesc (JNIEnv *env, jclass, jlong self, jstring refName)
{
    static const char method_name[] = "MetadataDesc::n_1getReferenceDesc";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        return (jlong) (obj->getReferenceDesc (sName)).get();
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getFieldDesc
 * Signature: (JLcom/intel/vmf/FieldDesc;Ljava/lang/String;)Z
 */
JNIEXPORT jboolean JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFieldDesc (JNIEnv *env, jclass, jlong self, jlong fieldDescAddr, jstring fieldName)
{
    static const char method_name[] = "MetadataDesc::n_1getFieldDesc";

    try
    {
        MetadataDesc* obj = (MetadataDesc*) self;
        FieldDesc* fieldDesc = (FieldDesc*) fieldDescAddr;
        std::string sName (env->GetStringUTFChars (fieldName, NULL));
        return (jboolean) obj->getFieldDesc (*fieldDesc, sName);
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_delete
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1delete (JNIEnv *, jclass, jlong self)
{
    delete (MetadataDesc*) self;
}
<commit_msg>Add shared_ptr to JNI MetadataDesc<commit_after>#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "../com_intel_vmf_MetadataDesc.h"

using namespace vmf;

static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method)
{
    std::string what = "unknown exception";
    jclass je = 0;

    if (e)
    {
        std::string exception_type = "std::exception";

        if (dynamic_cast<const Exception*>(e))
        {
            exception_type = "vmf::Exception";
            je = env->FindClass("com/intel/vmf/VmfException");
        }

        what = exception_type + ": " + e->what();
    }

    if (!je)
        je = env->FindClass("java/lang/Exception");

    env->ThrowNew(je, what.c_str());

    VMF_LOG_ERROR(what.c_str());
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__ (JNIEnv *, jclass)
{
    std::shared_ptr<MetadataDesc>* p = new std::shared_ptr<MetadataDesc>(new MetadataDesc());
    return (jlong) p;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: (Ljava/lang/String;J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2J (JNIEnv *env, jclass, jstring mdName, jlong type)
{
    std::string sName (env->GetStringUTFChars (mdName, NULL));

    std::shared_ptr<MetadataDesc>* p = new std::shared_ptr<MetadataDesc>(new MetadataDesc(sName, (Variant::Type) type));
    return (jlong) p;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: (Ljava/lang/String;[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs)
{
    std::string sName (env->GetStringUTFChars (mdName, NULL));
    std::vector <FieldDesc> descs;
    jlong* cArray = env->GetLongArrayElements (fieldDescs, 0);
    jsize len = env->GetArrayLength (fieldDescs);

    for (int i = 0; i < len; i++)
    {
        std::shared_ptr<FieldDesc>* pFieldDesc = (std::shared_ptr<FieldDesc>*)cArray[i];
        descs.push_back (**pFieldDesc);
    }

    env->ReleaseLongArrayElements (fieldDescs, cArray, 0);
    return (jlong) new std::shared_ptr<MetadataDesc>(new MetadataDesc(sName, descs));
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_MetadataDesc
 * Signature: (Ljava/lang/String;[J[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1MetadataDesc__Ljava_lang_String_2_3J_3J (JNIEnv *env, jclass, jstring mdName, jlongArray fieldDescs, jlongArray refDescs)
{
    std::string sName (env->GetStringUTFChars (mdName, NULL));
    std::vector <FieldDesc> fdVec;
    std::vector<std::shared_ptr<ReferenceDesc>> rdVec;
    jlong* descArray = env->GetLongArrayElements (fieldDescs, 0);
    jlong* refArray = env->GetLongArrayElements (refDescs, 0);
    jsize lenDescs = env->GetArrayLength (fieldDescs);
    jsize lenRefs = env->GetArrayLength (refDescs);

    for (int i = 0; i < lenDescs; i++)
    {
        std::shared_ptr<FieldDesc>* pFieldDesc = (std::shared_ptr<FieldDesc>*) descArray[i];
        fdVec.push_back (**pFieldDesc);
    }

    for (int i = 0; i < lenRefs; i++)
    {
       std::shared_ptr<ReferenceDesc>* pRefDesc = (std::shared_ptr<ReferenceDesc>*)refArray[i];
       rdVec.push_back (*pRefDesc);
    }

    env->ReleaseLongArrayElements (fieldDescs, descArray, 0);
    env->ReleaseLongArrayElements (refDescs, refArray, 0);
    return (jlong) new std::shared_ptr<MetadataDesc>(new MetadataDesc(sName, fdVec, rdVec));
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getMetadataName
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getMetadataName (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getMetadataName";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::string str = (*obj)->getMetadataName ();
        return env->NewStringUTF (str.c_str());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;

}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getSchemaName
 * Signature: (J)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_intel_vmf_MetadataDesc_n_1getSchemaName (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getSchemaName";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::string str = (*obj)->getSchemaName ();
        return env->NewStringUTF (str.c_str());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getFields
 * Signature: (J)[Lcom/intel/vmf/FieldDesc;
 */
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFields (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getFields";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::vector<FieldDesc> vec = (*obj)->getFields ();
        jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
        jlong* body = env->GetLongArrayElements (nObjs, 0);

        for (std::size_t i = 0; i < vec.size(); i++)
        {
            body[i] = (jlong) new std::shared_ptr<FieldDesc>(new FieldDesc (vec[i].name, vec[i].type, vec[i].optional));
        }

        env->ReleaseLongArrayElements (nObjs, body, 0);
        return nObjs;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getAllReferenceDescs
 * Signature: (J)[Lcom/intel/vmf/ReferenceDesc;
 */
JNIEXPORT jlongArray JNICALL Java_com_intel_vmf_MetadataDesc_n_1getAllReferenceDescs (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1getAllReferenceDescs";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::vector<std::shared_ptr<ReferenceDesc>> vec = (*obj)->getAllReferenceDescs ();
        jlongArray nObjs = env->NewLongArray ((jsize)vec.size());
        jlong* body = env->GetLongArrayElements (nObjs, 0);

        for (std::size_t i = 0; i < vec.size(); i++)
        {
            body[i] = (jlong) new std::shared_ptr<ReferenceDesc>(new ReferenceDesc(vec[i]->name, vec[i]->isUnique, vec[i]->isCustom));
        }

        env->ReleaseLongArrayElements (nObjs, body, 0);
        return nObjs;
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_declareCustomReference
 * Signature: (JLjava/lang/String;Z)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1declareCustomReference (JNIEnv *env, jclass, jlong self, jstring refName, jboolean isUnique)
{
    static const char method_name[] = "MetadataDesc::n_1declareCustomReference";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        (*obj)->declareCustomReference (sName, (isUnique == 1) ? true : false);
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getReferenceDesc
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataDesc_n_1getReferenceDesc (JNIEnv *env, jclass, jlong self, jstring refName)
{
    static const char method_name[] = "MetadataDesc::n_1getReferenceDesc";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        std::shared_ptr<ReferenceDesc> sp = (*obj)->getReferenceDesc(sName);
        return (jlong) new std::shared_ptr<ReferenceDesc>(new ReferenceDesc (sp->name, sp->isUnique, sp->isCustom));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_getFieldDesc
 * Signature: (JLcom/intel/vmf/FieldDesc;Ljava/lang/String;)Z
 */
JNIEXPORT jboolean JNICALL Java_com_intel_vmf_MetadataDesc_n_1getFieldDesc (JNIEnv *env, jclass, jlong self, jlong fieldDescAddr, jstring fieldName)
{
    static const char method_name[] = "MetadataDesc::n_1getFieldDesc";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        std::shared_ptr<FieldDesc>* fieldDesc = (std::shared_ptr<FieldDesc>*)fieldDescAddr;
        std::string sName (env->GetStringUTFChars (fieldName, NULL));
        return (jboolean) (*obj)->getFieldDesc (**fieldDesc, sName);
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataDesc
 * Method:    n_delete
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataDesc_n_1delete (JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataDesc::n_1delete";

    try
    {
        std::shared_ptr<MetadataDesc>* obj = (std::shared_ptr<MetadataDesc>*)self;
        delete obj;
    }
    catch (const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }
}
<|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>
#include "configure.h"

using namespace tiramisu;

int main(int argc, char **argv)
{
    tiramisu::init("relu_tiramisu");

    var i("i", 0, 4);
    input parameters("parameters", {i}, p_float32);

    constant C_N("C_N", cast(p_int32, parameters(0)));
    constant C_FIn("C_FIn", cast(p_int32, parameters(1)));
    constant C_BATCH_SIZE("C_BATCH_SIZE", cast(p_int32, parameters(2)));

    var x("x", 0, C_N), y("y", 0, C_N), z("z", 0, C_FIn), n("n", 0, C_BATCH_SIZE);

    input c_input("c_input", {n, z, y, x}, p_float32);
    computation c_relu("c_relu", {n, z, y, x}, expr(o_max, c_input(n, z, y, x), expr((float)0)) + parameters(3) * expr(o_min, c_input(n, z, y, x), expr((float)0)));

    // Layer II

    int o_block = 4;
    int vec_len = N / 4;
    int y_block = N / 4;

    if (LARGE_DATA_SET)
    {
        c_relu.tag_parallel_level(0);
        c_relu.split(3, vec_len);
        c_relu.tag_vector_level(4, vec_len);
        c_relu.tag_unroll_level(5);
    }
    else if (MEDIUM_DATA_SET)
    {
        c_relu.split(3, y_block);
        c_relu.tag_vector_level(5, vec_len);
        c_relu.tag_unroll_level(6);
    }
    else if (SMALL_DATA_SET)
    {
        c_relu.tag_parallel_level(0);
        c_relu.split(3, 32);
        c_relu.tag_vector_level(4, 32);
        c_relu.tag_unroll_level(5);
    }

    // Layer III

    buffer input_buff("input_buff", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N), expr(C_N)}, p_float32, a_input);
    buffer parameters_buff("parameters_buff", {expr(4)}, p_float32, a_input);
    buffer output_buff("output_buff", {expr(C_BATCH_SIZE), expr(C_FIn), expr(C_N), expr(C_N)}, p_float32, a_output);

    c_input.store_in(&input_buff);
    c_relu.store_in(&output_buff);
    parameters.store_in(&parameters_buff);

    tiramisu::codegen({&input_buff, &parameters_buff, &output_buff}, "relu_layer_generator_tiramisu.o");

    return 0;
}
<commit_msg>Delete relu_layer_generator_tiramisu.cpp<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "Client.hpp"

#define OT_METHOD "opentxs::notary::Client::"

namespace opentxs::notary
{
Client::Client(
    const opentxs::api::client::Manager& client,
    const opentxs::api::server::Manager& server,
    const int network)
    : client_(client)
    , server_(server)
    , network_(network)
    , server_nym_callback_(network::zeromq::ListenCallback::Factory(
          std::bind(&Client::server_nym_updated, this, std::placeholders::_1)))
    , server_nym_subscriber_(
          server_.ZeroMQ().SubscribeSocket(server_nym_callback_))
{
    const auto started =
        server_nym_subscriber_->Start(server_.Endpoints().NymDownload());

    OT_ASSERT(started);

    test_nym();
    migrate_contract();
    set_address_type();
    client_.Sync().StartIntroductionServer(server_.NymID());
    client_.Sync().SchedulePublishServerContract(
        server_.NymID(), client_.Sync().IntroductionServer(), server_.ID());
}

void Client::import_nym() const
{
    const auto serverNym = server_.Wallet().Nym(server_.NymID());

    OT_ASSERT(serverNym);

    proto::HDPath path{};
    const auto havePath = serverNym->Path(path);

    OT_ASSERT(havePath);

    const auto seedID = Identifier::Factory(path.root());
    OTPassword words{}, passphrase{};
    words.setPassword(server_.Seeds().Words(seedID->str()));
    passphrase.setPassword(server_.Seeds().Passphrase(seedID->str()));
    const auto imported = client_.Seeds().ImportSeed(words, passphrase);

    OT_ASSERT(imported == seedID->str());
    OT_ASSERT(2 == path.child_size());

    // TODO const auto index = path.child(1);

    // TODO OT_ASSERT(0 == index);

    {
#if OT_CRYPTO_SUPPORTED_KEY_HD
        NymParameters nymParameters(proto::CREDTYPE_HD);
        nymParameters.SetSeed(seedID->str());
        nymParameters.SetNym(0);
        nymParameters.SetDefault(false);
#else
        NymParameters nymParameters(proto::CREDTYPE_LEGACY);
#endif
        auto clientNym = client_.Wallet().Nym(nymParameters);

        OT_ASSERT(clientNym);
        OT_ASSERT(clientNym->CompareID(server_.NymID()));
    }
}

void Client::migrate_contract() const
{
    const auto serverContract = server_.Wallet().Server(server_.ID());

    OT_ASSERT(serverContract);

    auto clientContract =
        client_.Wallet().Server(serverContract->PublicContract());

    OT_ASSERT(clientContract);
}

void Client::migrate_nym() const
{
    const auto serverNym = server_.Wallet().Nym(server_.NymID());

    OT_ASSERT(serverNym);

    auto clientNym = client_.Wallet().mutable_Nym(server_.NymID());
    clientNym.SetContactData(serverNym->Claims().Serialize());
}

void Client::server_nym_updated(const network::zeromq::Message& message) const
{
    if (1 > message.Body().size()) {
        otErr << OT_METHOD << __FUNCTION__ << ": Missing nym ID." << std::endl;

        return;
    }

    const auto& frame = message.Body_at(0);
    const auto id = Identifier::Factory(frame);

    if (server_.NymID() == id) { migrate_nym(); }
}

void Client::set_address_type() const
{
    if (network_ != client_.ZMQ().DefaultAddressType()) {
        bool notUsed{false};
        client_.Config().Set_long(
            "Connection", "preferred_address_type", network_, notUsed);
        client_.Config().Save();
    }
}

void Client::test_nym() const
{
    const auto clientNym = client_.Wallet().Nym(server_.NymID());

    if (false == bool(clientNym)) { import_nym(); }

    migrate_nym();
}
}  // namespace opentxs::notary
<commit_msg>Use OTString to Instantiate String Objects: Client.cpp<commit_after>// Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "Client.hpp"

#define OT_METHOD "opentxs::notary::Client::"

namespace opentxs::notary
{
Client::Client(
    const opentxs::api::client::Manager& client,
    const opentxs::api::server::Manager& server,
    const int network)
    : client_(client)
    , server_(server)
    , network_(network)
    , server_nym_callback_(network::zeromq::ListenCallback::Factory(
          std::bind(&Client::server_nym_updated, this, std::placeholders::_1)))
    , server_nym_subscriber_(
          server_.ZeroMQ().SubscribeSocket(server_nym_callback_))
{
    const auto started =
        server_nym_subscriber_->Start(server_.Endpoints().NymDownload());

    OT_ASSERT(started);

    test_nym();
    migrate_contract();
    set_address_type();
    client_.Sync().StartIntroductionServer(server_.NymID());
    client_.Sync().SchedulePublishServerContract(
        server_.NymID(), client_.Sync().IntroductionServer(), server_.ID());
}

void Client::import_nym() const
{
    const auto serverNym = server_.Wallet().Nym(server_.NymID());

    OT_ASSERT(serverNym);

    proto::HDPath path{};
    const auto havePath = serverNym->Path(path);

    OT_ASSERT(havePath);

    const auto seedID = Identifier::Factory(path.root());
    OTPassword words{}, passphrase{};
    words.setPassword(server_.Seeds().Words(seedID->str()));
    passphrase.setPassword(server_.Seeds().Passphrase(seedID->str()));
    const auto imported = client_.Seeds().ImportSeed(words, passphrase);

    OT_ASSERT(imported == seedID->str());
    OT_ASSERT(2 == path.child_size());

    // TODO const auto index = path.child(1);

    // TODO OT_ASSERT(0 == index);

    {
#if OT_CRYPTO_SUPPORTED_KEY_HD
        NymParameters nymParameters(proto::CREDTYPE_HD);
        nymParameters.SetSeed(seedID->str());
        nymParameters.SetNym(0);
        nymParameters.SetDefault(false);
#else
        NymParameters nymParameters(proto::CREDTYPE_LEGACY);
#endif
        auto clientNym = client_.Wallet().Nym(nymParameters);

        OT_ASSERT(clientNym);
        OT_ASSERT(clientNym->CompareID(server_.NymID()));
    }
}

void Client::migrate_contract() const
{
    const auto serverContract = server_.Wallet().Server(server_.ID());

    OT_ASSERT(serverContract);

    auto clientContract =
        client_.Wallet().Server(serverContract->PublicContract());

    OT_ASSERT(clientContract);
}

void Client::migrate_nym() const
{
    const auto serverNym = server_.Wallet().Nym(server_.NymID());

    OT_ASSERT(serverNym);

    auto clientNym = client_.Wallet().mutable_Nym(server_.NymID());
    clientNym.SetContactData(serverNym->Claims().Serialize());
}

void Client::server_nym_updated(const network::zeromq::Message& message) const
{
    if (1 > message.Body().size()) {
        otErr << OT_METHOD << __FUNCTION__ << ": Missing nym ID." << std::endl;

        return;
    }

    const auto& frame = message.Body_at(0);
    const auto id = Identifier::Factory(frame);

    if (server_.NymID() == id) { migrate_nym(); }
}

void Client::set_address_type() const
{
    if (network_ != client_.ZMQ().DefaultAddressType()) {
        bool notUsed{false};
        client_.Config().Set_long(
        String::Factory("Connection"),
        String::Factory("preferred_address_type"),
        network_, notUsed);
        client_.Config().Save();
    }
}

void Client::test_nym() const
{
    const auto clientNym = client_.Wallet().Nym(server_.NymID());

    if (false == bool(clientNym)) { import_nym(); }

    migrate_nym();
}
}  // namespace opentxs::notary
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Visualization/ShowField.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Utils/Exception.h>
#include <Core/Logging/Log.h>

using namespace SCIRun::Testing;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core;
using namespace SCIRun;
using namespace SCIRun::Core::Logging;
using ::testing::Values;
using ::testing::Combine;
using ::testing::Range;

class ShowFieldScalingTest : public ParameterizedModuleTest<int>
{
protected:
  virtual void SetUp()
  {
    Log::get().setVerbose(false);
    showField = makeModule("ShowField");
    showField->setStateDefaults();
    auto size = GetParam();
    latVol = CreateEmptyLatVol(size, size, size);
    stubPortNWithThisData(showField, 0, latVol);
    Log::get() << INFO << "Setting up ShowField with size " << size << "^3 latvol" << std::endl;
  }

  UseRealModuleStateFactory f;
  ModuleHandle showField;
  FieldHandle latVol;
};

TEST_P(ShowFieldScalingTest, ConstructLatVolGeometry)
{
  Log::get() << INFO << "Start ShowField::execute" << std::endl;
  showField->execute();
  Log::get() << INFO << "End ShowField::execute" << std::endl;
}

INSTANTIATE_TEST_CASE_P(
  ConstructLatVolGeometry,
  ShowFieldScalingTest,
  Values(20, 40, 60, 80, 100
  //, 120, 150, 200 //to speed up make test
  //, 256 // probably runs out of memory
  )
  );
<commit_msg>Closes #625<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Testing/ModuleTestBase/ModuleTestBase.h>
#include <Modules/Visualization/ShowField.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Utils/Exception.h>
#include <Core/Logging/Log.h>

using namespace SCIRun::Testing;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core;
using namespace SCIRun;
using namespace SCIRun::Core::Logging;
using ::testing::Values;
using ::testing::Combine;
using ::testing::Range;

class ShowFieldScalingTest : public ParameterizedModuleTest<int>
{
protected:
  virtual void SetUp()
  {
    Log::get().setVerbose(false);
    showField = makeModule("ShowField");
    showField->setStateDefaults();
    auto size = GetParam();
    latVol = CreateEmptyLatVol(size, size, size);
    stubPortNWithThisData(showField, 0, latVol);
    Log::get() << INFO << "Setting up ShowField with size " << size << "^3 latvol" << std::endl;
  }

  UseRealModuleStateFactory f;
  ModuleHandle showField;
  FieldHandle latVol;
};

TEST_P(ShowFieldScalingTest, ConstructLatVolGeometry)
{
  Log::get() << INFO << "Start ShowField::execute" << std::endl;
  showField->execute();
  Log::get() << INFO << "End ShowField::execute" << std::endl;
}

INSTANTIATE_TEST_CASE_P(
  ConstructLatVolGeometry,
  ShowFieldScalingTest,
  Values(20, 40, 60, 80
  //, 100, 120, 150, 200 //to speed up make test
  //, 256 // probably runs out of memory
  )
  );
<|endoftext|>


<commit_before>/*
    This file is part of KAddressbook.
    Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org>

    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 2 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, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qlayout.h>

#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <klocale.h>
#include <kparts/genericfactory.h>

#include "kabcore.h"
#include "kaddressbookiface.h"
#include "libkdepim/infoextension.h"

#include "kaddressbook_part.h"

typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory;
K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory );

KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName,
                                    QObject *parent, const char *name,
                                    const QStringList & )
  : DCOPObject( "KAddressBookIface" ), KParts::ReadOnlyPart( parent, name )
{
  kdDebug(5720) << "KAddressbookPart()" << endl;
  kdDebug(5720) << "  InstanceName: " << kapp->instanceName() << endl;

  setInstance( KAddressbookFactory::instance() );

  kdDebug(5720) << "KAddressbookPart()..." << endl;
  kdDebug(5720) << "  InstanceName: " << kapp->instanceName() << endl;

  // create a canvas to insert our widget
  QWidget *canvas = new QWidget( parentWidget, widgetName );
  canvas->setFocusPolicy( QWidget::ClickFocus );
  setWidget( canvas );

  mExtension = new KAddressbookBrowserExtension( this );

  QVBoxLayout *topLayout = new QVBoxLayout( canvas );

  KGlobal::iconLoader()->addAppDir( "kaddressbook" );

  mCore = new KABCore( this, true, canvas );
  mCore->restoreSettings();
  topLayout->addWidget( mCore );

  KParts::InfoExtension *info = new KParts::InfoExtension( this, "KABPart" );
  connect( mCore, SIGNAL( contactSelected( const QString& ) ),
           info, SIGNAL( textChanged( const QString& ) ) );
  connect( mCore, SIGNAL( contactSelected( const QPixmap& ) ),
           info, SIGNAL( iconChanged( const QPixmap& ) ) );

  setXMLFile( "kaddressbook_part.rc" );
}

KAddressbookPart::~KAddressbookPart()
{
  mCore->save();
  closeURL();
}

KAboutData *KAddressbookPart::createAboutData()
{
  return KABCore::createAboutData();
}

void KAddressbookPart::addEmail( QString addr )
{
  mCore->addEmail( addr );
}

ASYNC KAddressbookPart::showContactEditor( QString uid )
{
  mCore->editContact( uid );
}

void KAddressbookPart::newContact()
{
  mCore->newContact();
}

QString KAddressbookPart::getNameByPhone( QString phone )
{
  return mCore->getNameByPhone( phone );
}

void KAddressbookPart::save()
{
  mCore->save();
}

void KAddressbookPart::exit()
{
  delete this;
}

bool KAddressbookPart::openFile()
{
  kdDebug(5720) << "KAddressbookPart:openFile()" << endl;

  mCore->show();
  return true;
}

void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e )
{
  kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl;
  KParts::ReadOnlyPart::guiActivateEvent( e );
}

KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent )
  : KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" )
{
}

KAddressbookBrowserExtension::~KAddressbookBrowserExtension()
{
}

using namespace KParts;

#include "kaddressbook_part.moc"
<commit_msg>Pass KAboutData to Kontact<commit_after>/*
    This file is part of KAddressbook.
    Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org>

    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 2 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, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qlayout.h>

#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <klocale.h>
#include <kparts/genericfactory.h>

#include "kabcore.h"
#include "kaddressbookiface.h"
#include "libkdepim/aboutdataextension.h"
#include "libkdepim/infoextension.h"

#include "kaddressbook_part.h"

typedef KParts::GenericFactory< KAddressbookPart > KAddressbookFactory;
K_EXPORT_COMPONENT_FACTORY( libkaddressbookpart, KAddressbookFactory );

KAddressbookPart::KAddressbookPart( QWidget *parentWidget, const char *widgetName,
                                    QObject *parent, const char *name,
                                    const QStringList & )
  : DCOPObject( "KAddressBookIface" ), KParts::ReadOnlyPart( parent, name )
{
  kdDebug(5720) << "KAddressbookPart()" << endl;
  kdDebug(5720) << "  InstanceName: " << kapp->instanceName() << endl;

  setInstance( KAddressbookFactory::instance() );

  kdDebug(5720) << "KAddressbookPart()..." << endl;
  kdDebug(5720) << "  InstanceName: " << kapp->instanceName() << endl;

  // create a canvas to insert our widget
  QWidget *canvas = new QWidget( parentWidget, widgetName );
  canvas->setFocusPolicy( QWidget::ClickFocus );
  setWidget( canvas );

  mExtension = new KAddressbookBrowserExtension( this );

  QVBoxLayout *topLayout = new QVBoxLayout( canvas );

  KGlobal::iconLoader()->addAppDir( "kaddressbook" );

  mCore = new KABCore( this, true, canvas );
  mCore->restoreSettings();
  topLayout->addWidget( mCore );

  KParts::InfoExtension *info = new KParts::InfoExtension( this, "KABPart" );
  connect( mCore, SIGNAL( contactSelected( const QString& ) ),
           info, SIGNAL( textChanged( const QString& ) ) );
  connect( mCore, SIGNAL( contactSelected( const QPixmap& ) ),
           info, SIGNAL( iconChanged( const QPixmap& ) ) );

  new KParts::AboutDataExtension( createAboutData(), this, "AboutData" );

  setXMLFile( "kaddressbook_part.rc" );
}

KAddressbookPart::~KAddressbookPart()
{
  mCore->save();
  closeURL();
}

KAboutData *KAddressbookPart::createAboutData()
{
  return KABCore::createAboutData();
}

void KAddressbookPart::addEmail( QString addr )
{
  mCore->addEmail( addr );
}

ASYNC KAddressbookPart::showContactEditor( QString uid )
{
  mCore->editContact( uid );
}

void KAddressbookPart::newContact()
{
  mCore->newContact();
}

QString KAddressbookPart::getNameByPhone( QString phone )
{
  return mCore->getNameByPhone( phone );
}

void KAddressbookPart::save()
{
  mCore->save();
}

void KAddressbookPart::exit()
{
  delete this;
}

bool KAddressbookPart::openFile()
{
  kdDebug(5720) << "KAddressbookPart:openFile()" << endl;

  mCore->show();
  return true;
}

void KAddressbookPart::guiActivateEvent( KParts::GUIActivateEvent *e )
{
  kdDebug(5720) << "KAddressbookPart::guiActivateEvent" << endl;
  KParts::ReadOnlyPart::guiActivateEvent( e );
}

KAddressbookBrowserExtension::KAddressbookBrowserExtension( KAddressbookPart *parent )
  : KParts::BrowserExtension( parent, "KAddressbookBrowserExtension" )
{
}

KAddressbookBrowserExtension::~KAddressbookBrowserExtension()
{
}

using namespace KParts;

#include "kaddressbook_part.moc"
<|endoftext|>


<commit_before>/*
 * plan_and_run_node.cpp
 *
 *  Created on: Apr 10, 2015
 *      Author: Jorge Nicho
 */

#include <plan_and_run/demo_application.h>

int main(int argc,char** argv)
{
  ros::init(argc,argv,"plan_and_run");
  ros::AsyncSpinner spinner(2);
  spinner.start();

  // creating application
  plan_and_run::DemoApplication application;

  // loading parameters
  application.loadParameters();

  // initializing ros components
  application.initRos();

  // initializing descartes
  application.initDescartes();

  // moving to home position
  application.moveHome();

  // generating trajectory
  plan_and_run::DescartesTrajectory traj;
  application.generateTrajectory(traj);

  // planning robot path
  plan_and_run::DescartesTrajectory output_path;
  application.planPath(traj,output_path);

  // running robot path
  application.runPath(output_path);

  // exiting ros node
  spinner.stop();

  return 0;
}

<commit_msg>Added vectorization fix for 32bit machines<commit_after>/*
 * plan_and_run_node.cpp
 *
 *  Created on: Apr 10, 2015
 *      Author: Jorge Nicho
 */

#ifdef __i386__
  #pragma message("i386 Architecture detected, disabling EIGEN VECTORIZATION")
  #define EIGEN_DONT_VECTORIZE
  #define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT
#else
  #pragma message("64bit Architecture detected, enabling EIGEN VECTORIZATION")
#endif

#include <plan_and_run/demo_application.h>

int main(int argc,char** argv)
{
  ros::init(argc,argv,"plan_and_run");
  ros::AsyncSpinner spinner(2);
  spinner.start();

  // creating application
  plan_and_run::DemoApplication application;

  // loading parameters
  application.loadParameters();

  // initializing ros components
  application.initRos();

  // initializing descartes
  application.initDescartes();

  // moving to home position
  application.moveHome();

  // generating trajectory
  plan_and_run::DescartesTrajectory traj;
  application.generateTrajectory(traj);

  // planning robot path
  plan_and_run::DescartesTrajectory output_path;
  application.planPath(traj,output_path);

  // running robot path
  application.runPath(output_path);

  // exiting ros node
  spinner.stop();

  return 0;
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "AdvCalc.h"
#include <intrin.h>

AdvCalc::AdvCalc()
{
	// ڴ
	m_pV = (float*)_aligned_malloc(sizeof(float) * c_len, 64);
	//
	for (int i = 0;i < c_len;i++) {
		m_pV[i] = 1.0f * rand() / RAND_MAX;
	}
}

AdvCalc::~AdvCalc()
{
	_aligned_free(m_pV);
	m_pV = NULL;
}

// SIMD֧
BOOL AdvCalc::IsSupport(SIMD level)
{
	// https://en.wikipedia.org/wiki/CPUID

	int cpuinfo[4], cpuinfo7[4];
	__cpuid(cpuinfo, 0x01);
	__cpuid(cpuinfo7, 0x07);
	int ebx = cpuinfo7[1];
	int ecx = cpuinfo[2];
	int edx = cpuinfo[3];

	BOOL bSupport = FALSE;
	switch (level)
	{
	case NA:
		bSupport = TRUE;
		break;
	case MMX:
		bSupport = edx & 0x00800000;
		break;
	case SSE:
		bSupport = edx & 0x02000000;
		break;
	case AVX:
		bSupport = ecx & 0x10000000;
		break;
	case FMA:
		bSupport = ecx & 0x00001000;
		break;
	case AVX512:
		bSupport = ebx & 0x04000000;
		break;
	default:
		break;
	}

	return bSupport;
}

//
float AdvCalc::calcBasic()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		fSum = 0.0f;
		for (int i = 0;i < c_len;i++) {
			float fX = m_fA * m_pV[i] + m_fB;
			fSum += fX;
		}
	}
	return fSum;
}

// SSE
float AdvCalc::calcSSE()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m128 a = _mm_set_ps1(m_fA);
		__m128 b = _mm_set_ps1(m_fB);
		__m128* pV = (__m128*)m_pV;
		__m128 sum = _mm_set_ps1(0.0f);

		for (int i = 0;i < c_len / 4;i++) {
			__m128 x = _mm_mul_ps(a, pV[i]);
			x = _mm_add_ps(x, b);
			sum = _mm_add_ps(sum, x);
		}

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 4, 64);
		_mm_store_ps(pSum, sum);

		fSum = 0.0f;
		for (int i = 0;i < 4;i++) {
			fSum += pSum[i];
		}
		_aligned_free(pSum);
	}

	return fSum;
}

// AVX
float AdvCalc::calcAVX()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m256 a = _mm256_set1_ps(m_fA);
		__m256 b = _mm256_set1_ps(m_fB);
		__m256* pV = (__m256*)m_pV;
		__m256 sum = _mm256_set1_ps(0.0f);

		for (int i = 0;i < c_len / 8;i++) {
			__m256 x = _mm256_mul_ps(a, pV[i]);
			x = _mm256_add_ps(x, b);
			sum = _mm256_add_ps(sum, x);
		}

		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64);
		_mm256_store_ps(pSum, sum);
		fSum = *pSum;
		_aligned_free(pSum);
	}
	return fSum;
}

// FMA
float AdvCalc::calcFMA()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m256 a = _mm256_set1_ps(m_fA);
		__m256 b = _mm256_set1_ps(m_fB);
		__m256* pV = (__m256*)m_pV;
		__m256 sum = _mm256_set1_ps(0.0f);

		for (int i = 0;i < c_len / 8;i++) {
			__m256 x = _mm256_fmadd_ps(pV[i], a, b);
			sum = _mm256_add_ps(sum, x);
		}

		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64);
		_mm256_store_ps(pSum, sum);
		fSum = *pSum;
		_aligned_free(pSum);
	}
	return fSum;
}

// AVX512
float AdvCalc::calcAVX512()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m512 a = _mm512_set1_ps(m_fA);
		__m512 b = _mm512_set1_ps(m_fB);
		__m512* pV = (__m512*)m_pV;
		__m512 sum = _mm512_set1_ps(0.0f);

		for (int i = 0;i < c_len / 16;i++) {
			__m512 x = _mm512_fmadd_ps(pV[i], a, b);
			sum = _mm512_add_ps(sum, x);
		}

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 16, 64);
		_mm512_store_ps(pSum, sum);

		fSum = 0.0f;
		for (int i = 0;i < 16;i++) {
			fSum += pSum[i];
		}
		_aligned_free(pSum);
	}
	return fSum;
}<commit_msg>reduce add<commit_after>#include "stdafx.h"
#include "AdvCalc.h"
#include <intrin.h>

AdvCalc::AdvCalc()
{
	// ڴ
	m_pV = (float*)_aligned_malloc(sizeof(float) * c_len, 64);
	//
	for (int i = 0;i < c_len;i++) {
		m_pV[i] = 1.0f * rand() / RAND_MAX;
	}
}

AdvCalc::~AdvCalc()
{
	_aligned_free(m_pV);
	m_pV = NULL;
}

// SIMD֧
BOOL AdvCalc::IsSupport(SIMD level)
{
	// https://en.wikipedia.org/wiki/CPUID

	int cpuinfo[4], cpuinfo7[4];
	__cpuid(cpuinfo, 0x01);
	__cpuid(cpuinfo7, 0x07);
	int ebx = cpuinfo7[1];
	int ecx = cpuinfo[2];
	int edx = cpuinfo[3];

	BOOL bSupport = FALSE;
	switch (level)
	{
	case NA:
		bSupport = TRUE;
		break;
	case MMX:
		bSupport = edx & 0x00800000;
		break;
	case SSE:
		bSupport = edx & 0x02000000;
		break;
	case AVX:
		bSupport = ecx & 0x10000000;
		break;
	case FMA:
		bSupport = ecx & 0x00001000;
		break;
	case AVX512:
		bSupport = ebx & 0x04000000;
		break;
	default:
		break;
	}

	return bSupport;
}

//
float AdvCalc::calcBasic()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		fSum = 0.0f;
		for (int i = 0;i < c_len;i++) {
			float fX = m_fA * m_pV[i] + m_fB;
			fSum += fX;
		}
	}
	return fSum;
}

// SSE
float AdvCalc::calcSSE()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m128 a = _mm_set_ps1(m_fA);
		__m128 b = _mm_set_ps1(m_fB);
		__m128* pV = (__m128*)m_pV;
		__m128 sum = _mm_set_ps1(0.0f);

		for (int i = 0;i < c_len / 4;i++) {
			__m128 x = _mm_mul_ps(a, pV[i]);
			x = _mm_add_ps(x, b);
			sum = _mm_add_ps(sum, x);
		}

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 4, 64);
		_mm_store_ps(pSum, sum);

		fSum = 0.0f;
		for (int i = 0;i < 4;i++) {
			fSum += pSum[i];
		}
		_aligned_free(pSum);
	}

	return fSum;
}

// AVX
float AdvCalc::calcAVX()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m256 a = _mm256_set1_ps(m_fA);
		__m256 b = _mm256_set1_ps(m_fB);
		__m256* pV = (__m256*)m_pV;
		__m256 sum = _mm256_set1_ps(0.0f);

		for (int i = 0;i < c_len / 8;i++) {
			__m256 x = _mm256_mul_ps(a, pV[i]);
			x = _mm256_add_ps(x, b);
			sum = _mm256_add_ps(sum, x);
		}

		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64);
		_mm256_store_ps(pSum, sum);
		fSum = *pSum;
		_aligned_free(pSum);
	}
	return fSum;
}

// FMA
float AdvCalc::calcFMA()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m256 a = _mm256_set1_ps(m_fA);
		__m256 b = _mm256_set1_ps(m_fB);
		__m256* pV = (__m256*)m_pV;
		__m256 sum = _mm256_set1_ps(0.0f);

		for (int i = 0;i < c_len / 8;i++) {
			__m256 x = _mm256_fmadd_ps(pV[i], a, b);
			sum = _mm256_add_ps(sum, x);
		}

		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);
		sum = _mm256_hadd_ps(sum, sum);

		float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64);
		_mm256_store_ps(pSum, sum);
		fSum = *pSum;
		_aligned_free(pSum);
	}
	return fSum;
}

// AVX512
float AdvCalc::calcAVX512()
{
	float fSum;
	for (int j = 0;j < c_loop;j++) {
		__m512 a = _mm512_set1_ps(m_fA);
		__m512 b = _mm512_set1_ps(m_fB);
		__m512* pV = (__m512*)m_pV;
		__m512 sum = _mm512_set1_ps(0.0f);

		for (int i = 0;i < c_len / 16;i++) {
			__m512 x = _mm512_fmadd_ps(pV[i], a, b);
			sum = _mm512_add_ps(sum, x);
		}

		fSum = _mm512_reduce_add_ps(sum);
	}
	return fSum;
}<|endoftext|>


<commit_before>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include <cctag/fileDebug.hpp>
#include <cctag/visualDebug.hpp>
#include <cctag/progBase/exceptions.hpp>
#include <cctag/progBase/MemoryPool.hpp>
#include <cctag/detection.hpp>
#include <cctag/view.hpp>

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/gil/gil_all.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/extension/io/jpeg_io.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

#include <terry/sampler/all.hpp>
#include <terry/sampler/resample_subimage.hpp>

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

using namespace cctag::vision;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frame, cctag::View& view, const std::string & paramsFilename = "")
{
    POP_ENTER;
    // Process markers detection
    boost::timer t;
    boost::ptr_list<marker::CCTag> markers;
    cctag::vision::marker::Parameters params;
    if (paramsFilename != "") {
        std::ifstream ifs(paramsFilename.c_str());
        boost::archive::xml_iarchive ia(ifs);
        // write class instance to archive
        ia >> boost::serialization::make_nvp("CCTagsParams", params);
    } else {
        std::ofstream ofs("detectionCCTagParams.xml");
        boost::archive::xml_oarchive oa(ofs);
        // write class instance to archive
        oa << boost::serialization::make_nvp("CCTagsParams", params);
    }

    view.setNumLayers( params._numberOfMultiresLayers );

    ROM_COUT("beforecctagDetection");
    cctagDetection( markers, frame, view._grayView, params, true );
    ROM_COUT("aftercctagDetection");

    std::cout << "Id : ";

    int i = 0;
    BOOST_FOREACH(const cctag::vision::marker::CCTag & marker, markers) {
        cctag::vision::marker::drawMarkerOnGilImage(view._view, marker, false);
        cctag::vision::marker::drawMarkerInfos(view._view, marker, false);

        if (i == 0) {
            std::cout << marker.id() + 1;
        } else {
            std::cout << ", " << marker.id() + 1;
        }
        ++i;
    }
    std::cout << std::endl;

    ROM_TCOUT( markers.size() << " markers.");
    ROM_TCOUT("Total time: " << t.elapsed());
    POP_LEAVE;
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
    try {
        if (argc <= 1) {
            BOOST_THROW_EXCEPTION(cctag::exception::Bug() << cctag::exception::user() + kUsageString);
        }
        cctag::MemoryPool::instance().updateMemoryAuthorizedWithRAM();
        const std::string filename(argv[1]);
        std::string paramsFilename;
        if (argc >= 3) {
            paramsFilename = argv[2];
        }

        bfs::path myPath(filename);

        const bfs::path extPath(myPath.extension());
        const bfs::path subFilenamePath(myPath.filename());
        const bfs::path parentPath(myPath.parent_path());
        std::string ext(extPath.string());

        bfs::path folder(argv[1]);

        if ((ext == ".png") || (ext == ".jpg")) {

            cctag::View my_view( filename );

            rgb8_image_t& image = my_view._image;
            rgb8_view_t&  svw   = my_view._view;

            // Increase image size.
            /*{
                    rgb8_image_t simage;
                    simage.recreate( 2 * image.width(), 2 * image.height() );
                    rgb8_view_t osvw( view( simage ) );
                    terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
            }*/

            // Create inputImagePath/result if it does not exist
            std::stringstream resultFolderName, localizationFolderName, identificationFolderName;
            resultFolderName << parentPath.string() << "/result";
            localizationFolderName << resultFolderName.str() << "/localization";
            identificationFolderName << resultFolderName.str() << "/identification";

            if (!bfs::exists(resultFolderName.str())) {
                bfs::create_directory(resultFolderName.str());
            }

            if (!bfs::exists(localizationFolderName.str())) {
                bfs::create_directory(localizationFolderName.str());
            }

            if (!bfs::exists(identificationFolderName.str())) {
                bfs::create_directory(identificationFolderName.str());
            }

            // Set the output image name, holding the same name as the original image
            // so that the result will be placed in the inputImagePath/result/ folder
            std::stringstream strstreamResult;
            strstreamResult << resultFolderName.str() << "/" << myPath.stem().string() << ".png";
            ROM_TCOUT(strstreamResult.str());

            resultFolderName << "/" << myPath.stem().string();

            if (!bfs::exists(resultFolderName.str())) {
                bfs::create_directory(resultFolderName.str());
            }
            POP_INFO << "using result folder " << resultFolderName.str() << std::endl;
            POP_INFO << "looking at image " << myPath.stem().string() << std::endl;

            CCTagVisualDebug::instance().initBackgroundImage(svw);
            CCTagVisualDebug::instance().initPath(resultFolderName.str());
            CCTagVisualDebug::instance().setImageFileName(myPath.stem().string());

            CCTagFileDebug::instance().setPath(resultFolderName.str());

            detection(0, my_view, paramsFilename);

            CCTagFileDebug::instance().outPutAllSessions();
            CCTagFileDebug::instance().clearSessions();

            // write visual file output
            CCTagVisualDebug::instance().outPutAllSessions();
        } else if (bfs::is_directory(folder)) {
          // todo@Lilian: does not work
            std::cout << folder << " is a directory containing:\n";

            std::vector<bfs::path> filesInFolder;

            copy(bfs::directory_iterator(folder), bfs::directory_iterator(), back_inserter(filesInFolder)); // is directory_entry, which is
            // converted to a path by the
            // path stream inserter

            sort(filesInFolder.begin(), filesInFolder.end());
            std::size_t frame = 0;

            BOOST_FOREACH(const bfs::path & fileInFolder, filesInFolder) {
                ROM_TCOUT(fileInFolder);

                const std::string ext(bfs::extension(fileInFolder));
                std::stringstream outFilename, inFilename;

                if (ext == ".png") {
                    inFilename << argv[3] << "/orig/" << std::setfill('0') << std::setw(5) << frame << ".png";
                    outFilename << argv[3] << "/" << std::setfill('0') << std::setw(5) << frame << ".png";

                    cctag::View my_view( inFilename.str() );
                    rgb8_image_t& image      = my_view._image;
                    rgb8_view_t&  sourceView = my_view._view;

                    // rgb8_image_t image(png_read_dimensions(fileInFolder.c_str()));
                    // rgb8_view_t sourceView(view(image));
                    // png_read_and_convert_view(fileInFolder.c_str(), sourceView);

                    POP_INFO << "writing input image to " << inFilename.str() << std::endl;
                    png_write_view(inFilename.str(), sourceView);

                    CCTagVisualDebug::instance().initBackgroundImage(sourceView);

                    detection(frame, my_view, paramsFilename);

                    POP_INFO << "writing ouput image to " << outFilename.str() << std::endl;
                    png_write_view(outFilename.str(), sourceView);

                    ++frame;
                }
            }
        } else {
            throw std::logic_error("Unrecognized input.");
        }
    } catch (...) {
        std::cerr << boost::current_exception_diagnostic_information() << std::endl;
        return 1;
    }
    return 0;
}

<commit_msg>Add video mode: - read - process<commit_after>#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>

#include <cctag/fileDebug.hpp>
#include <cctag/visualDebug.hpp>
#include <cctag/progBase/exceptions.hpp>
#include <cctag/progBase/MemoryPool.hpp>
#include <cctag/detection.hpp>
#include <cctag/view.hpp>
#include <cctag/image.hpp>

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/gil/gil_all.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/extension/io/jpeg_io.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

#include <terry/sampler/all.hpp>
#include <terry/sampler/resample_subimage.hpp>

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/core/core.hpp>

#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>

using namespace cctag::vision;
using boost::timer;

using namespace boost::gil;
namespace bfs = boost::filesystem;

static const std::string kUsageString = "Usage: detection image_file.png\n";

void detection(std::size_t frame, cctag::View& view, const std::string & paramsFilename = "")
{
    POP_ENTER;
    // Process markers detection
    boost::timer t;
    boost::ptr_list<marker::CCTag> markers;
    cctag::vision::marker::Parameters params;
    if (paramsFilename != "") {
        std::ifstream ifs(paramsFilename.c_str());
        boost::archive::xml_iarchive ia(ifs);
        // write class instance to archive
        ia >> boost::serialization::make_nvp("CCTagsParams", params);
    } else {
        std::ofstream ofs("detectionCCTagParams.xml");
        boost::archive::xml_oarchive oa(ofs);
        // write class instance to archive
        oa << boost::serialization::make_nvp("CCTagsParams", params);
    }

    view.setNumLayers( params._numberOfMultiresLayers );

    ROM_COUT("beforecctagDetection");
    cctagDetection( markers, frame, view._grayView, params, true );
    ROM_COUT("aftercctagDetection");

    std::cout << "Id : ";

    int i = 0;
    BOOST_FOREACH(const cctag::vision::marker::CCTag & marker, markers) {
        cctag::vision::marker::drawMarkerOnGilImage(view._view, marker, false);
        cctag::vision::marker::drawMarkerInfos(view._view, marker, false);

        if (i == 0) {
            std::cout << marker.id() + 1;
        } else {
            std::cout << ", " << marker.id() + 1;
        }
        ++i;
    }
    std::cout << std::endl;

    ROM_TCOUT( markers.size() << " markers.");
    ROM_TCOUT("Total time: " << t.elapsed());
    POP_LEAVE;
}

/*************************************************************/
/*                    Main entry                             */
/*************************************************************/
int main(int argc, char** argv)
{
    try {
        if (argc <= 1) {
            BOOST_THROW_EXCEPTION(cctag::exception::Bug() << cctag::exception::user() + kUsageString);
        }
        cctag::MemoryPool::instance().updateMemoryAuthorizedWithRAM();
        const std::string filename(argv[1]);
        std::string paramsFilename;
        if (argc >= 3) {
            paramsFilename = argv[2];
        }

        bfs::path myPath(filename);

        const bfs::path extPath(myPath.extension());
        const bfs::path subFilenamePath(myPath.filename());
        const bfs::path parentPath(myPath.parent_path());
        std::string ext(extPath.string());

        bfs::path folder(argv[1]);

        if ((ext == ".png") || (ext == ".jpg")) {

            cctag::View my_view( filename );

            rgb8_image_t& image = my_view._image;
            rgb8_view_t&  svw   = my_view._view;

            // Increase image size.
            /*{
                    rgb8_image_t simage;
                    simage.recreate( 2 * image.width(), 2 * image.height() );
                    rgb8_view_t osvw( view( simage ) );
                    terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() );
            }*/

            // Create inputImagePath/result if it does not exist
            std::stringstream resultFolderName, localizationFolderName, identificationFolderName;
            resultFolderName << parentPath.string() << "/result";
            localizationFolderName << resultFolderName.str() << "/localization";
            identificationFolderName << resultFolderName.str() << "/identification";

            if (!bfs::exists(resultFolderName.str())) {
                bfs::create_directory(resultFolderName.str());
            }

            if (!bfs::exists(localizationFolderName.str())) {
                bfs::create_directory(localizationFolderName.str());
            }

            if (!bfs::exists(identificationFolderName.str())) {
                bfs::create_directory(identificationFolderName.str());
            }

            // Set the output image name, holding the same name as the original image
            // so that the result will be placed in the inputImagePath/result/ folder
            std::stringstream strstreamResult;
            strstreamResult << resultFolderName.str() << "/" << myPath.stem().string() << ".png";
            ROM_TCOUT(strstreamResult.str());

            resultFolderName << "/" << myPath.stem().string();

            if (!bfs::exists(resultFolderName.str())) {
                bfs::create_directory(resultFolderName.str());
            }
            POP_INFO << "using result folder " << resultFolderName.str() << std::endl;
            POP_INFO << "looking at image " << myPath.stem().string() << std::endl;

            CCTagVisualDebug::instance().initBackgroundImage(svw);
            CCTagVisualDebug::instance().initPath(resultFolderName.str());
            CCTagVisualDebug::instance().setImageFileName(myPath.stem().string());

            CCTagFileDebug::instance().setPath(resultFolderName.str());

            detection(0, my_view, paramsFilename);

            CCTagFileDebug::instance().outPutAllSessions();
            CCTagFileDebug::instance().clearSessions();

            // write visual file output
            CCTagVisualDebug::instance().outPutAllSessions();
        } else if (bfs::is_directory(folder)) {
          // todo@Lilian: does not work
            std::cout << folder << " is a directory containing:\n";

            std::vector<bfs::path> filesInFolder;

            copy(bfs::directory_iterator(folder), bfs::directory_iterator(), back_inserter(filesInFolder)); // is directory_entry, which is
            // converted to a path by the
            // path stream inserter

            sort(filesInFolder.begin(), filesInFolder.end());
            std::size_t frame = 0;

            BOOST_FOREACH(const bfs::path & fileInFolder, filesInFolder) {
                ROM_TCOUT(fileInFolder);

                const std::string ext(bfs::extension(fileInFolder));
                std::stringstream outFilename, inFilename;

                if (ext == ".png") {
                    inFilename << argv[3] << "/orig/" << std::setfill('0') << std::setw(5) << frame << ".png";
                    outFilename << argv[3] << "/" << std::setfill('0') << std::setw(5) << frame << ".png";

                    cctag::View my_view( inFilename.str() );
                    rgb8_image_t& image      = my_view._image;
                    rgb8_view_t&  sourceView = my_view._view;

                    // rgb8_image_t image(png_read_dimensions(fileInFolder.c_str()));
                    // rgb8_view_t sourceView(view(image));
                    // png_read_and_convert_view(fileInFolder.c_str(), sourceView);

                    POP_INFO << "writing input image to " << inFilename.str() << std::endl;
                    png_write_view(inFilename.str(), sourceView);

                    CCTagVisualDebug::instance().initBackgroundImage(sourceView);

                    detection(frame, my_view, paramsFilename);

                    POP_INFO << "writing ouput image to " << outFilename.str() << std::endl;
                    png_write_view(outFilename.str(), sourceView);

                    ++frame;
                }
            }
        } else if (ext == ".avi" ){// || ext == ".mts" || ext == ".mov") {
          std::cout << "*** Video mode ***" << std::endl;

          // open video and check
          cv::VideoCapture video(filename.c_str());
        if(!video.isOpened()) {std::cout << "Unable to open the video : " << filename; return -1;}

        // play loop
        int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT);
        int frameId = 0;
        while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame )
        {
            cv::Mat frame;
            video >> frame;
            cv::Mat imgGray;
            cv::cvtColor( frame, imgGray, CV_BGR2GRAY );
            cctag::View cctagView((const unsigned char *) imgGray.data, imgGray.cols, imgGray.rows , imgGray.step );
            cctag::vision::marker::Parameters params;
            boost::ptr_list<marker::CCTag> cctags;
            cctagDetection(cctags, frameId ,cctagView._grayView ,params, true);
            ++frameId;
        }

        } else {
            throw std::logic_error("Unrecognized input.");
        }
    } catch (...) {
        std::cerr << boost::current_exception_diagnostic_information() << std::endl;
        return 1;
    }
    return 0;
}

<|endoftext|>


<commit_before><commit_msg>Fix warning<commit_after><|endoftext|>


<commit_before>#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include <osgDB/WriteFile>
#include <osg/ref_ptr>
#include <iostream>

#include "TXPNode.h"

using namespace osg;

bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw);

osgDB::RegisterDotOsgWrapperProxy TXPNode_Proxy
(
    new txp::TXPNode,
    "TXPNode",
    "Object Node TXPNode",
    TXPNode_readLocalData,
    TXPNode_writeLocalData
);

bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
    txp::TXPNode &txpNode = static_cast<txp::TXPNode &>(obj);
    bool itrAdvanced = false;

    if (fr.matchSequence("databaseOptions %s"))
    {
        txpNode.setOptions(fr[1].getStr());
        fr += 2;
        itrAdvanced = true;
    }

    if (fr.matchSequence("databaseName %s"))
    {
        txpNode.setArchiveName(fr[1].getStr());
        txpNode.loadArchive();

        fr += 2;
        itrAdvanced = true;
    }

    return itrAdvanced;
}

class Dump2Osg : public osg::NodeVisitor
{
public:
    Dump2Osg(osgDB::Output &fw) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _fw(fw) {};

    virtual void apply(osg::Node& node)
    {
        _fw.writeObject(node);
        NodeVisitor::apply(node);
    }
    osgDB::Output &_fw;
};

bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
    const txp::TXPNode &txpNode = static_cast<const txp::TXPNode&>(obj);

    if (!txpNode.getOptions().empty()) fw.indent() << "databaseOptions \"" << txpNode.getOptions() << "\""<<std::endl;
    if (!txpNode.getArchiveName().empty()) fw.indent() << "archive name\"" << txpNode.getArchiveName() << "\"" << std::endl;

    osg::Group* grp = const_cast<osg::Group*>(txpNode.asGroup());

    Dump2Osg wrt(fw);
    grp->accept(wrt);

    return true;
}

<commit_msg>Fixed keyword used for setting the database name.<commit_after>#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include <osgDB/WriteFile>
#include <osg/ref_ptr>
#include <iostream>

#include "TXPNode.h"

using namespace osg;

bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw);

osgDB::RegisterDotOsgWrapperProxy TXPNode_Proxy
(
    new txp::TXPNode,
    "TXPNode",
    "Object Node TXPNode",
    TXPNode_readLocalData,
    TXPNode_writeLocalData
);

bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
    txp::TXPNode &txpNode = static_cast<txp::TXPNode &>(obj);
    bool itrAdvanced = false;

    if (fr.matchSequence("databaseOptions %s"))
    {
        txpNode.setOptions(fr[1].getStr());
        fr += 2;
        itrAdvanced = true;
    }

    if (fr.matchSequence("databaseName %s"))
    {
        txpNode.setArchiveName(fr[1].getStr());
        txpNode.loadArchive();

        fr += 2;
        itrAdvanced = true;
    }

    return itrAdvanced;
}

class Dump2Osg : public osg::NodeVisitor
{
public:
    Dump2Osg(osgDB::Output &fw) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _fw(fw) {};

    virtual void apply(osg::Node& node)
    {
        _fw.writeObject(node);
        NodeVisitor::apply(node);
    }
    osgDB::Output &_fw;
};

bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
    const txp::TXPNode &txpNode = static_cast<const txp::TXPNode&>(obj);

    if (!txpNode.getOptions().empty()) fw.indent() << "databaseOptions \"" << txpNode.getOptions() << "\""<<std::endl;
    if (!txpNode.getArchiveName().empty()) fw.indent() << "databaseName \"" << txpNode.getArchiveName() << "\"" << std::endl;

    osg::Group* grp = const_cast<osg::Group*>(txpNode.asGroup());

    Dump2Osg wrt(fw);
    grp->accept(wrt);

    return true;
}

<|endoftext|>