<commit_before>#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "../com_intel_vmf_MetadataSet.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_MetadataSet
 * Method:    n_MetadataSet
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__ (JNIEnv *env, jclass)
{
    std::shared_ptr<MetadataSet>* p = new std::shared_ptr<MetadataSet>(new MetadataSet());
    return (jlong) p;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_MetadataSet
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__J (JNIEnv *, jclass, jlong otherAddr)
{
    std::shared_ptr<MetadataSet>* other = (std::shared_ptr<MetadataSet>*)otherAddr;
    return (jlong) new std::shared_ptr<MetadataSet> (new MetadataSet (**other));
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_setTo
 * Signature: (JJ)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataSet_n_1setTo (JNIEnv *, jclass, jlong selfAddr, jlong otherAddr)
{
    std::shared_ptr<MetadataSet>* self = (std::shared_ptr<MetadataSet>*)selfAddr;
    std::shared_ptr<MetadataSet>* other = (std::shared_ptr<MetadataSet>*)otherAddr;
    (**self) = (**other);
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByFrameIndex
 * Signature: (JJ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByFrameIndex (JNIEnv *env, jclass, jlong self, jlong id)
{
    static const char method_name[] = "MetadataSet::n_1queryByFrameIndex";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        size_t index = (size_t) id;
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByFrameIndex(index)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByTime
 * Signature: (JJJ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByTime (JNIEnv *env, jclass, jlong self, jlong startTime, jlong endTime)
{
    static const char method_name[] = "MetadataSet::n_1queryByTime";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByTime((long long)startTime, (long long)endTime)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryBySchema
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryBySchema (JNIEnv *env, jclass, jlong self, jstring schemaName)
{
    static const char method_name[] = "MetadataSet::n_1queryBySchema";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::string sName (env->GetStringUTFChars (schemaName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryBySchema(sName)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByName
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByName (JNIEnv *env, jclass, jlong self, jstring mdName)
{
    static const char method_name[] = "MetadataSet::n_1queryByName";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::string sName (env->GetStringUTFChars (mdName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByName(sName)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByNameAndValue
 * Signature: (JLjava/lang/String;J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndValue (JNIEnv *env, jclass, jlong self, jstring mdName, jlong fieldValueAddr)
{
    static const char method_name[] = "MetadataSet::n_1queryByNameAndValue";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::shared_ptr<FieldValue>* value = (std::shared_ptr<FieldValue>*)fieldValueAddr;
        std::string sName (env->GetStringUTFChars (mdName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByNameAndValue(sName, (**value))));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByNameAndFields
 * Signature: (JLjava/lang/String;[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndFields (JNIEnv *env, jclass, jlong self, jstring mdName, jlongArray fieldValues)
{
    static const char method_name[] = "MetadataSet::n_1queryByNameAndFields";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::vector <FieldValue> values;

        std::string sName (env->GetStringUTFChars (mdName, NULL));
        jlong* cArray= env->GetLongArrayElements (fieldValues, 0);
        jsize len = env->GetArrayLength (fieldValues);

        for (int i = 0; i < len; i++)
        {
            std::shared_ptr<FieldValue>* addr = (std::shared_ptr<FieldValue>*)cArray[i];
            values.push_back (**addr);
        }

        env->ReleaseLongArrayElements (fieldValues, cArray, 0);
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet ((*obj)->queryByNameAndFields(sName, values)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByReference
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2 (JNIEnv *env, jclass, jlong self, jstring refName)
{
    static const char method_name[] = "MetadataSet::n_1queryByReference__JLjava_lang_String_2";

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

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByReference
 * Signature: (JLjava/lang/String;J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2J (JNIEnv *env, jclass, jlong self, jstring refName, jlong valueAddr)
{
    static const char method_name[] = "MetadataSet::n_1queryByReference__JLjava_lang_String_2J";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::shared_ptr<FieldValue>* value = (std::shared_ptr<FieldValue>*)valueAddr;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByReference(sName, **value)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByReference
 * Signature: (JLjava/lang/String;[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2_3J (JNIEnv *env, jclass, jlong self, jstring refName, jlongArray fieldValues)
{
    static const char method_name[] = "MetadataSet::n_1queryByReference__JLjava_lang_String_2_3J";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        jlong *body = env->GetLongArrayElements (fieldValues, 0);
        std::vector <FieldValue> values;
        jsize len = env->GetArrayLength (fieldValues);

        for (int i = 0; i < len; i++)
        {
            std::shared_ptr<FieldValue>* addr = (std::shared_ptr<FieldValue>*)body[i];
            values.push_back (**addr);
        }

        env->ReleaseLongArrayElements (fieldValues, body, 0);
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByReference(sName, values)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_shift
 * Signature: (JJJJJ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1shift (JNIEnv *env, jclass, jlong self, jlong dstFrameIndex, jlong srcFrameIndex, jlong numOfFrames, jlong setFailureAddr)
{
    static const char method_name[] = "MetadataSet::n_1shift";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::shared_ptr<MetadataSet>* setFailure = (std::shared_ptr<MetadataSet>*)setFailureAddr;

        return (jlong) (*obj)->shift((long long) dstFrameIndex, (long long) srcFrameIndex, (long long) numOfFrames, (*setFailure).get());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

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

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        delete obj;
    }
    catch (const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }
}
<commit_msg>fix for gcc compilation issue 2<commit_after>#include<string>
#include<vector>
#include "vmf/metadatastream.hpp"
#include "../com_intel_vmf_MetadataSet.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_MetadataSet
 * Method:    n_MetadataSet
 * Signature: ()J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__ (JNIEnv *env, jclass)
{
    std::shared_ptr<MetadataSet>* p = new std::shared_ptr<MetadataSet>(new MetadataSet());
    return (jlong) p;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_MetadataSet
 * Signature: (J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1MetadataSet__J (JNIEnv *, jclass, jlong otherAddr)
{
    std::shared_ptr<MetadataSet>* other = (std::shared_ptr<MetadataSet>*)otherAddr;
    return (jlong) new std::shared_ptr<MetadataSet> (new MetadataSet (**other));
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_setTo
 * Signature: (JJ)V
 */
JNIEXPORT void JNICALL Java_com_intel_vmf_MetadataSet_n_1setTo (JNIEnv *, jclass, jlong selfAddr, jlong otherAddr)
{
    std::shared_ptr<MetadataSet>* self = (std::shared_ptr<MetadataSet>*)selfAddr;
    std::shared_ptr<MetadataSet>* other = (std::shared_ptr<MetadataSet>*)otherAddr;
    MetadataSet tmp = (*(*other));
    (*(*self)) = tmp;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByFrameIndex
 * Signature: (JJ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByFrameIndex (JNIEnv *env, jclass, jlong self, jlong id)
{
    static const char method_name[] = "MetadataSet::n_1queryByFrameIndex";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        size_t index = (size_t) id;
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByFrameIndex(index)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByTime
 * Signature: (JJJ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByTime (JNIEnv *env, jclass, jlong self, jlong startTime, jlong endTime)
{
    static const char method_name[] = "MetadataSet::n_1queryByTime";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByTime((long long)startTime, (long long)endTime)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryBySchema
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryBySchema (JNIEnv *env, jclass, jlong self, jstring schemaName)
{
    static const char method_name[] = "MetadataSet::n_1queryBySchema";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::string sName (env->GetStringUTFChars (schemaName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryBySchema(sName)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByName
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByName (JNIEnv *env, jclass, jlong self, jstring mdName)
{
    static const char method_name[] = "MetadataSet::n_1queryByName";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::string sName (env->GetStringUTFChars (mdName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByName(sName)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByNameAndValue
 * Signature: (JLjava/lang/String;J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndValue (JNIEnv *env, jclass, jlong self, jstring mdName, jlong fieldValueAddr)
{
    static const char method_name[] = "MetadataSet::n_1queryByNameAndValue";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::shared_ptr<FieldValue>* value = (std::shared_ptr<FieldValue>*)fieldValueAddr;
        std::string sName (env->GetStringUTFChars (mdName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByNameAndValue(sName, (**value))));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByNameAndFields
 * Signature: (JLjava/lang/String;[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByNameAndFields (JNIEnv *env, jclass, jlong self, jstring mdName, jlongArray fieldValues)
{
    static const char method_name[] = "MetadataSet::n_1queryByNameAndFields";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::vector <FieldValue> values;

        std::string sName (env->GetStringUTFChars (mdName, NULL));
        jlong* cArray= env->GetLongArrayElements (fieldValues, 0);
        jsize len = env->GetArrayLength (fieldValues);

        for (int i = 0; i < len; i++)
        {
            std::shared_ptr<FieldValue>* addr = (std::shared_ptr<FieldValue>*)cArray[i];
            values.push_back (**addr);
        }

        env->ReleaseLongArrayElements (fieldValues, cArray, 0);
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet ((*obj)->queryByNameAndFields(sName, values)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByReference
 * Signature: (JLjava/lang/String;)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2 (JNIEnv *env, jclass, jlong self, jstring refName)
{
    static const char method_name[] = "MetadataSet::n_1queryByReference__JLjava_lang_String_2";

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

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByReference
 * Signature: (JLjava/lang/String;J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2J (JNIEnv *env, jclass, jlong self, jstring refName, jlong valueAddr)
{
    static const char method_name[] = "MetadataSet::n_1queryByReference__JLjava_lang_String_2J";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::shared_ptr<FieldValue>* value = (std::shared_ptr<FieldValue>*)valueAddr;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByReference(sName, **value)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_queryByReference
 * Signature: (JLjava/lang/String;[J)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1queryByReference__JLjava_lang_String_2_3J (JNIEnv *env, jclass, jlong self, jstring refName, jlongArray fieldValues)
{
    static const char method_name[] = "MetadataSet::n_1queryByReference__JLjava_lang_String_2_3J";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::string sName (env->GetStringUTFChars (refName, NULL));
        jlong *body = env->GetLongArrayElements (fieldValues, 0);
        std::vector <FieldValue> values;
        jsize len = env->GetArrayLength (fieldValues);

        for (int i = 0; i < len; i++)
        {
            std::shared_ptr<FieldValue>* addr = (std::shared_ptr<FieldValue>*)body[i];
            values.push_back (**addr);
        }

        env->ReleaseLongArrayElements (fieldValues, body, 0);
        return (jlong) new std::shared_ptr<MetadataSet>(new MetadataSet((*obj)->queryByReference(sName, values)));
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

/*
 * Class:     com_intel_vmf_MetadataSet
 * Method:    n_shift
 * Signature: (JJJJJ)J
 */
JNIEXPORT jlong JNICALL Java_com_intel_vmf_MetadataSet_n_1shift (JNIEnv *env, jclass, jlong self, jlong dstFrameIndex, jlong srcFrameIndex, jlong numOfFrames, jlong setFailureAddr)
{
    static const char method_name[] = "MetadataSet::n_1shift";

    try
    {
        std::shared_ptr<MetadataSet>* obj = (std::shared_ptr<MetadataSet>*)self;
        std::shared_ptr<MetadataSet>* setFailure = (std::shared_ptr<MetadataSet>*)setFailureAddr;

        return (jlong) (*obj)->shift((long long) dstFrameIndex, (long long) srcFrameIndex, (long long) numOfFrames, (*setFailure).get());
    }
    catch(const std::exception &e)
    {
        throwJavaException(env, &e, method_name);
    }
    catch (...)
    {
        throwJavaException(env, 0, method_name);
    }

    return 0;
}

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

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


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkMutualInformationMetricTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
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.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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.

=========================================================================*/
#include "itkImage.h"
#include "itkImageRegionIterator.h"

#include "itkImageMapper.h"
#include "itkAffineTransform.h"
#include "itkMutualInformationImageToImageMetric.h"

#include <iostream>

/**
 *  This test uses two 2D-Gaussians (standard deviation RegionSize/2)
 *  One is shifted by 5 pixels from the other.
 *
 *  This test computes the mutual information value and derivatives
 *  for various shift values in (-10,10).
 *
 */

int main()
{

//------------------------------------------------------------
// Create two simple images
//------------------------------------------------------------

  //Allocate Images
  typedef itk::Image<unsigned char,2>           ReferenceType;
  typedef itk::Image<unsigned char,2>           TargetType;
  enum { ImageDimension = ReferenceType::ImageDimension };

  ReferenceType::SizeType size = {{100,100}};
  ReferenceType::IndexType index = {{0,0}};
  ReferenceType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  ReferenceType::Pointer imgReference = ReferenceType::New();
  imgReference->SetLargestPossibleRegion( region );
  imgReference->SetBufferedRegion( region );
  imgReference->SetRequestedRegion( region );
  imgReference->Allocate();

  TargetType::Pointer imgTarget = TargetType::New();
  imgTarget->SetLargestPossibleRegion( region );
  imgTarget->SetBufferedRegion( region );
  imgTarget->SetRequestedRegion( region );
  imgTarget->Allocate();

  // Fill images with a 2D gaussian
  typedef  itk::ImageRegionIterator<ReferenceType>
    ReferenceIteratorType;
  typedef  itk::ImageRegionIterator<TargetType>
    TargetIteratorType;

  itk::Point<double,2> center;
  center[0] = (double)region.GetSize()[0]/2.0;
  center[1] = (double)region.GetSize()[1]/2.0;

  const double s = (double)region.GetSize()[0]/2.0;

  itk::Point<double,2>  p;
  itk::Vector<double,2> d;

  // Set the displacement
  itk::Vector<double,2> displacement;
  displacement[0] = 5;
  displacement[1] = 0;

  ReferenceIteratorType ri(imgReference,region);
  TargetIteratorType ti(imgTarget,region);
  ri.Begin();
  while(!ri.IsAtEnd())
  {
    p[0] = ri.GetIndex()[0];
    p[1] = ri.GetIndex()[1];
    d = p-center;
    d += displacement;
    const double x = d[0];
    const double y = d[1];
    ri.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
    ++ri;
  }

  ti.Begin();
  while(!ti.IsAtEnd())
  {
    p[0] = ti.GetIndex()[0];
    p[1] = ti.GetIndex()[1];
  d = p-center;
  const double x = d[0];
  const double y = d[1];
    ti.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
    ++ti;
  }

//-----------------------------------------------------------
// Set up a transformer
//-----------------------------------------------------------
  enum{ ParametersDimension = ImageDimension * ( ImageDimension + 1 ) };
  typedef itk::Vector<double,ParametersDimension> ParametersType;
  typedef itk::AffineTransform<
    double, ImageDimension, ParametersType > TransformType;

  TransformType::Pointer transformer = TransformType::New();

//------------------------------------------------------------
// Set up a mapper
//------------------------------------------------------------
  typedef itk::ImageMapper< ReferenceType, TransformType >
     MapperType;

  MapperType::Pointer mapper = MapperType::New();

  // connect the transformer to the mapper
  mapper->SetTransform( transformer );

  // connect the reference image to the mapper
  mapper->SetDomain( imgReference );

//------------------------------------------------------------
// Set up the metric
//------------------------------------------------------------
  typedef itk::MutualInformationImageToImageMetric<
    TargetType, MapperType > MetricType;

  MetricType::Pointer metric = MetricType::New();

  // connect the mapper to the metric
  metric->SetMapper( mapper );

  // connect the target image to the mapper
  metric->SetTarget( imgTarget );

  // set the standard deviations
  metric->SetTargetStandardDeviation( 5.0 );
  metric->SetReferenceStandardDeviation( 5.0 );

  // set the number of samples to use
  metric->SetNumberOfSpatialSamples( 100 );

//------------------------------------------------------------
// Set up a affine transform parameters
//------------------------------------------------------------
  ParametersType parameters;

  // set the parameters to the identity
  ParametersType::Iterator it = parameters.Begin();

     // initialize the linear/matrix part
  for( unsigned int row = 0; row < ImageDimension; row++ )
    {
    for( unsigned int col = 0; col < ImageDimension; col++ )
      {
      *it = 0;
      if( row == col )
        {
        *it = 1;
        }
      ++it;
      }
    }

     // initialize the offset/vector part
  for( unsigned int k = 0; k < ImageDimension; k++ )
    {
    *it = 0;
    ++it;
    }

//---------------------------------------------------------
// Print out mutual information values
// for parameters[4] = {-10,10}
//---------------------------------------------------------

  MetricType::MeasureType measure;
  MetricType::DerivativeType derivative;

  printf("%s\t%s\t%s\n", "param[4]", "MI", "dMI/dparam[4]" );

  for( double trans = -10; trans <= 5; trans += 0.5 )
    {
    parameters[4] = trans;
    metric->GetValueAndDerivative( parameters, measure, derivative );

    printf( "%f\t%f\t%f\n", trans, measure,
      derivative[4] );

    // exercise the other functions
    metric->GetValue( parameters );
    metric->GetDerivative( parameters );

    }

//-------------------------------------------------------
// exercise misc member functions
//-------------------------------------------------------
  std::cout << "Name of class: " <<
    metric->GetNameOfClass() << std::endl;
  std::cout << "No. of samples used = " <<
    metric->GetNumberOfSpatialSamples() << std::endl;
  std::cout << "Target std dev = " <<
    metric->GetTargetStandardDeviation() << std::endl;
  std::cout << "Reference std dev = " <<
    metric->GetReferenceStandardDeviation() << std::endl;

  std::cout << "Try causing a exception by making std dev too small";
  std::cout << std::endl;
  metric->SetTargetStandardDeviation( 0.001 );
  try
    {
    std::cout << "Value = " << metric->GetValue( parameters );
    std::cout << std::endl;
    }
  catch(...)
    {
    std::cout << "Caught the exception." << std::endl;
    }

  // reset standard deviation
  metric->SetTargetStandardDeviation( 5.0 );

  std::cout << "Check case when Target is NULL" << std::endl;
  metric->SetTarget( NULL );
  std::cout << "Value = " << metric->GetValue( parameters );
  std::cout << std::endl;

  metric->GetValueAndDerivative( parameters, measure, derivative );
  std::cout << "Value = " << measure << std::endl;

  return EXIT_SUCCESS;

}

<commit_msg>ENH: tests more member functions. Cleanup spacing<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkMutualInformationMetricTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2001 Insight Consortium
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.

 * The name of the Insight Consortium, nor the names of any consortium members,
   nor of any contributors, may be used to endorse or promote products derived
   from this software without specific prior written permission.

  * Modified source versions must be plainly marked as such, and must not be
    misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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.

=========================================================================*/
#include "itkImage.h"
#include "itkImageRegionIterator.h"

#include "itkImageMapper.h"
#include "itkAffineTransform.h"
#include "itkMutualInformationImageToImageMetric.h"

#include <iostream>

/**
 *  This test uses two 2D-Gaussians (standard deviation RegionSize/2)
 *  One is shifted by 5 pixels from the other.
 *
 *  This test computes the mutual information value and derivatives
 *  for various shift values in (-10,10).
 *
 */

int main()
{

//------------------------------------------------------------
// Create two simple images
//------------------------------------------------------------

  //Allocate Images
  typedef itk::Image<unsigned char,2>           ReferenceType;
  typedef itk::Image<unsigned char,2>           TargetType;
  enum { ImageDimension = ReferenceType::ImageDimension };

  ReferenceType::SizeType size = {{100,100}};
  ReferenceType::IndexType index = {{0,0}};
  ReferenceType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  ReferenceType::Pointer imgReference = ReferenceType::New();
  imgReference->SetLargestPossibleRegion( region );
  imgReference->SetBufferedRegion( region );
  imgReference->SetRequestedRegion( region );
  imgReference->Allocate();

  TargetType::Pointer imgTarget = TargetType::New();
  imgTarget->SetLargestPossibleRegion( region );
  imgTarget->SetBufferedRegion( region );
  imgTarget->SetRequestedRegion( region );
  imgTarget->Allocate();

  // Fill images with a 2D gaussian
  typedef  itk::ImageRegionIterator<ReferenceType>
    ReferenceIteratorType;
  typedef  itk::ImageRegionIterator<TargetType>
    TargetIteratorType;

  itk::Point<double,2> center;
  center[0] = (double)region.GetSize()[0]/2.0;
  center[1] = (double)region.GetSize()[1]/2.0;

  const double s = (double)region.GetSize()[0]/2.0;

  itk::Point<double,2>  p;
  itk::Vector<double,2> d;

  // Set the displacement
  itk::Vector<double,2> displacement;
  displacement[0] = 5;
  displacement[1] = 0;

  ReferenceIteratorType ri(imgReference,region);
  TargetIteratorType ti(imgTarget,region);
  ri.Begin();
  while(!ri.IsAtEnd())
    {
    p[0] = ri.GetIndex()[0];
    p[1] = ri.GetIndex()[1];
    d = p-center;
    d += displacement;
    const double x = d[0];
    const double y = d[1];
    ri.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
    ++ri;
    }

  ti.Begin();
  while(!ti.IsAtEnd())
    {
    p[0] = ti.GetIndex()[0];
    p[1] = ti.GetIndex()[1];
    d = p-center;
    const double x = d[0];
    const double y = d[1];
    ti.Set( (unsigned char) ( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ) );
    ++ti;
    }

//-----------------------------------------------------------
// Set up a transformer
//-----------------------------------------------------------
  enum{ ParametersDimension = ImageDimension * ( ImageDimension + 1 ) };
  typedef itk::Vector<double,ParametersDimension> ParametersType;
  typedef itk::AffineTransform<
    double, ImageDimension, ParametersType > TransformType;

  TransformType::Pointer transformer = TransformType::New();

//------------------------------------------------------------
// Set up a mapper
//------------------------------------------------------------
  typedef itk::ImageMapper< ReferenceType, TransformType >
     MapperType;

  MapperType::Pointer mapper = MapperType::New();

  // connect the transformer to the mapper
  mapper->SetTransform( transformer );

  // connect the reference image to the mapper
  mapper->SetDomain( imgReference );

//------------------------------------------------------------
// Set up the metric
//------------------------------------------------------------
  typedef itk::MutualInformationImageToImageMetric<
    TargetType, MapperType > MetricType;

  MetricType::Pointer metric = MetricType::New();

  // connect the mapper to the metric
  metric->SetMapper( mapper );

  // connect the target image to the mapper
  metric->SetTarget( imgTarget );

  // set the standard deviations
  metric->SetTargetStandardDeviation( 5.0 );
  metric->SetReferenceStandardDeviation( 5.0 );

  // set the number of samples to use
  metric->SetNumberOfSpatialSamples( 100 );

//------------------------------------------------------------
// Set up a affine transform parameters
//------------------------------------------------------------
  ParametersType parameters;

  // set the parameters to the identity
  ParametersType::Iterator it = parameters.Begin();

     // initialize the linear/matrix part
  for( unsigned int row = 0; row < ImageDimension; row++ )
    {
    for( unsigned int col = 0; col < ImageDimension; col++ )
      {
      *it = 0;
      if( row == col )
        {
        *it = 1;
        }
      ++it;
      }
    }

     // initialize the offset/vector part
  for( unsigned int k = 0; k < ImageDimension; k++ )
    {
    *it = 0;
    ++it;
    }

//---------------------------------------------------------
// Print out mutual information values
// for parameters[4] = {-10,10}
//---------------------------------------------------------

  MetricType::MeasureType measure;
  MetricType::DerivativeType derivative;

  printf("%s\t%s\t%s\n", "param[4]", "MI", "dMI/dparam[4]" );

  for( double trans = -10; trans <= 5; trans += 0.5 )
    {
    parameters[4] = trans;
    metric->GetValueAndDerivative( parameters, measure, derivative );

    printf( "%f\t%f\t%f\n", trans, measure,
      derivative[4] );

    // exercise the other functions
    metric->GetValue( parameters );
    metric->GetDerivative( parameters );

    }

//-------------------------------------------------------
// exercise misc member functions
//-------------------------------------------------------
  std::cout << "Name of class: " <<
    metric->GetNameOfClass() << std::endl;
  std::cout << "No. of samples used = " <<
    metric->GetNumberOfSpatialSamples() << std::endl;
  std::cout << "Target std dev = " <<
    metric->GetTargetStandardDeviation() << std::endl;
  std::cout << "Reference std dev = " <<
    metric->GetReferenceStandardDeviation() << std::endl;

  metric->Print( std::cout );

  itk::KernelFunction::Pointer theKernel = metric->GetKernelFunction();
  metric->SetKernelFunction( theKernel );
  theKernel->Print( std::cout );

  std::cout << "Try causing a exception by making std dev too small";
  std::cout << std::endl;
  metric->SetTargetStandardDeviation( 0.001 );
  try
    {
    std::cout << "Value = " << metric->GetValue( parameters );
    std::cout << std::endl;
    }
  catch(...)
    {
    std::cout << "Caught the exception." << std::endl;
    }

  // reset standard deviation
  metric->SetTargetStandardDeviation( 5.0 );

  std::cout << "Check case when Target is NULL" << std::endl;
  metric->SetTarget( NULL );
  std::cout << "Value = " << metric->GetValue( parameters );
  std::cout << std::endl;

  metric->GetValueAndDerivative( parameters, measure, derivative );
  std::cout << "Value = " << measure << std::endl;

  return EXIT_SUCCESS;

}

<|endoftext|>


<commit_before>#include "BtuLinear.h"

BtuLinear::BtuLinear():
    m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),
    m_posAPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),
    m_posBPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),
    m_velAPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),
    m_velBPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),
	m_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),
    m_actAPwm(PIN_ACTA_PWM),
    m_actBPwm(PIN_ACTB_PWM),
    m_actAPot(PIN_ACTA_POT),
    m_actBPot(PIN_ACTB_POT),
    m_actADir(PIN_ACTA_DIR),
    m_actBDir(PIN_ACTB_DIR)
{};

BtuLinear::~BtuLinear(){}

void BtuLinear::init() {
    m_mode = DEFAULT_CTRL_MODE;

    // default gain values for depth controller
    m_kc = DEP_K_C;
    m_tauI = DEP_TAU_I;
    m_tauD = DEP_TAU_D;

    // default gain values for position controller
    m_p_kc = SP_K_C;
    m_p_tauI = SP_TAU_I;
    m_p_tauD = SP_TAU_D;

    // default gain values for velocity controller
    m_v_kc = VEL_K_C;
    m_v_tauI = VEL_TAU_I;
    m_v_tauD = VEL_TAU_D;

    // initialize Pressure Sensor
    m_pressureSensor.MS5837Init();
    m_pressureSensor.MS5837Start();
    wait(0.1);                    // remnant from old BTU class TODO: check if can be removed

    // initialize old position readings for Actuators
    m_oldPosA = getActPosition(ACT_A);
    m_oldPosB = getActPosition(ACT_B);

    // initialize the Windows for SMA to 0
    for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {
        m_avg_windowA[i] = 0;
        m_avg_windowB[i] = 0;
    }

    // initialize all pointers, size of window to reflect that it is empty
    m_avg_windowPtr = 0;
    m_avg_windowSize = 0;
    m_currentAvgA = 0;

    m_currentAvgB = 0;

    // initialize starting voltage for velocity control to 0
    m_currentVoltage = 0;
}

// return a pressure reading
float BtuLinear::getPressure() {
    return m_pressureSensor.MS5837_Pressure();
}

// resets values of the controllers
void BtuLinear::stop() {
	m_currentVoltage = 0;
	m_currentAvgA = 0;
	m_currentAvgB = 0;
	m_avg_windowSize = 0;
	m_depthPid.reset();
	m_posAPid.reset();
	m_posBPid.reset();
	m_velAPid.reset();
	m_velBPid.reset();
	return;
}

// updates depth PID tunings
void BtuLinear::updateDepthTunings(float kc, float tauI, float tauD) {
    m_kc = kc;
    m_tauI = tauI;
    m_tauD = tauD;
    m_depthPid.setTunings(kc, tauI, tauD);
}

// updates Position PID tunings
void BtuLinear::updatePosTunings(float kc, float tauI, float tauD) {
    m_p_kc = kc;
    m_p_tauI = tauI;
    m_p_tauD = tauD;
    m_posAPid.setTunings(kc, tauI, tauD);
    m_posBPid.setTunings(kc, tauI, tauD);
}

// updates Velocity PID tunings
void BtuLinear::updateVelTunings(float kc, float tauI, float tauD) {
    m_v_kc = kc;
    m_v_tauI = tauI;
    m_v_tauD = tauD;
    m_velAPid.setTunings(kc, tauI, tauD);
    m_velBPid.setTunings(kc, tauI, tauD);
}

// updates Mode.  Resets most values if the mode has changed
void BtuLinear::updateMode(int mode) {
    if(m_mode != mode) {
        stop();
        m_mode = mode;
    }
}

// runs one cycle of the controller dictated by mode
void BtuLinear::runCycle(float setVal) {
    switch (m_mode) {

    case VOLTAGE_CTRL_MODE:
        voltageControl(setVal);
        break;

    case VELOCITY_CTRL_MODE:
        velocityControl(setVal);
        break;

    case DEPTH_CTRL_MODE:
        depthControl(setVal);
        break;

    case POSITION_CTRL_MODE:
        positionControl(setVal);
        break;
    }
}

// convenience function, updates mode, then runs a cycle in the chosen mode
void BtuLinear::updateAndRunCycle(int mode, float value) {
    updateMode(mode);
    runCycle(value);
}

// sends a duty cycle to one of the actuators, based on the second argument
void BtuLinear::voltageControlHelper(float setDuty, int ctrl) {
    // PwmOut* actPwm;
    // DigitalOut* actDir;
    // if(ctrl == ACT_A) {
    //     actPwm = &m_actAPwm;
    //     actDir = &m_actADir;
    // } else {
    //     actPwm = &m_actBPwm;
    //     actDir = &m_actBDir;
    // }
    // if(setDuty > 0) {
    //     *actPwm = setDuty;
    //     *actDir = 1;
    // } else {
    //     *actDir = 0;
    //     *actPwm = -setDuty;
    // }
    if(ctrl == ACT_A) {
        if(setDuty > 0) {       // extending
            m_actAPwm = setDuty;
            m_actADir = 1;
        } else {                // contracting
            m_actADir = 0;
            m_actAPwm = -setDuty;
        }
    } else {
        if(setDuty > 0) {
            m_actBPwm = setDuty;
            m_actBDir = 1;
        } else {
            m_actBDir = 0;
            m_actBPwm = -setDuty;
        }
    }
}

// calls voltageControlHelper on both actuators
void BtuLinear::voltageControl(float setDuty) {
    voltageControlHelper(setDuty, ACT_A);
    voltageControlHelper(setDuty, ACT_B);
}

// updates the SMA window with the current position reading
void BtuLinear::updatePositionReadings() {
    float aPosition = m_actAPot;
    float bPosition = m_actBPot;

    float aOldPos = m_avg_windowA[m_avg_windowPtr];
    float bOldPos = m_avg_windowB[m_avg_windowPtr];
    m_avg_windowA[m_avg_windowPtr] = aPosition;
    m_avg_windowB[m_avg_windowPtr] = bPosition;
    m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;
    if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {
        // buffer is full
    	m_currentAvgA = m_currentAvgA + (aPosition / AVG_WINDOW_WIDTH)- (aOldPos / AVG_WINDOW_WIDTH);
        m_currentAvgB = m_currentAvgB + (bPosition / AVG_WINDOW_WIDTH)- (bOldPos / AVG_WINDOW_WIDTH);
    } else {
    	// buffer is still filling up
        m_avg_windowSize++;
        m_currentAvgA = 0;
        m_currentAvgB = 0;
        for(int i = 0; i < m_avg_windowSize; i++) {
            m_currentAvgA = (m_avg_windowA[i] / m_avg_windowSize);
            m_currentAvgB = (m_avg_windowB[i] / m_avg_windowSize);
        }
    }
}

// gets the current Actuator Position.  No SMA, just reads and rescales the potentiometer
float BtuLinear::getActPosition(int act) {
    // Following code is for moving average, TODO: currently uncommented
	// updatePositionReadings();
    // float position;
    // if(act == ACT_A) {
    //     position = m_currentAvgA;
    // } else {
    //     position = m_currentAvgB;
    // }
    float position;
    if(act == ACT_A) {
        position = m_actAPot;
    } else {
        position = m_actBPot;
    }
    float scaledPos = (position - POT_MIN) / (POT_MAX - POT_MIN);
    return scaledPos;
}

// controls velocity on one actuator
void BtuLinear::velocityControlHelper(float setVelocity, int ctrl) {
    // Check if one of the two allowable actuators is called
	if(ctrl != ACT_A && ctrl != ACT_B) {
        return;
    }
    // Acquire the actuator position from the potentiometer
	l_actPosVC = getActPosition(ctrl);

    // avoid going past the very edges:
	// Currently at 0.99 and 0.01 due to some uncertainty in scaling/pot readings
    // also to help avoid accumulation of error during such a period
    if ((l_actPosVC <= POSITION_MIN && setVelocity < 0) || (l_actPosVC >= POSITION_MAX && setVelocity > 0)) {
		//at an edge, set the setVelocity to 0
        l_setVelVC = 0;
    }
    else {
    	// not at an edge, use setVelocity
    	l_setVelVC = setVelocity;
    }

    if(ctrl == ACT_A) {
        l_actVelVC = (l_actPosVC - m_oldPosA) / PID_FREQ;
        // set process value to the derivative of position (velocity)
    	m_velAPid.setProcessValue(l_actVelVC);
        m_velAPid.setSetPoint(l_setVelVC);
        l_deltaVoltVC = m_velAPid.compute();
        m_oldPosA = l_actPosVC;        // update old position for so we can keep calculating derivatives
    }
    else {
    	l_actVelVC = (l_actPosVC - m_oldPosB) / PID_FREQ;
        m_velBPid.setProcessValue(l_actVelVC);
        m_velBPid.setSetPoint(l_setVelVC);
        l_deltaVoltVC = m_velBPid.compute();
        m_oldPosB = l_actPosVC;
    }
    //add the voltage delta to the current voltage that is the current operating point
    m_currentVoltage = utility::clip(m_currentVoltage + l_deltaVoltVC, -1.0, 1.0); // increase or decrease current voltage to get closer to desired velocity

    // arrest any movement at the edges, and reset accumulated voltage, to aid responsiveness at the edges
    if ((l_actPosVC <= POSITION_MIN && l_setVelVC <= 0) || (l_actPosVC >= POSITION_MAX && l_setVelVC >= 0)) {
        m_currentVoltage = 0;
    }

    l_cmdVoltVC = m_currentVoltage;

	// have a small dead zone TODO: either better tune or remove,
    // causes small offsets in position sometimes (of about 0.025% at current gain values)
    l_cmdVoltVC = utility::deadzone(l_cmdVoltVC,VOLTAGE_THRESHOLD);

    voltageControlHelper(l_cmdVoltVC, ctrl);

}

// does velocity control on both actuators
void BtuLinear::velocityControl(float setVel) {
    velocityControlHelper(setVel, ACT_A);
    velocityControlHelper(setVel, ACT_B);
}

// control position of one actuator
void BtuLinear::positionControlHelper(float setPos, int ctrl) {
	 // Check if one of the two allowable actuators is called
	if(ctrl != ACT_A && ctrl != ACT_B) {
		return;
	}
    // Acquire the actuator position from the potentiometer
	l_actPosPC = getActPosition(ctrl);

	if(ctrl == ACT_A) {
        m_posAPid.setSetPoint(setPos);
        m_posAPid.setProcessValue(l_actPosPC);
        l_cmdVoltPC = m_posAPid.compute();
        //m_cmdVel = m_posAPid.compute();
    } else {
        m_posBPid.setSetPoint(setPos);
        m_posBPid.setProcessValue(l_actPosPC);
        l_cmdVoltPC = m_posBPid.compute();
        //m_cmdVel = m_posBPid.compute();
    }
	//velocityControlHelper(m_cmdVel, ctrl);

	//clip commanded voltage to upper and lower limit
	l_cmdVoltPC = utility::clip(l_cmdVoltPC, -1.0, 1.0); // increase or decrease current voltage to get closer to desired velocity

    // arrest any movement at the edges, and reset current voltage, to aid responsiveness at the edges
    if ((l_actPosPC <= POSITION_MIN && l_cmdVoltPC <= 0) || (l_actPosPC >= POSITION_MAX && l_cmdVoltPC >= 0)) {
    	l_cmdVoltPC = 0;
    }

	// have a small dead zone TODO: either better tune or remove,
    // causes small offsets in position sometimes (of about 0.025% at current gain values)
    l_cmdVoltPC = utility::deadzone(l_cmdVoltPC,VOLTAGE_THRESHOLD);

    voltageControlHelper(l_cmdVoltPC, ctrl);

}

// control position of both actuators
void BtuLinear::positionControl(float setPos) {
    positionControlHelper(setPos, ACT_A);
    positionControlHelper(setPos, ACT_B);
}

// control depth via master-slave
void BtuLinear::depthControlHelper(float cmdVelocity) {
    velocityControlHelper(cmdVelocity, ACT_B); // control velocity on one actuator
    positionControlHelper(getActPosition(ACT_B), ACT_A); // have the other actuator constantly try to mirror the first
}

// do depth control
void BtuLinear::depthControl(float setDepthMeters) {

	m_depthPid.setSetPoint(setDepthMeters);

    float curDepth = getDepth();

    m_depthPid.setProcessValue(curDepth);

    float cmdVel = m_depthPid.compute();
    depthControlHelper(-1*cmdVel);
    // velocityControl(cmdVel);
}

// get a depth reading
float BtuLinear::getDepth() {
    float pvDepth = getPressure();
    float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) / P_WATER_SURFACE_MBAR;
    return pvDepthMeters;
}

// float BTU::getServoPos() {
// 	return m_motorServo.readPosition();
// }
<commit_msg>moved clipping and other checks to voltage control<commit_after>#include "BtuLinear.h"

BtuLinear::BtuLinear():
    m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),
    m_posAPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),
    m_posBPid(SP_K_C, SP_TAU_I, SP_TAU_D, PID_FREQ, POS_MIN, POS_MAX, VEL_MIN, VEL_MAX, 0),
    m_velAPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),
    m_velBPid(VEL_K_C, VEL_TAU_I, VEL_TAU_D, PID_FREQ, VEL_MIN, VEL_MAX, -1, 1, 0),
	m_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),
    m_actAPwm(PIN_ACTA_PWM),
    m_actBPwm(PIN_ACTB_PWM),
    m_actAPot(PIN_ACTA_POT),
    m_actBPot(PIN_ACTB_POT),
    m_actADir(PIN_ACTA_DIR),
    m_actBDir(PIN_ACTB_DIR)
{};

BtuLinear::~BtuLinear(){}

void BtuLinear::init() {
    m_mode = DEFAULT_CTRL_MODE;

    // default gain values for depth controller
    m_kc = DEP_K_C;
    m_tauI = DEP_TAU_I;
    m_tauD = DEP_TAU_D;

    // default gain values for position controller
    m_p_kc = SP_K_C;
    m_p_tauI = SP_TAU_I;
    m_p_tauD = SP_TAU_D;

    // default gain values for velocity controller
    m_v_kc = VEL_K_C;
    m_v_tauI = VEL_TAU_I;
    m_v_tauD = VEL_TAU_D;

    // initialize Pressure Sensor
    m_pressureSensor.MS5837Init();
    m_pressureSensor.MS5837Start();
    wait(0.1);                    // remnant from old BTU class TODO: check if can be removed

    // initialize old position readings for Actuators
    m_oldPosA = getActPosition(ACT_A);
    m_oldPosB = getActPosition(ACT_B);

    // initialize the Windows for SMA to 0
    for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {
        m_avg_windowA[i] = 0;
        m_avg_windowB[i] = 0;
    }

    // initialize all pointers, size of window to reflect that it is empty
    m_avg_windowPtr = 0;
    m_avg_windowSize = 0;
    m_currentAvgA = 0;

    m_currentAvgB = 0;

    // initialize starting voltage for velocity control to 0
    m_currentVoltage = 0;
}

// return a pressure reading
float BtuLinear::getPressure() {
    return m_pressureSensor.MS5837_Pressure();
}

// resets values of the controllers
void BtuLinear::stop() {
	m_currentVoltage = 0;
	m_currentAvgA = 0;
	m_currentAvgB = 0;
	m_avg_windowSize = 0;
	m_depthPid.reset();
	m_posAPid.reset();
	m_posBPid.reset();
	m_velAPid.reset();
	m_velBPid.reset();
	return;
}

// updates depth PID tunings
void BtuLinear::updateDepthTunings(float kc, float tauI, float tauD) {
    m_kc = kc;
    m_tauI = tauI;
    m_tauD = tauD;
    m_depthPid.setTunings(kc, tauI, tauD);
}

// updates Position PID tunings
void BtuLinear::updatePosTunings(float kc, float tauI, float tauD) {
    m_p_kc = kc;
    m_p_tauI = tauI;
    m_p_tauD = tauD;
    m_posAPid.setTunings(kc, tauI, tauD);
    m_posBPid.setTunings(kc, tauI, tauD);
}

// updates Velocity PID tunings
void BtuLinear::updateVelTunings(float kc, float tauI, float tauD) {
    m_v_kc = kc;
    m_v_tauI = tauI;
    m_v_tauD = tauD;
    m_velAPid.setTunings(kc, tauI, tauD);
    m_velBPid.setTunings(kc, tauI, tauD);
}

// updates Mode.  Resets most values if the mode has changed
void BtuLinear::updateMode(int mode) {
    if(m_mode != mode) {
        stop();
        m_mode = mode;
    }
}

// runs one cycle of the controller dictated by mode
void BtuLinear::runCycle(float setVal) {
    switch (m_mode) {

    case VOLTAGE_CTRL_MODE:
        voltageControl(setVal);
        break;

    case VELOCITY_CTRL_MODE:
        velocityControl(setVal);
        break;

    case DEPTH_CTRL_MODE:
        depthControl(setVal);
        break;

    case POSITION_CTRL_MODE:
        positionControl(setVal);
        break;
    }
}

// convenience function, updates mode, then runs a cycle in the chosen mode
void BtuLinear::updateAndRunCycle(int mode, float value) {
    updateMode(mode);
    runCycle(value);
}

// sends a duty cycle to one of the actuators, based on the second argument
void BtuLinear::voltageControlHelper(float setDuty, int ctrl) {

    l_actPosPC = getActPosition(ctrl);
	//clip commanded voltage to upper and lower limit
	l_cmdVoltPC = utility::clip(setDuty, -1.0, 1.0); // increase or decrease current voltage to get closer to desired velocity

    // arrest any movement at the edges, and reset current voltage, to aid responsiveness at the edges
    if ((l_actPosPC <= POSITION_MIN && l_cmdVoltPC <= 0) || (l_actPosPC >= POSITION_MAX && l_cmdVoltPC >= 0)) {
    	l_cmdVoltPC = 0;
    }

	// have a small dead zone TODO: either better tune or remove,
    // causes small offsets in position sometimes (of about 0.025% at current gain values)
    l_cmdVoltPC = utility::deadzone(l_cmdVoltPC,VOLTAGE_THRESHOLD);

    if(ctrl == ACT_A) {
        if(setDuty > 0) {       // extending
            m_actAPwm = setDuty;
            m_actADir = 1;
        } else {                // contracting
            m_actADir = 0;
            m_actAPwm = -setDuty;
        }
    } else {
        if(setDuty > 0) {
            m_actBPwm = setDuty;
            m_actBDir = 1;
        } else {
            m_actBDir = 0;
            m_actBPwm = -setDuty;
        }
    }
}

// calls voltageControlHelper on both actuators
void BtuLinear::voltageControl(float setDuty) {
    voltageControlHelper(setDuty, ACT_A);
    voltageControlHelper(setDuty, ACT_B);
}

// updates the SMA window with the current position reading
void BtuLinear::updatePositionReadings() {
    float aPosition = m_actAPot;
    float bPosition = m_actBPot;

    float aOldPos = m_avg_windowA[m_avg_windowPtr];
    float bOldPos = m_avg_windowB[m_avg_windowPtr];
    m_avg_windowA[m_avg_windowPtr] = aPosition;
    m_avg_windowB[m_avg_windowPtr] = bPosition;
    m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;
    if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {
        // buffer is full
    	m_currentAvgA = m_currentAvgA + (aPosition / AVG_WINDOW_WIDTH)- (aOldPos / AVG_WINDOW_WIDTH);
        m_currentAvgB = m_currentAvgB + (bPosition / AVG_WINDOW_WIDTH)- (bOldPos / AVG_WINDOW_WIDTH);
    } else {
    	// buffer is still filling up
        m_avg_windowSize++;
        m_currentAvgA = 0;
        m_currentAvgB = 0;
        for(int i = 0; i < m_avg_windowSize; i++) {
            m_currentAvgA = (m_avg_windowA[i] / m_avg_windowSize);
            m_currentAvgB = (m_avg_windowB[i] / m_avg_windowSize);
        }
    }
}

// gets the current Actuator Position.  No SMA, just reads and rescales the potentiometer
float BtuLinear::getActPosition(int act) {
    // Following code is for moving average, TODO: currently uncommented
	// updatePositionReadings();
    // float position;
    // if(act == ACT_A) {
    //     position = m_currentAvgA;
    // } else {
    //     position = m_currentAvgB;
    // }
    float position;
    if(act == ACT_A) {
        position = m_actAPot;
    } else {
        position = m_actBPot;
    }
    float scaledPos = (position - POT_MIN) / (POT_MAX - POT_MIN);
    return scaledPos;
}

// controls velocity on one actuator
void BtuLinear::velocityControlHelper(float setVelocity, int ctrl) {
    // Check if one of the two allowable actuators is called
	if(ctrl != ACT_A && ctrl != ACT_B) {
        return;
    }
    // Acquire the actuator position from the potentiometer
	l_actPosVC = getActPosition(ctrl);

    // avoid going past the very edges:
	// Currently at 0.99 and 0.01 due to some uncertainty in scaling/pot readings
    // also to help avoid accumulation of error during such a period
    if ((l_actPosVC <= POSITION_MIN && setVelocity < 0) || (l_actPosVC >= POSITION_MAX && setVelocity > 0)) {
		//at an edge, set the setVelocity to 0
        l_setVelVC = 0;
    }
    else {
    	// not at an edge, use setVelocity
    	l_setVelVC = setVelocity;
    }

    if(ctrl == ACT_A) {
        l_actVelVC = (l_actPosVC - m_oldPosA) / PID_FREQ;
        // set process value to the derivative of position (velocity)
    	m_velAPid.setProcessValue(l_actVelVC);
        m_velAPid.setSetPoint(l_setVelVC);
        l_deltaVoltVC = m_velAPid.compute();
        m_oldPosA = l_actPosVC;        // update old position for so we can keep calculating derivatives
    }
    else {
    	l_actVelVC = (l_actPosVC - m_oldPosB) / PID_FREQ;
        m_velBPid.setProcessValue(l_actVelVC);
        m_velBPid.setSetPoint(l_setVelVC);
        l_deltaVoltVC = m_velBPid.compute();
        m_oldPosB = l_actPosVC;
    }
    //add the voltage delta to the current voltage that is the current operating point
    l_cmdVoltVC = utility::clip(m_currentVoltage + l_deltaVoltVC, -1.0, 1.0); // increase or decrease current voltage to get closer to desired velocity

    voltageControlHelper(l_cmdVoltVC, ctrl);

}

// does velocity control on both actuators
void BtuLinear::velocityControl(float setVel) {
    velocityControlHelper(setVel, ACT_A);
    velocityControlHelper(setVel, ACT_B);
}

// control position of one actuator
void BtuLinear::positionControlHelper(float setPos, int ctrl) {
	 // Check if one of the two allowable actuators is called
	if(ctrl != ACT_A && ctrl != ACT_B) {
		return;
	}
    // Acquire the actuator position from the potentiometer
	l_actPosPC = getActPosition(ctrl);

	if(ctrl == ACT_A) {
        m_posAPid.setSetPoint(setPos);
        m_posAPid.setProcessValue(l_actPosPC);
        l_cmdVoltPC = m_posAPid.compute();
        //m_cmdVel = m_posAPid.compute();
    } else {
        m_posBPid.setSetPoint(setPos);
        m_posBPid.setProcessValue(l_actPosPC);
        l_cmdVoltPC = m_posBPid.compute();
        //m_cmdVel = m_posBPid.compute();
    }
	//velocityControlHelper(m_cmdVel, ctrl);
    voltageControlHelper(l_cmdVoltPC, ctrl);

}

// control position of both actuators
void BtuLinear::positionControl(float setPos) {
    positionControlHelper(setPos, ACT_A);
    positionControlHelper(setPos, ACT_B);
}

// control depth via master-slave
void BtuLinear::depthControlHelper(float cmdVelocity) {
    velocityControlHelper(cmdVelocity, ACT_B); // control velocity on one actuator
    positionControlHelper(getActPosition(ACT_B), ACT_A); // have the other actuator constantly try to mirror the first
}

// do depth control
void BtuLinear::depthControl(float setDepthMeters) {

	m_depthPid.setSetPoint(setDepthMeters);

    float curDepth = getDepth();

    m_depthPid.setProcessValue(curDepth);

    float cmdVel = m_depthPid.compute();
    depthControlHelper(-1*cmdVel);
    // velocityControl(cmdVel);
}

// get a depth reading
float BtuLinear::getDepth() {
    float pvDepth = getPressure();
    float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) / P_WATER_SURFACE_MBAR;
    return pvDepthMeters;
}

// float BTU::getServoPos() {
// 	return m_motorServo.readPosition();
// }
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkJoinSeriesImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImage.h"

#include "itkJoinSeriesImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkStreamingImageFilter.h"
#include "itkCommand.h"
#include "itkFileOutputWindow.h"

#include <iostream>
#include <vector>

int itkJoinSeriesImageFilterPrintTest(int, char* [])
{
  typedef itk::Image<float,2> InputType;
  typedef itk::Image<float,2> OutputType;

  // NOTE: A compile error should be here (by extending itk::Concept?),
  // because InputImageDimension must be less than OutputImageDimension.
  itk::JoinSeriesImageFilter<InputType,OutputType>::Pointer JoinSeriesImageFilterObj =
    itk::JoinSeriesImageFilter<InputType,OutputType>::New();
  std::cout << "-------------JoinSeriesImageFilter" << JoinSeriesImageFilterObj;

  return 0;
}

class ShowProgressObject
{
public:
  ShowProgressObject(itk::ProcessObject* o)
    {m_Process = o;}
  void ShowProgress()
    {std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
  itk::ProcessObject::Pointer m_Process;
};

int itkJoinSeriesImageFilterTest(int, char* [] )
{
  // to write informations to "itkMessageLog.txt" when DebugOn()
//   itk::OutputWindow::SetInstance( itk::FileOutputWindow::New() );

  const unsigned int streamDivisions = 2;
  typedef unsigned char PixelType;
  typedef itk::Image< PixelType, 2 > InputImageType;
  // typedef itk::Image< PixelType, 3 > OutputImageType;
  typedef itk::Image< PixelType, 4 > OutputImageType;

  // the expected result
  OutputImageType::IndexType expectedIndex = {{1, 2, 0, 0}};
  OutputImageType::SizeType expectedSize = {{8, 5, 4, 1}};
  OutputImageType::RegionType expectedRegion;
  expectedRegion.SetIndex( expectedIndex );
  expectedRegion.SetSize( expectedSize );
  OutputImageType::SpacingType expectedSpacing;
  expectedSpacing[0] = 1.1;
  expectedSpacing[1] = 1.2;
  expectedSpacing[2] = 1.3;
  expectedSpacing[3] = 1.0;
  OutputImageType::PointType expectedOrigin;
  expectedOrigin[0] = 0.1;
  expectedOrigin[1] = 0.2;
  expectedOrigin[2] = 0.3;
  expectedOrigin[3] = 0.0;

  // make the input images
  int numInputs = 4;
  InputImageType::IndexType index = {{1, 2}};
  InputImageType::SizeType size = {{8, 5}};
  InputImageType::RegionType region;
  region.SetIndex( index );
  region.SetSize( size );
  const double spacingValue = 1.3;
  InputImageType::SpacingType spacing;
  spacing[0] = 1.1;
  spacing[1] = 1.2;
  const double originValue = 0.3;
  InputImageType::PointType origin;
  origin[0] = 0.1;
  origin[1] = 0.2;

  std::vector<InputImageType::Pointer> inputs;

  PixelType counter1 = 0;
  for ( int i = 0; i < numInputs; i++ )
    {
    inputs.push_back( InputImageType::New() );
    inputs[i]->SetLargestPossibleRegion( region );
    inputs[i]->SetBufferedRegion( region );
    inputs[i]->Allocate();

    itk::ImageRegionIterator<InputImageType>
      inputIter( inputs[i], inputs[i]->GetBufferedRegion() );
    while ( !inputIter.IsAtEnd() )
      {
      inputIter.Set( counter1 );
      ++counter1;
      ++inputIter;
      }

    inputs[i]->SetSpacing( spacing );
    inputs[i]->SetOrigin( origin );
//     inputs[i]->DebugOn();
    }

  // create the filter
  typedef itk::JoinSeriesImageFilter< InputImageType, OutputImageType >
    JoinSeriesImageType;
  JoinSeriesImageType::Pointer joinSeriesImage = JoinSeriesImageType::New();

  // check the default values
  if ( joinSeriesImage->GetSpacing() != 1.0 )
    {
    std::cout << "Default spacing is not 1.0" << std::endl;
    return EXIT_FAILURE;
    }
  if ( joinSeriesImage->GetOrigin() != 0.0 )
    {
    std::cout << "Default origin is not 0.0" << std::endl;
    return EXIT_FAILURE;
    }

  // setup the filter
  joinSeriesImage->SetSpacing( spacingValue );
  joinSeriesImage->SetOrigin( originValue );
  for ( int i = 0; i < numInputs; i++ )
    {
    joinSeriesImage->SetInput( i, inputs[i] );
    }

  // to test ProgressReporter
  ShowProgressObject progressWatch( joinSeriesImage );
  typedef itk::SimpleMemberCommand< ShowProgressObject > CommandType;
  CommandType::Pointer command = CommandType::New();
  command->SetCallbackFunction( &progressWatch,
                                &ShowProgressObject::ShowProgress );
  joinSeriesImage->AddObserver( itk::ProgressEvent(), command );

  // to test streaming
  typedef itk::StreamingImageFilter< OutputImageType, OutputImageType >
    StreamingImageType;
  StreamingImageType::Pointer streamingImage = StreamingImageType::New();
  streamingImage->SetInput( joinSeriesImage->GetOutput() );
  streamingImage->SetNumberOfStreamDivisions( streamDivisions );

  // run
  try
    {
    streamingImage->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << err << std::endl;
    //for InvalidRequestedRegionError
    itk::DataObjectError * errp = dynamic_cast<itk::DataObjectError *>( &err );
    if ( errp )
      {
      errp->GetDataObject()->Print( std::cout );
      }
    return EXIT_FAILURE;
    }

  OutputImageType::Pointer output = streamingImage->GetOutput();

  // check the informations
  if ( output->GetLargestPossibleRegion() != expectedRegion )
    {
    std::cout << "LargestPossibleRegion mismatch" << std::endl;
    return EXIT_FAILURE;
    }
  if ( output->GetSpacing() != expectedSpacing )
    {
    std::cout << "Spacing mismatch" << std::endl;
    return EXIT_FAILURE;
    }
  if ( output->GetOrigin() != expectedOrigin )
    {
    std::cout << "Origin mismatch" << std::endl;
    return EXIT_FAILURE;
    }

  // check the contents
  bool passed = true;

  PixelType counter2 = 0;
  itk::ImageRegionIterator<OutputImageType>
    outputIter( output, output->GetBufferedRegion() );
  while ( !outputIter.IsAtEnd() )
    {
    if ( outputIter.Get() != counter2 )
      {
      passed = false;
      std::cout << "Mismatch at index: " << outputIter.GetIndex() << std::endl;
      }
    ++counter2;
    ++outputIter;
    }

  if ( !passed || counter1 != counter2 )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  // An exception is raised when an input is missing.
  passed = false;

  // set the 2nd input null
  joinSeriesImage->SetInput( 1, 0 );
  try
    {
    joinSeriesImage->Update();
    }
  catch( itk::InvalidRequestedRegionError & err )
    {
    if ( strcmp("Missing input 1", err.GetDescription()) == 0 )
      {
      passed = true;
      }
    else
      {
      std::cout << err << std::endl;
      return EXIT_FAILURE;
      }
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }

  if ( !passed )
    {
    std::cout << "Expected exception is missing" << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;
}

<commit_msg>BUG: tests should not depend on the text of the exception message.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkJoinSeriesImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImage.h"

#include "itkJoinSeriesImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkStreamingImageFilter.h"
#include "itkCommand.h"
#include "itkFileOutputWindow.h"

#include <iostream>
#include <vector>

int itkJoinSeriesImageFilterPrintTest(int, char* [])
{
  typedef itk::Image<float,2> InputType;
  typedef itk::Image<float,2> OutputType;

  // NOTE: A compile error should be here (by extending itk::Concept?),
  // because InputImageDimension must be less than OutputImageDimension.
  itk::JoinSeriesImageFilter<InputType,OutputType>::Pointer JoinSeriesImageFilterObj =
    itk::JoinSeriesImageFilter<InputType,OutputType>::New();
  std::cout << "-------------JoinSeriesImageFilter" << JoinSeriesImageFilterObj;

  return 0;
}

class ShowProgressObject
{
public:
  ShowProgressObject(itk::ProcessObject* o)
    {m_Process = o;}
  void ShowProgress()
    {std::cout << "Progress " << m_Process->GetProgress() << std::endl;}
  itk::ProcessObject::Pointer m_Process;
};

int itkJoinSeriesImageFilterTest(int, char* [] )
{
  // to write informations to "itkMessageLog.txt" when DebugOn()
//   itk::OutputWindow::SetInstance( itk::FileOutputWindow::New() );

  const unsigned int streamDivisions = 2;
  typedef unsigned char PixelType;
  typedef itk::Image< PixelType, 2 > InputImageType;
  // typedef itk::Image< PixelType, 3 > OutputImageType;
  typedef itk::Image< PixelType, 4 > OutputImageType;

  // the expected result
  OutputImageType::IndexType expectedIndex = {{1, 2, 0, 0}};
  OutputImageType::SizeType expectedSize = {{8, 5, 4, 1}};
  OutputImageType::RegionType expectedRegion;
  expectedRegion.SetIndex( expectedIndex );
  expectedRegion.SetSize( expectedSize );
  OutputImageType::SpacingType expectedSpacing;
  expectedSpacing[0] = 1.1;
  expectedSpacing[1] = 1.2;
  expectedSpacing[2] = 1.3;
  expectedSpacing[3] = 1.0;
  OutputImageType::PointType expectedOrigin;
  expectedOrigin[0] = 0.1;
  expectedOrigin[1] = 0.2;
  expectedOrigin[2] = 0.3;
  expectedOrigin[3] = 0.0;

  // make the input images
  int numInputs = 4;
  InputImageType::IndexType index = {{1, 2}};
  InputImageType::SizeType size = {{8, 5}};
  InputImageType::RegionType region;
  region.SetIndex( index );
  region.SetSize( size );
  const double spacingValue = 1.3;
  InputImageType::SpacingType spacing;
  spacing[0] = 1.1;
  spacing[1] = 1.2;
  const double originValue = 0.3;
  InputImageType::PointType origin;
  origin[0] = 0.1;
  origin[1] = 0.2;

  std::vector<InputImageType::Pointer> inputs;

  PixelType counter1 = 0;
  for ( int i = 0; i < numInputs; i++ )
    {
    inputs.push_back( InputImageType::New() );
    inputs[i]->SetLargestPossibleRegion( region );
    inputs[i]->SetBufferedRegion( region );
    inputs[i]->Allocate();

    itk::ImageRegionIterator<InputImageType>
      inputIter( inputs[i], inputs[i]->GetBufferedRegion() );
    while ( !inputIter.IsAtEnd() )
      {
      inputIter.Set( counter1 );
      ++counter1;
      ++inputIter;
      }

    inputs[i]->SetSpacing( spacing );
    inputs[i]->SetOrigin( origin );
//     inputs[i]->DebugOn();
    }

  // create the filter
  typedef itk::JoinSeriesImageFilter< InputImageType, OutputImageType >
    JoinSeriesImageType;
  JoinSeriesImageType::Pointer joinSeriesImage = JoinSeriesImageType::New();

  // check the default values
  if ( joinSeriesImage->GetSpacing() != 1.0 )
    {
    std::cout << "Default spacing is not 1.0" << std::endl;
    return EXIT_FAILURE;
    }
  if ( joinSeriesImage->GetOrigin() != 0.0 )
    {
    std::cout << "Default origin is not 0.0" << std::endl;
    return EXIT_FAILURE;
    }

  // setup the filter
  joinSeriesImage->SetSpacing( spacingValue );
  joinSeriesImage->SetOrigin( originValue );
  for ( int i = 0; i < numInputs; i++ )
    {
    joinSeriesImage->SetInput( i, inputs[i] );
    }

  // to test ProgressReporter
  ShowProgressObject progressWatch( joinSeriesImage );
  typedef itk::SimpleMemberCommand< ShowProgressObject > CommandType;
  CommandType::Pointer command = CommandType::New();
  command->SetCallbackFunction( &progressWatch,
                                &ShowProgressObject::ShowProgress );
  joinSeriesImage->AddObserver( itk::ProgressEvent(), command );

  // to test streaming
  typedef itk::StreamingImageFilter< OutputImageType, OutputImageType >
    StreamingImageType;
  StreamingImageType::Pointer streamingImage = StreamingImageType::New();
  streamingImage->SetInput( joinSeriesImage->GetOutput() );
  streamingImage->SetNumberOfStreamDivisions( streamDivisions );

  // run
  try
    {
    streamingImage->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << err << std::endl;
    //for InvalidRequestedRegionError
    itk::DataObjectError * errp = dynamic_cast<itk::DataObjectError *>( &err );
    if ( errp )
      {
      errp->GetDataObject()->Print( std::cout );
      }
    return EXIT_FAILURE;
    }

  OutputImageType::Pointer output = streamingImage->GetOutput();

  // check the informations
  if ( output->GetLargestPossibleRegion() != expectedRegion )
    {
    std::cout << "LargestPossibleRegion mismatch" << std::endl;
    return EXIT_FAILURE;
    }
  if ( output->GetSpacing() != expectedSpacing )
    {
    std::cout << "Spacing mismatch" << std::endl;
    return EXIT_FAILURE;
    }
  if ( output->GetOrigin() != expectedOrigin )
    {
    std::cout << "Origin mismatch" << std::endl;
    return EXIT_FAILURE;
    }

  // check the contents
  bool passed = true;

  PixelType counter2 = 0;
  itk::ImageRegionIterator<OutputImageType>
    outputIter( output, output->GetBufferedRegion() );
  while ( !outputIter.IsAtEnd() )
    {
    if ( outputIter.Get() != counter2 )
      {
      passed = false;
      std::cout << "Mismatch at index: " << outputIter.GetIndex() << std::endl;
      }
    ++counter2;
    ++outputIter;
    }

  if ( !passed || counter1 != counter2 )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  // An exception is raised when an input is missing.
  passed = false;

  // set the 2nd input null
  joinSeriesImage->SetInput( 1, 0 );
  try
    {
    joinSeriesImage->Update();
    }
  catch( itk::InvalidRequestedRegionError & err )
    {
    passed = true;
    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }

  if ( !passed )
    {
    std::cout << "Expected exception is missing" << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file linear_observation_model.hpp
 * \date October 2014
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP
#define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP

#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/decorrelated_gaussian.hpp>
#include <fl/model/adaptive_model.hpp>
#include <fl/model/observation/interface/observation_density.hpp>
#include <fl/model/observation/interface/observation_model_interface.hpp>
#include <fl/model/observation/interface/additive_observation_function.hpp>

namespace fl
{

/**
 * \ingroup observation_models
 *
 * This represents the linear gaussian observation model \f$p(y_t \mid x_t)\f$
 * governed by the linear equation
 *
 * \f$ y_t  = H_t x_t + N_t v_t \f$
 *
 * where \f$ y_t\f$ is the observation, \f$ x_t\f$ is the state. The matrix
 * \f$H_t\f$ is the sensor model mapping the state into the observation space.
 * The vector \f$ v_t \sim {\cal N}(v_t; 0, I)\f$ is a standard normal variate
 * which is mapped into the the observation space via the noise model matrix
 * \f$N_t\f$. Any Gaussian noise \f$\tilde{v}_t \sim {\cal N}(\tilde{v}_t ; 0,
 * R_t) \f$ can be represented via \f$\tilde{v}_t = N_t v_t\f$ with\f$N_t
 * = \sqrt{R_t}\f$. Hence, the linear equation may be restated as the more
 * familiar but equivalent form
 *
 * \f$ y_t  = H_t x_t + \tilde{v}_t \f$.
 */
template <typename Obsrv, typename State>
class LinearObservationModel<Obsrv, State>
#ifdef GENERATING_DOCUMENTATION
    : public LinearObservationModel<Obsrv_, State_, Density>,
#else
    : public LinearObservationModel<Obsrv, State, Gaussian<Obsrv>>,
#endif
      public Descriptor
{
public:
    /**
     * Constructs a linear gaussian observation model
     * \param obsrv_dim     observation dimension if dynamic size
     * \param state_dim     state dimension if dynamic size
     */
    explicit
    LinearObservationModel(int obsrv_dim = DimensionOf<Obsrv>(),
                           int state_dim = DimensionOf<State>())
        : LinearObservationModel<Obsrv, State, Gaussian<Obsrv>>(
              obsrv_dim, state_dim)
    { }

    virtual std::string name() const
    {
        return "LinearObservationModel";
    }

    virtual std::string description() const
    {
        return "Linear observation model";
    }
};

}

#endif
<commit_msg>Updated descriptor details<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */

/**
 * \file linear_observation_model.hpp
 * \date October 2014
 * \author Jan Issac (jan.issac@gmail.com)
 */

#ifndef FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP
#define FL__MODEL__OBSERVATION__LINEAR_OBSERVATION_MODEL_HPP

#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/decorrelated_gaussian.hpp>
#include <fl/model/adaptive_model.hpp>
#include <fl/model/observation/interface/observation_density.hpp>
#include <fl/model/observation/interface/observation_model_interface.hpp>
#include <fl/model/observation/interface/additive_observation_function.hpp>

namespace fl
{

/**
 * \ingroup observation_models
 *
 * This represents the linear gaussian observation model \f$p(y_t \mid x_t)\f$
 * governed by the linear equation
 *
 * \f$ y_t  = H_t x_t + N_t v_t \f$
 *
 * where \f$ y_t\f$ is the observation, \f$ x_t\f$ is the state. The matrix
 * \f$H_t\f$ is the sensor model mapping the state into the observation space.
 * The vector \f$ v_t \sim {\cal N}(v_t; 0, I)\f$ is a standard normal variate
 * which is mapped into the the observation space via the noise model matrix
 * \f$N_t\f$. Any Gaussian noise \f$\tilde{v}_t \sim {\cal N}(\tilde{v}_t ; 0,
 * R_t) \f$ can be represented via \f$\tilde{v}_t = N_t v_t\f$ with\f$N_t
 * = \sqrt{R_t}\f$. Hence, the linear equation may be restated as the more
 * familiar but equivalent form
 *
 * \f$ y_t  = H_t x_t + \tilde{v}_t \f$.
 */
template <typename Obsrv, typename State>
class LinearObservationModel<Obsrv, State>
#ifdef GENERATING_DOCUMENTATION
    : public LinearObservationModel<Obsrv_, State_, Density>,
#else
    : public LinearObservationModel<Obsrv, State, Gaussian<Obsrv>>,
#endif
      public Descriptor
{
public:
    /**
     * Constructs a linear gaussian observation model
     * \param obsrv_dim     observation dimension if dynamic size
     * \param state_dim     state dimension if dynamic size
     */
    explicit
    LinearObservationModel(int obsrv_dim = DimensionOf<Obsrv>(),
                           int state_dim = DimensionOf<State>())
        : LinearObservationModel<Obsrv, State, Gaussian<Obsrv>>(
              obsrv_dim, state_dim)
    { }

    virtual std::string name() const
    {
        return "LinearGaussianObservationModel";
    }

    virtual std::string description() const
    {
        return "Linear observation model with additive Gaussian noise";
    }
};

}

#endif
<|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// 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
// ===========================================================================
//
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
// Created on: Aug 25, 2017
//
#include <stdexcept>
#include <h5cpp/property/class.hpp>
#include <h5cpp/property/dataset_creation_list.hpp>
#include <h5cpp/types.hpp>

namespace hdf5 {
namespace property {

std::ostream &operator<<(std::ostream &stream,const DatasetFillValueStatus &status)
{
  switch(status)
  {
    case DatasetFillValueStatus::UNDEFINED:
      return stream<<"UNDEFINED";
    case DatasetFillValueStatus::DEFAULT:
      return stream<<"DEFAULT";
    case DatasetFillValueStatus::USER_DEFINED:
      return stream<<"USER_DEFINED";
  }
}

std::ostream &operator<<(std::ostream &stream,const DatasetFillTime &time)
{
  switch(time)
  {
    case DatasetFillTime::IFSET:
      return stream<<"IFSET";
    case DatasetFillTime::ALLOC:
      return stream<<"ALLOC";
    case DatasetFillTime::NEVER:
      return stream<<"NEVER";
  }
}

std::ostream &operator<<(std::ostream &stream,const DatasetAllocTime &time)
{
  switch(time)
  {
    case DatasetAllocTime::DEFAULT:
      return stream<<"DEFAULT";
    case DatasetAllocTime::EARLY:
      return stream<<"EARLY";
    case DatasetAllocTime::INCR:
      return stream<<"INCR";
    case DatasetAllocTime::LATE:
      return stream<<"LATE";
  }
}

std::ostream &operator<<(std::ostream &stream,const DatasetLayout &layout)
{
  switch(layout)
  {
    case DatasetLayout::COMPACT:
      return stream<<"COMPACT";
    case DatasetLayout::CONTIGUOUS:
      return stream<<"CONTIGUOUS";
    case DatasetLayout::CHUNKED:
      return stream<<"CHUNKED";
#if H5_VERSION_GE(1,10,0)
    case DatasetLayout::VIRTUAL:
      return stream<<"VIRTUAL";
#endif
  }
}

DatasetCreationList::DatasetCreationList():
    ObjectCreationList(kDatasetCreate)
{}

DatasetCreationList::~DatasetCreationList()
{}

void DatasetCreationList::layout(DatasetLayout layout) const
{
  if(H5Pset_layout(static_cast<hid_t>(*this),static_cast<H5D_layout_t>(layout))<0)
  {
    throw std::runtime_error("Failure setting the dataset layout!");
  }
}

DatasetLayout DatasetCreationList::layout() const
{
  switch(H5Pget_layout(static_cast<hid_t>(*this)))
  {
    case H5D_COMPACT:
      return DatasetLayout::COMPACT;
    case H5D_CONTIGUOUS:
      return DatasetLayout::CONTIGUOUS;
    case H5D_CHUNKED:
      return DatasetLayout::CHUNKED;
#if H5_VERSION_GE(1,10,0)
    case H5D_VIRTUAL:
      return DatasetLayout::VIRTUAL;
#endif
    default:
      throw std::runtime_error("Failure retrieving the dataset layout!");
  }
}

void DatasetCreationList::chunk(const Dimensions &chunk_dims) const
{
  if(H5Pset_chunk(static_cast<hid_t>(*this),chunk_dims.size(),chunk_dims.data())<0)
  {
    throw std::runtime_error("Failure setting chunk dimensions!");
  }
}

Dimensions DatasetCreationList::chunk() const
{
  int s = H5Pget_chunk(static_cast<hid_t>(*this),0,NULL);
  if(s<0)
  {
    throw std::runtime_error("Failure retrieving the chunk rank!");
  }

  Dimensions buffer(s);
  if(H5Pget_chunk(static_cast<hid_t>(*this),s,buffer.data())<0)
  {
    throw std::runtime_error("Failure retrieving the chunk dimension!");
  }

  return buffer;
}

DatasetFillValueStatus DatasetCreationList::fill_value_status() const
{
  H5D_fill_value_t status;
  if(H5Pfill_value_defined(static_cast<hid_t>(*this),&status)<0)
  {
    throw std::runtime_error("Failure obtaining the fill value status!");
  }
  return static_cast<DatasetFillValueStatus>(status);
}

void DatasetCreationList::fill_time(DatasetFillTime time) const
{
  if(H5Pset_fill_time(static_cast<hid_t>(*this),
                      static_cast<H5D_fill_time_t>(time))<0)
  {
    throw std::runtime_error("Failure setting the fill time for the dataset!");
  }
}

DatasetFillTime DatasetCreationList::fill_time() const
{
  H5D_fill_time_t buffer;
  if(H5Pget_fill_time(static_cast<hid_t>(*this),&buffer)<0)
  {
    throw std::runtime_error("Failure retrieving dataset fill time!");
  }
  return static_cast<DatasetFillTime>(buffer);
}

void DatasetCreationList::allocation_time(DatasetAllocTime time) const
{
  if(H5Pset_alloc_time(static_cast<hid_t>(*this),
                       static_cast<H5D_alloc_time_t>(time))<0)
  {
    throw std::runtime_error("Failure setting dataset allocation time!");
  }
}

DatasetAllocTime DatasetCreationList::allocation_time() const
{
  H5D_alloc_time_t buffer;
  if(H5Pget_alloc_time(static_cast<hid_t>(*this),&buffer)<0)
  {
    throw std::runtime_error("Failure retrieving dataset allocation time!");
  }
  return static_cast<DatasetAllocTime>(buffer);
}

} // namespace property
} // namespace hdf5
<commit_msg>fixed DatasetCreationList warnings; updates #26'<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// 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
// ===========================================================================
//
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
// Created on: Aug 25, 2017
//
#include <stdexcept>
#include <h5cpp/property/class.hpp>
#include <h5cpp/property/dataset_creation_list.hpp>
#include <h5cpp/types.hpp>

namespace hdf5 {
namespace property {

std::ostream &operator<<(std::ostream &stream,const DatasetFillValueStatus &status)
{
  switch(status)
  {
    case DatasetFillValueStatus::UNDEFINED:
      return stream<<"UNDEFINED";
    case DatasetFillValueStatus::DEFAULT:
      return stream<<"DEFAULT";
    case DatasetFillValueStatus::USER_DEFINED:
      return stream<<"USER_DEFINED";
  }
  return stream;
}

std::ostream &operator<<(std::ostream &stream,const DatasetFillTime &time)
{
  switch(time)
  {
    case DatasetFillTime::IFSET:
      return stream<<"IFSET";
    case DatasetFillTime::ALLOC:
      return stream<<"ALLOC";
    case DatasetFillTime::NEVER:
      return stream<<"NEVER";
  }
  return stream;
}

std::ostream &operator<<(std::ostream &stream,const DatasetAllocTime &time)
{
  switch(time)
  {
    case DatasetAllocTime::DEFAULT:
      return stream<<"DEFAULT";
    case DatasetAllocTime::EARLY:
      return stream<<"EARLY";
    case DatasetAllocTime::INCR:
      return stream<<"INCR";
    case DatasetAllocTime::LATE:
      return stream<<"LATE";
  }
  return stream;
}

std::ostream &operator<<(std::ostream &stream,const DatasetLayout &layout)
{
  switch(layout)
  {
    case DatasetLayout::COMPACT:
      return stream<<"COMPACT";
    case DatasetLayout::CONTIGUOUS:
      return stream<<"CONTIGUOUS";
    case DatasetLayout::CHUNKED:
      return stream<<"CHUNKED";
#if H5_VERSION_GE(1,10,0)
    case DatasetLayout::VIRTUAL:
      return stream<<"VIRTUAL";
#endif
  }
  return stream;
}

DatasetCreationList::DatasetCreationList():
    ObjectCreationList(kDatasetCreate)
{}

DatasetCreationList::~DatasetCreationList()
{}

void DatasetCreationList::layout(DatasetLayout layout) const
{
  if(H5Pset_layout(static_cast<hid_t>(*this),static_cast<H5D_layout_t>(layout))<0)
  {
    throw std::runtime_error("Failure setting the dataset layout!");
  }
}

DatasetLayout DatasetCreationList::layout() const
{
  switch(H5Pget_layout(static_cast<hid_t>(*this)))
  {
    case H5D_COMPACT:
      return DatasetLayout::COMPACT;
    case H5D_CONTIGUOUS:
      return DatasetLayout::CONTIGUOUS;
    case H5D_CHUNKED:
      return DatasetLayout::CHUNKED;
#if H5_VERSION_GE(1,10,0)
    case H5D_VIRTUAL:
      return DatasetLayout::VIRTUAL;
#endif
    default:
      throw std::runtime_error("Failure retrieving the dataset layout!");
  }
}

void DatasetCreationList::chunk(const Dimensions &chunk_dims) const
{
  if(H5Pset_chunk(static_cast<hid_t>(*this),chunk_dims.size(),chunk_dims.data())<0)
  {
    throw std::runtime_error("Failure setting chunk dimensions!");
  }
}

Dimensions DatasetCreationList::chunk() const
{
  int s = H5Pget_chunk(static_cast<hid_t>(*this),0,NULL);
  if(s<0)
  {
    throw std::runtime_error("Failure retrieving the chunk rank!");
  }

  Dimensions buffer(s);
  if(H5Pget_chunk(static_cast<hid_t>(*this),s,buffer.data())<0)
  {
    throw std::runtime_error("Failure retrieving the chunk dimension!");
  }

  return buffer;
}

DatasetFillValueStatus DatasetCreationList::fill_value_status() const
{
  H5D_fill_value_t status;
  if(H5Pfill_value_defined(static_cast<hid_t>(*this),&status)<0)
  {
    throw std::runtime_error("Failure obtaining the fill value status!");
  }
  return static_cast<DatasetFillValueStatus>(status);
}

void DatasetCreationList::fill_time(DatasetFillTime time) const
{
  if(H5Pset_fill_time(static_cast<hid_t>(*this),
                      static_cast<H5D_fill_time_t>(time))<0)
  {
    throw std::runtime_error("Failure setting the fill time for the dataset!");
  }
}

DatasetFillTime DatasetCreationList::fill_time() const
{
  H5D_fill_time_t buffer;
  if(H5Pget_fill_time(static_cast<hid_t>(*this),&buffer)<0)
  {
    throw std::runtime_error("Failure retrieving dataset fill time!");
  }
  return static_cast<DatasetFillTime>(buffer);
}

void DatasetCreationList::allocation_time(DatasetAllocTime time) const
{
  if(H5Pset_alloc_time(static_cast<hid_t>(*this),
                       static_cast<H5D_alloc_time_t>(time))<0)
  {
    throw std::runtime_error("Failure setting dataset allocation time!");
  }
}

DatasetAllocTime DatasetCreationList::allocation_time() const
{
  H5D_alloc_time_t buffer;
  if(H5Pget_alloc_time(static_cast<hid_t>(*this),&buffer)<0)
  {
    throw std::runtime_error("Failure retrieving dataset allocation time!");
  }
  return static_cast<DatasetAllocTime>(buffer);
}

} // namespace property
} // namespace hdf5
<|endoftext|>


<commit_before>#include "ofApp.h"

//------------------------------------------------------------------------------
void ofApp::setup()
{
    ofSetFrameRate(30);
    ofEnableAlphaBlending();
}

//------------------------------------------------------------------------------
void ofApp::draw()
{

    ofBackground(0);

    // get the current time
    unsigned long long now = ofGetElapsedTimeMillis();

    // cycle through the rectangles
    for(int i = 0; i < numRectangles; i++)
    {
        // if now is past the next scheduled blink time
        if(now > nextRectangleBlinkTime[i])
        {
            // schedule the next blink time
            nextRectangleBlinkTime[i] = now + rectangleDelays[i];
            // toggle the rectangle state
            rectangleState[i] = !rectangleState[i];
        }

        // draw the rectangles
        if(rectangleState[i])
        {
            // draw an unfilled rectangle if the state is "true"
            ofNoFill();
        }
        else
        {
            // draw a filled rectangle if the state is "false"
            ofFill();
        }

        ofSetColor(ofColor::yellow);
        ofRect(rectangles[i]);

        // Uncomment the following to draw based on the amount of time left
        // before the next blink happens.

//        unsigned long long timeUntilNextBlink = nextRectangleBlinkTime[i] - now;
//
//        float percent = ofNormalize(timeUntilNextBlink,0,rectangleDelays[i]);
//
//        ofFill();
//        ofSetColor(255,0,0);
//        ofRect(rectangles[i].x,
//               rectangles[i].y + rectangles[i].height,
//               10,
//               -rectangles[i].height * percent);

    }
}
<commit_msg>Cleanup.<commit_after>#include "ofApp.h"

//------------------------------------------------------------------------------
void ofApp::setup()
{
    ofSetFrameRate(30);
    ofEnableAlphaBlending();
}

//------------------------------------------------------------------------------
void ofApp::draw()
{
    ofBackground(0);

    // get the current time
    unsigned long long now = ofGetElapsedTimeMillis();

    // cycle through the rectangles
    for(int i = 0; i < numRectangles; i++)
    {
        // if now is past the next scheduled blink time
        if(now > nextRectangleBlinkTime[i])
        {
            // schedule the next blink time
            nextRectangleBlinkTime[i] = now + rectangleDelays[i];
            // toggle the rectangle state
            rectangleState[i] = !rectangleState[i];
        }

        // draw the rectangles
        if(rectangleState[i])
        {
            // draw an unfilled rectangle if the state is "true"
            ofNoFill();
        }
        else
        {
            // draw a filled rectangle if the state is "false"
            ofFill();
        }

        ofSetColor(ofColor::yellow);
        ofRect(rectangles[i]);

        // Uncomment the following to draw based on the amount of time left
        // before the next blink happens.

//        unsigned long long timeUntilNextBlink = nextRectangleBlinkTime[i] - now;
//
//        float percent = ofNormalize(timeUntilNextBlink,0,rectangleDelays[i]);
//
//        ofFill();
//        ofSetColor(255,0,0);
//        ofRect(rectangles[i].x,
//               rectangles[i].y + rectangles[i].height,
//               10,
//               -rectangles[i].height * percent);

    }
}
<|endoftext|>